text
stringlengths 2
6.14k
|
|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.util.lang.gridfunc;
import java.util.HashSet;
import java.util.Set;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.lang.IgniteCallable;
/**
* Hash set factory.
*/
public class SetFactoryCallable implements IgniteCallable<Set> {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public Set call() {
return new HashSet();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SetFactoryCallable.class, this);
}
}
|
<html>
<head>
<style id="stylesheet">
#polygon-shape-inside, #polygon-svg-shape {
position: absolute;
left: 0px;
top: 0px;
width: 200px;
height: 200px;
}
#shape-inside {
position: absolute;
left: 0px;
top: 0px;
width: 50px;
height: 50px;
float: left;
margin-left: 50px;
background-color: yellow;
}
</style>
</head>
<body>
<svg id="polygon-svg-shape" xmlns="http://www.w3.org/2000/svg">
<polygon points="0,0 200,0 200,200" fill="#636363"></polygon>
</svg>
<div id="shape-inside">
</div>
<p style="margin-top: 200px;">
There is a triangle shape-inside (represented by the matching filled SVG polygon), the shape-inside contains a 50x50px yellow float left,
the float should be at the very left and top position inside the triangle shape where it fits first.
</p>
<p>Bug <a href="http://webkit.org/b/102846">102846</a>: [CSS Shapes] Use the float height to determine position in shape-inside</p>
</body>
</html>
|
/*!\file
* The main contribution of this file is the abstact interface dve_prob_process_t.
*/
#ifndef DIVINE_DVE_PROB_PROCESS_HH
#define DIVINE_DVE_PROB_PROCESS_HH
#ifndef DOXYGEN_PROCESSING
#include "system/system.hh"
#include "system/dve/syntax_analysis/dve_parser.hh"
#include "system/prob_process.hh"
#include "system/dve/dve_process.hh"
#include "system/dve/dve_prob_transition.hh"
namespace divine { //We want Doxygen not to see namespace `divine'
#endif //DOXYGEN_PROCESSING
//predeclarations of classes:
class prob_process_t;
class dve_prob_transition_t;
class dve_process_t;
class dve_parser_t;
//!Class representing a DVE process in probabilistic system
/*!This class implements the abstract interface prob_process_t.
*/
class dve_prob_process_t: public prob_process_t, public dve_process_t
{
private:
static dve_parser_t prob_proc_parser;
array_t<dve_prob_transition_t*> prob_transitions;
public:
//!A constructor
dve_prob_process_t() {}
//!A constructor
dve_prob_process_t(prob_system_t * const system): process_t(system),
prob_process_t(system), dve_process_t(system) {}
//!A destructor
virtual ~dve_prob_process_t();
//!Implements prob_process_t::add_prob_transition() for DVE probabilistics process
virtual void add_prob_transition(prob_transition_t * const prob_trans);
//!Implements prob_process_t::remove_prob_transition() for DVE probabilistics process
virtual void remove_prob_transition(const size_int_t transition_index);
//!Implements prob_process_t::get_prob_transition() for DVE probabilistics process
virtual prob_transition_t * get_prob_transition
(const size_int_t prob_trans_lid);
//!Implements prob_process_t::get_prob_transition() for DVE probabilistics process
virtual const prob_transition_t * get_prob_transition
(const size_int_t prob_trans_lid) const;
//!Implements prob_process_t::get_prob_trans_count() for DVE probabilistics process
virtual size_int_t get_prob_trans_count() const
{ return prob_transitions.size(); }
//!Implements process_t::to_string() for DVE probabilistics process
virtual std::string to_string() const;
//!Implements process_t::write() for DVE probabilistics process
virtual void write(std::ostream & ostr) const;
//!Implements process_t::from_string() for DVE probabilistics process
virtual int from_string(std::string & proc_str);
//!Implements process_t::read() for DVE probabilistics process
virtual int read(std::istream & istr);
};
#ifndef DOXYGEN_PROCESSING
} //END of namespace divine
#endif //DOXYGEN_PROCESSING
#endif
|
/**
* Created by Administrator on 2016/4/30.
*/
var canvas;
var stage;
var img = new Image;
var sprite;
window.onload = function(){
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
stage.addEventListener("stagemousedown",clickCanvas);
stage.addEventListener("stagemousemove",moveCanvas);
var data={
images:["177.jpg"],
frames:{width:20,height:20,ragX:10,regY:10}
}
sprite = new createjs.Sprite(new createjs.SpriteSheet(data));
createjs.Ticker.setFPS(20);
createjs.Ticker.addEventListener("tick",tick);
}
function tick(e){
var t =stage.getNumChildren();
for(var i = t-1;i>0;i--){
var s =stage.getChildAt(i);
s.vY +=2;
s.vX +=1;
s.x += s.vX;
s.y += s.vY;
s.scaleX = s.scaleY =s.scaleX+ s.vS;
s.alpha += s.vA;
if(s.alpha <=0 || s.y > canvas.height){
stage.removeChildAt(i);
}
}
stage.update(e);
}
function clickCanvas(e){
addS(Math.random()*200 +100,stage.mouseX,stage.mouseY,2);
}
function moveCanvas(e){
addS(Math.random()*2 +1,stage.mouseX,stage.mouseY,1);
}
function addS(count,x,y,speed){
for(var i =0;i<count;i++){
var s =sprite.clone();
s.x = x;
s.y = y;
s.alpha = Math.random()*0.5 + 0.5;
s.scaleX = s.scaleY = Math.random() +0.3;
var a= Math.PI * 2 *Math.random();
var v= (Math.random() - 0.5)*30*speed;
s.vX = Math.cos(a)*v;
s.vY = Math.sin(a)*v;
s.vS = (Math.random() - 0.5)*0.2;//scale
s.vA = -Math.random()*0.05 -0.01;//alpha
stage.addChild(s);
}
}
|
var maxDiff = function(data) {
var memory = {};
var maxDiff = -1;
var maxRight = _.last(data);
memory.max = maxRight;
for (var i = data.length-2; i >= 0; i--) {
if (data[i].close > maxRight.close) {
maxRight = data[i];
memory.max = maxRight;
} else {
var diff = maxRight.close - data[i].close;
if (diff > maxDiff) {
memory.min = data[i];
maxDiff = diff;
}
}
}
memory.maxDiff = maxDiff;
return memory;
}
|
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import json
import google.appengine.ext.ndb as ndb
class GithubResource(ndb.Model):
# A key holder used to define an entitygroup for
# each Issue/PR, for easy ancestor queries.
@staticmethod
def make_key(repo, number):
return ndb.Key(GithubResource, '%s %s' % (repo, number))
def shrink(body):
'''
Recursively remove Github API urls from an object, to make it
more human-readable.
'''
toremove = []
for key, value in body.iteritems():
if isinstance(value, basestring):
if key.endswith('url'):
if (value.startswith('https://api.github.com/') or
value.startswith('https://avatars.githubusercontent.com')):
toremove.append(key)
elif isinstance(value, dict):
shrink(value)
elif isinstance(value, list):
for el in value:
if isinstance(el, dict):
shrink(el)
for key in toremove:
body.pop(key)
return body
class GithubWebhookRaw(ndb.Model):
repo = ndb.StringProperty()
number = ndb.IntegerProperty(indexed=False)
event = ndb.StringProperty()
timestamp = ndb.DateTimeProperty(auto_now_add=True)
body = ndb.TextProperty(compressed=True)
def to_tuple(self):
return (self.event, shrink(json.loads(self.body)), float(self.timestamp.strftime('%s.%f')))
def from_iso8601(t):
return t and datetime.datetime.strptime(t, '%Y-%m-%dT%H:%M:%SZ')
def make_kwargs(body, fields):
kwargs = {}
for field in fields:
if field.endswith('_at'):
kwargs[field] = from_iso8601(body[field])
else:
kwargs[field] = body[field]
return kwargs
class GHStatus(ndb.Model):
# Key: {repo}\t{sha}\t{context}
state = ndb.StringProperty(indexed=False)
target_url = ndb.StringProperty(indexed=False)
description = ndb.TextProperty()
created_at = ndb.DateTimeProperty(indexed=False)
updated_at = ndb.DateTimeProperty(indexed=False)
@staticmethod
def make_key(repo, sha, context):
return ndb.Key(GHStatus, '%s\t%s\t%s' % (repo, sha, context))
@staticmethod
def make(repo, sha, context, **kwargs):
return GHStatus(key=GHStatus.make_key(repo, sha, context), **kwargs)
@staticmethod
def query_for_sha(repo, sha):
before = GHStatus.make_key(repo, sha, '')
after = GHStatus.make_key(repo, sha, '\x7f')
return GHStatus.query(GHStatus.key > before, GHStatus.key < after)
@staticmethod
def from_json(body):
kwargs = make_kwargs(body,
'sha context state target_url description '
'created_at updated_at'.split())
kwargs['repo'] = body['name']
return GHStatus.make(**kwargs)
@property
def repo(self):
return self.key.id().split('\t', 1)[0]
@property
def sha(self):
return self.key.id().split('\t', 2)[1]
@property
def context(self):
return self.key.id().split('\t', 2)[2]
class GHIssueDigest(ndb.Model):
# Key: {repo} {number}
is_pr = ndb.BooleanProperty()
is_open = ndb.BooleanProperty()
involved = ndb.StringProperty(repeated=True)
xref = ndb.StringProperty(repeated=True)
payload = ndb.JsonProperty()
updated_at = ndb.DateTimeProperty()
head = ndb.StringProperty()
@staticmethod
def make_key(repo, number):
return ndb.Key(GHIssueDigest, '%s %s' % (repo, number))
@staticmethod
def make(repo, number, is_pr, is_open, involved, payload, updated_at):
return GHIssueDigest(key=GHIssueDigest.make_key(repo, number),
is_pr=is_pr, is_open=is_open, involved=involved, payload=payload,
updated_at=updated_at, head=payload.get('head'),
xref=payload.get('xrefs', []))
@staticmethod
def get(repo, number):
return GHIssueDigest.make_key(repo, number).get()
@property
def repo(self):
return self.key.id().split()[0]
@property
def number(self):
return int(self.key.id().split()[1])
@staticmethod
def find_head(repo, head):
return GHIssueDigest.query(GHIssueDigest.key > GHIssueDigest.make_key(repo, ''),
GHIssueDigest.key < GHIssueDigest.make_key(repo, '~'),
GHIssueDigest.head == head)
@staticmethod
def find_xrefs(xref):
return GHIssueDigest.query(GHIssueDigest.xref == xref)
class GHUserState(ndb.Model):
# Key: {github username}
acks = ndb.JsonProperty() # dict of issue keys => ack time (seconds since epoch)
@staticmethod
def make_key(user):
return ndb.Key(GHUserState, user)
@staticmethod
def make(user, acks=None):
return GHUserState(key=GHUserState.make_key(user), acks=acks or {})
@ndb.transactional
def save_if_newer(obj):
assert obj.updated_at is not None
old = obj.key.get()
if old is None:
obj.put()
return True
else:
if old.updated_at is None or obj.updated_at >= old.updated_at:
obj.put()
return True
return False
|
package org.apache.mesos.elasticsearch.systemtest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.log4j.Logger;
import org.apache.mesos.mini.MesosCluster;
import org.apache.mesos.mini.mesos.MesosClusterConfig;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* System tests which verifies configuring a separate Zookeeper cluster for the framework.
*/
@SuppressWarnings({"PMD.AvoidUsingHardCodedIP"})
public class ZookeeperFrameworkSystemTest {
private static final Logger LOGGER = Logger.getLogger(ZookeeperFrameworkSystemTest.class);
@Rule
public final MesosCluster CLUSTER = new MesosCluster(
MesosClusterConfig.builder()
.numberOfSlaves(3)
.privateRegistryPort(15000) // Currently you have to choose an available port by yourself
.slaveResources(new String[]{"ports(*):[9200-9200,9300-9300]", "ports(*):[9201-9201,9301-9301]", "ports(*):[9202-9202,9302-9302]"})
.build()
);
private ElasticsearchSchedulerContainer scheduler;
private ZookeeperContainer zookeeper;
@Rule
public TestWatcher watchman = new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
CLUSTER.stop();
scheduler.remove();
}
};
@Before
public void startScheduler() throws Exception {
CLUSTER.injectImage("mesos/elasticsearch-executor");
LOGGER.info("Starting Elasticsearch scheduler");
zookeeper = new ZookeeperContainer(CLUSTER.getConfig().dockerClient);
CLUSTER.addAndStartContainer(zookeeper);
scheduler = new ElasticsearchSchedulerContainer(CLUSTER.getConfig().dockerClient, CLUSTER.getMesosContainer().getIpAddress());
LOGGER.info("Started Elasticsearch scheduler on " + scheduler.getIpAddress() + ":8080");
}
@Test
public void testZookeeperFramework() throws UnirestException {
scheduler.setZookeeperFrameworkUrl("zk://" + zookeeper.getIpAddress() + ":2181");
CLUSTER.addAndStartContainer(scheduler);
TasksResponse tasksResponse = new TasksResponse(scheduler.getIpAddress(), CLUSTER.getConfig().getNumberOfSlaves());
List<JSONObject> tasks = tasksResponse.getTasks();
ElasticsearchNodesResponse nodesResponse = new ElasticsearchNodesResponse(tasks, CLUSTER.getConfig().getNumberOfSlaves());
assertTrue("Elasticsearch nodes did not discover each other within 5 minutes", nodesResponse.isDiscoverySuccessful());
ElasticsearchZookeeperResponse elasticsearchZookeeperResponse = new ElasticsearchZookeeperResponse(tasks.get(0).getString("http_address"));
assertEquals("zk://" + zookeeper.getIpAddress() + ":2181", elasticsearchZookeeperResponse.getHost());
}
@Test
public void testZookeeperFramework_differentPath() throws UnirestException {
scheduler.setZookeeperFrameworkUrl("zk://" + zookeeper.getIpAddress() + ":2181/framework");
CLUSTER.addAndStartContainer(scheduler);
TasksResponse tasksResponse = new TasksResponse(scheduler.getIpAddress(), CLUSTER.getConfig().getNumberOfSlaves());
List<JSONObject> tasks = tasksResponse.getTasks();
ElasticsearchNodesResponse nodesResponse = new ElasticsearchNodesResponse(tasks, CLUSTER.getConfig().getNumberOfSlaves());
assertTrue("Elasticsearch nodes did not discover each other within 5 minutes", nodesResponse.isDiscoverySuccessful());
ElasticsearchZookeeperResponse elasticsearchZookeeperResponse = new ElasticsearchZookeeperResponse(tasks.get(0).getString("http_address"));
assertEquals("zk://" + zookeeper.getIpAddress() + ":2181", elasticsearchZookeeperResponse.getHost());
}
}
|
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.heuristic.selector.common.iterator;
import java.util.NoSuchElementException;
public abstract class UpcomingSelectionIterator<S> extends SelectionIterator<S> {
protected boolean upcomingCreated = false;
protected boolean hasUpcomingSelection = true;
protected S upcomingSelection;
public boolean hasNext() {
if (!upcomingCreated) {
upcomingSelection = createUpcomingSelection();
upcomingCreated = true;
}
return hasUpcomingSelection;
}
public S next() {
if (!hasUpcomingSelection) {
throw new NoSuchElementException();
}
if (!upcomingCreated) {
upcomingSelection = createUpcomingSelection();
}
upcomingCreated = false;
return upcomingSelection;
}
protected abstract S createUpcomingSelection();
protected S noUpcomingSelection() {
hasUpcomingSelection = false;
return null;
}
}
|
/* This file is part of MAPS.
*
* MAPS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* MAPS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* MAPS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cpu.hpp"
#include "alu.hpp"
#include "controlunit.hpp"
#include "mmu.hpp"
namespace maps {
namespace emulator {
CPU::~CPU() = default;
CPU::CPU() : cu{new ControlUnit{*this}},
alu{new ALU},
mmu{new MMU}
{
reset();
}
void CPU::reset()
{
for (auto& x : R) {
x = 0;
}
CCR.reset();
}
ControlUnit& CPU::getCU()
{
return *cu;
}
ALU& CPU::getALU()
{
return *alu;
}
MMU& CPU::getMMU()
{
return *mmu;
}
} // namespace emulator
} // namespace maps
|
import * as React from 'react';
import { CSSModule } from '../index';
export interface ButtonToolbarProps extends React.HTMLAttributes<HTMLElement> {
[key: string]: any;
tag?: React.ElementType;
'aria-label'?: string;
cssModule?: CSSModule;
}
declare class ButtonToolbar<T = {[key: string]: any}> extends React.Component<ButtonToolbarProps> {}
export default ButtonToolbar;
|
(function($,Edge,compId){var Composition=Edge.Composition,Symbol=Edge.Symbol;
//Edge symbol: 'stage'
(function(symbolName){Symbol.bindElementAction(compId,symbolName,"${_pin3}","click",function(sym,e){window.open("http://www.achievechiropractic.com/","_self");});
//Edge binding end
Symbol.bindElementAction(compId,symbolName,"${_pin2}","mouseover",function(sym,e){sym.play(4405);});
//Edge binding end
Symbol.bindTriggerAction(compId,symbolName,"Default Timeline",4275,function(sym,e){sym.stop(4275);});
//Edge binding end
Symbol.bindElementAction(compId,symbolName,"document","scroll",function(sym,e){});
//Edge binding end
})("stage");
//Edge symbol: 'newmedia'
(function(symbolName){Symbol.bindElementAction(compId,symbolName,"${_pin2Copy}","mouseover",function(sym,e){sym.play(4405);});
//Edge binding end
Symbol.bindElementAction(compId,symbolName,"${_pin3Copy}","click",function(sym,e){window.open("http://www.achievechiropractic.com/","_self");});
//Edge binding end
})("newmedia");
//Edge symbol end:'newmedia'
})(jQuery,AdobeEdge,"EDGE-608325628");
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FappSettings.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FappSettings.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d8239545-bebb-4b52-933d-fd1f604880d3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
#!/usr/bin/env python
# Netsink - Network Sinkhole for Isolated Malware Analysis
# Copyright (C) 2013-2014 Steve Henderson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import socket
import sys
import threading
import time
from netsink.config import Config, ModuleConfig, parseints
from netsink.listener import Listener
from netsink.modules import registry
from netsink.redirection import Redirector
log = logging.getLogger("netsink")
def initlogging():
"""Initialise the logging format and handler.
"""
formatter = logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
def startlisteners(config):
"""Start all the listeners defined in the supplied config and block indefintely.
"""
for x in config.listeners.values():
if not registry.get(x.module):
log.warn("Netsink module '%s' not found for config item '%s'... skipping",
x.module, x.name)
continue
x.servers = []
for p in x.ports:
try:
server = Listener(x.name, p, registry[x.module], x.socktype, x.config).server
x.servers.append(server)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.setDaemon(True)
server_thread.start()
except socket.error:
log.warning("Unable to establish listener on port %s... skipping.", p)
x.ports.remove(p)
if x.ports:
log.info("Listener '%s' awaiting %s activity on port/s %s",
x.name, x.socktype, str(x.ports))
return config.listeners.values()
def redirection(config, listeners):
"""Setup port forwarding and redirection for the given listeners/config.
"""
if not Redirector.available():
log.warn("Connection redirection enabled but not available. "
"Ensure 'iptables' is installed and current user has sufficient privileges.")
return
if Redirector.existing_rules():
log.warn("Existing rules found in iptables. Not enabling connection redirection in case of conflict.")
return
redir = Redirector()
# pass through all listener ports
for listener in [ x for x in listeners if x.socktype in ['SSL', 'TCP'] ]:
redir.add_forwarding("tcp", listener.ports)
# pass through any explicitly excluded ports
exclusions = list(parseints(config.cfg.get("redirection", "port_exclusions")))
if exclusions:
redir.add_forwarding("tcp", exclusions)
# forward all other ports to generic listener
generic = config.cfg.get("redirection", "port_forwarding")
if generic:
redir.add_forwarding("tcp", outport=generic)
# forward all protocols to local address
redir.add_forwarding()
def wait():
"""Block indefinitely until Ctrl-C.
"""
log.info("Waiting...")
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
sys.exit()
def main():
"""Script entry point.
"""
initlogging()
log.setLevel(logging.DEBUG)
l = startlisteners(Config())
if Config().redirection:
redirection(ModuleConfig("redirection.conf"), l)
wait()
if __name__ == '__main__':
main()
|
/*
* Copyright (C) 2013 Google Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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.
*/
#include "config.h"
#include "HTMLResourcePreloader.h"
#include "CachedResourceLoader.h"
#include "Document.h"
namespace WebCore {
bool PreloadRequest::isSafeToSendToAnotherThread() const
{
return m_initiator.isSafeToSendToAnotherThread()
&& m_charset.isSafeToSendToAnotherThread()
&& m_resourceURL.isSafeToSendToAnotherThread()
&& m_baseURL.isSafeToSendToAnotherThread();
}
KURL PreloadRequest::completeURL(Document* document)
{
return document->completeURL(m_resourceURL, m_baseURL.isEmpty() ? document->url() : m_baseURL);
}
CachedResourceRequest PreloadRequest::resourceRequest(Document* document)
{
ASSERT(isMainThread());
CachedResourceRequest request(ResourceRequest(completeURL(document)));
request.setInitiator(m_initiator);
// FIXME: It's possible CORS should work for other request types?
if (m_resourceType == CachedResource::Script)
request.mutableResourceRequest().setAllowCookies(m_crossOriginModeAllowsCookies);
return request;
}
void HTMLResourcePreloader::takeAndPreload(PreloadRequestStream& r)
{
PreloadRequestStream requests;
requests.swap(r);
for (PreloadRequestStream::iterator it = requests.begin(); it != requests.end(); ++it)
preload(it->release());
}
void HTMLResourcePreloader::preload(PassOwnPtr<PreloadRequest> preload)
{
CachedResourceRequest request = preload->resourceRequest(m_document);
m_document->cachedResourceLoader()->preload(preload->resourceType(), request, preload->charset());
}
}
|
import serial
import io
CONST_HEADER = '<?xml version="1.0" encoding="UTF-8"?><gpx version="1.0">'
CONST_TAIL = '</gpx>'
class Point:
def __init__(self, latitude, longitude, time, src, description=''):
self.latitude = latitude
self.longitude = longitude
self.time = time
self.description = description
self.src = src
def toGPX (listWaypoints, listTracks):
waypointFullString = ''
for waypoint in listWaypoints:
waypointString = '<wpt lat="' + waypoint.latitude + '" lon="' + waypoint.longitude + '">'
waypointString += '<name>' + waypoint.description + '</name>'
waypointString += '<src>' + waypoint.src + '</src>'
waypointString += '</wpt>'
waypointFullString += waypointString
trackFullString = ''
for track in listTracks:
trackString = '<trk>'
trackString += '<src>' + track[0].src + '</src>'
if len(track[0].description) > 0:
trackString += '<name>' + track[0].description + '</name>'
trackString += '<trkseg>'
for trackpoint in track:
trackpointString = '<trkpt lat="' + trackpoint.latitude + '" lon="' + trackpoint.longitude + '">'
trackpointString += '<time>'+ trackpoint.time +'</time>'
trackpointString += '</trkpt>'
trackString += trackpointString
trackString += '</trkseg></trk>'
trackFullString += trackString
return CONST_HEADER + waypointFullString + trackFullString + CONST_TAIL
def parseGPS(GPSLine):
line = GPSLine
while line[-1] == '0':
line = line[0:-1]
isPOI = True if int(line[0:2]) == 1 else False
if isPOI:
while len(line)<30:
line = line + '0'
poi_id = line[1:3][::-1]
latitude = hexCoordToString(line[6:16])
longitude = hexCoordToString(line[16:26])
scout_id = line[26:28]
category = line[28:30]
description = line[31:]
waypoint = Point(latitude, longitude, 0, scout_id, description)
listWaypoints.append(waypoint)
else:
while len(line)%30 !=2:
line = line + '0'
for i in range(min(5, len(line)//30)): # int division
start = i * 30
latitude = hexCoordToString(line[start + 2 : start + 12])
longitude = hexCoordToString(line[start + 12 : start + 22])
scout_id = line[start + 22:start+24]
timestamp = str(timeHexToInt(line[start + 24 : start + 32]))
trackpoint = Point(latitude, longitude, timestamp, scout_id, '')
isFound = False
for track in listTracks:
if track[0].src == scout_id:
track.append(trackpoint)
isFound = True
if not isFound:
listTracks.append([trackpoint])
GPSString = toGPX(listWaypoints, listTracks)
writeToDisk(GPSString)
return GPSString
def writeToDisk(GPSString):
file = open("testfile.gpx","w")
file.write(GPSString)
file.close()
def hexCoordToString(hexString):
hexarray = []
for i in range(5):
hexarray.append(hexString[2*i:2*i+2])
numarray = hexarray[0:4][::-1]
numstring = ''.join(numarray[0:4])
output = int(numstring,16)
output = float(output)/(10**6)
if hexarray[-1]=='02':
output = -output
return str(output)
def timeHexToInt(hexstring):
return int(''.join([
hexstring[6:8],
hexstring[4:6],
hexstring[2:4],
hexstring[0:2]
]),16)
## Actual code that runs
# these lists keep track of all the points
listWaypoints = []
listTracks = []
# this below serial code needs to be tested with serial inputs
ser = serial.Serial('COM4', 9600)
while True:
readin = ser.read(80)
#the above serial code needs to be tested
inputString = bytearray(readin).hex()
printString = parseGPS(inputString)
print(printString)
## Code to test the above functions
# inpString = '0 34567 89012 3 4444 00567 89012 3 4444 34567 89012 1 4444'.replace(' ', '')
# parseGPS(inpString) # 0 34567 89012 3 4444 0 00567 89012 3 4444 0 34567 89012 1 4444
# print parseGPS('122345678901234description') # 1 22 34567 89012 3 4 description
# inputHex = '31 32 32 33 34 35 36 37 38 39 30 31 32 33 34 64 65 73 63 72 69 70 74 69 6f 6e'
|
// boost/cstdlib.hpp header ------------------------------------------------//
// Copyright Beman Dawes 2001. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/utility/cstdlib.html for documentation.
// Revision History
// 26 Feb 01 Initial version (Beman Dawes)
#ifndef BOOST_CSTDLIB_HPP
#define BOOST_CSTDLIB_HPP
#include <cstdlib>
namespace pdalboost
{
// The intent is to propose the following for addition to namespace std
// in the C++ Standard Library, and to then deprecate EXIT_SUCCESS and
// EXIT_FAILURE. As an implementation detail, this header defines the
// new constants in terms of EXIT_SUCCESS and EXIT_FAILURE. In a new
// standard, the constants would be implementation-defined, although it
// might be worthwhile to "suggest" (which a standard is allowed to do)
// values of 0 and 1 respectively.
// Rationale for having multiple failure values: some environments may
// wish to distinguish between different classes of errors.
// Rationale for choice of values: programs often use values < 100 for
// their own error reporting. Values > 255 are sometimes reserved for
// system detected errors. 200/201 were suggested to minimize conflict.
const int exit_success = EXIT_SUCCESS; // implementation-defined value
const int exit_failure = EXIT_FAILURE; // implementation-defined value
const int exit_exception_failure = 200; // otherwise uncaught exception
const int exit_test_failure = 201; // report_error or
// report_critical_error called.
}
#endif
|
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Evaluates inception resnet.
Evaluates the generated images on the comp split, stores a webpage with
results, and computes metrics based on supervised learning.
NOTE: Currently this eval is specific to deepmind 2d shapes and labels.
Author: vrama@
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cPickle as pickle
import logging
import math
import os
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from classification import classification_model
from joint_vae import utils
app = tf.app
flags = tf.flags
gfile = tf.gfile
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('batch_size', 64,
'The number of images in each batch.')
tf.app.flags.DEFINE_string('dataset_dir', '', 'Path to the dataset we want to'
' train on.')
# Data augmentation.
tf.app.flags.DEFINE_boolean('blur_image', False, 'Whether to blur input images.')
tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/inception_resnet_train/',
'Directory where the model was written to.')
tf.app.flags.DEFINE_string('eval_dir', '/tmp/inception_resnet_train/',
'Directory where the results are saved to.')
tf.app.flags.DEFINE_integer(
'eval_interval_secs', 120,
'The frequency, in seconds, with which evaluation is run.')
tf.app.flags.DEFINE_string('split_name', 'val',
"""Either 'train' or 'val' or 'test'.""")
tf.logging.set_verbosity(tf.logging.INFO)
def create_restore_fn(checkpoint_path, saver):
"""Return a function to restore variables.
Args:
checkpoint_path: Path to the checkpoint to load.
saver: tf.train.Saver object
Returns:
restore_fn: An op to which we can pass a session to restore
variables.
global_step_ckpt: Int, the global checkpoint number.
Raises:
ValueError: If invalid checkpoint name is found or there are no checkpoints
in the directory specified.
"""
tf.logging.info('Checkpoint path: %s', (checkpoint_path))
global_step_ckpt = checkpoint_path.split('-')[-1]
# Checks for fraudulent checkpoints without a global_step.
if global_step_ckpt == checkpoint_path:
raise ValueError('Invalid checkpoint name %s.' % (checkpoint_path))
def restore_fn(sess):
"""Restore model and feature extractor."""
tf.logging.info('Restoring the model from %s', (checkpoint_path))
saver.restore(sess, checkpoint_path)
return restore_fn, global_step_ckpt
def evaluate_loop():
"""Run evaluation in a loop."""
batch_size = FLAGS.batch_size
g = tf.Graph()
with g.as_default():
tf.set_random_seed(123)
classifier = classification_model.ClassifyFaces(
mode='eval', split=FLAGS.split_name)
classifier.build_model()
saver = classifier.setup_saver()
num_iter = int(math.ceil(classifier.num_samples / float(FLAGS.batch_size)))
summary_writer = tf.summary.FileWriter(FLAGS.eval_dir)
for checkpoint_path in slim.evaluation.checkpoints_iterator(
FLAGS.checkpoint_dir, FLAGS.eval_interval_secs):
init_fn, global_step = create_restore_fn(checkpoint_path, saver)
with tf.Session() as sess:
init_fn(sess)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
total_correct = []
total_data = []
for this_iter in xrange(num_iter):
logits, labels = sess.run([classifier.logits, classifier.labels])
predictions = np.argmax(logits, axis=-1)
total_correct.append(predictions == labels)
total_data.append(predictions.shape[0])
if this_iter % 10 == 0:
tf.logging.info('Done with iteration %d/%d' % (this_iter, num_iter))
if len(total_correct) > 1:
total_correct = np.vstack(total_correct)
else:
total_correct = total_correct[0]
total_correct = np.sum(total_correct, axis=0)
accuracy_per_class = total_correct / float(np.sum(total_data))
overall_accuracy = np.mean(accuracy_per_class)
tf.logging.info('Accuracy: %f' % (overall_accuracy))
utils.add_simple_summary(
summary_writer,
overall_accuracy,
'Accuracy',
global_step,)
# Add summaries for each class.
for attribute_name, accuracy in zip(classifier.attribute_names,
accuracy_per_class):
utils.add_simple_summary(summary_writer, accuracy,
'Accuracy_' + attribute_name, global_step)
tf.logging.info('Accuracy for class %s is %f' % (attribute_name,
accuracy))
coord.request_stop()
coord.join(threads, stop_grace_period_secs=10)
def main(_):
np.random.seed(42)
assert FLAGS.checkpoint_dir is not None, ('Please specify a checkpoint '
'directory.')
assert FLAGS.eval_dir is not None, 'Please specify an evaluation directory.'
evaluate_loop()
if __name__ == '__main__':
tf.app.run()
|
// Copyright © 2012 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's 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 AUTHORS OF THE SOFTWARE 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VirtualRadar.Interface.Adsb
{
/// <summary>
/// An enumeration of the different values of HMI that can be transmitted in ADS-B version 1 target state and status messages.
/// </summary>
public enum HorizontalModeIndicator : byte
{
/// <summary>
/// The information is not available.
/// </summary>
Unknown = 0,
/// <summary>
/// The aircraft is turning towards the target heading or track.
/// </summary>
Acquiring = 1,
/// <summary>
/// The aircraft is maintaining the target heading or track.
/// </summary>
Maintaining = 2,
/// <summary>
/// Reserved.
/// </summary>
Reserved = 3,
}
}
|
using UnityEngine;
using System.Collections;
public class EnemyPortal : Entity
{
FAnimatedSprite animatedSprite;
public EnemyPortal(Vector2 pos)
{
Position = pos;
animatedSprite = new FAnimatedSprite("portal");
animatedSprite.addAnimation(new FAnimation("glow", new int[]{
0,1,2,3}, 200, true));
AddChild(animatedSprite);
animatedSprite.color = Color.red;
boundingBox = new Rectangle();
useGravity = false;
ListenForUpdate(Update);
HealthPoints = 10;
Size = new Vector2(animatedSprite.width, animatedSprite.height);
boundingBox = new Rectangle();
}
public override void Update()
{
base.Update();
float posY = Mathf.Lerp(Position.y - 10f, Position.y + 10f, Mathf.PingPong(Time.time, 1.0f));
SetPosition(Position.x, posY);
if (Time.frameCount % 120 == 0)
{
if (Vector2.Distance(TileMap.CurrentMap.getPlayer().Position, Position) < 200)
{
EnemyBouncer en = new EnemyBouncer(Position);
TileMap.CurrentMap.getEnemyList().Add(en);
TileMap.CurrentMap.AddChild(en);
}
}
if (HealthPoints <= 0)
Destroy();
}
}
|
'''
Created on 12.08.2014
@author: oliver
'''
import os
import platform
from bayeos import simpleEncryptor
from os import path
import random
import string
KEY_LENGTH=32
def read(alias, path=None):
""" Read connection information from file and return list: [url, user, password] """
return readConnections(path)[alias]
def readConnections(path=None):
""" Returns connection information as a dictionary """
if not path:
path = getHomePath()
key = _readKey(getKeyPath(path))
if key:
return _readConnections(key,getConnectionPath(path))
else:
return {}
def write(alias,url,user,password='', path=None):
""" Write connection information to file """
if not path:
path = getHomePath()
keyFile = getKeyPath(path)
key = _readKey(keyFile)
if not key:
key = _writeKey(keyFile)
if not key: raise Exception("Failed to create key file")
conFile = getConnectionPath(path)
cons = _readConnections(key,conFile)
cons[alias] = [url,user,password]
_writeConnections(key,conFile,cons)
return True
def _readKey(keyFile):
""" Reads key from file and returns key as string """
if not path.isfile(keyFile):
return None
file = open(keyFile)
key = file.read()
file.close()
return key
def _writeKey(keyFile):
""" Writes key to file and returns key as string """
file = open(keyFile, "w")
key = ''.join(random.choice(string.ascii_lowercase) for i in range(KEY_LENGTH))
file.write(key)
file.close()
return key
def getConnectionPath(path):
""" Gets path of connection file as string """
return path + os.sep + ".bayeos.pwd"
def getKeyPath(path):
""" Gets path of key file as string """
return path + os.sep + ".bayeos.pwd_key"
def getHomePath():
""" Gets default path location for key and connection file"""
p = path.expanduser("~")
if (platform.system() == 'Windows'): p = p + "\Documents"
return p
def _readConnections(key,conFile):
""" Reads connections form file and returns information as dictionary with values as list:[url,user,password]"""
cons = {}
if not path.isfile(conFile):
return cons
file = open(conFile)
for line in file:
v = line.split(None,4)
if (len(v)==3):
cons[v[0]] = [v[1],v[2],None]
elif (len(v)==4):
cons[v[0]] = [v[1],v[2],simpleEncryptor.decrypt(key, v[3])]
else:
file.close()
raise Exception("Invalid file format: " + file)
file.close()
return cons
def _writeConnections(key, conFile, cons):
""" Writes connections to file """
file = open(conFile, "w")
for alias, con in cons.items():
if len(con)>1:
file.write(alias)
file.write(" " + con[0])
file.write(" " + con[1])
if con[2]:
file.write(" " + simpleEncryptor.encrypt(key, con[2]))
file.write("\n")
file.close()
|
// DR 2007
// We shouldn't instantiate A<void> to lookup operator=, since operator=
// must be a non-static member function.
template<typename T> struct A { typename T::error e; };
template<typename T> struct B { };
B<A<void> > b1, &b2 = (b1 = b1);
|
from django.contrib.markup.templatetags.markup import restructuredtext
from django.http import HttpResponse, Http404
from django.views.generic.simple import direct_to_template
from django.utils.safestring import mark_safe
from django.utils.simplejson import dumps
from docutils.utils import SystemMessage
from richtemplates.settings import RESTRUCTUREDTEXT_PARSER_MAX_CHARS
def handle403(request, template_name='403.html'):
"""
Default error 403 (Permission denied) handler.
"""
response = direct_to_template(request, template=template_name)
response.status_code = 403
return response
def rst_preview(request):
"""
Returns rendered restructured text.
"""
def get_rst_error_as_html(message, title='Parser error occured'):
"""
Returns restructured text error message as html. Manual marking as safe
is required for rendering.
"""
html = '\n'.join((
'<div class="system-message">',
'<p class="system-message-title">%s</p>' % title,
message,
'</div>',
))
return html
if not request.is_ajax() or not request.method == 'POST':
raise Http404()
data = request.POST.get('data', '')
if len(data) > RESTRUCTUREDTEXT_PARSER_MAX_CHARS:
html = get_rst_error_as_html('Text is too long (%s). Maximum is %s.' %
(len(data), RESTRUCTUREDTEXT_PARSER_MAX_CHARS))
else:
try:
html = restructuredtext(data)
except SystemMessage:
html = get_rst_error_as_html(
'Sorry but there are at severe errors in your text '
'and we cannot show it\'s preview.')
rendered = mark_safe(html)
return HttpResponse(dumps(rendered), mimetype='application/json')
|
/*********************************************************
*********************************************************
** DO NOT EDIT **
** **
** THIS FILE HAS BEEN GENERATED AUTOMATICALLY **
** BY UPA PORTABLE GENERATOR **
** (c) vpc **
** **
*********************************************************
********************************************************/
namespace Net.TheVpc.Upa.Expressions
{
public class InsertSelection : Net.TheVpc.Upa.Expressions.DefaultEntityStatement, Net.TheVpc.Upa.Expressions.NonQueryStatement {
private static readonly Net.TheVpc.Upa.Expressions.DefaultTag ENTITY = new Net.TheVpc.Upa.Expressions.DefaultTag("ENTITY");
private static readonly Net.TheVpc.Upa.Expressions.DefaultTag SELECTION = new Net.TheVpc.Upa.Expressions.DefaultTag("SELECTION");
private Net.TheVpc.Upa.Expressions.QueryStatement selection;
private System.Collections.Generic.List<Net.TheVpc.Upa.Expressions.Var> fields;
private Net.TheVpc.Upa.Expressions.EntityName entity;
private string alias;
public InsertSelection() {
selection = null;
fields = new System.Collections.Generic.List<Net.TheVpc.Upa.Expressions.Var>(1);
}
public override System.Collections.Generic.IList<Net.TheVpc.Upa.Expressions.TaggedExpression> GetChildren() {
System.Collections.Generic.IList<Net.TheVpc.Upa.Expressions.TaggedExpression> list = new System.Collections.Generic.List<Net.TheVpc.Upa.Expressions.TaggedExpression>((fields).Count + 2);
if (entity != null) {
list.Add(new Net.TheVpc.Upa.Expressions.TaggedExpression(entity, ENTITY));
}
for (int i = 0; i < (fields).Count; i++) {
list.Add(new Net.TheVpc.Upa.Expressions.TaggedExpression(fields[i], new Net.TheVpc.Upa.Expressions.IndexedTag("FIELD", i)));
}
if (selection != null) {
list.Add(new Net.TheVpc.Upa.Expressions.TaggedExpression(selection, SELECTION));
}
return list;
}
public override void SetChild(Net.TheVpc.Upa.Expressions.Expression e, Net.TheVpc.Upa.Expressions.ExpressionTag tag) {
if (ENTITY.Equals(tag)) {
this.entity = (Net.TheVpc.Upa.Expressions.EntityName) e;
} else if (SELECTION.Equals(tag)) {
this.selection = (Net.TheVpc.Upa.Expressions.QueryStatement) e;
} else {
Net.TheVpc.Upa.Expressions.IndexedTag ii = (Net.TheVpc.Upa.Expressions.IndexedTag) tag;
fields[ii.GetIndex()]=(Net.TheVpc.Upa.Expressions.Var) e;
}
}
public InsertSelection(Net.TheVpc.Upa.Expressions.InsertSelection other) : this(){
AddQuery(other);
}
private Net.TheVpc.Upa.Expressions.InsertSelection Into(string entity, string alias) {
this.entity = new Net.TheVpc.Upa.Expressions.EntityName(entity);
this.alias = alias;
return this;
}
public virtual Net.TheVpc.Upa.Expressions.InsertSelection Into(string entity) {
return Into(entity, null);
}
public override string GetEntityName() {
Net.TheVpc.Upa.Expressions.EntityName e = GetEntity();
return (e != null) ? ((Net.TheVpc.Upa.Expressions.EntityName) e).GetName() : null;
}
public virtual Net.TheVpc.Upa.Expressions.EntityName GetEntity() {
return entity;
}
public virtual string GetAlias() {
return alias;
}
public virtual int Size() {
return 3;
}
public virtual Net.TheVpc.Upa.Expressions.InsertSelection AddQuery(Net.TheVpc.Upa.Expressions.InsertSelection other) {
if (other == null) {
return this;
}
if (other.entity != null) {
entity = other.entity;
}
if (other.alias != null) {
alias = other.alias;
}
for (int i = 0; i < (other.fields).Count; i++) {
Field(other.GetField(i).GetName());
}
if (other.selection != null) {
selection = (Net.TheVpc.Upa.Expressions.QueryStatement) other.selection.Copy();
}
return this;
}
public override Net.TheVpc.Upa.Expressions.Expression Copy() {
Net.TheVpc.Upa.Expressions.InsertSelection o = new Net.TheVpc.Upa.Expressions.InsertSelection();
o.AddQuery(this);
return o;
}
public virtual Net.TheVpc.Upa.Expressions.InsertSelection Field(string key) {
fields.Add(new Net.TheVpc.Upa.Expressions.Var(key));
return this;
}
public virtual Net.TheVpc.Upa.Expressions.InsertSelection Field(string[] keys) {
foreach (string key in keys) {
Field(key);
}
return this;
}
public virtual Net.TheVpc.Upa.Expressions.InsertSelection From(Net.TheVpc.Upa.Expressions.QueryStatement selection) {
this.selection = selection;
return this;
}
public virtual int CountFields() {
return (fields).Count;
}
public virtual Net.TheVpc.Upa.Expressions.Var GetField(int i) {
return fields[i];
}
public virtual Net.TheVpc.Upa.Expressions.QueryStatement GetSelection() {
return selection;
}
public override bool IsValid() {
return entity != null && (fields).Count > 0 && selection.IsValid();
}
public override string GetEntityAlias() {
return null;
}
}
}
|
# ==========================================================================
# Benchmark Results Analysis Settings
# ==========================================================================
# Test parameters (used for Linear Regression and others)
NUM_SAMPLES = 4 # Number of the first runs to use in the Linear Regression (e.g. first 4 over 10)
NUM_RUNS = 10 # Number of runs in one test, usually 10 (i.e. number of steps in one growing load ladder)
NUM_TESTS = 10 # Number of test repetitions, usually 10 (i.e. number of growing load ladders). Globally we have a number of single runs equal to NUM_RUNS * NUM_TESTS
# BENCHMARK = "RUBBoS Benchmark"
# BENCHMARK = "CBench Benchmark"
BENCHMARK = "SPECpower\_ssj 2008 Benchmark"
# SUT = "SUT: HT on, TB on, Governor powersave"
SUT = "SUT: HT on, TB on, Governor performance"
# SUT = "SUT: HT on, TB off, Governor powersave"
# SUT = "SUT: HT on, TB off, Governor performance"
# SUT = "SUT: HT off, TB on, Governor powersave"
# SUT = "SUT: HT off, TB on, Governor performance"
# SUT = "SUT: HT off, TB off, Governor powersave"
# SUT = "SUT: HT off, TB off, Governor performance"
# Runs to be considered in computing real IPC
START_RUN = 1
END_RUN = 10
# Value added to x_max to plot streched line
# X_MAX_PADDING = 20 # Graphs without LR to strech
# X_MAX_PADDING = 50 # CBench
# X_MAX_PADDING = 100 # Rubbos
X_MAX_PADDING = 20000 # SPECpower
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.executor.connection_info import ConnectionInformation
from ansible.executor.play_iterator import PlayIterator
from ansible.playbook import Playbook
from units.mock.loader import DictDataLoader
class TestPlayIterator(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_play_iterator(self):
fake_loader = DictDataLoader({
"test_play.yml": """
- hosts: all
gather_facts: false
roles:
- test_role
pre_tasks:
- debug: msg="this is a pre_task"
tasks:
- debug: msg="this is a regular task"
post_tasks:
- debug: msg="this is a post_task"
""",
'/etc/ansible/roles/test_role/tasks/main.yml': """
- debug: msg="this is a role task"
""",
})
p = Playbook.load('test_play.yml', loader=fake_loader)
hosts = []
for i in range(0, 10):
host = MagicMock()
host.get_name.return_value = 'host%02d' % i
hosts.append(host)
inventory = MagicMock()
inventory.get_hosts.return_value = hosts
inventory.filter_hosts.return_value = hosts
connection_info = ConnectionInformation(play=p._entries[0])
itr = PlayIterator(
inventory=inventory,
play=p._entries[0],
connection_info=connection_info,
all_vars=dict(),
)
(host_state, task) = itr.get_next_task_for_host(hosts[0])
print(task)
self.assertIsNotNone(task)
(host_state, task) = itr.get_next_task_for_host(hosts[0])
print(task)
self.assertIsNotNone(task)
(host_state, task) = itr.get_next_task_for_host(hosts[0])
print(task)
self.assertIsNotNone(task)
(host_state, task) = itr.get_next_task_for_host(hosts[0])
print(task)
self.assertIsNotNone(task)
(host_state, task) = itr.get_next_task_for_host(hosts[0])
print(task)
self.assertIsNone(task)
|
from .common import *
from .dnsparam import *
from .dnsmsg import *
from .query import *
def print_answer_rr(server_addr, port, family, qname, qtype, options):
"""Only print the answer RRs; used by zonewalk() routine"""
txid = mk_id()
tc = 0
qtype_val = qt.get_val(qtype)
options["use_edns0"] = True
options["dnssec_ok"] = False
query = DNSquery(qname, qtype_val, 1)
requestpkt = mk_request(query, txid, options)
(responsepkt, responder_addr) = \
send_request_udp(requestpkt, server_addr, port, family,
ITIMEOUT, RETRIES)
if not responsepkt:
raise ErrorMessage("No response from server")
response = DNSresponse(family, query, requestpkt, responsepkt, txid)
if response.rcode != 0:
raise ErrorMessage("got rcode=%d(%s)" %
(response.rcode, rc.get_name(response.rcode)))
r = responsepkt
offset = 12 # skip over DNS header
for i in range(response.qdcount):
domainname, rrtype, rrclass, offset = decode_question(r, offset)
if response.ancount == 0:
dprint("Warning: no answer RRs found for %s,%s" % \
(qname, qt.get_name(qtype_val)))
return
for i in range(response.ancount):
rrname, rrtype, rrclass, ttl, rdata, offset = \
decode_rr(r, offset, False)
print "%s\t%d\t%s\t%s\t%s" % \
(pdomainname(rrname), ttl,
qc.get_name(rrclass), qt.get_name(rrtype), rdata)
return
def zonewalk(server_addr, port, family, qname, options):
"""perform zone walk of zone containing the specified qname"""
print ";;\n;; Performing walk of zone containing %s\n;;" % qname
start_qname = qname
nsec_count = 0
options["use_edns0"] = True
options["dnssec_ok"] = False
while True:
txid = mk_id()
query = DNSquery(qname, 47, 1)
requestpkt = mk_request(query, txid, options)
dprint("Querying NSEC for %s .." % query.qname)
(responsepkt, responder_addr) = \
send_request_udp(requestpkt, server_addr, port, family,
ITIMEOUT, RETRIES)
if not responsepkt:
raise ErrorMessage("No response from server")
response = DNSresponse(family, query, requestpkt, responsepkt, txid)
if response.rcode != 0:
raise ErrorMessage("got rcode=%d(%s), querying %s, NSEC" %
(response.rcode, rc.get_name(response.rcode), qname))
if response.ancount == 0:
raise ErrorMessage("unable to find NSEC record at %s" % qname)
elif response.ancount != 1:
raise ErrorMessage("found %d answers, expecting 1 for %s NSEC" %
(ancount, qname))
r = responsepkt
offset = 12 # skip over DNS header
for i in range(response.qdcount): # skip over question section
domainname, rrtype, rrclass, offset = decode_question(r, offset)
domainname, rrtype, rrclass, ttl, nextrr, rrtypelist, offset = \
decode_nsec_rr(r, offset)
rrname = pdomainname(domainname)
nsec_count += 1
if (nsec_count !=1) and \
(domain_name_match(rrname, nextrr) or
domain_name_match(rrname, start_qname)):
break
for rrtype in rrtypelist:
dprint("Querying RR %s %s .." % (qname, rrtype))
print_answer_rr(server_addr, port, family, qname, rrtype, options)
qname = nextrr
time.sleep(0.3) # be nice
return
|
module.exports = {
vendorFiles: [
'zepto/zepto.min.js',
'zepto/zepto-touch.js',
'topcoat/css/topcoat-mobile-light.min.css',
'fastclick/lib/fastclick.js',
'overthrow/src/overthrow-detect.js',
'overthrow/src/overthrow-polyfill.js',
'overthrow/src/overthrow-toss.js',
'overthrow/src/overthrow-init.js',
'snapjs/snap.min.js',
'snapjs/snap.css'
],
htmlFiles: [
'index.html'
],
cssFiles: [
'style.css',
'transitions.css',
'fastgap.css',
'reset.css'
],
jsFiles: [
'controllers/AppController.js',
'controllers/HomeController.js',
'controllers/Page1Controller.js',
'controllers/Page2Controller.js',
'controllers/Page3Controller.js',
'controllers/Page4Controller.js',
'controllers/Page5Controller.js',
'History.js',
'FG.js',
'Navigator.js',
'Transition.js',
'PageLoad.js',
'index.js'
]
};
|
Bitrix 16.5 Business Demo = 382f1de29b8f4916a670ad1176e603a0
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-01-30 14:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('views', '0011_rename_de_to_lang2'),
]
operations = [
migrations.AlterField(
model_name='view',
name='help_lang1',
field=models.TextField(blank=True, help_text='The help text for this view in the primary language.', null=True, verbose_name='Help (primary)'),
),
migrations.AlterField(
model_name='view',
name='help_lang2',
field=models.TextField(blank=True, help_text='The help text for this view in the secondary language.', null=True, verbose_name='Help (secondary)'),
),
migrations.AlterField(
model_name='view',
name='title_lang1',
field=models.CharField(blank=True, help_text='The title for this view in the primary language.', max_length=256, null=True, verbose_name='Title (primary)'),
),
migrations.AlterField(
model_name='view',
name='title_lang2',
field=models.CharField(blank=True, help_text='The title for this view in the secondary language.', max_length=256, null=True, verbose_name='Title (secondary)'),
),
]
|
import array
'''
set the abnormal float numbers for unittest
'''
import numpy
import os
floattype=os.environ['SASSIE_FLOATTYPE']
# Convert a number to a floattype ft
def num_to_floattype(a, ft):
b = []
b.append(a)
if ft=='float32':
result = array.array('f',b)[0]
elif ft=='float64':
result = array.array('d',b)[0]
return result
# Recursively convert a list to a floattype type list
def list_to_floattype(lo, ft):
try:
l = list(lo)
except:
raise "ListConvertError"
ltmp = []
for i in range(len(l)):
if isinstance(l[i], list):
ltmp.append(list_to_floattype(l[i], ft))
else:
ltmp.append(num_to_floattype(l[i],ft))
return ltmp
# Recursively format-print a list
import sys
def printfl(l, fmt='%.3f'):
for i in l:
if isinstance(i, (list,numpy.ndarray)):
sys.stdout.write('[')
printfl(i, fmt)
sys.stdout.write('\b\b], ')
else:
sys.stdout.write(fmt%float(i)+', ')
NAN = float('nan')
INF = float('inf')
HUGE = float(numpy.finfo(floattype).max)
TINY = float(numpy.finfo(floattype).tiny)
ZERO = num_to_floattype(0.0, floattype)
if __name__=="__main__":
ft = 'float32'
a=[[1,2],[3,4,[5]],[[6,[7,8]],6],0]
na=[]
list_to_floattype(a,ft)
print a,'\n',na
|
#include "ui.h"
#include <QtGui>
#include <QtWebKit>
Ui::Ui(QWidget *parent) :
QWidget(parent){
// --------------- Widgets --------------- //
web = new QWebView;
// --- Left Block --- //
leftBlock = new QGroupBox;
//settingLab = new QLabel(tr("Properties"));
wLab = new QLabel(tr("Width: "));
hLab = new QLabel(tr("Height: "));
/* -- Spin Boxes -- */
wSpin = new QSpinBox;
wSpin->setRange(800, 2560);
wSpin->setValue(1280);
hSpin = new QSpinBox;
hSpin->setRange(600, 1600);
/* -- Check Boxes -- */
fullEn = new QCheckBox(tr("Full Size"));
fullEn->setChecked(true);
if(fullEn->isChecked()) { hSpin->setEnabled(false); }
else { hSpin->setEnabled(true); }
flashEn = new QCheckBox(tr("Flash"));
jsEn = new QCheckBox(tr("JavaScript"));
jsEn->setChecked(true);
javaEn = new QCheckBox(tr("Java"));
// --- Right Block --- //
urlLab = new QLabel(tr("Url: "));
urlLine = new QLineEdit;
startBtn = new QPushButton(">");
prevArea = new QScrollArea;
prevArea->setFrameShape(QFrame::NoFrame);
rightBlock = new QGroupBox;
pBar = new QProgressBar();
pBar->setOrientation(Qt::Horizontal);
pBar->setMaximumWidth(200);
pBar->setMaximumHeight(12);
QFont font;
font.setPixelSize(10);
pBar->setFont(font);
pBar->setValue(100);
// --------------- Layouts --------------- //
// --- Left block layouts --- //
QHBoxLayout *wLay = new QHBoxLayout;
wLay->addWidget(wLab);
wLay->addWidget(wSpin);
QHBoxLayout *hLay = new QHBoxLayout;
hLay->addWidget(hLab);
hLay->addWidget(hSpin);
QVBoxLayout *leftMainLay = new QVBoxLayout;
leftMainLay->addLayout(wLay);
leftMainLay->addLayout(hLay);
leftMainLay->addWidget(fullEn);
leftMainLay->addWidget(jsEn);
leftMainLay->addWidget(flashEn);
leftMainLay->addWidget(javaEn);
leftMainLay->addStretch();
// --- Right block layouts --- //
QHBoxLayout *progLay = new QHBoxLayout;
progLay->addStretch();
progLay->addWidget(pBar);
QHBoxLayout *urlLay = new QHBoxLayout;
urlLay->addWidget(urlLab);
urlLay->addWidget(urlLine);
urlLay->addWidget(startBtn);
QVBoxLayout *rightMainLay = new QVBoxLayout;
rightMainLay->addLayout(urlLay);
rightMainLay->addWidget(prevArea);
rightMainLay->addLayout(progLay);
rightMainLay->setContentsMargins(3,3,3,0);
// --- Main Layouts --- //
QSplitter *split= new QSplitter(Qt::Horizontal);
split->addWidget(leftBlock);
split->addWidget(rightBlock);
QHBoxLayout *mainLay = new QHBoxLayout;
mainLay->addWidget(split);
mainLay->setContentsMargins(3,3,3,0);
// --------------- Settings --------------- //
// --- Left Block Settings --- //
leftBlock->setTitle(tr("Properties"));
leftBlock->setLayout(leftMainLay);
leftBlock->setMinimumWidth(200);
// --- Right Block Settings --- //
rightBlock->setTitle(tr("Browser"));
rightBlock->setLayout(rightMainLay);
rightBlock->resize(1280, 0);
// --- Main Settings --- //
setLayout(mainLay);
// --------------- SIGNALS / SLOTS --------------- //
connect(urlLine, SIGNAL(returnPressed()), startBtn, SLOT(click()));
connect(startBtn, SIGNAL(clicked()), this, SLOT(setUrl()));
connect(fullEn, SIGNAL(toggled(bool)), hSpin, SLOT(setDisabled(bool)));
connect(flashEn, SIGNAL(clicked()), this, SLOT(setPlugins()));
connect(jsEn, SIGNAL(clicked()), this, SLOT(setPlugins()));
connect(javaEn, SIGNAL(clicked()), this, SLOT(setPlugins()));
}
// --- Get Url from menu and send signal to load --- //
void Ui::addUrl(){
bool ok;
QString urlText = QInputDialog::getText(this, tr("Input URL"),
tr("URL"),QLineEdit::Normal, "http://", &ok);
if(!urlText.isEmpty() && urlText != "http://" && urlText.contains('.') && ok == true){
if(urlText.contains("http://")) { url = urlText; }
else { url = "http://" + urlText; }
urlLine->setText(url);
loadUrl();
}
}
// --- Get Url from urlLine and send signal to load --- //
void Ui::setUrl(){
if(!urlLine->text().isEmpty() && urlLine->text() != "http://" && urlLine->text().contains('.')){
if(urlLine->text().contains("http://")){ url = urlLine->text(); }
else { url = "http://" + urlLine->text(); }
urlLine->setText(url);
loadUrl();
}
}
// --- Set destination path to save screenshot and send signal to start rendering --- //
void Ui::saveFile(){
QString fileName = QFileDialog::getSaveFileName(this, tr("Save as"), "~",
tr("PNG Image (*.png);;JPEG Image (*.jpg)"));
if(!fileName.isEmpty()){
saveFileName = fileName;
printPage();
}
}
void Ui::setPlugins(){
web->settings()->setAttribute(QWebSettings::PluginsEnabled, flashEn->isChecked());
web->settings()->setAttribute(QWebSettings::JavascriptEnabled, jsEn->isChecked());
web->settings()->setAttribute(QWebSettings::JavaEnabled, javaEn->isChecked());
}
// --- Load WebPage --- //
void Ui::loadUrl(){
prevArea->setWidget(web);
web->settings()->clearMemoryCaches();
web->resize(prevArea->width(), prevArea->height());
connect(web, SIGNAL(loadProgress(int)), pBar, SLOT(setValue(int)));
connect(web, SIGNAL(loadStarted()), this, SIGNAL(loadStart()));
connect(web, SIGNAL(loadFinished(bool)), this, SIGNAL(loadComplete()));
web->load(url);
}
// --- Rendering Screenshot --- //
void Ui::printPage(){
if(fullEn->isChecked()) { hSize = web->page()->mainFrame()->contentsSize().height(); }
else { hSize = hSpin->value(); }
QImage *image = new QImage(QSize(wSpin->value(), hSize), QImage::Format_ARGB32);
QPainter *paint = new QPainter(image);
web->page()->setViewportSize(QSize(wSpin->value() + 16, hSize));
web->page()->mainFrame()->render(paint);
paint->end();
image->save(saveFileName);
web->settings()->clearMemoryCaches();
delete image;
delete paint;
web->page()->setViewportSize(QSize(prevArea->width(), prevArea->height()));
}
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Middleware for authenticating against custom backends.
"""
import logging
from heat.openstack.common import local
from heat.rpc import client as rpc_client
import webob.exc
LOG = logging.getLogger(__name__)
class AuthProtocol(object):
def __init__(self, app, conf):
self.conf = conf
self.app = app
def __call__(self, env, start_response):
"""
Handle incoming request.
Authenticate send downstream on success. Reject request if
we can't authenticate.
"""
LOG.debug('Authenticating user token')
context = local.store.context
engine = rpc_client.EngineClient()
authenticated = engine.authenticated_to_backend(context)
if authenticated:
return self.app(env, start_response)
else:
return self._reject_request(env, start_response)
def _reject_request(self, env, start_response):
"""
Redirect client to auth server.
:param env: wsgi request environment
:param start_response: wsgi response callback
:returns HTTPUnauthorized http response
"""
resp = webob.exc.HTTPUnauthorized("Backend authentication failed", [])
return resp(env, start_response)
def filter_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
def auth_filter(app):
return AuthProtocol(app, conf)
return auth_filter
|
#include <iostream>
#include <set>
#include <cstdio>
#include <ace/ACE.h>
#include <ace/Get_Opt.h>
#include <ace/Log_Msg.h>
#include <ace/OS.h>
#include <so_5/api/h/api.hpp>
#include <so_5/rt/h/rt.hpp>
#include <so_5/disp/active_obj/h/pub.hpp>
struct cfg_t
{
unsigned int m_request_count;
bool m_active_objects;
cfg_t()
: m_request_count( 1000 )
, m_active_objects( false )
{}
};
int
try_parse_cmdline(
int argc,
char ** argv,
cfg_t & cfg )
{
if( 1 == argc )
{
std::cout << "usage:\n"
"sample.so_5.ping_pong <options>\n"
"\noptions:\n"
"-a, --active-objects agents should be active objects\n"
"-r, --requests count of requests to send\n"
<< std::endl;
ACE_ERROR_RETURN(
( LM_ERROR, ACE_TEXT( "No arguments supplied\n" ) ), -1 );
}
ACE_Get_Opt opt( argc, argv, ":ar:" );
if( -1 == opt.long_option(
"active-objects", 'a', ACE_Get_Opt::NO_ARG ) )
ACE_ERROR_RETURN(( LM_ERROR, ACE_TEXT(
"Unable to set long option 'active-objects'\n" )), -1 );
if( -1 == opt.long_option(
"requests", 'r', ACE_Get_Opt::ARG_REQUIRED ) )
ACE_ERROR_RETURN(( LM_ERROR, ACE_TEXT(
"Unable to set long option 'requests'\n" )), -1 );
cfg_t tmp_cfg;
int o;
while( EOF != ( o = opt() ) )
{
switch( o )
{
case 'a' :
tmp_cfg.m_active_objects = true;
break;
case 'r' :
tmp_cfg.m_request_count = ACE_OS::atoi( opt.opt_arg() );
break;
case ':' :
ACE_ERROR_RETURN(( LM_ERROR,
ACE_TEXT( "-%c requieres argument\n" ),
opt.opt_opt() ), -1 );
}
}
if( opt.opt_ind() < argc )
ACE_ERROR_RETURN(( LM_ERROR,
ACE_TEXT( "Unknown argument: '%s'\n" ),
argv[ opt.opt_ind() ] ),
-1 );
cfg = tmp_cfg;
return 0;
}
void
show_cfg(
const cfg_t & cfg )
{
std::cout << "Configuration: "
<< "active objects: " << ( cfg.m_active_objects ? "yes" : "no" )
<< ", requests: " << cfg.m_request_count
<< std::endl;
}
void
run_sample(
const cfg_t & cfg )
{
// This variable will be a part of pinger agent's state.
unsigned int pings_left = cfg.m_request_count;
so_5::api::run_so_environment(
[&pings_left, &cfg]( so_5::rt::so_environment_t & env )
{
// Types of signals for the agents.
struct msg_ping : public so_5::rt::signal_t {};
struct msg_pong : public so_5::rt::signal_t {};
auto mbox = env.create_local_mbox();
auto coop = env.create_coop( "ping_pong",
// Agents will be active or passive.
// It depends on sample arguments.
cfg.m_active_objects ?
so_5::disp::active_obj::create_disp_binder( "active_obj" ) :
so_5::rt::create_default_disp_binder() );
// Pinger agent.
coop->define_agent()
.on_start( [mbox]() { mbox->deliver_signal< msg_ping >(); } )
.event( mbox, so_5::signal< msg_pong >,
[&pings_left, &env, mbox]()
{
if( pings_left ) --pings_left;
if( pings_left )
mbox->deliver_signal< msg_ping >();
else
env.stop();
} );
// Ponger agent.
coop->define_agent()
.event( mbox, so_5::signal< msg_ping >,
[mbox]() { mbox->deliver_signal< msg_pong >(); } );
env.register_coop( std::move( coop ) );
},
[&cfg]( so_5::rt::so_environment_params_t & p )
{
if( cfg.m_active_objects )
// Special dispatcher is necessary for agents.
p.add_named_dispatcher( "active_obj",
so_5::disp::active_obj::create_disp() );
} );
}
int
main( int argc, char ** argv )
{
cfg_t cfg;
if( -1 != try_parse_cmdline( argc, argv, cfg ) )
{
show_cfg( cfg );
try
{
run_sample( cfg );
return 0;
}
catch( const std::exception & x )
{
std::cerr << "*** Exception caught: " << x.what() << std::endl;
}
}
return 2;
}
|
/*
** Copyright (c) 2016, Xin YUAN, courses of Zhejiang University
** All rights reserved.
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the 2-Clause BSD License.
**
** Author contact information:
** [email protected]
**
*/
/*
This file contains main functions for SA.
*/
////////////////////////////////////////////////////////////////////////////////
#include "PreComp.h"
#include "EntryPoint.h"
////////////////////////////////////////////////////////////////////////////////
#include "base/GkcSAMain.cpp"
////////////////////////////////////////////////////////////////////////////////
|
package ameba.message.error;
import ameba.core.Requests;
import org.glassfish.jersey.server.ContainerRequest;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* @author icode
*/
public class ExceptionMapperUtils {
private static final MediaType LOW_IE_DEFAULT_REQ_TYPE = new MediaType("application", "x-ms-application");
private ExceptionMapperUtils() {
}
public static MediaType getResponseType() {
return getResponseType(Requests.getRequest(), null);
}
public static MediaType getResponseType(Integer status) {
return getResponseType(Requests.getRequest(), status);
}
public static MediaType getResponseType(ContainerRequest request) {
return getResponseType(request, null);
}
public static MediaType getResponseType(ContainerRequest request, Integer status) {
if (status != null && status == 406) {
return MediaType.TEXT_HTML_TYPE;
}
List<MediaType> accepts = request.getAcceptableMediaTypes();
MediaType m;
if (accepts != null && accepts.size() > 0) {
m = accepts.get(0);
} else {
m = Requests.getMediaType();
}
if (m.isWildcardType() || m.equals(LOW_IE_DEFAULT_REQ_TYPE)) {
m = MediaType.TEXT_HTML_TYPE;
}
return m;
}
}
|
@(messages: List[String])(errors: List[String])(destination: Destination)
<!-- Section title -->
<div id="section">
<div id="container">
<div id="title">@Messages("destination.title.add")</div>
</div>
</div>
<!-- Section messages -->
<!-- Hide section messages if the list is empty -->
@if(messages != List("")) {
<div id="section">
<div id="container">
<div id="messages">
@for(message <- messages) {
@message<br>
}
</div>
</div>
</div>
}
<!-- Section errors -->
<!-- Hide section errors if the list is empty -->
@if(errors != List("")) {
<div id="section">
<div id="container">
<div id="errors">
@for(error <- errors) {
@error<br>
}
</div>
</div>
</div>
}
<!-- Section content -->
<div id="section">
<div id="container">
<form method="post" id="destination" action="@routes.Destinations.create">
<!-- User -->
<!-- Username -->
<!-- Hidden -->
<input type="text" name="username" id="username"
placeholder="@Messages("destination.label.username")"
value="@destination.username" maxlength="35" required readonly hidden>
<!-- Destination -->
<label for="destination">@Messages("submission.label.destination")</label>
<!-- Username -->
<input type="text" name="destinationUsername" id="destinationUsername"
placeholder="@Messages("destination.label.username")"
value="@destination.destinationUsername" maxlength="35" required>
<!-- Hostname -->
<input type="text" name="destinationHostname" id="destinationHostname"
placeholder="@Messages("destination.label.hostname")"
value="@destination.destinationHostname" maxlength="50" required>
<!-- Password -->
<input type="password" name="destinationPassword" id="destinationPassword"
placeholder="@Messages("destination.label.password")"
value="@destination.destinationPassword" maxlength="35" required>
<!-- Configuration -->
<select name="configuration" id="configuration">
<option value="cluster">Cluster</option>
<option value="dagman">DAGMan</option>
</select>
<!-- Submit -->
<input type="submit" id="destinationSubmit" value="@Messages("destination.label.submit")">
</form>
</div>
</div>
|
//
// CORTransparentViewController.h
// CORKit
//
// Created by Seiya Sasaki on 2014/02/20.
// Copyright (c) 2014年 Seiya Sasaki. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void (^CORTransparentPresentCompletion)();
@interface CORTransparentViewController : UIViewController
- (void)presentTransparentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(CORTransparentPresentCompletion)completion;
- (void)dismissTransparentViewControllerAnimated:(BOOL)animated completion:(CORTransparentPresentCompletion)completion;
@end
|
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Network, Connection } from 'ionic-native';
@Component({
templateUrl: 'build/pages/network-test/network-test.html',
})
export class NetworkTestPage {
connectionType: any;
constructor(private nav: NavController) {}
check(){
this.connectionType = Network.connection;
if(Network.connection == Connection.WIFI){
console.log("WIFI");
}
}
}
|
module.exports = function(grunt) {
require('time-grunt')(grunt);
var reportjs = [
'src/js/reports/Rickshaw.Graph.Axis.LabeledY.js',
'src/js/reports/Rickshaw.Graph.ClickDetail.js',
'src/js/reports/Rickshaw.Graph.TableLegend.js',
'src/js/reports/acquia_lift.liftgraph.jquery.js',
'src/js/reports/acquia_lift.reports.js'
];
var flowjs = [
'src/js/flow/acquia_lift.modal.js',
'src/js/flow/acquia_lift.variations.js',
'src/js/flow/acquia_lift.variations.models.js',
'src/js/flow/acquia_lift.variations.collections.js',
'src/js/flow/acquia_lift.variations.theme.js',
'src/js/flow/acquia_lift.variations.views.js',
'src/js/flow/acquia_lift.variations.editInContext.js',
'src/js/flow/acquia_lift.ctools.modal.js'
];
var goalqueuejs = [
'src/js/agent/acquia_lift.utility.queue.js',
'src/js/agent/acquia_lift.agent.goal_queue.js',
];
var unibarjs = [
'src/js/menu/acquia_lift.personalize.theme.js',
'src/js/menu/acquia_lift.personalize.js',
'src/js/menu/acquia_lift.personalize.models.js',
'src/js/menu/acquia_lift.personalize.collections.js',
'src/js/menu/acquia_lift.personalize.views.js',
'src/js/menu/acquia_lift.personalize.factories.js',
'src/js/menu/acquia_lift.personalize.commands.js',
'src/js/menu/acquia_lift.personalize.behaviors.js'
];
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
autoprefixer: {
css: {
options: {
// Uncomment the map setting to enable sourcemaps.
// map: true
},
src: 'css/**/*.css'
}
},
concat: {
options: {
sourceMap: true,
separator: "\n"
},
reports: {
src: reportjs,
dest: 'js/acquia_lift.reports.js'
},
help: {
src: ['src/js/help/acquia_lift.help.js'],
dest: 'js/acquia_lift.help.js'
},
flow: {
src: flowjs,
dest: 'js/acquia_lift.flow.js'
},
agent: {
src: goalqueuejs,
dest: 'js/acquia_lift.goals_queue.js'
},
unibar: {
src: unibarjs,
dest: 'js/acquia_lift.personalize.js'
}
},
concurrent: {
all: ['style', 'script', 'test']
},
// Can only test those QUnit tests that do not require Drupal interaction.
qunit: {
all: ['qunit/core_personalization.html']
},
sass: {
dist: {
options: {
// Comment out the sourcemap setting to enable sourcemaps.
sourcemap: 'none',
style: 'expanded'
},
files: {
'css/acquia_lift.help.css': 'src/css/acquia_lift.help.scss',
'css/acquia_lift.reports.css': 'src/css/acquia_lift.reports.scss',
'css/acquia_lift.navbar.css': 'src/css/acquia_lift.navbar.scss',
'css/acquia_lift.navbar_1-5.css': 'src/css/acquia_lift.navbar_1-5.scss'
}
}
},
watch: {
sass: {
files: 'src/css/**/*.scss',
tasks: ['style']
},
scripts: {
files: 'src/js/**/*.js',
tasks: ['script']
},
gruntfile: {
files: 'Gruntfile.js',
tasks: ['default']
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-qunit');
// Default task(s).
grunt.registerTask('default', ['concurrent:all']);
grunt.registerTask('style', ['sass', 'autoprefixer']);
grunt.registerTask('script', ['concat']);
grunt.registerTask('test', ['qunit']);
};
|
import os
import psycogreen.gevent; psycogreen.gevent.patch_psycopg()
from peewee import Proxy, OP, Model
from peewee import Expression
from playhouse.postgres_ext import PostgresqlExtDatabase
REGISTERED_MODELS = []
# Create a database proxy we can setup post-init
database = Proxy()
OP['IRGX'] = 'irgx'
def pg_regex_i(lhs, rhs):
return Expression(lhs, OP.IRGX, rhs)
PostgresqlExtDatabase.register_ops({OP.IRGX: '~*'})
class BaseModel(Model):
class Meta:
database = database
@staticmethod
def register(cls):
REGISTERED_MODELS.append(cls)
return cls
def init_db(env):
if env == 'docker':
database.initialize(PostgresqlExtDatabase(
'rowboat',
host='db',
user='postgres',
port=int(os.getenv('PG_PORT', 5432)),
autorollback=True))
else:
database.initialize(PostgresqlExtDatabase(
'rowboat',
user='rowboat',
port=int(os.getenv('PG_PORT', 5432)),
autorollback=True))
for model in REGISTERED_MODELS:
model.create_table(True)
if hasattr(model, 'SQL'):
database.execute_sql(model.SQL)
def reset_db():
init_db()
for model in REGISTERED_MODELS:
model.drop_table(True)
model.create_table(True)
|
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update Item</h4>
</div>
<div class="modal-body">
<?php echo form_open('Purchasing/update_item_inventory');?>
<input type="hidden" name="itemid">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" id="description" name="description" placeholder="Description" required>
</div>
<div>
<label for="name">Quantity</label>
<input type="text" class="form-control" id="quantity" name="quantity" placeholder="Quantity" required>
</div>
<div class="form-group">
<label for="description">Price</label>
<input type="text" class="form-control" id="price" name="price" placeholder="Price" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
|
namespace JokeSystem.Web
{
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using JokeSystem.Data;
using JokeSystem.Data.Models;
using Owin;
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
}
}
}
|
# flake8: noqa
from sentry.conf.server import *
import os
import getpass
SENTRY_APIDOCS_REDIS_PORT = 12355
SENTRY_APIDOCS_WEB_PORT = 12356
SENTRY_URL_PREFIX = 'https://sentry.io'
# Unsupported here
SENTRY_SINGLE_ORGANIZATION = False
DEBUG = True
CONF_ROOT = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/tmp/sentry_apidocs.db',
}
}
SENTRY_USE_BIG_INTS = True
SENTRY_CACHE = 'sentry.cache.redis.RedisCache'
CELERY_ALWAYS_EAGER = True
BROKER_URL = 'redis://localhost:%s' % SENTRY_APIDOCS_REDIS_PORT
SENTRY_RATELIMITER = 'sentry.ratelimits.redis.RedisRateLimiter'
SENTRY_BUFFER = 'sentry.buffer.redis.RedisBuffer'
SENTRY_QUOTAS = 'sentry.quotas.redis.RedisQuota'
SENTRY_TSDB = 'sentry.tsdb.redis.RedisTSDB'
LOGIN_REDIRECT_URL = SENTRY_URL_PREFIX + '/'
SENTRY_WEB_HOST = '127.0.0.1'
SENTRY_WEB_PORT = SENTRY_APIDOCS_WEB_PORT
SENTRY_WEB_OPTIONS = {
'workers': 2,
'limit_request_line': 0,
'secure_scheme_headers': {'X-FORWARDED-PROTO': 'https'},
}
SENTRY_OPTIONS.update({
'redis.clusters': {
'default': {
'hosts': {i: {'port': SENTRY_APIDOCS_REDIS_PORT} for i in range(0, 4)},
},
},
'system.secret-key': 'super secret secret key',
'system.admin-email': '[email protected]',
'system.url-prefix': SENTRY_URL_PREFIX,
'mail.backend': 'django.core.mail.backends.smtp.EmailBackend',
'mail.host': 'localhost',
'mail.password': '',
'mail.username': '',
'mail.port': 25,
'mail.use-tls': False,
'mail.from': '[email protected]',
'filestore.backend': 'filesystem',
'filestore.options': {'location': '/tmp/sentry-files'},
})
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QMLBACKENDTRIGGERCHANGEAO_H_
#define QMLBACKENDTRIGGERCHANGEAO_H_
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <e32base.h> // For CActive, link against: euser.lib
#include <lbs.h>
#include <lbscommon.h>
#include <lbtsessiontrigger.h>
#include "qgeoareamonitor.h"
#include <lbt.h>
QTM_BEGIN_NAMESPACE
class QMLBackendTriggerChangeAO : public CActive
{
public :
static QMLBackendTriggerChangeAO* NewL(RLbtServer& aLbtServ);
static void DeleteAO();
void NotifyChangeEvent();
void DoCancel();
void RunL();
private :
QMLBackendTriggerChangeAO();
~QMLBackendTriggerChangeAO();
inline bool isValid() {
return subsessionCreated && (iTriggerMonitorInfo != NULL);
}
void ConstructL(RLbtServer& albtServ);
static QMLBackendTriggerChangeAO* instance;
CBackendMonitorInfo* iTriggerMonitorInfo; //single instance of the CBackendMonitorInfo object
TLbtTriggerChangeEvent iTriggerChangeEvent;
bool subsessionCreated;
static TInt refCount;
RLbt iLbt;
};
QTM_END_NAMESPACE
#endif /* QMLBACKENDMONITORAO_H_ */
|
################################################################################
#
# Copyright 2015-2020 Félix Brezo and Yaiza Rubio
#
# This program is part of OSRFramework. 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/>.
#
################################################################################
__author__ = "Felix Brezo, Yaiza Rubio <[email protected]>"
__version__ = "2.0"
from osrframework.utils.platforms import Platform
class Scribd(Platform):
"""A <Platform> object for Scribd"""
def __init__(self):
self.platformName = "Scribd"
self.tags = ["file-sharing"]
########################
# Defining valid modes #
########################
self.isValidMode = {}
self.isValidMode["phonefy"] = False
self.isValidMode["usufy"] = True
self.isValidMode["searchfy"] = False
######################################
# Search URL for the different modes #
######################################
# Strings with the URL for each and every mode
self.url = {}
#self.url["phonefy"] = "http://anyurl.com//phone/" + "<phonefy>"
self.url["usufy"] = "http://es.scribd.com/" + "<usufy>"
#self.url["searchfy"] = "http://anyurl.com/search/" + "<searchfy>"
######################################
# Whether the user needs credentials #
######################################
self.needsCredentials = {}
#self.needsCredentials["phonefy"] = False
self.needsCredentials["usufy"] = False
#self.needsCredentials["searchfy"] = False
#################
# Valid queries #
#################
# Strings that will imply that the query number is not appearing
self.validQuery = {}
# The regular expression '.+' will match any query.
#self.validQuery["phonefy"] = ".*"
self.validQuery["usufy"] = ".+"
#self.validQuery["searchfy"] = ".*"
###################
# Not_found clues #
###################
# Strings that will imply that the query number is not appearing
self.notFoundText = {}
#self.notFoundText["phonefy"] = []
self.notFoundText["usufy"] = ["<h1>Page not found</h1>"]
#self.notFoundText["searchfy"] = []
#########################
# Fields to be searched #
#########################
self.fieldsRegExp = {}
# Definition of regular expressions to be searched in phonefy mode
#self.fieldsRegExp["phonefy"] = {}
# Example of fields:
#self.fieldsRegExp["phonefy"]["i3visio.location"] = ""
# Definition of regular expressions to be searched in usufy mode
self.fieldsRegExp["usufy"] = {}
# Example of fields:
#self.fieldsRegExp["usufy"]["i3visio.location"] = ""
# Definition of regular expressions to be searched in searchfy mode
#self.fieldsRegExp["searchfy"] = {}
# Example of fields:
#self.fieldsRegExp["searchfy"]["i3visio.location"] = ""
################
# Fields found #
################
# This attribute will be feeded when running the program.
self.foundFields = {}
|
# Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PySCAP. If not, see <http://www.gnu.org/licenses/>.
TAG_MAP = {
'{http://scap.nist.gov/schema/ocil/2.0}ocil': 'OCILElement',
}
BOOLEAN_QUESTION_MODEL_ENUMERATION = [
'MODEL_YES_NO',
'MODEL_TRUE_FALSE',
]
EXCEPTIONAL_RESULT_ENUMERATION = [
'UNKNOWN',
'ERROR',
'NOT_TESTED',
'NOT_APPLICABLE',
]
OPERATOR_ENUMERATION = [
'AND',
'OR',
]
RESULT_ENUMERATION = [
'PASS',
'FAIL',
# exceptionals
'UNKNOWN',
'ERROR',
'NOT_TESTED',
'NOT_APPLICABLE',
]
# || P | F | E | U | NT | NA ||
# ---------------||-----------------------------||------------------||------------------------------------------
# || 1+ | 0 | 0 | 0 | 0 | 0+ || Pass
# || 0+ | 1+ | 0+ | 0+ | 0+ | 0+ || Fail
# AND || 0+ | 0 | 1+ | 0+ | 0+ | 0+ || Error
# || 0+ | 0 | 0 | 1+ | 0+ | 0+ || Unknown
# || 0+ | 0 | 0 | 0 | 1+ | 0+ || Not Tested
# || 0 | 0 | 0 | 0 | 0 | 1+ || Not Applicable
# || 0 | 0 | 0 | 0 | 0 | 0 || Not Tested
#TODO operator_AND
# ---------------||-----------------------------||------------------||------------------------------------------
# || 1+ | 0+ | 0+ | 0+ | 0+ | 0+ || Pass
# || 0 | 1+ | 0 | 0 | 0 | 0+ || Fail
# OR || 0 | 0+ | 1+ | 0+ | 0+ | 0+ || Error
# || 0 | 0+ | 0 | 1+ | 0+ | 0+ || Unknown
# || 0 | 0+ | 0 | 0 | 1+ | 0+ || Not Tested
# || 0 | 0 | 0 | 0 | 0 | 1+ || Not Applicable
# || 0 | 0 | 0 | 0 | 0 | 0 || Not Tested
# TODO operator_OR
USER_RESPONSE_ENUMERATION = [
'ANSWERED',
'UNKNOWN',
'ERROR',
'NOT_TESTED',
'NOT_APPLICABLE',
]
VARIABLE_DATA_ENUMERATION = [
'TEXT',
'NUMERIC',
]
|
#include <iostream>
using namespace std;
int main()
{
int eta[3];
int x=0,k;
cout << "inserire l'eta di tre persone" << endl;
for (int i=0; i<3 ; i++) {
cin >> eta[i];
}
for (int i=0;i<3; i++){
for (int k=i+1;k<3; k++){
if (eta[i]>eta[k]) {
x=eta[i];
eta[i]=eta[k];
eta[k]=x
}
}
}
return 0;
}
|
/***********************************************************************
* Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Carsten Urbach
*
* This file is part of tmLQCD.
*
* tmLQCD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* tmLQCD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with tmLQCD. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
#ifndef _MUL_ADD_MUL_R_H
#define _MUL_ADD_MUL_R_H
#include "su3.h"
/* Makes (*R)=c1*(*S)+c2*(*U) , c1 and c2 are real constants */
void mul_add_mul_r(spinor * const R, spinor * const S, spinor * const U,
const double c1,const double c2, const int N);
#endif
|
"""The tests for the Transport NSW (AU) sensor platform."""
import unittest
from unittest.mock import patch
from homeassistant.setup import setup_component
from tests.common import get_test_home_assistant
VALID_CONFIG = {
"sensor": {
"platform": "transport_nsw",
"stop_id": "209516",
"route": "199",
"destination": "",
"api_key": "YOUR_API_KEY",
}
}
def get_departuresMock(_stop_id, route, destination, api_key):
"""Mock TransportNSW departures loading."""
data = {
"stop_id": "209516",
"route": "199",
"due": 16,
"delay": 6,
"real_time": "y",
"destination": "Palm Beach",
"mode": "Bus",
}
return data
class TestRMVtransportSensor(unittest.TestCase):
"""Test the TransportNSW sensor."""
def setUp(self):
"""Set up things to run when tests begin."""
self.hass = get_test_home_assistant()
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
@patch("TransportNSW.TransportNSW.get_departures", side_effect=get_departuresMock)
def test_transportnsw_config(self, mock_get_departures):
"""Test minimal TransportNSW configuration."""
assert setup_component(self.hass, "sensor", VALID_CONFIG)
state = self.hass.states.get("sensor.next_bus")
assert state.state == "16"
assert state.attributes["stop_id"] == "209516"
assert state.attributes["route"] == "199"
assert state.attributes["delay"] == 6
assert state.attributes["real_time"] == "y"
assert state.attributes["destination"] == "Palm Beach"
assert state.attributes["mode"] == "Bus"
|
// This script will show the health of the project as circle diagram
// depends on d3
function createHealthchart(urlPath)
{
var width = 200;
var height = 200;
var donutWidth = 45;
var legendRectSize = 18;
var legendSpacing = 4;
var radius = Math.min(width, height) / 2;
var svg = d3.select('graph')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')');
var arc = d3.svg.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function(d) { return d.count; })
.sort(null);
d3.csv(urlPath, function(error, dataset)
{
// dataset.forEach(function(d) {
// d.count = +d.count;
// });
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return dataset[i].color;
});
var legend = svg.selectAll('.legend')
.data(dataset)
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = height * dataset.length / 2;
var horz = -2 * legendRectSize;
var vert = i * height - offset;
return 'translate(' + horz + ',' + vert + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', function(d) { return d.color; })
.style('stroke', function(d) { return d.color; });
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d.category; });
});
}
|
try:
extra_coverage
except NameError:
print("SKIP")
raise SystemExit
import uerrno
import uio
data = extra_coverage()
# test hashing of str/bytes that have an invalid hash
print(data[0], data[1])
print(hash(data[0]))
print(hash(data[1]))
print(hash(bytes(data[0], "utf8")))
print(hash(str(data[1], "utf8")))
# test streams
stream = data[2] # has set_error and set_buf. Write always returns error
stream.set_error(uerrno.EAGAIN) # non-blocking error
print(stream.read()) # read all encounters non-blocking error
print(stream.read(1)) # read 1 byte encounters non-blocking error
print(stream.readline()) # readline encounters non-blocking error
print(stream.readinto(bytearray(10))) # readinto encounters non-blocking error
print(stream.write(b"1")) # write encounters non-blocking error
print(stream.write1(b"1")) # write1 encounters non-blocking error
stream.set_buf(b"123")
print(stream.read(4)) # read encounters non-blocking error after successful reads
stream.set_buf(b"123")
print(stream.read1(4)) # read1 encounters non-blocking error after successful reads
stream.set_buf(b"123")
print(stream.readline(4)) # readline encounters non-blocking error after successful reads
try:
print(stream.ioctl(0, 0)) # ioctl encounters non-blocking error; raises OSError
except OSError:
print("OSError")
stream.set_error(0)
print(stream.ioctl(0, bytearray(10))) # successful ioctl call
stream2 = data[3] # is textio
print(stream2.read(1)) # read 1 byte encounters non-blocking error with textio stream
# test BufferedWriter with stream errors
stream.set_error(uerrno.EAGAIN)
buf = uio.BufferedWriter(stream, 8)
print(buf.write(bytearray(16)))
# test basic import of frozen scripts
import frzstr1
print(frzstr1.__file__)
import frzmpy1
print(frzmpy1.__file__)
# test import of frozen packages with __init__.py
import frzstr_pkg1
print(frzstr_pkg1.__file__, frzstr_pkg1.x)
import frzmpy_pkg1
print(frzmpy_pkg1.__file__, frzmpy_pkg1.x)
# test import of frozen packages without __init__.py
from frzstr_pkg2.mod import Foo
print(Foo.x)
from frzmpy_pkg2.mod import Foo
print(Foo.x)
# test raising exception in frozen script
try:
import frzmpy2
except ZeroDivisionError:
print("ZeroDivisionError")
# test loading a resource from a frozen string
import uio
buf = uio.resource_stream("frzstr_pkg2", "mod.py")
print(buf.read(21))
# test for MP_QSTR_NULL regression
from frzqstr import returns_NULL
print(returns_NULL())
|
import os
import unittest
import mock
from pulp.server import config
from pulp.server.db import connection
from pulp.server.logs import start_logging, stop_logging
class _ConfigAlteredDuringTestingError(RuntimeError):
"""Exception raised during attempts to modify the pulp config during unit testing"""
def drop_database():
"""
Drop the database so that the next test run starts with a clean database.
"""
connection._CONNECTION.drop_database(connection._DATABASE.name)
def start_database_connection():
"""
Start the database connection, if it is not already established.
"""
# It's important to only call this once during the process
if not connection._CONNECTION:
_load_test_config()
connection.initialize()
def _enforce_config(wrapped_func_name):
"""
Raise an Exception that tells developers to mock the config rather than trying to change the
real config.
:param wrapped_func_name: Name of function being replaced by the config enforcer
:type str :
:raises: Exception
"""
def the_enforcer(*args, **kwargs):
raise _ConfigAlteredDuringTestingError(
"Attempt to modify the config during a test run has been blocked. "
"{0} was called with args {1} and kwargs {2}".format(
wrapped_func_name, args, kwargs))
return the_enforcer
def _load_test_config():
"""
Load test configuration, reconfigure logging, block config changes during testing
"""
# prevent reading of server.conf
block_load_conf()
# allow altering the conf during config load, since we have to load the defaults
restore_config_attrs()
# force reloading the config
config.load_configuration()
# configure the test database
config.config.set('database', 'name', 'pulp_unittest')
config.config.set('server', 'storage_dir', '/tmp/pulp')
# reset logging conf
stop_logging()
start_logging()
# block future attempts to alter the config in place
override_config_attrs()
def override_config_attrs():
if not hasattr(config, '_overridden_attrs'):
# only save these once so we don't end up saving _enforce_config as the "original" values
setattr(config, '_overridden_attrs', {
'__setattr__': config.__setattr__,
'load_configuration': config.load_configuration,
'config.set': config.config.set,
})
# Prevent the tests from altering the config so that nobody accidentally makes global changes
config.__setattr__ = _enforce_config(
'.'.join((config.__package__, 'config.__setattr__')))
config.load_configuration = _enforce_config(
'.'.join((config.__package__, 'config.load_configuration')))
config.config.set = _enforce_config(
'.'.join((config.__package__, 'config.config.set')))
def restore_config_attrs():
# Restore values overridden by _override_config_attrs
if not hasattr(config, '_overridden_attrs'):
return
for attr in '__setattr__', 'load_configuration':
setattr(config, attr, config._overridden_attrs[attr])
config.config.set = config._overridden_attrs['config.set']
def block_load_conf():
# Remove server.conf from the list of autoloaded config files
# This is needed when testing modules that create objects using conf data found in the
# server config, such as DB connections, celery, etc. This should be used as little as
# possible and as early as possible, before config file loads happen
try:
config.remove_config_file('/etc/pulp/server.conf')
except RuntimeError:
# server.conf already removed, move along...
pass
class PulpWebservicesTests(unittest.TestCase):
"""
Base class for tests of webservice controllers. This base is used to work around the
authentication tests for each each method
"""
def setUp(self):
self.patch1 = mock.patch('pulp.server.webservices.views.decorators.'
'check_preauthenticated')
self.patch2 = mock.patch('pulp.server.webservices.views.decorators.'
'is_consumer_authorized')
self.patch3 = mock.patch('pulp.server.webservices.http.resource_path')
self.patch4 = mock.patch('web.webapi.HTTPError')
self.patch5 = mock.patch('pulp.server.managers.factory.principal_manager')
self.patch6 = mock.patch('pulp.server.managers.factory.user_query_manager')
self.patch7 = mock.patch('pulp.server.webservices.http.uri_path')
self.mock_check_pre_auth = self.patch1.start()
self.mock_check_pre_auth.return_value = 'ws-user'
self.mock_check_auth = self.patch2.start()
self.mock_check_auth.return_value = True
self.mock_http_resource_path = self.patch3.start()
self.patch4.start()
self.patch5.start()
self.mock_user_query_manager = self.patch6.start()
self.mock_user_query_manager.return_value.is_superuser.return_value = False
self.mock_user_query_manager.return_value.is_authorized.return_value = True
self.mock_uri_path = self.patch7.start()
self.mock_uri_path.return_value = "/mock/"
def tearDown(self):
self.patch1.stop()
self.patch2.stop()
self.patch3.stop()
self.patch4.stop()
self.patch5.stop()
self.patch6.stop()
self.patch7.stop()
def validate_auth(self, operation):
"""
validate that a validation check was performed for a given operation
:param operation: the operation to validate
"""
self.mock_user_query_manager.return_value.is_authorized.assert_called_once_with(
mock.ANY, mock.ANY, operation)
def get_mock_uri_path(self, *args):
"""
:param object_id: the id of the object to get the uri for
:type object_id: str
"""
return os.path.join('/mock', *args) + '/'
|
/* $OpenBSD: atexit.h,v 1.7 2007/09/03 14:40:16 millert Exp $ */
/*
* Copyright (c) 2002 Daniel Hartmeier
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 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 HOLDERS 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.
*
*/
struct atexit {
struct atexit *next; /* next in list */
int ind; /* next index in this table */
int max; /* max entries >= ATEXIT_SIZE */
struct atexit_fn {
union {
void (*std_func)(void);
void (*cxa_func)(void *);
} fn_ptr;
void *fn_arg; /* argument for CXA callback */
void *fn_dso; /* shared module handle */
} fns[1]; /* the table itself */
};
extern int __atexit_invalid;
extern struct atexit *__atexit; /* points to head of LIFO stack */
int __cxa_atexit(void (*)(void *), void *, void *);
void __cxa_finalize(void *);
|
"""
sentry.plugins.base.structs
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
__all__ = ['ReleaseHook']
from sentry.models import Release
from sentry.plugins import ReleaseHook
from sentry.testutils import TestCase
class StartReleaseTest(TestCase):
def test_minimal(self):
project = self.create_project()
version = 'bbee5b51f84611e4b14834363b8514c2'
hook = ReleaseHook(project)
hook.start_release(version)
release = Release.objects.get(
project=project,
version=version,
)
assert release.date_started
class FinishReleaseTest(TestCase):
def test_minimal(self):
project = self.create_project()
version = 'bbee5b51f84611e4b14834363b8514c2'
hook = ReleaseHook(project)
hook.finish_release(version)
release = Release.objects.get(
project=project,
version=version,
)
assert release.date_released
|
package de.hsrm.derns002.dsmoa.service.dsm.clusterer;
import android.content.Context;
import moa.clusterers.CobWeb;
/**
* Produces one cluster only, and adjusts that cluster to fit them all.
* No matter the parameters here. Also, CobWeb "hasn't been tested very
* well in MOA" as stated by MOA-author A. Bifet himself.
*/
public class CobWebLocationClusterer extends LocationClustererTemplate {
public CobWebLocationClusterer(Context context) {
super(context);
CobWeb cobWeb = new CobWeb();
cobWeb.resetLearningImpl();
//-a acuity (default: 1.0), Acuity (minimum standard deviation)
cobWeb.setAcuity(1.0);
//-c cutoff (default: 0.002), Cutoff (minimum category utility)
cobWeb.setCutoff(0.002);
//-r randomSeed (default: 1), Seed for random noise.
cobWeb.randomSeedOption.setValue(1);
setClusterer("CobWeb", cobWeb);
}
}
|
var class_field_helper =
[
[ "FieldHelper", "class_field_helper.html#a06729cbd5da2993e8007cb62f1d00b3a", null ],
[ "field", "class_field_helper.html#a69f50394c04733e6dc854f5186b10fd5", null ],
[ "field_", "class_field_helper.html#a50a7ec9efc60377363d5ce8bea1708ac", null ]
];
|
package cn.felord.wepay.ali.sdk.api.domain;
import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;
/**
* 分页查询模型列表接口
*
* @author auto create
* @version $Id: $Id
*/
public class AlipayMarketingDataModelBatchqueryModel extends AlipayObject {
private static final long serialVersionUID = 3362364948998348477L;
/**
* 当前页面。输入参数值为模型页数,一页最多30条;用于查询模型清单
*/
@ApiField("page")
private String page;
/**
* 每页最大条数。输入参数值为模型页面展现条数,最多展现30条;用于查询模型清单条数
*/
@ApiField("size")
private String size;
/**
* <p>Getter for the field <code>page</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getPage() {
return this.page;
}
/**
* <p>Setter for the field <code>page</code>.</p>
*
* @param page a {@link java.lang.String} object.
*/
public void setPage(String page) {
this.page = page;
}
/**
* <p>Getter for the field <code>size</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getSize() {
return this.size;
}
/**
* <p>Setter for the field <code>size</code>.</p>
*
* @param size a {@link java.lang.String} object.
*/
public void setSize(String size) {
this.size = size;
}
}
|
{% load widget_tweaks %}
{% load widget_tweaks_extras %}
{% load i18n %}
<p>{% blocktrans %}The data provided here will be saved into the Database to retrieve the calendar on voting in Polls.
The column is encrypted on the server side with a global key.{% endblocktrans %}</p>
<p>{% blocktrans %}You can enter either a world readable CalDav calendar Url, or provide user and password to login to
the CalDav Server. If you make the calendar world readable check that the url is not predictable by
other people{% endblocktrans %}</p>
{% if edit %}
<h3>{% trans "Change Calendar"%}</h3>
<form action="{% url 'edit_save_calendar' calendar_id%}" method="post">
{% else %}
<h3>{% trans "Add a Calendar"%}</h3>
<form action="{% url 'change_calendar' %}" method="post">
{% endif %}
{% csrf_token %}
{% if calendar_form.non_field_errors %}
{% for error in calendar_form.non_field_errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% endif %}
{{ calendar_form.name.label_tag }}
{% render_field calendar_form.name class+='form-control'%}
{% if calendar_form.name.errors %}
<div class="form-errors">
<div class="alert alert-danger">
<div class="container">
<i class="fa fa-times"></i>{{ calendar_form.name.errors }}
</div>
</div>
</div>
{% endif %}
{% with calendar_form.url.auto_id|add:"_0" as url_id %}
<label for="{{ url_id }}_0">{% trans "Calendar URL:"%}</label>
{% render_multi_field calendar_form.url 0 class="form-control" id=url_id%}
{% endwith %}
{% if calendar_form.url.errors %}
<div class="form-errors">
<div class="alert alert-danger">
<div class="container">
<i class="fa fa-times"></i>{{ calendar_form.url.errors }}
</div>
</div>
</div>
{% endif %}
{% with calendar_form.url.auto_id|add:"_1" as user_id %}
<label for="{{ user_id }}_1">{% trans "User:"%}</label>
{% render_multi_field calendar_form.url 1 class='form-control' id=user_id%}
{% endwith %}
{% with calendar_form.url.auto_id|add:"_2" as pw_id %}
<label for="{{ pw_id }}">{% trans "Password:"%}</label>
{% render_multi_field calendar_form.url 2 class+="form-control" id=pw_id %}
{% endwith %}
<input type="submit" name="submit" value="{% trans 'Save' %}" class="action primary">
</form>
<form action="{% url 'change_calendar' %}" method="post">
{% csrf_token %}
{% if not edit %}
<h3>{% trans "Current Calendars:"%}</h3>
<ul>
{% for calendar in calendars %}
<li>{{ calendar.name }}
<button name="delete" value="{{ calendar.id }}" class="btn btn-default btn-xs">
<i class="fa fa-trash-o"></i>
</button>
<a href="{% url 'edit_calendar' calendar.id %}" class="btn btn-xs btn-default"><i class="fa fa-pencil"></i> </a>
</li>
{% endfor %}
</ul>
{% endif %}
</form>
|
# -*- coding: utf-8 -*-
WS_NFE_ENVIO_LOTE = 0
WS_NFE_CONSULTA_RECIBO = 1
WS_NFE_CANCELAMENTO = 2
WS_NFE_INUTILIZACAO = 3
WS_NFE_CONSULTA = 4
WS_NFE_SITUACAO = 5
WS_NFE_CONSULTA_CADASTRO = 6
WS_DPEC_RECEPCAO = 7
WS_DPEC_CONSULTA = 8
WS_NFE_EVENTO= 9
WS_NFE_CONSULTA_DESTINATARIO = 10
WS_NFE_DOWNLOAD_XML_DESTINATARIO = 11
WS_NFE_AUTORIZACAO = 12
WS_NFE_RET_AUTORIZACAO = 13
NFE_AMBIENTE_PRODUCAO = 1
NFE_AMBIENTE_HOMOLOGACAO = 2
PROC_ENVIO_NFE = 101
PROC_CANCELAMENTO_NFE = 102
PROC_INUTILIZACAO_NFE = 103
UF_CODIGO = {
u'AC': 12,
u'AL': 27,
u'AM': 13,
u'AP': 16,
u'BA': 29,
u'CE': 23,
u'DF': 53,
u'ES': 32,
u'GO': 52,
u'MA': 21,
u'MG': 31,
u'MS': 50,
u'MT': 51,
u'PA': 15,
u'PB': 25,
u'PE': 26,
u'PI': 22,
u'PR': 41,
u'RJ': 33,
u'RN': 24,
u'RO': 11,
u'RR': 14,
u'RS': 43,
u'SC': 42,
u'SE': 28,
u'SP': 35,
u'TO': 17,
u'NACIONAL': 91,
}
CODIGO_UF = {
12: u'AC',
27: u'AL',
13: u'AM',
16: u'AP',
29: u'BA',
23: u'CE',
53: u'DF',
32: u'ES',
52: u'GO',
21: u'MA',
31: u'MG',
50: u'MS',
51: u'MT',
15: u'PA',
25: u'PB',
26: u'PE',
22: u'PI',
41: u'PR',
33: u'RJ',
24: u'RN',
11: u'RO',
14: u'RR',
43: u'RS',
42: u'SC',
28: u'SE',
35: u'SP',
17: u'TO',
91: u'NACIONAL',
}
|
import threading
from peewee import *
from playhouse.kv import JSONKeyStore
from playhouse.kv import KeyStore
from playhouse.kv import PickledKeyStore
from playhouse.tests.base import PeeweeTestCase
from playhouse.tests.base import skip_if
class TestKeyStore(PeeweeTestCase):
def setUp(self):
super(TestKeyStore, self).setUp()
self.kv = KeyStore(CharField())
self.ordered_kv = KeyStore(CharField(), ordered=True)
self.pickled_kv = PickledKeyStore(ordered=True)
self.json_kv = JSONKeyStore(ordered=True)
self.kv.clear()
self.json_kv.clear()
def test_json(self):
self.json_kv['foo'] = 'bar'
self.json_kv['baze'] = {'baze': [1, 2, 3]}
self.json_kv['nugget'] = None
self.assertEqual(self.json_kv['foo'], 'bar')
self.assertEqual(self.json_kv['baze'], {'baze': [1, 2, 3]})
self.assertIsNone(self.json_kv['nugget'])
self.assertRaises(KeyError, lambda: self.json_kv['missing'])
results = self.json_kv[self.json_kv.key << ['baze', 'bar', 'nugget']]
self.assertEqual(results, [
{'baze': [1, 2, 3]},
None,
])
def test_storage(self):
self.kv['a'] = 'A'
self.kv['b'] = 1
self.assertEqual(self.kv['a'], 'A')
self.assertEqual(self.kv['b'], '1')
self.assertRaises(KeyError, self.kv.__getitem__, 'c')
del(self.kv['a'])
self.assertRaises(KeyError, self.kv.__getitem__, 'a')
self.kv['a'] = 'A'
self.kv['c'] = 'C'
self.assertEqual(self.kv[self.kv.key << ('a', 'c')], ['A', 'C'])
self.kv[self.kv.key << ('a', 'c')] = 'X'
self.assertEqual(self.kv['a'], 'X')
self.assertEqual(self.kv['b'], '1')
self.assertEqual(self.kv['c'], 'X')
key = self.kv.key
results = self.kv[key << ('a', 'b')]
self.assertEqual(results, ['X', '1'])
del(self.kv[self.kv.key << ('a', 'c')])
self.assertRaises(KeyError, self.kv.__getitem__, 'a')
self.assertRaises(KeyError, self.kv.__getitem__, 'c')
self.assertEqual(self.kv['b'], '1')
self.pickled_kv['a'] = 'A'
self.pickled_kv['b'] = 1.1
self.assertEqual(self.pickled_kv['a'], 'A')
self.assertEqual(self.pickled_kv['b'], 1.1)
def test_container_properties(self):
self.kv['x'] = 'X'
self.kv['y'] = 'Y'
self.assertEqual(len(self.kv), 2)
self.assertTrue('x' in self.kv)
self.assertFalse('a' in self.kv)
def test_dict_methods(self):
for kv in (self.ordered_kv, self.pickled_kv):
kv['a'] = 'A'
kv['c'] = 'C'
kv['b'] = 'B'
self.assertEqual(list(kv.keys()), ['a', 'b', 'c'])
self.assertEqual(list(kv.values()), ['A', 'B', 'C'])
self.assertEqual(list(kv.items()), [
('a', 'A'),
('b', 'B'),
('c', 'C'),
])
def test_iteration(self):
for kv in (self.ordered_kv, self.pickled_kv):
kv['a'] = 'A'
kv['c'] = 'C'
kv['b'] = 'B'
items = list(kv)
self.assertEqual(items, [
('a', 'A'),
('b', 'B'),
('c', 'C'),
])
def test_shared_mem(self):
self.kv['a'] = 'xxx'
self.assertEqual(self.ordered_kv['a'], 'xxx')
def set_k():
kv_t = KeyStore(CharField())
kv_t['b'] = 'yyy'
t = threading.Thread(target=set_k)
t.start()
t.join()
self.assertEqual(self.kv['b'], 'yyy')
def test_get(self):
self.kv['a'] = 'A'
self.kv['b'] = 'B'
self.assertEqual(self.kv.get('a'), 'A')
self.assertEqual(self.kv.get('x'), None)
self.assertEqual(self.kv.get('x', 'y'), 'y')
self.assertEqual(
list(self.kv.get(self.kv.key << ('a', 'b'))),
['A', 'B'])
self.assertEqual(
list(self.kv.get(self.kv.key << ('x', 'y'))),
[])
def test_pop(self):
self.ordered_kv['a'] = 'A'
self.ordered_kv['b'] = 'B'
self.ordered_kv['c'] = 'C'
self.assertEqual(self.ordered_kv.pop('a'), 'A')
self.assertEqual(list(self.ordered_kv.keys()), ['b', 'c'])
self.assertRaises(KeyError, self.ordered_kv.pop, 'x')
self.assertEqual(self.ordered_kv.pop('x', 'y'), 'y')
self.assertEqual(
list(self.ordered_kv.pop(self.ordered_kv.key << ['b', 'c'])),
['B', 'C'])
self.assertEqual(list(self.ordered_kv.keys()), [])
try:
import psycopg2
except ImportError:
psycopg2 = None
@skip_if(lambda: psycopg2 is None)
class TestPostgresqlKeyStore(PeeweeTestCase):
def setUp(self):
self.db = PostgresqlDatabase('peewee_test')
self.kv = KeyStore(CharField(), ordered=True, database=self.db)
self.kv.clear()
def tearDown(self):
self.db.close()
def test_non_native_upsert(self):
self.kv['a'] = 'A'
self.kv['b'] = 'B'
self.assertEqual(self.kv['a'], 'A')
self.kv['a'] = 'C'
self.assertEqual(self.kv['a'], 'C')
|
#include <mutex>
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
namespace caffe2 {
namespace fb {
namespace {
class CreateMutexOp final : public Operator<CPUContext> {
public:
CreateMutexOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CPUContext>(operator_def, ws) {}
bool RunOnDevice() override {
*OperatorBase::Output<std::unique_ptr<std::mutex>>(0) =
std::unique_ptr<std::mutex>(new std::mutex);
return true;
}
};
class AtomicFetchAddOp final : public Operator<CPUContext> {
public:
AtomicFetchAddOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CPUContext>(operator_def, ws) {}
bool RunOnDevice() override {
auto& mutex = OperatorBase::Input<std::unique_ptr<std::mutex>>(0);
auto& a = Input(1);
auto& b = Input(2);
auto* c = Output(0);
auto* d = Output(1);
c->Resize(std::vector<TIndex>());
d->Resize(std::vector<TIndex>());
auto* aPtr = a.data<int32_t>();
auto* bPtr = b.data<int32_t>();
auto* cPtr = c->mutable_data<int32_t>();
auto* dPtr = d->mutable_data<int32_t>();
std::lock_guard<std::mutex> lg(*mutex);
*dPtr = *aPtr;
*cPtr = *aPtr + *bPtr;
return true;
}
};
class CreateAtomicBoolOp final : public Operator<CPUContext> {
public:
using Operator::Operator;
bool RunOnDevice() override {
*OperatorBase::Output<std::unique_ptr<std::atomic<bool>>>(0) =
std::unique_ptr<std::atomic<bool>>(new std::atomic<bool>(false));
return true;
}
};
class ConditionalSetAtomicBoolOp final : public Operator<CPUContext> {
public:
using Operator::Operator;
bool RunOnDevice() override {
auto& ptr =
OperatorBase::Input<std::unique_ptr<std::atomic<bool>>>(ATOMIC_BOOL);
if (Input(CONDITION).data<bool>()[0]) {
ptr->store(true);
}
return true;
}
private:
INPUT_TAGS(ATOMIC_BOOL, CONDITION);
};
class CheckAtomicBoolOp final : public Operator<CPUContext> {
public:
using Operator::Operator;
bool RunOnDevice() override {
auto& ptr = OperatorBase::Input<std::unique_ptr<std::atomic<bool>>>(0);
Output(0)->Resize(1);
*Output(0)->mutable_data<bool>() = ptr->load();
return true;
}
};
REGISTER_CPU_OPERATOR(CreateMutex, CreateMutexOp);
REGISTER_CPU_OPERATOR(AtomicFetchAdd, AtomicFetchAddOp);
REGISTER_CPU_OPERATOR(CreateAtomicBool, CreateAtomicBoolOp);
REGISTER_CPU_OPERATOR(ConditionalSetAtomicBool, ConditionalSetAtomicBoolOp);
REGISTER_CPU_OPERATOR(CheckAtomicBool, CheckAtomicBoolOp);
OPERATOR_SCHEMA(CreateMutex)
.NumInputs(0)
.NumOutputs(1)
.SetDoc("Creates an unlocked mutex and returns it in a unique_ptr blob.")
.Output(0, "mutex_ptr", "Blob containing a std::unique_ptr<mutex>.");
OPERATOR_SCHEMA(AtomicFetchAdd)
.NumInputs(3)
.NumOutputs(2)
.SetDoc(R"DOC(
Given a mutex and two int32 scalar tensors, performs an atomic fetch add
by mutating the first argument and adding it to the second input
argument. Returns the updated integer and the value prior to the update.
)DOC")
.Input(0, "mutex_ptr", "Blob containing to a unique_ptr<mutex>")
.Input(1, "mut_value", "Value to be mutated after the sum.")
.Input(2, "increment", "Value to add to the first operand.")
.Output(0, "mut_value", "Mutated value after sum. Usually same as input 1.")
.Output(1, "fetched_value", "Value of the first operand before sum.")
.AllowInplace({{1, 0}});
OPERATOR_SCHEMA(CreateAtomicBool)
.NumInputs(0)
.NumOutputs(1)
.SetDoc("Create an unique_ptr blob to hold an atomic<bool>")
.Output(0, "atomic_bool", "Blob containing a unique_ptr<atomic<bool>>");
OPERATOR_SCHEMA(ConditionalSetAtomicBool)
.NumInputs(2)
.NumOutputs(0)
.SetDoc(R"DOC(
Set an atomic<bool> to true if the given condition bool variable is true
)DOC")
.Input(0, "atomic_bool", "Blob containing a unique_ptr<atomic<bool>>")
.Input(1, "condition", "Blob containing a bool");
OPERATOR_SCHEMA(CheckAtomicBool)
.NumInputs(1)
.NumOutputs(1)
.SetDoc("Copy the value of an atomic<bool> to a bool")
.Input(0, "atomic_bool", "Blob containing a unique_ptr<atomic<bool>>")
.Output(0, "value", "Copy of the value for the atomic<bool>");
SHOULD_NOT_DO_GRADIENT(CreateMutex);
SHOULD_NOT_DO_GRADIENT(AtomicFetchAdd);
SHOULD_NOT_DO_GRADIENT(CreateAtomicBool);
SHOULD_NOT_DO_GRADIENT(ConditionalSetAtomicBool);
SHOULD_NOT_DO_GRADIENT(CheckAtomicBool);
}
}
}
|
<?php
// $Header: /var/cvs/arsgate/client_cpanel/include/html2pdf/xhtml.deflist.inc.php,v 1.2 2008-06-08 18:29:06 cvs Exp $
function process_dd(&$sample_html, $offset) {
return autoclose_tag($sample_html, $offset, "(dt|dd|dl|/dl|/dd)", array("dl" => "process_dl"), "/dd");
}
function process_dt(&$sample_html, $offset) {
return autoclose_tag($sample_html, $offset, "(dt|dd|dl|/dl|/dd)", array("dl" => "process_dl"), "/dt");
}
function process_dl(&$sample_html, $offset) {
return autoclose_tag($sample_html, $offset, "(dt|dd|/dl)",
array("dt" => "process_dt",
"dd" => "process_dd"),
"/dl");
};
function process_deflists(&$sample_html, $offset) {
return autoclose_tag($sample_html, $offset, "(dl)",
array("dl" => "process_dl"),
"");
};
?>
|
namespace ProjectTasks.Business.Domain.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Threading;
using System.Linq;
using Newtonsoft.Json;
/// <summary>
/// Represents an area to split the project in few functional / technical parts.
/// </summary>
public class Area : IEntity
{
#region < Properties >
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
[Key]
public int Id { get; set; }
/// <summary>
/// Gets or sets the parent identifier.
/// </summary>
/// <value>
/// The parent identifier.
/// </value>
public int? ParentId { get; set; }
/// <summary>
/// Gets or sets the label.
/// </summary>
/// <value>
/// The label.
/// </value>
[Required, StringLength(64)]
public string Label { get; set; }
/// <summary>
/// Gets or sets the creation date.
/// </summary>
/// <value>
/// The creation date.
/// </value>
public DateTime CreationDate { get; set; }
/// <summary>
/// Gets or sets the creation login.
/// </summary>
/// <value>
/// The creation login.
/// </value>
[StringLength(64)]
public string CreationLogin { get; set; }
/// <summary>
/// Gets or sets the update date.
/// </summary>
/// <value>
/// The update date.
/// </value>
public DateTime UpdateDate { get; set; }
/// <summary>
/// Gets or sets the update login.
/// </summary>
/// <value>
/// The update login.
/// </value>
[StringLength(64)]
public string UpdateLogin { get; set; }
/// <summary>
/// Gets or sets the parent.
/// </summary>
/// <value>
/// The parent.
/// </value>
[ForeignKey("ParentId"), JsonIgnore]
public Area Parent { get; set; }
/// <summary>
/// Gets or sets the children.
/// </summary>
/// <value>
/// The children.
/// </value>
[JsonIgnore]
public ICollection<Area> Children { get; set; }
/// <summary>
/// Gets the sorted children items.
/// </summary>
public IEnumerable<Area> SortedChildren
{
get
{
if (this.Children == null)
return Enumerable.Empty<Area>();
return this.Children.OrderBy(c => c.Label);
}
}
/// <summary>
/// Gets the parent label.
/// </summary>
[NotMapped]
public string ParentLabel
{
get
{
return this.Parent != null ? this.Parent.Label : string.Empty;
}
}
#endregion < Properties >
#region < Constructors >
/// <summary>
/// Initializes a new instance of the <see cref="Area"/> class.
/// </summary>
public Area()
{
this.CreationDate = DateTime.Now;
this.CreationLogin = Thread.CurrentPrincipal.Identity.Name;
this.UpdateDate = DateTime.Now;
this.UpdateLogin = Thread.CurrentPrincipal.Identity.Name;
}
#endregion < Constructors >
}
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrays in the Ruby Koans
#
from runner.koan import *
class AboutLists(Koan):
def test_creating_lists(self):
empty_list = list()
self.assertEqual(list, type(empty_list))
self.assertEqual(0, len(empty_list))
def test_list_literals(self):
nums = list()
self.assertEqual([], nums)
nums[0:] = [1]
self.assertEqual([1], nums)
nums[1:] = [2]
self.assertListEqual([1, 2], nums)
nums.append(333)
self.assertListEqual([1, 2, 333], nums)
def test_accessing_list_elements(self):
noms = ['peanut', 'butter', 'and', 'jelly']
self.assertEqual('peanut', noms[0])
self.assertEqual('jelly', noms[3])
self.assertEqual('jelly', noms[-1])
self.assertEqual('butter', noms[-3])
def test_slicing_lists(self):
noms = ['peanut', 'butter', 'and', 'jelly']
self.assertEqual(['peanut'], noms[0:1])
self.assertEqual(['peanut','butter'], noms[0:2])
self.assertEqual([], noms[2:2])
self.assertEqual(['and', 'jelly'], noms[2:20])
self.assertEqual([], noms[4:0])
self.assertEqual([], noms[4:100])
self.assertEqual([], noms[5:0])
def test_slicing_to_the_edge(self):
noms = ['peanut', 'butter', 'and', 'jelly']
self.assertEqual(['and', 'jelly'], noms[2:])
self.assertEqual(['peanut', 'butter'], noms[:2])
def test_lists_and_ranges(self):
self.assertEqual(range, type(range(5)))
self.assertNotEqual([1, 2, 3, 4, 5], range(1,6))
self.assertEqual([0, 1, 2, 3, 4], list(range(5)))
self.assertEqual([5, 6, 7, 8], list(range(5, 9)))
def test_ranges_with_steps(self):
self.assertEqual([5, 4], list(range(5, 3, -1)))
self.assertEqual([0, 2, 4, 6], list(range(0, 8, 2)))
self.assertEqual([1, 4, 7], list(range(1, 8, 3)))
self.assertEqual([5, 1, -3], list(range(5, -7, -4)))
self.assertEqual([5, 1, -3, -7], list(range(5, -8, -4)))
def test_insertions(self):
knight = ['you', 'shall', 'pass']
knight.insert(2, 'not')
self.assertEqual(['you', 'shall', 'not', 'pass'], knight)
knight.insert(0, 'Arthur')
self.assertEqual(['Arthur', 'you', 'shall', 'not', 'pass'], knight)
def test_popping_lists(self):
stack = [10, 20, 30, 40]
stack.append('last')
self.assertEqual([10, 20, 30, 40, 'last'], stack)
popped_value = stack.pop()
self.assertEqual('last', popped_value)
self.assertEqual([10, 20, 30, 40], stack)
popped_value = stack.pop(1)
self.assertEqual(20, popped_value)
self.assertEqual([10, 30, 40], stack)
# Notice that there is a "pop" but no "push" in python?
# Part of the Python philosophy is that there ideally should be one and
# only one way of doing anything. A 'push' is the same as an 'append'.
# To learn more about this try typing "import this" from the python
# console... ;)
def test_making_queues(self):
queue = [1, 2]
queue.append('last')
self.assertEqual([1, 2, 'last'], queue)
popped_value = queue.pop(0)
self.assertEqual(1, popped_value)
self.assertEqual([2, 'last'], queue)
# Note, popping from the left hand side of a list is
# inefficient. Use collections.deque instead.
|
from waxy import *
from mywaxy import *
from utils import *
class Output_Parameters_Dialog(Dialog):
def __init__(self,parent=None,title="",info=None):
self.info=info
Dialog.__init__(self,parent,title)
def Nop(self,event):
pass
def AddHeading(self,parent,txt):
l=Label(parent,txt,align='c')
f=Font(l.GetFont().GetFaceName(),12,bold=1,underline=1)
l.SetFont(f)
parent.AddComponent(l,align='c',expand='h')
def Body(self):
panel=Panel(self,direction='vertical')
self.AddHeading(panel,"Moments")
p = FlexGridPanel(panel, rows=3, cols=2, hgap=2, vgap=2)
self.AddLabel(p,0,0,"Tau")
self.textbox_tau=TextBox(p,str(self.info['tau']))
p.AddComponent(1, 0, self.textbox_tau)
self.AddLabel(p,0,1,"Initial Minimum")
self.textbox_initial_min=TextBox(p,str(self.info['initial_moment_range'][0]))
p.AddComponent(1, 1, self.textbox_initial_min)
self.AddLabel(p,0,2,"Initial Maximum")
self.textbox_initial_max=TextBox(p,str(self.info['initial_moment_range'][1]))
p.AddComponent(1, 2, self.textbox_initial_max)
p.Pack()
panel.AddComponent(p, expand='h', border=10,align='c')
self.AddHeading(panel,"Output")
p = FlexGridPanel(panel, rows=6, cols=2, hgap=2, vgap=2)
layer=0
choices=['Linear','Tanh','Piecewise-linear','Exponential']
self.type_dropdown=DropDownBox(p,choices)
self.type_dropdown.SetSelection(self.info['output'][layer]['type'])
self.type_dropdown.OnSelect=self.Output_Type
p.AddComponent(1, 0, self.type_dropdown)
self.AddLabel(p,0,1,"Bottom")
self.textbox_bottom=TextBox(p,str(self.info['output'][layer]['bottom']))
p.AddComponent(1, 1, self.textbox_bottom)
self.AddLabel(p,0,2,"Top")
self.textbox_top=TextBox(p,str(self.info['output'][layer]['top']))
p.AddComponent(1, 2, self.textbox_top)
self.AddLabel(p,0,3,"Exponential Scale")
self.textbox_scale=TextBox(p,str(self.info['output'][layer]['scale']))
p.AddComponent(1, 3, self.textbox_scale)
self.AddLabel(p,0,4,"Sigma Tau")
self.textbox_sigma_tau=TextBox(p,str(self.info['output'][layer]['sigma_tau']))
p.AddComponent(1, 4, self.textbox_sigma_tau)
self.AddLabel(p,0,5,"Sigma_o")
self.textbox_sigma_o=TextBox(p,str(self.info['output'][layer]['sigma_o']))
p.AddComponent(1, 5, self.textbox_sigma_o)
p.Pack()
panel.AddComponent(p, expand='h', border=10,align='c')
panel.Pack()
self.AddComponent(panel, expand='both', border=3)
self.Output_Type()
def Output_Type(self,event=None):
layer=0
if event:
self.info['output'][layer]['type']=event.GetSelection()
if self.info['output'][layer]['type']==0: # linear
self.textbox_bottom.Enable(False)
self.textbox_top.Enable(False)
else:
self.textbox_bottom.Enable(True)
self.textbox_top.Enable(True)
def AddLabel(self, parent, col, row, text, align=None):
label = Label(parent, text)
parent.AddComponent(col, row, label, expand=0, align=align or 'vr')
# note: expand=0 allows us to align the label properly.
# in this case, 'v' centers it vertically, and 'r' aligns it to
# the right.
def set_output_parameters(params,parent=None):
keys=['output',
'tau',
'initial_moment_range']
info=deepcopy(subdict(params,keys))
if not parent:
app = Application(EmptyFrame)
dlg=Output_Parameters_Dialog(parent,"Set Output Parameters",info)
result=dlg.ShowModal()
if result == 'ok':
mn=float(dlg.textbox_initial_min.GetValue())
mx=float(dlg.textbox_initial_max.GetValue())
tau=float(dlg.textbox_tau.GetValue())
layer=0
info['output'][layer]['type']=int(dlg.type_dropdown.GetSelection())
info['output'][layer]['top']=float(dlg.textbox_top.GetValue())
info['output'][layer]['bottom']=float(dlg.textbox_bottom.GetValue())
info['output'][layer]['sigma_o']=float(dlg.textbox_sigma_o.GetValue())
info['output'][layer]['scale']=float(dlg.textbox_scale.GetValue())
info['output'][layer]['sigma_tau']=float(dlg.textbox_sigma_tau.GetValue())
info['initial_moment_range']=[mn,mx]
info['tau']=tau
for k in keys:
params[k]=info[k]
else:
pass
dlg.Destroy()
if not parent:
app.Run()
|
#==============================================================================#
# ez_process_base.py #
#==============================================================================#
#============#
# Includes #
#============#
import os
import types
import Queue
# adding the eZchat path to search directory
import sys, os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.pardir))
import ez_pipe as pipe
import ez_process_preferences as epp
#==============================================================================#
# class p2pCommand #
#==============================================================================#
class p2pCommand(object):
"""
A p2pCommand encapsulates ``'commandQueue'`` commands. The p2pCommand instance
can be appended to the client's command queue for execution via:
cmd = p2pCommand(...)
client_class_instance.commandQueue.put(cmd)
The funcStr is the name of the function which must match a key in the client
handler functions (see ez_process_base_meta). Data must be a dictionary and
has to be filled with key,value pairs as required by the handler function.
"""
def __init__(self, funcStr=None, data=None):
"""
:param funcStr: Storing the function name which should be called when
executed.
:type funcStr: String
:param data: Keyword arguments (*kwargs*) passed to the called
function.
:type data: Dict
"""
self.funcStr = funcStr
self.data = data
#==============================================================================#
# class p2pReply #
#==============================================================================#
class p2pReply(object):
"""
Encapsulate received data.
A p2pReply instance can be appended to the reply queue.
replyType = success: type(data) = str
replyType = error: type(data) = str
"""
error, success = range(2)
msg = 2
def __init__(self, replyType=None, data=None):
self.replyType = replyType
self.data = data
#==============================================================================#
# class ez_process_base(_meta) #
#==============================================================================#
class ez_process_base_meta(type):
"""
The metaclass __init__ function is called after the class is created, but
before any class instance initialization. Any class with set
__metaclass__ attribute to ez_process_base_meta which is equivalent to
inheriting the class ez_process_base is extended by:
- self.handlers: dictionary storing all user-defined functions
- global attributes as class attributes
self.handlers is called in the client main loop in p2pclient
"""
def __init__(cls, name, bases, dct):
if not hasattr(cls, 'handlers'):
cls.handlers = {}
if not hasattr(cls, 'handler_rules'):
cls.handler_rules = {}
for attr in [x for x in dct if not x.startswith('_')]:
# register process functionalities and inherit them to child classes
if isinstance(dct[attr], types.FunctionType):
assert not attr in cls.handlers
cls.handlers[attr] = dct[attr]
# register global attributes and inherit them to child classes
else:
cls.attr = dct[attr]
super(ez_process_base_meta, cls).__init__(name, bases, dct)
class ez_process_base(object):
__metaclass__ = ez_process_base_meta
commandQueue = Queue.Queue()
# storing active and/or sleeping background process
background_processes = {}
# storing the cmd with which the background processes were initiated
background_process_cmds = {}
# storing user-defined functions for calling after a process has been
# terminated successfully
success_callback = {}
def __init__(self, **kwargs):
if 'write_to_pipe' in kwargs:
class RQueue(Queue.Queue):
def __init__(self, write_to_pipe = False, *args, **kwargs):
Queue.Queue.__init__(self, *args, **kwargs)
self.write_to_pipe = write_to_pipe
def put(self, cmd):
Queue.Queue.put(self, cmd)
if self.write_to_pipe:
os.write(pipe.pipe, 'status')
self.replyQueue = RQueue(write_to_pipe = kwargs['write_to_pipe'])
else:
self.replyQueue = Queue.Queue()
# user defined parameters are passed to the process preferences potentiall
# overwriting default values.
epp.init_process_preferences(**kwargs)
# client related
def success(self, success_msg=None):
return p2pReply(p2pReply.success, success_msg)
# client related
def error(self, error_msg=None):
return p2pReply(p2pReply.error, error_msg)
# MsgDb update
def msg(self, msg=None):
return p2pReply(p2pReply.msg, msg)
|
#!/usr/bin/env python
#
# Copyright 2015 Flavio Garcia
#
# 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.
#
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
import firenado.core
from firenado.core.service import served_by
class LoginHandler(firenado.core.TornadoHandler):
@served_by('diasporapy.pod.components.user.services.UserService')
def get(self):
self.render('pod:user/accounts.html',
message=self.user_service.get_message('User Login'))
class RegisterHandler(firenado.core.TornadoHandler):
def get(self):
self.render('pod:user/register.html')
|
# coding: utf-8
#
# Copyright 2010-2014 Ning, Inc.
# Copyright 2014-2020 Groupon, Inc
# Copyright 2020-2021 Equinix, Inc
# Copyright 2014-2021 The Billing Project, LLC
#
# The Billing Project, LLC licenses this file to you 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.
#
"""
Kill Bill
Kill Bill is an open-source billing and payments platform # noqa: E501
OpenAPI spec version: 0.22.22-SNAPSHOT
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class Unit(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'Str',
'pretty_name': 'Str'
}
attribute_map = {
'name': 'name',
'pretty_name': 'prettyName'
}
def __init__(self, name=None, pretty_name=None): # noqa: E501
"""Unit - a model defined in Swagger""" # noqa: E501
self._name = None
self._pretty_name = None
self.discriminator = None
if name is not None:
self.name = name
if pretty_name is not None:
self.pretty_name = pretty_name
@property
def name(self):
"""Gets the name of this Unit. # noqa: E501
:return: The name of this Unit. # noqa: E501
:rtype: Str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this Unit.
:param name: The name of this Unit. # noqa: E501
:type: Str
"""
self._name = name
@property
def pretty_name(self):
"""Gets the pretty_name of this Unit. # noqa: E501
:return: The pretty_name of this Unit. # noqa: E501
:rtype: Str
"""
return self._pretty_name
@pretty_name.setter
def pretty_name(self, pretty_name):
"""Sets the pretty_name of this Unit.
:param pretty_name: The pretty_name of this Unit. # noqa: E501
:type: Str
"""
self._pretty_name = pretty_name
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Unit):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
@extends('layout')
@section('content')
<a href="{{ route('home') }}">go to home</a>
<h1>Database</h1>
<h2>{{$db->name}}</h2>
<h3>Conversation "{{$conversation->displayname}}"</h3>
<a href="{{ route('db.conversation.messages', array('db' => $db->id, 'conversation' => $conversation->id)) }}">messages</a>
<br />
<table>
<thead>
<th>Count</th>
<th>Author</th>
</thead>
<tbody>
@foreach($words['authors'] as $author => $count)
<tr>
<td>{{$count}}</td>
<td>{{$author}}</td>
</tr>
@endforeach
</tbody>
</table>
<br />
<table>
<thead>
<th>Count</th>
<th>Wort</th>
</thead>
<tbody>
@foreach($words['allWords'] as $word)
<tr>
<td>{{$word['count']}}</td>
<td>{{$word['word']}}</td>
</tr>
@endforeach
</tbody>
</table>
@stop
|
using System.Runtime.Serialization;
namespace DaaSDemo.KubeClient.Models
{
[DataContract]
public class VoyagerIngressV1Beta1
{
[DataMember(Name = "apiVersion", EmitDefaultValue = false)]
public string ApiVersion { get; set; }
[DataMember(Name = "kind", EmitDefaultValue = false)]
public string Kind { get; set; }
[DataMember(Name = "metadata", EmitDefaultValue = false)]
public ObjectMetaV1 Metadata { get; set; }
[DataMember(Name = "spec", EmitDefaultValue = false)]
public VoyagerIngressSpecV1Beta1 Spec { get; set; }
public IngressStatusV1Beta1 Status { get; set; }
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.connect.connector.policy;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PrincipalConnectorClientConfigOverridePolicyTest extends BaseConnectorClientConfigOverridePolicyTest {
ConnectorClientConfigOverridePolicy principalConnectorClientConfigOverridePolicy = new PrincipalConnectorClientConfigOverridePolicy();
@Test
public void testPrincipalOnly() {
Map<String, Object> clientConfig = Collections.singletonMap(SaslConfigs.SASL_JAAS_CONFIG, "test");
testValidOverride(clientConfig);
}
@Test
public void testPrincipalPlusOtherConfigs() {
Map<String, Object> clientConfig = new HashMap<>();
clientConfig.put(SaslConfigs.SASL_JAAS_CONFIG, "test");
clientConfig.put(ProducerConfig.ACKS_CONFIG, "none");
testInvalidOverride(clientConfig);
}
@Override
protected ConnectorClientConfigOverridePolicy policyToTest() {
return principalConnectorClientConfigOverridePolicy;
}
}
|
package arithmeticandalgebra.primaryarithmetic;
import java.io.IOException;
public class Main implements Runnable {
static String readLn(int maxLength) {
byte line[] = new byte[maxLength];
int length = 0;
int input = -1;
try {
while (length < maxLength) {
input = System.in.read();
if ((input < 0) || (input == '\n')) {
break;
}
line[length++] += input;
}
if ((input < 0) && (length == 0)) {
return null;
}
return new String(line, 0, length);
} catch (IOException e) {
return null;
}
}
public static void main(String args[]) {
Main myWork = new Main();
myWork.run();
}
public void run() {
new PrimaryArithmetic().run();
}
}
class PrimaryArithmetic implements Runnable {
public void run() {
while(true) {
String line = Main.readLn(22);
String numbers[] = line.split("\\s");
int firstNumber = Integer.valueOf(numbers[0]);
int secondNumber = Integer.valueOf(numbers[1]);
if(firstNumber == 0 && secondNumber == 0) {
return;
}
int numberOfCarry = calculateResult(firstNumber, secondNumber);
printResult(numberOfCarry);
}
}
private void printResult(int numberOfCarry) {
if(numberOfCarry == 0) {
System.out.println("No carry operation.");
} else if(numberOfCarry == 1) {
System.out.println("1 carry operation.");
} else {
System.out.println(String.format("%d carry operations.", numberOfCarry));
}
}
private int calculateResult(int firstNumber, int secondNumber) {
int totalCarry = 0;
int currentCarry = 0;
int firstShiftedNumber = firstNumber;
int secondShiftedNumber = secondNumber;
while(firstShiftedNumber != 0 || secondShiftedNumber != 0) {
int firstShiftedNumberModTen = firstShiftedNumber % 10;
int secondShiftedNumberModTen = secondShiftedNumber % 10;
if(firstShiftedNumberModTen + secondShiftedNumberModTen + currentCarry > 9) {
currentCarry = 1;
} else {
currentCarry = 0;
}
totalCarry += currentCarry;
firstShiftedNumber /= 10;
secondShiftedNumber /= 10;
}
return totalCarry;
}
}
|
"use strict";
module.exports = function(entity, game) { // eslint-disable-line no-unused-vars
console.log("right");
var slideX = game.entities.get(entity, "slideX");
delete slideX.onRight;
game.entities.remove(entity, "failure");
};
|
#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import time
import sys
from datetime import datetime
import glob
import os
from logreader import filtered_blinks
import sqlite3
duration = int(sys.argv[1])
interval = int(sys.argv[2])
graph = sys.argv[3]
db = sys.argv[4]
x = list()
y = list()
conn = sqlite3.connect(db)
c = conn.cursor()
for row in c.execute("""
select max(a.time),
ifnull( 3600.0*1000*(count(a.time)+1) /
( (select min(b.time) from wh b where b.time > max(a.time)) -
ifnull( (select max(b.time) from wh b where b.time < min(a.time)), 0)
),
3600.0*1000*count(a.time) /
( max(a.time) -
ifnull( (select max(b.time) from wh b where b.time < min(a.time)), 0)
)
),
((select max(d.time) from wh d) - a.time) / (?*1000) as bin
from wh a
where a.time > ((select max(c.time) from wh c) - ?*1000)
group by bin
order by max(a.time)
""", (interval, duration)):
x = x + [datetime.fromtimestamp(row[0]/1000.0)]
y = y + [row[1]]
conn.commit()
c = conn.cursor()
for row in c.execute("select max(a.time), ifnull( 3600.0*1000*(count(a.time)+1)/( (select min(b.time) from wh b where b.time > max(a.time)) - ifnull( (select max(b.time) from wh b where b.time < min(a.time)), 0 )), 3600.0*1000*count(a.time)/(max(a.time) - ifnull( (select max(b.time) from wh b where b.time < min(a.time)), 0 ) ) ), count(a.time)/1000.0, ifnull(3600.0*1000*count(a.time)/(max(a.time) - (select max(b.time) from wh b where b.time < min(a.time))), 0)*24*365/1000, ((select max(d.time) from wh d) - a.time)/(?*1000) as bin from wh a where a.time > ((select max(c.time) from wh c) - ?*1000) group by bin order by max(a.time)", (duration, duration)):
print str(int(row[1])) + " W"
print str(row[2]) + " kWh"
print str(int(row[3])) + " kWh/year"
conn.commit()
# Remove spikes in the graph
y2 = list(y)
for i in range(1, len(y)-1):
y2[i] = min(y[i], min(y[i-1], y[i+1]))
plt.plot(list(reversed(x)), list(reversed(y2)))
plt.gcf().autofmt_xdate()
plt.savefig(graph)
|
#!/usr/bin/env python
"""
This script can be used for running performance tests on an exported Eclipse.
Put the script in the directory that contains the "eclipse" folder of
the exported application.
@author: Tamas Borbas
"""
import subprocess
import shutil
from subprocess import TimeoutExpired
from subprocess import CalledProcessError
"""
TIMEOUT is in seconds
"""
CONST_TIMEOUT=1000
"""
RUNS determines how many times the same test is run
"""
CONST_RUNS=5
"""
Valid values for TRANSFORMATOR_TYPES:
"BATCH_SIMPLE",
"BATCH_OPTIMIZED",
"BATCH_INCQUERY",
"BATCH_VIATRA",
"INCR_QUERY_RESULT_TRACEABILITY",
"INCR_EXPLICIT_TRACEABILITY",
"INCR_AGGREGATED",
"INCR_VIATRA"
"""
TRANSFORMATOR_TYPES=[
"BATCH_SIMPLE",
"BATCH_OPTIMIZED",
"BATCH_INCQUERY",
"BATCH_VIATRA",
"INCR_QUERY_RESULT_TRACEABILITY",
"INCR_EXPLICIT_TRACEABILITY",
"INCR_AGGREGATED",
"INCR_VIATRA"
]
"""
SCALES are integers
"""
SCALES=[1,2,4,8,16,32,64,128,256,512]
"""
Valid values for GENERATOR_TYPES:
"TEMPLATE",
"JDT"
"""
GENERATOR_TYPES=["TEMPLATE","JDT"]
def flatten(lst):
return sum(([x] if not isinstance(x, list) else flatten(x) for x in lst), [])
def starteclipses():
for genType in GENERATOR_TYPES:
for trafoType in TRANSFORMATOR_TYPES:
for scale in SCALES:
timeoutOrError = False
for runIndex in range(1,CONST_RUNS+1):
print("Clearing workspace")
shutil.rmtree("workspace", ignore_errors=True)
print("Running test XFORM: ", trafoType, ", GENERATOR: ", genType, ", SCALE: ", str(scale), ", RUN: ", str(runIndex))
try:
subprocess.call(flatten(["eclipse\eclipse.exe", trafoType, str(scale), genType, str(runIndex)]), timeout=CONST_TIMEOUT)
except TimeoutExpired:
print(" >> Timed out after ", CONST_TIMEOUT, "s, continuing with the next transformation type.")
timeoutOrError = True
break
except CalledProcessError as e:
print(" >> Program exited with error, continuing with the next transformation type.")
timeoutOrError = True
break
if timeoutOrError:
break
if __name__ == "__main__":
starteclipses()
|
/**
* example-angularjs
* https://github.com/3lXample/example-angularjs
*
* Copyright (c) 2017 3lXample (https://github.com/3lXample)
* Licensed under the MIT license
*/
(function() {
'use strict';
var name = '3XApp';
var dependencies = [];
var module = angular.module(name, dependencies);
})();
|
#!/usr/bin/env python
#
# shellUIinput.py
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Sam Caldwell.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# This script creates a class to add interactive functionality
# to the shellUI. This class will instantiate a history class,
# a status window and a main window and orchestrate the user
# interactions with the two windows while maintaining a user
# history log for 'up-arrow' history retrieval.
#
import curses
from logger import logger
from shellUIwindow import shellUIwindow
from shellUIhistory import shellUIhistory
class shellUIinput:
__history=None
__log=None
__window=None
__status=None
__statusLine=''
__wRow=0
__wCol=0
__buffer=''
__prompt='#'
__hasCommand=False
def __init__(self,motd='Starting...',prompt='#'):
self.__statusLine=motd
self.__prompt=prompt
self.__log=logger('shellUIinput')
self.__history=shellUIhistory(10)
self.__status=shellUIwindow(n="status",sRow=0,sCol=0,szRows=1,szCols=80)
self.__window=shellUIwindow(n="window",sRow=self.__wRow,sCol=self.__wCol,szRows=20,szCols=80)
(self.__wRow,self.wCol)=self.__window.move(0,0)
self.__window.write(self.__prompt)
(self.__wRow,self.wCol)=self.__window.move(1,0)
self.__statusLine=self.__statusLine
self.__hasCommand=False
self.repaint()
def __del__(self):
self.__log=None
self.__history=None
self.__window=None
self.__status=None
def setStatus(self,m):
self.__statusLine=str(m)
self.updateStatus(m)
def updateStatus(self,m):
try:
if m!="":
self.__statusLine=m
self.__status.move(0,0)
fillChars=" " * ( 80 - len(self.__statusLine) -1)
self.__status.write( \
"Row:"+str(self.__wRow) + "," + \
"Col:"+str(self.__wCol) + "," + \
"Status:"+str(self.__statusLine)[0:(80-self.__wCol-len(self.__statusLine))] + fillChars \
)
self.__window.move(self.__wRow,self.__wCol)
except Exception as err:
self.__log.write("__updateStatus__(): " + str(err))
return m
def repaint(self):
fillString=" " * (80-len(self.__buffer)-2)
lineString=self.__prompt+self.__buffer+fillString
(self.__wRow,self.wCol)=self.__window.move(self.__wRow,0)
self.__window.write(lineString)
(self.__wRow,self.__wCol)=self.__window.move(self.__wRow,len(self.__buffer)+1)
self.updateStatus("")
def __actionBackspace__(self):
try:
self.__buffer=self.__buffer[0:len(self.__buffer)-1]
self.repaint()
except Exception as err:
raise Exception('on Backspace: '+str(err))
def __actionKeyRight__(self):
curses.beep()
def __actionKeyDown__(self):
try:
curses.beep()
pass
except Exception as err:
raise Exception('on KeyDown: ' + str(err))
def __actionKeyUp__(self):
try:
lastLine=self.__history.pop().strip()
if lastLine=="":
curses.beep()
else:
self.__buffer=lastLine
self.repaint(self.__buffer)
except Exception as err:
curses.beep()
def __actionKeyEnter__(self):
try:
if self.__buffer.strip() == "":
self.__log.write("Empty buffer")
else:
self.__history.push(self.__buffer.strip())
(self.__wRow,self.__wCol)=self.__window.move(self.__wRow+1,0)
self.repaint()
self.__hasCommand=True
return self.__buffer.strip()
except Exception as err:
raise Exception('on KeyEnter: ' + str(err))
def __actionKeyCapture__(self,ascii):
try:
try:
self.__buffer+=chr(ascii)
except Exception as err:
raise Exception('appending self.__buffer '+str(err))
self.repaint()
except Exception as err:
raise Exception('on anyKey: ' + str(err))
def getRow(self):
return self.__wRow
def getInput(self,startRow):
(self.__wRow,self.__wCol)=self.__window.move(startRow,0)
self.__buffer=''
try:
self.repaint()
while not self.__hasCommand:
self.updateStatus(self.__statusLine)
try:
ascii=self.__window.getch()
except Exception as err:
raise Exception('failed to get char from terminal. Err:'+str(err))
try:
if (ascii==curses.KEY_LEFT) or (ascii==127):
self.__actionBackspace__()
elif ascii==curses.KEY_RIGHT:
self.__actionKeyRight__()
elif ascii==curses.KEY_DOWN:
self.__actionKeyDown__()
elif ascii==curses.KEY_UP:
self.__actionKeyUp__()
elif ascii==13:
return self.__actionKeyEnter__()
break
else:
self.__actionKeyCapture__(ascii)
except Exception as err:
raise Exception('in eval char. Err:'+str(err))
except Exception as err:
self.__log.write("getInput() Err:"+str(err))
#
# Unit Testing
#
if __name__ == "__main__":
f=open('shellUIinput.log','a')
f.write("Unit Test starting\n")
ui=shellUIinput()
f.write("ui instantiated.\n")
f.write("ui.getInput() called.\n")
row=1
while True:
(row,dataString)=ui.getInput(row)
if dataString=="q":
break
f.write("ui.getInput() returned.\n")
f.write("Test complete\n")
f.close()
|
</div><form action="search.asp" name="form1" id="form1">
<table border="1" id="table1" style="border-collapse: collapse">
<tr>
<td height="25" align="center"><span style="font-size: 16px">明</span></td>
<td height="25" align="center"><span style="font-size: 16px">公元1549年</span></td>
<td height="25" align="center"><span style="font-size: 16px">己酉</span></td>
<td height="25px" align="center"><span style="font-size: 16px">嘉靖二十八年</span></td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>历史纪事</b> </td>
<td>
<div>俺答大举入寇
嘉靖二十八年(1549)二月,俺答大举入侵大同,直抵怀来。指挥江瀚、董旸迎战,力竭无援而亡。总兵周尚文率兵万人,追杀至曹家庄,大败俺答。宣府总兵赵国忠又败敌于滹沱。总督翁万达率精兵增援,俺答败退。
筑大同内外边
嘉靖二十八年(1549)四月二十日,总督翁万达请筑内外边,拟自新宁东路之新宁墩而北至六台子,别为内垣,一百六十九里有余,敌台三百零八,暗门十九,以重卫京师,控带北路。又东路镇南墩与蓟州火焰墩,中空未塞,而镇南而北、而西,亦原未议塞垣,俱宜补筑,以成全险。又请还乘塞之兵。其时,客兵承调,主兵摆边,自夏至冬,聚而不散,劳费数倍,甚觉不堪。故乘塞之客兵及远地主兵,入冬以后可以撤罢,本路土兵则仍其旧。世宗允准。
户部奏议宣府军饷
嘉靖二十八年(1549)六月六日,户部奏言,宣府官军,国初时三分城守,七分屯种,备操者只三万九千余名;正统以后,撤屯丁为操军;弘治间,增至五万八千余名;正德间,增至六万九千二百余名;今日增至八万四千五百余名。近年,军倍于昔,粮限于额,屯地多荒,塞上粟贵,子粒常蠲,岁派多逋。今查宣府镇岁入粮二十七万三千一百余石,银八十二万二千九百余两,除放折赏俸之外,所余无几。因此折色搭配,甚非得已。若尽放本色,计每年添粮二十一万余石,何以给之。但宜本色、折色通融兼支。从其议。
户部议岁征、岁收、岁支、岁储
嘉靖十八年(1549)八月二日,户部议复财赋。其时边费浩大,土木屡兴,祷祀频繁,以致帑藏匮竭,海内骚然。成化以前,一岁收入,沛然有余,今则不然。京通仓粮,嘉靖十年以前廪中常有八九年之积,至今所储仅余四年。太仓银库,岁入二百万两,先年一年大约所出一百三十三万两,常余六十七万两。嘉靖八年以前,内库积有四百余万两,外库积有一百余万两。近岁一年大约所出三百四十七万两,较之岁入常多一百四十七万两。年复一年,将至不可措手。请敕诸臣,专意清理,务求节财,每岁年终将一年出纳钱谷修成会计录,内分四顷,即岁征,岁收,岁支,岁储,务令简明,进呈御览。得旨允行。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>文化纪事</b> </td>
<td>
<div>增补《后湖志》
《后湖志》十一卷,赵官编辑于正德八年,万文彩增补于嘉靖二十八年(1549)。赵官,字惟贤,正德时历官南京户科给事中。万文彩为嘉靖二十七、八年南京户科给事中。全书十一卷。卷一至三为事迹。记述明代后湖沿革、形胜、黄册数目及明代户口、事产等。卷四至十为事例,记载了自洪武以来历代管理黄册官员的奏收。记述了明统治者通过黄册的编置,达到控制人口、稳定税收、确保差役的用心,记述了黄册制度的发生、发展的经过,反映了明代由盛到衰的变化。卷十一为诗文,描绘了南京玄武湖的胜景。后湖即南京太平门外的玄武湖,是收贮黄册的地方。《后湖志》保存了大量有关黄册制度的贵重资料,是明代黄册制度的专书。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>杂谭逸事</b> </td>
<td>
<div>盛端明致仕
盛端明(1470-1550),字希道,号程斋,饶平人。弘治十五年(1502)进士,历官中外,颇有声。晚年因进修仙方术而宠显,献《摄生集要》、《万年金鉴录》、《永寿真铨》等书,加官至太子少保礼部尚书。虽汲汲引退,然终为士论所不齿。嘉靖二十八年(1549)正月二十四日致仕,次年七月卒,赠太子太保,谥荣简。隆庆初年夺官。
朱纨罢官
朱纨(1493-1550),字子纯,号秋涯,长洲(今江苏苏州)人。正德十六年(1521)进士。历官知州。嘉靖初,累迁至广东布政使。嘉靖二十五年(1546)擢右副都御史,巡抚江西南安(今大余)、赣州。其时罢市舶,海防废弛,沿海豪族贵姓多与倭寇相通。嘉靖二十六年七月,朱纨改任浙江巡抚兼管福建海防军务。嘉靖二十七年四月,一举捣毁宁波府双屿港,接着破倭于海上。次年四月败倭于福建诏安,擒海盗九十六人,皆斩之,并穷治通倭豪右。因朱纨严禁私通外番,故闽浙巨家望族多恨之。闽人巡按御史周亮请改巡抚为巡视,以杀其权。嘉靖二十八年四月,御史陈九德劾其擅杀,世宗遂遣官按问,削其官职。次年,朱纨含愤服毒自杀,终年五十八岁。自此海防复废,倭患日重。其著作有《茂边纪事》、《甓余集》。
范鏓削籍
范鏓,字平甫,生卒不详,其先江西乐平人,迁沈阳,遂家焉。正德十二年(1517)进士。授工部主事。迁员外郎。嘉靖三年(1524),伏阙哭争“大礼”,下狱廷杖。由户部郎中改长芦盐运司同知,迁河南知府。岁大饥,开仓赈济,全活十余万,名由此显,迁两淮盐运使。条上盐政十要。历四川 参政,湖广按察使,浙江、河南左、右布政使。嘉靖二十年,擢右副都御史,巡抚宁夏。起抚河南,召为兵部左侍郎,奉诏经理两关。嘉靖二十八年四月十七日,兵部尚书赵廷瑞罢,命鏓入代,鏓以老辞,世宗责其不恭,削籍为民,久之乃卒。隆庆元年复官。
周尚文逝世
周尚文(1475-1549),字彦章,西安后卫人。年十六,袭指挥同知。弘治、正德间,屡出塞有功,进指挥使。嘉靖初年,任凉州副总兵,后拜征西将军宁夏总兵官,又镇山西、延绥,俱有战功,进都督同知。嘉靖二十年(1541)召入提督团营听征,进后府右都督掌府事。出镇大同,条上御敌四十余事,修补墙堡七百里,垦田五万顷。与吉囊战墨山,杀其子满罕,大败之,进左都督,又败敌于宣府曹家庄。累加阶至太保兼太子太傅,荫子锦衣世千户。终明之世,总兵官加三公者,惟周尚文一人。嘉靖二十八年五月六日病卒,年七十五。周尚文多谋善战,清廉爱士,故战辄胜,为一时名将。然因曾与严嵩父子相抗,故死后恤典为其所阻,至隆庆初,始赠太傅,谥武襄。
沈束下狱
沈束(1514-1581),字宗安,号梅冈,会稽(今浙江绍兴)人。嘉靖二十三年(1544)进士,除徽州推官,擢礼科给事中。时大学士严嵩擅政。大同总兵周尚文卒,请恤典。严嵩因周尚文曾劾其子严世蕃骄蹇不法,怀恨在心,遂格不予。嘉靖二十八年(1549)五月十日,沈束上言,“尚文为将,忠义自许。曹家庄之役,奇功也。虽晋秩,未酬勋,宜赠封爵延子孙。”并斥严嵩为“当事之臣,任意予夺,冒滥或倖蒙,忠勤反捐弃,何以鼓士气,激军心?”疏入,严嵩大恚,激世宗怒,杖沈于廷,锢于诏狱。沈束在狱十八年,世宗令狱卒每天奏报沈束语言食息,谓之监帖,或无所得,虽谐语亦以闻。一天,有喜鹊鼓噪于束前,沈束问道:“岂有喜及罪人耶?”狱卒奏闻,帝心动,释沈束出狱。隆庆初,复官不赴。万历九年(1581)卒于家。
赵廷瑞逝世
赵廷瑞(1492-1549),字信臣,号洪洋,直隶开州人,正德十六年(1521)进士,改翰林院庶吉士,授给事中,累迁副都御史巡抚陕西,进兵部右侍郎,巡抚如故。改户部右侍郎总督宣大山西军饷,改兵部左侍郎。嘉靖二十六年(1547)擢南京户部尚书,未及行,改兵部尚书。嘉靖二十八年三月,以边功晋太子少保,引疾求去,上疑其畏难避事,令革职闲住。当年六月二日病逝。
议决京营事宜
嘉靖二十八年(1549)六月九日,兵科给事中张廷槐疏陈京营坐营等官多营私罔利,培克诛求,以致行伍渐虚,士马消耗。以前听征兵号十二万,今括为两官厅仅三万六千,且老弱居十分之三,武备废弛,此乃失之择人之过。团营专官之设,似不容已。得旨,仍由兵部尚书兼理,不必增置。其时,给事中张侃亦陈营务四事:一,复重臣;二,久任用;慎选补;四,重马政。得旨,各营军少官多,兵部即议查革。兵部议,五军、神机二营,把总官可存者五十九,可革去者三十六。诏如议。
崔元逝世
崔元(1478-1549),字懋仁,号岱屏,代州人,永康大长公主之夫,封爵至太傅兼太子太傅驸马都尉京山候。世宗入继帝位,崔元奉金符迎銮于兴王府,故宠眷隆渥,诸勋臣戚畹莫敢比望。嘉靖二十八年(1549)六月十三日逝世,赠左柱国,谥荣恭。
闻渊致仕
闻渊(1480-1563),字静中,号石塘,鄞人,弘治十八年(1505)进士,历官礼部主事,刑部主事,考功郎中,文选郎中。嘉靖初,进应天府、顺天府尹,累迁南京兵部、刑部侍郎,进南京刑部、吏部尚书。嘉靖二十一年(1542)召为刑部尚书,嘉靖二十六年进吏部尚书,累加太子太保。时严嵩势横,侵夺部权,数以小过夺闻渊俸。嘉靖二十八年九月十二日,以年七十,请乞致仕,许之。家居十四年卒。赠少保,谥庄简。
詹荣闲住
詹荣(1500-1551),字仁甫,号角山,山海卫人。嘉靖五年(1526)进士。授户部主事,历郎中。督饷大同,值兵变,詹荣计擒之,擢光禄寺少卿,再迁太常寺卿。嘉靖二十二年,以右佥都御史巡抚甘肃。逾年,移大同,因功进右副都御史。筑大同边墙一百三十八里,筑堡七所,墩台一百五十四座,召军佃作边地,免其租徭。进兵部右侍郎,署部事。嘉靖二十八年十月二十五日以疾乞休,夺职闲住。嘉靖三十年十二月十二日卒。万历中,赠工部尚书。
呈报宗藩人数
宗人府上玉牒,嘉靖二十八年(1549),亲王至庶人现在一万九千八百九十三人,其阳曲、永和二府及南京齐庶人、建庶人后,不下千人。郡主、县主、郡君、乡君等共九千七百八十二人。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>注释</b></td>
<td>
<div></div></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr></table>
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
from telemetry.core import exceptions
from telemetry.internal.backends.chrome_inspector import inspector_backend_list
from telemetry.internal.browser import tab
import py_utils
class TabUnexpectedResponseException(exceptions.DevtoolsTargetCrashException):
pass
class TabListBackend(inspector_backend_list.InspectorBackendList):
"""A dynamic sequence of tab.Tabs in UI order."""
def __init__(self, browser_backend):
super(TabListBackend, self).__init__(browser_backend)
def New(self, timeout):
"""Makes a new tab.
Returns:
A Tab object.
Raises:
devtools_http.DevToolsClientConnectionError
"""
if not self._browser_backend.supports_tab_control:
raise NotImplementedError("Browser doesn't support tab control.")
response = self._browser_backend.devtools_client.RequestNewTab(timeout)
try:
response = json.loads(response)
context_id = response['id']
except (KeyError, ValueError):
raise TabUnexpectedResponseException(
app=self._browser_backend.browser,
msg='Received response: %s' % response)
return self.GetBackendFromContextId(context_id)
def CloseTab(self, tab_id, timeout=300):
"""Closes the tab with the given debugger_url.
Raises:
devtools_http.DevToolsClientConnectionError
devtools_client_backend.TabNotFoundError
TabUnexpectedResponseException
py_utils.TimeoutException
"""
assert self._browser_backend.supports_tab_control
# TODO(dtu): crbug.com/160946, allow closing the last tab on some platforms.
# For now, just create a new tab before closing the last tab.
if len(self) <= 1:
self.New(timeout)
response = self._browser_backend.devtools_client.CloseTab(tab_id, timeout)
if response != 'Target is closing':
raise TabUnexpectedResponseException(
app=self._browser_backend.browser,
msg='Received response: %s' % response)
py_utils.WaitFor(lambda: tab_id not in self.IterContextIds(), timeout=5)
def ActivateTab(self, tab_id, timeout=30):
"""Activates the tab with the given debugger_url.
Raises:
devtools_http.DevToolsClientConnectionError
devtools_client_backend.TabNotFoundError
TabUnexpectedResponseException
"""
assert self._browser_backend.supports_tab_control
response = self._browser_backend.devtools_client.ActivateTab(tab_id,
timeout)
if response != 'Target activated':
raise TabUnexpectedResponseException(
app=self._browser_backend.browser,
msg='Received response: %s' % response)
def Get(self, index, ret):
"""Returns self[index] if it exists, or ret if index is out of bounds."""
if len(self) <= index:
return ret
return self[index]
def ShouldIncludeContext(self, context):
if 'type' in context:
return (context['type'] == 'page' or
context['url'] == 'chrome://media-router/')
# TODO: For compatibility with Chrome before r177683.
# This check is not completely correct, see crbug.com/190592.
return not context['url'].startswith('chrome-extension://')
def CreateWrapper(self, inspector_backend):
return tab.Tab(inspector_backend, self, self._browser_backend.browser)
def _HandleDevToolsConnectionError(self, error):
if not self._browser_backend.IsAppRunning():
error.AddDebuggingMessage('The browser is not running. It probably '
'crashed.')
elif not self._browser_backend.HasBrowserFinishedLaunching():
error.AddDebuggingMessage('The browser exists but cannot be reached.')
else:
error.AddDebuggingMessage('The browser exists and can be reached. '
'The devtools target probably crashed.')
|
# Django settings for celery_http_gateway project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
CARROT_BACKEND = "amqp"
CELERY_RESULT_BACKEND = "database"
BROKER_URL = "amqp://guest:guest@localhost:5672//"
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
# 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_ENGINE = 'sqlite3'
# path to database file if using sqlite3.
DATABASE_NAME = 'development.db'
# Not used with sqlite3.
DATABASE_USER = ''
# Not used with sqlite3.
DATABASE_PASSWORD = ''
# Set to empty string for localhost. Not used with sqlite3.
DATABASE_HOST = ''
# Set to empty string for default. Not used with sqlite3.
DATABASE_PORT = ''
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '#1i=edpk55k3781$z-p%b#dbn&n+-rtt83pgz2o9o)v8g7(owq'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'celery_http_gateway.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'djcelery',
)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
import django.contrib.auth.models
import accounts.models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name='Tutorial',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(help_text='The name of the tutorial', max_length=100, blank=True)),
],
),
migrations.CreateModel(
name='User',
fields=[
('user_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
('mat_number', models.IntegerField(blank=True, null=True, validators=[accounts.models.validate_mat_number])),
('final_grade', models.CharField(help_text='The final grade for the whole class.', max_length=100, null=True, blank=True)),
('programme', models.CharField(help_text='The programme the student is enlisted in.', max_length=100, null=True, blank=True)),
('activation_key', models.CharField(verbose_name='activation key', max_length=40, editable=False)),
('tutorial', models.ForeignKey(blank=True, to='accounts.Tutorial', help_text='The tutorial the student belongs to.', null=True)),
],
options={
'ordering': ['first_name', 'last_name'],
},
bases=('auth.user',),
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.AddField(
model_name='tutorial',
name='tutors',
field=models.ManyToManyField(help_text='The tutors in charge of the tutorium.', related_name='tutored_tutorials', to='accounts.User'),
),
]
|
<?php
/**
* This loads and initializes the Stripe API.
*/
Stripe::setApiKey (Appconf::stripe ('Stripe', 'secret_key'));
?>
|
<?php
/******************************************************
This file is part of OpenWebSoccer-Sim.
OpenWebSoccer-Sim is free software: you can redistribute it
and/or modify it under the terms of the
GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or any later version.
OpenWebSoccer-Sim is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with OpenWebSoccer-Sim.
If not, see <http://www.gnu.org/licenses/>.
******************************************************/
/**
* @author Ingo Hofmann
*/
class FinancesModel implements IModel {
private $_db;
private $_i18n;
private $_websoccer;
public function __construct($db, $i18n, $websoccer) {
$this->_db = $db;
$this->_i18n = $i18n;
$this->_websoccer = $websoccer;
}
public function renderView() {
return TRUE;
}
public function getTemplateParameters() {
$teamId = $this->_websoccer->getUser()->getClubId($this->_websoccer, $this->_db);
if ($teamId < 1) {
throw new Exception($this->_i18n->getMessage("feature_requires_team"));
}
$team = TeamsDataService::getTeamSummaryById($this->_websoccer, $this->_db, $teamId);
$count = BankAccountDataService::countAccountStatementsOfTeam($this->_websoccer, $this->_db, $teamId);
$eps = $this->_websoccer->getConfig("entries_per_page");
$paginator = new Paginator($count, $eps, $this->_websoccer);
if ($count > 0) {
$statements = BankAccountDataService::getAccountStatementsOfTeam($this->_websoccer, $this->_db, $teamId, $paginator->getFirstIndex(), $eps);
} else {
$statements = array();
}
return array("budget" => $team["team_budget"], "statements" => $statements, "paginator" => $paginator);
}
}
?>
|
MOVIEXP.Link = function () {
this.links = [];
}
MOVIEXP.Link.prototype.build = function (nodes) {
var dubs = {},
roots = [],
nlength = nodes.length;
for (var i = 0; i < nlength; i ++) {
var n = nodes[i];
if (n.type === 'base') {
} else {
if (!dubs[n.name]) {
dubs[n.name] = n;
} else {
dubs[n.name]['group'].push(n.group[0]);
}
}
}
nodes = [];
for (var key in dubs) {
nodes.push(dubs[key]);
}
nlength = nodes.length;
for (var i = 0; i < nlength; i++) {
var n = nodes[i];
if (n.root) {
var root = {};
root['group'] = n.group;
root['index'] = i;
roots.push(root);
}
}
var rlength = roots.length;
for (var i = 0; i < nlength; i++) {
var glength = nodes[i]['group'].length;
if (glength > 1 && nodes[i]['root'] === undefined) {
for (var k = 0; k < glength; k++) {
for (var j = 0; j < rlength; j++) {
if (nodes[i]['group'][k] === roots[j].group[0]) {
this.addLink(i, roots[j].index, "red", 300);
}
}
}
} else {
for (var j = 0; j < rlength; j++) {
if (nodes[i]['group'][0] === roots[j].group[0]) {
this.addLink(i, roots[j].index, "#ccc", 100);
}
}
}
}
var data = {'nodes':nodes, 'links':this.links};
return data;
}
MOVIEXP.Link.prototype.addLink = function (source, dest, color, dist) {
var link = {};
link['source'] = source;
link['target'] = dest;
link['dist'] = dist;
link['color'] = color;
this.links.push(link);
}
|
//this function is for switch To Primary Window when using FB, twitter, google+
exports.command = function ( socialmedia ) {
this.windowHandles( function ( newwindow ) {
var new_handle = newwindow.value[ 0 ];
this.switchWindow( new_handle );
} ).
//check whether the new window open a facebook link
verify.urlContains( socialmedia ).pause( 2000 ).windowMaximize();
return this;
};
|
#
# Copyright 2012 New Dream Network, LLC (DreamHost)
#
# Author: Doug Hellmann <[email protected]>
#
# 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.
"""Tests for ceilometer/storage/impl_log.py
"""
from oslotest import base
from ceilometer.storage import impl_log
class ConnectionTest(base.BaseTestCase):
def test_get_connection(self):
conn = impl_log.Connection(None)
conn.record_metering_data({'counter_name': 'test',
'resource_id': __name__,
'counter_volume': 1,
})
|
/**
File:
Quaternion.cpp
Author:
Ethem Kurt (BigETI)
*/
#include "../stdafx.h"
const Quaternion Quaternion::identity(CVector3::null, 1.0f);
Quaternion::Quaternion() : vp(CVector3::null), w(1.0f)
{
//
}
Quaternion::Quaternion(const Quaternion & q) : vp(q.vp), w(q.w)
{
//
}
Quaternion::Quaternion(const CVector3 & _vp, float_t _w) : vp(_vp), w(_w)
{
//
}
Quaternion::Quaternion(float_t x, float_t y, float_t z, float_t _w) : vp(x, y, z), w(_w)
{
//
}
Quaternion::~Quaternion()
{
//
}
Quaternion Quaternion::FromEuler(const CVector3 & euler)
{
float_t xh = euler.x * 0.5f,
yh = euler.y * 0.5f,
zh = euler.z * 0.5f,
sxh = sin(xh), cxh = cos(xh),
syh = sin(yh), cyh = cos(yh),
szh = sin(zh), czh = cos(zh);
return Quaternion(((czh * syh) * cxh) + ((szh * cyh) * sxh), ((szh * cyh) * cxh) - ((czh * syh) * sxh), ((czh * cyh) * sxh) - ((szh * syh) * cxh), ((czh * cyh) * cxh) + ((szh * syh) * sxh));
}
Quaternion Quaternion::FromEulerDegrees(const CVector3 & euler_degrees)
{
CVector3 e(euler_degrees);
e *= PI;
e /= 180.0f;
return FromEuler(e);
}
Quaternion & Quaternion::operator=(const Quaternion & q)
{
vp = q.vp;
w = q.w;
}
Quaternion & Quaternion::operator*=(const Quaternion & q)
{
Quaternion t(((vp.x * q.w) + (q.vp.x * w)) + ((vp.y * q.vp.z) - (vp.z * q.vp.y)),
((vp.y * q.w) + (q.vp.y * w)) + ((vp.z * q.vp.x) - (vp.x * q.vp.z)),
((vp.z * q.w) + (q.vp.z * w)) + ((vp.x * q.vp.y) - (vp.y * q.vp.x)),
(w * q.w) - (((vp.x * q.vp.x) + (vp.y * q.vp.y)) + (vp.z * q.vp.z)));
(*this) = t;
return (*this);
}
Quaternion & Quaternion::operator/=(const Quaternion & q)
{
float_t _1_ms = 1.0f / ((((q.vp.x * q.vp.x) + (q.vp.y * q.vp.y)) + (q.vp.z * q.vp.z)) + (q.w * q.w));
CVector3 _1_ms_nqvp(-q.vp.x * _1_ms, -q.vp.y * _1_ms, -q.vp.z * _1_ms);
float_t _1_ms_w = q.w * _1_ms;
Quaternion t(((vp.x * _1_ms_w) + (_1_ms_nqvp.x * w)) + ((vp.y * _1_ms_nqvp.z) - (vp.z * _1_ms_nqvp.y)),
((vp.y * _1_ms_w) + (_1_ms_nqvp.y * w)) + ((vp.z * _1_ms_nqvp.x) - (vp.x * _1_ms_nqvp.z)),
((vp.z * _1_ms_w) + (_1_ms_nqvp.z * w)) + ((vp.x * _1_ms_nqvp.y) - (vp.y * _1_ms_nqvp.x)),
(w * _1_ms_w) - (((vp.x * _1_ms_nqvp.x) + (vp.y * _1_ms_nqvp.y)) + (vp.z * _1_ms_nqvp.z)));
(*this) = t;
return (*this);
}
Quaternion & Quaternion::operator*(const Quaternion & q)
{
return Quaternion(*this) * q;
}
Quaternion & Quaternion::operator/(const Quaternion & q)
{
return Quaternion(*this) / q;
}
void Quaternion::Conjugate()
{
vp.Negate();
}
Quaternion Quaternion::CreateConjugated()
{
Quaternion ret(*this);
ret.Conjugate();
return ret;
}
void Quaternion::Negate()
{
vp.Negate();
w = -w;
}
Quaternion Quaternion::CreateNegated()
{
Quaternion ret(*this);
ret.Negate();
return ret;
}
void Quaternion::Inverse()
{
float_t _1_ms = 1.0f / (vp.MagnitudeSquared() + (w * w));
Quaternion t(-vp.x * _1_ms,
-vp.y * _1_ms,
-vp.z * _1_ms,
w * _1_ms);
(*this) = t;
}
Quaternion Quaternion::CreateInversed()
{
Quaternion ret(*this);
ret.Inverse();
return ret;
}
CVector3 Quaternion::ToEuler()
{
float_t ys = vp.y * vp.y,
ysin = 2.0f * ((w * vp.y) - (vp.z * vp.x));
ysin = ysin > 1.0f ? 1.0f : (ysin < -1.0f ? -1.0f : ysin);
return CVector3(atan2(2.0f * ((w * vp.x) + (vp.y * vp.z)), 1.0f - (2.0f * ((vp.x * vp.x) + ys))),
asin(ysin),
atan2(2.0f * (w * vp.z + vp.x * vp.y), 1.0f - (2.0f * (ys + vp.z * vp.z))));
}
CVector3 Quaternion::ToEulerDegrees()
{
return (ToEuler() * 180.0f) / PI;
}
|
# -*- coding: utf-8 -*-
"""Classes to represent a Windows Message Resource file."""
import logging
import pyexe
import pywrc
# pylint: disable=logging-format-interpolation
class MessageResourceFile(object):
"""Class that defines a Windows Message Resource file."""
_RESOURCE_IDENTIFIER_STRING = 0x06
_RESOURCE_IDENTIFIER_MESSAGE_TABLE = 0x0b
_RESOURCE_IDENTIFIER_VERSION = 0x10
def __init__(
self, windows_path, ascii_codepage='cp1252',
preferred_language_identifier=0x0409):
"""Initializes the Windows Message Resource file.
Args:
windows_path (str): normalized version of the Windows path.
ascii_codepage (Optional[str]): ASCII string codepage.
preferred_language_identifier (Optional[int]): preferred language
identifier (LCID).
"""
super(MessageResourceFile, self).__init__()
self._ascii_codepage = ascii_codepage
self._exe_file = pyexe.file()
self._exe_file.set_ascii_codepage(self._ascii_codepage)
self._file_object = None
self._file_version = None
self._is_open = False
self._preferred_language_identifier = preferred_language_identifier
self._product_version = None
self._wrc_stream = pywrc.stream()
# TODO: wrc stream set codepage?
self.windows_path = windows_path
def _GetVersionInformation(self):
"""Determines the file and product version."""
version_resource = self._wrc_stream.get_resource_by_identifier(
self._RESOURCE_IDENTIFIER_VERSION)
if not version_resource:
return
file_version = None
product_version = None
language_identifier = self._preferred_language_identifier
if language_identifier in version_resource.language_identifiers:
file_version = version_resource.get_file_version(language_identifier)
product_version = version_resource.get_product_version(
language_identifier)
if not file_version or not product_version:
for language_identifier in version_resource.language_identifiers:
file_version = version_resource.get_file_version(language_identifier)
product_version = version_resource.get_product_version(
language_identifier)
if file_version and product_version:
break
self._file_version = '{0:d}.{1:d}.{2:d}.{3:d}'.format(
(file_version >> 48) & 0xffff, (file_version >> 32) & 0xffff,
(file_version >> 16) & 0xffff, file_version & 0xffff)
self._product_version = '{0:d}.{1:d}.{2:d}.{3:d}'.format(
(product_version >> 48) & 0xffff, (product_version >> 32) & 0xffff,
(product_version >> 16) & 0xffff, product_version & 0xffff)
if file_version != product_version:
logging.warning((
'Mismatch between file version: {0:s} and product version: '
'{1:s} in message file: {2:s}.').format(
self._file_version, self._product_version, self.windows_path))
@property
def file_version(self):
"""str: the file version."""
if self._file_version is None:
self._GetVersionInformation()
return self._file_version
@property
def product_version(self):
"""str: the product version."""
if self._product_version is None:
self._GetVersionInformation()
return self._product_version
def Close(self):
"""Closes the Windows Message Resource file.
Raises:
IOError: if not open.
OSError: if not open.
"""
if not self._is_open:
raise IOError('Not opened.')
self._wrc_stream.close()
self._exe_file.close()
self._file_object = None
self._is_open = False
def GetMessageTableResource(self):
"""Retrieves the message table resource.
Returns:
pywrc.message_table: message table resource or None if not available.
"""
return self._wrc_stream.get_resource_by_identifier(
self._RESOURCE_IDENTIFIER_MESSAGE_TABLE)
def GetMUILanguage(self):
"""Retrieves the MUI language.
Returns:
str: MUI language or None if not available.
"""
mui_resource = self._wrc_stream.get_resource_by_name('MUI')
if not mui_resource:
return None
mui_language = None
language_identifier = self._preferred_language_identifier
if language_identifier in mui_resource.language_identifiers:
mui_language = mui_resource.get_language(language_identifier)
if not mui_language:
for language_identifier in mui_resource.language_identifiers:
mui_language = mui_resource.get_language(language_identifier)
if mui_language:
break
return mui_language
def GetStringResource(self):
"""Retrieves the string resource.
Returns:
pywrc.string: string resource or None if not available.
"""
return self._wrc_stream.get_resource_by_identifier(
self._RESOURCE_IDENTIFIER_STRING)
def OpenFileObject(self, file_object):
"""Opens the Windows Message Resource file using a file-like object.
Args:
file_object (file): file-like object.
Returns:
bool: True if successful or False if not.
Raises:
IOError: if already open.
OSError: if already open.
"""
if self._is_open:
raise IOError('Already open.')
self._exe_file.open_file_object(file_object)
exe_section = self._exe_file.get_section_by_name('.rsrc')
if not exe_section:
self._exe_file.close()
return False
self._wrc_stream.set_virtual_address(exe_section.virtual_address)
self._wrc_stream.open_file_object(exe_section)
self._file_object = file_object
self._is_open = True
return True
|
from corehq.apps.reports.filters.base import BaseMultipleOptionFilter, BaseReportFilter
from custom.zipline.models import EmergencyOrderStatusUpdate
class EmergencyOrderStatusChoiceFilter(BaseMultipleOptionFilter):
slug = 'statuses'
label = 'Status'
@property
def options(self):
statuses = dict(EmergencyOrderStatusUpdate.STATUS_CHOICES)
return [
(EmergencyOrderStatusUpdate.STATUS_PENDING, statuses[EmergencyOrderStatusUpdate.STATUS_PENDING]),
(EmergencyOrderStatusUpdate.STATUS_ERROR, statuses[EmergencyOrderStatusUpdate.STATUS_ERROR]),
(EmergencyOrderStatusUpdate.STATUS_RECEIVED, statuses[EmergencyOrderStatusUpdate.STATUS_RECEIVED]),
(EmergencyOrderStatusUpdate.STATUS_REJECTED, statuses[EmergencyOrderStatusUpdate.STATUS_REJECTED]),
(EmergencyOrderStatusUpdate.STATUS_APPROVED, statuses[EmergencyOrderStatusUpdate.STATUS_APPROVED]),
(EmergencyOrderStatusUpdate.STATUS_CANCELLED, statuses[EmergencyOrderStatusUpdate.STATUS_CANCELLED]),
(EmergencyOrderStatusUpdate.STATUS_DISPATCHED, statuses[EmergencyOrderStatusUpdate.STATUS_DISPATCHED]),
(EmergencyOrderStatusUpdate.STATUS_DELIVERED, statuses[EmergencyOrderStatusUpdate.STATUS_DELIVERED]),
(EmergencyOrderStatusUpdate.STATUS_CONFIRMED, statuses[EmergencyOrderStatusUpdate.STATUS_CONFIRMED]),
(EmergencyOrderStatusUpdate.STATUS_CANCELLED_BY_USER,
statuses[EmergencyOrderStatusUpdate.STATUS_CANCELLED_BY_USER]),
]
class EmergencyPackageStatusChoiceFilter(EmergencyOrderStatusChoiceFilter):
@property
def options(self):
statuses = dict(EmergencyOrderStatusUpdate.STATUS_CHOICES)
return [
(EmergencyOrderStatusUpdate.STATUS_DISPATCHED, statuses[EmergencyOrderStatusUpdate.STATUS_DISPATCHED]),
(EmergencyOrderStatusUpdate.STATUS_DELIVERED, statuses[EmergencyOrderStatusUpdate.STATUS_DELIVERED]),
(EmergencyOrderStatusUpdate.STATUS_CANCELLED_IN_FLIGHT,
statuses[EmergencyOrderStatusUpdate.STATUS_CANCELLED_IN_FLIGHT]),
]
class OrderIdFilter(BaseReportFilter):
slug = 'order_id'
label = 'Order id'
template = 'ilsgateway/filters/order_id_filter.html'
@property
def filter_context(self):
return {
'value': self.get_value(self.request, self.domain),
'slug': self.slug,
'input_css_class': self.css_class
}
|
var request = require('request')
var getRows = function(rows){
var merged = [];
if ( typeof rows !== 'undefined' && rows )
{
for(var i=0; i<rows.length; i++) {
merged = merged.concat(rows[i]['rows']);
}
}
return merged
}
var Lanyrd = {
get: function (path, cb){
var opts = {
url: 'http://lanyrd.com/mobile/ios2/'+path,
json: true,
headers: {
'X-Lanyrd-Auth': Math.random().toString()
}}
request(opts, cb)
},
popular: function (cb){
this.get('search/', function(error, response, body){
cb(error, response, body['sections'][0]['rows'])
})
},
search: function (query, cb){
this.get('search/?query='+query, function(error, response, body){
cb(error, response, body['sections'][0]['rows'])
})
},
event: function (slug, year, cb){
this.get(year +'/' + slug + '/', function(error, response, body){
cb(error, response, body)
})
},
speakers: function (slug, year, cb){
this.get(year +'/' + slug + '/speakers/', function(error, response, body){
cb(error, response, getRows(body['sections']))
})
},
attendees: function (slug, year, cb){
this.get(year +'/' + slug + '/attendees/', function(error, response, body){
cb(error, response, getRows(body['sections']))
})
},
schedule: function (slug, year, cb){
this.get(year +'/' + slug + '/schedule/', function(error, response, body){
cb(error, response, getRows(body['sections']))
})
},
scheduleDetail: function (date, slug, year, cb){
this.get(year +'/' + slug + '/schedule/' + date, function(error, response, body){
cb(error, response, getRows(body['sections']))
})
},
profile: function (username, cb){
this.get('profile/' + username + '/', function(error, response, body){
cb(error, response, body)
})
},
futureEvents: function (username, cb){
this.get('profile/' + username + '/action/', function(error, response, body){
cb(error, response, body['events'])
})
}
}
module.exports = Lanyrd
|
var gulp = require('gulp'),
concat = require('gulp-concat'),
lint = require('gulp-jslint'),
uglify = require('gulp-uglify'),
ngAnnotate = require('gulp-ng-annotate'),
del = require('del'),
SOURCES = 'src/**/*.js';
gulp.task('cleanDist', function(cb) {
del(['dist/*'], cb);
});
gulp.task('build', ['lint', 'cleanDist'], function () {
return gulp.src(['src/named-route-module.js', SOURCES])
.pipe(ngAnnotate())
.pipe(concat('angular-named-route.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('lint', function () {
return gulp.src(SOURCES)
.pipe(lint({
global: ['angular'],
browser: true,
devel: true,
todo: true,
noempty: false,
plusplus: true,
unparam: true //I like to include all callback params even if they're not used
}));
});
|
using System;
using System.ComponentModel.DataAnnotations;
namespace DataService.Entities.Pedagogy
{
/// <summary>
/// Ticket d'Absence ou de Retard
/// </summary>
public class AbsenceTicket
{
/// <summary>
/// Presence a un cours
/// </summary>
[Key]
public Guid AbsenceTicketGuid { get; set; }
/// <summary>
/// ID de la person => StudentGuid ou StaffGuid
/// </summary>
public Guid PersonGuid { get; set; }
/// <summary>
///
/// </summary>
public Guid CoursGuid { get; set; }
/// <summary>
/// La Date de La journee de Presence
/// </summary>
public DateTime? CoursDate { get; set; }
/// <summary>
/// Bool Present ?
/// </summary>
public bool IsPresent { get; set; } = true;
/// <summary>
/// Retard en Minute
/// </summary>
public TimeSpan RetardTime { get; set; } = new TimeSpan(0);
}
}
|
"use strict";
var log = require( "../class.log" );
var realmConfig = require( "../../config.realm" ).config;
var quest = require( "../class.quest" );
var npcBehaviors = require( "../class.npcBehaviors" );
var achievementsLibrary = require( "../class.achievementsLibrary" );
var timerObject = require( "../class.timer" ).timer;
exports.script = function( npcObject )
{
//
// Variables
//
var _iO = npcObject.getArgs().createdByInstanceObject,
_cooldownPointer = null;
var thisCharacterObjectConstant_1 = npcObject;
var achievementIdConstant_37 = 8;
var achievementParameterNameConstant_38 = "q8_1Stalkerskilled";
var numberConstant_39 = 4;
var pathConstant_43 = [{"x":596,"y":811},{"x":671,"y":878},{"x":498,"y":943},{"x":459,"y":931},{"x":567,"y":831},{"x":450,"y":721},{"x":581,"y":656},{"x":559,"y":775}];
var questIdConstant_48 = 75;
var questParameterNameConstant_49 = "q75_1ForlornStalkersKilled";
var numberConstant_50 = 1;
var timerObjectConstant_54 = new timerObject({ instanceObject: _iO });
var positiveNumberConstant_55 = 30000;
var positiveNumberConstant_56 = 45000;
//
// Events override
//
npcObject.events._add( "afterInit", function( args )
{
new npcBehaviors.npcPatrolAggressiveLoop.enable({
npcObject: thisCharacterObjectConstant_1,
movePath: pathConstant_43,
});
});
npcObject.events._add( "die", function( args )
{
var byCharacterObject_6 = args.byCharacterObject;
achievementsLibrary.achievementConditionUpdate(
{
characterObject: thisCharacterObjectConstant_1,
achievementId: achievementIdConstant_37,
parameterName: achievementParameterNameConstant_38,
value: numberConstant_39,
}
);
quest.questConditionUpdate(
{
characterObject: byCharacterObject_6,
questId: questIdConstant_48,
parameterName: questParameterNameConstant_49,
value: numberConstant_50,
}
);
timerObjectConstant_54.startTimer({
minDelay: positiveNumberConstant_55,
maxDelay: positiveNumberConstant_56,
onFinalize: function( args )
{
thisCharacterObjectConstant_1.resurrect({
resurrectCharacterObject: thisCharacterObjectConstant_1
});
},
});
});
//
// Post all objects initialisation
//
this.postInit = function()
{
}
//
// Initialize
//
// bind to instance
npcObject.events._add( "afterInit", function( args )
{
npcObject.bindToInstance( _iO, function() { } );
});
}
|
/* radare - LGPL - Copyright 2008-2014 - pancake */
/* TODO: write li->fds setter/getter helpers */
// TODO: return true/false everywhere,, not -1 or 0
// TODO: use RList here
#include "r_io.h"
#include "../config.h"
#include "list.h"
#include <stdio.h>
volatile static RIOPlugin *DEFAULT = NULL;
static RIOPlugin *io_static_plugins[] =
{ R_IO_STATIC_PLUGINS };
R_API int r_io_plugin_add(RIO *io, RIOPlugin *plugin) {
struct r_io_list_t *li;
if (!plugin || !plugin->name)
return R_FALSE;
li = R_NEW (struct r_io_list_t);
if (li == NULL)
return R_FALSE;
li->plugin = plugin;
list_add_tail (&(li->list), &(io->io_list));
return R_TRUE;
}
R_API int r_io_plugin_init(RIO *io) {
RIOPlugin *static_plugin;
int i;
INIT_LIST_HEAD (&io->io_list);
for (i=0; io_static_plugins[i]; i++) {
if (!io_static_plugins[i]->name)
continue;
static_plugin = R_NEW (RIOPlugin);
// memory leak here: static_plugin never freed
memcpy (static_plugin, io_static_plugins[i], sizeof (RIOPlugin));
if (!strncmp (static_plugin->name, "default", 7)) {
if (DEFAULT) free ((void*)DEFAULT);
DEFAULT = static_plugin;
continue;
}
r_io_plugin_add (io, static_plugin);
}
return R_TRUE;
}
R_API RIOPlugin *r_io_plugin_get_default(RIO *io, const char *filename, ut8 many) {
if (!DEFAULT ||
!DEFAULT->plugin_open ||
!DEFAULT->plugin_open (io, filename, many) ) return NULL;
return (RIOPlugin*) DEFAULT;
}
R_API RIOPlugin *r_io_plugin_resolve(RIO *io, const char *filename, ut8 many) {
struct list_head *pos = NULL;
list_for_each_prev (pos, &io->io_list) {
struct r_io_list_t *il = list_entry (pos, struct r_io_list_t, list);
if (il->plugin == NULL)
continue;
if (il->plugin->plugin_open == NULL)
continue;
if (il->plugin->plugin_open (io, filename, many))
return il->plugin;
}
return NULL;
}
R_API int r_io_plugin_open(RIO *io, int fd, RIOPlugin *plugin) {
#if 0
int i=0;
struct list_head *pos;
list_for_each_prev(pos, &io->io_list) {
struct r_io_list_t *il = list_entry(pos, struct r_io_list_t, list);
if (plugin == il->plugin) {
for(i=0;i<R_IO_NFDS;i++) {
if (il->plugin->fds[i] == -1) {
il->plugin->fds[i] = fd;
return 0;
}
}
return -1;
}
}
return -1;
#endif
return R_FALSE;
}
R_API int r_io_plugin_close(RIO *io, int fd, RIOPlugin *plugin) {
return R_FALSE;
}
// TODO: must return an r_iter ator
R_API int r_io_plugin_list(RIO *io) {
int n = 0;
struct list_head *pos;
io->cb_printf ("IO plugins:\n");
list_for_each_prev (pos, &io->io_list) {
struct r_io_list_t *il = list_entry (pos, struct r_io_list_t, list);
io->cb_printf (" - %s\n", il->plugin->name);
n++;
}
return n;
}
R_API int r_io_plugin_generate(RIO *io) {
//TODO
return -1;
}
|
// This file was procedurally generated from the following sources:
// - src/function-forms/params-trailing-comma-single.case
// - src/function-forms/default/async-arrow-function.template
/*---
description: A trailing comma should not increase the respective length, using a single parameter (async arrow function expression)
esid: sec-async-arrow-function-definitions
flags: [generated, async]
info: |
14.7 Async Arrow Function Definitions
AsyncArrowFunction :
...
CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
AsyncConciseBody :
{ AsyncFunctionBody }
...
Supplemental Syntax
When processing an instance of the production AsyncArrowFunction :
CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody the interpretation of
CoverCallExpressionAndAsyncArrowHead is refined using the following grammar:
AsyncArrowHead :
async ArrowFormalParameters
Trailing comma in the parameters list
14.1 Function Definitions
FormalParameters[Yield, Await] : FormalParameterList[?Yield, ?Await] ,
---*/
var callCount = 0;
// Stores a reference `ref` for case evaluation
var ref = async (a,) => {
assert.sameValue(a, 42);
callCount = callCount + 1;
};
ref(42, 39).then(() => {
assert.sameValue(callCount, 1, 'async arrow function invoked exactly once')
}).then($DONE, $DONE);
assert.sameValue(ref.length, 1, 'length is properly set');
|
import datetime
def BOOL(val):
return 'true' if val else 'false'
def INT(val):
return str(int(val))
def ONEOF(*values):
def proxy(val):
if not val in values:
raise ValueError('%s not in %s' % (val, ','.join(values)))
return val
return proxy
def SET(*set_values):
set_values = set(set_values)
def proxy(val):
if isinstance(val, basestring):
val = set(val.split(','))
else:
val = set(val)
if set_values.issuperset(val):
return ','.join(val)
else:
raise ValueError('%s not in %s' % (val, set_values))
return proxy
def DATETIME(dt):
if not isinstance(dt, datetime.datetime):
raise TypeError('%s not a datetime')
return dt.isoformat()
class GoogleApi(object):
_url = None
_apis = {}
def __init__(self, parent):
self._parent = parent
def request(self, url, method, query=None, body=None):
return self._parent.request(self._url + url, method, query, body)
def __getattr__(self, item):
if not item in self._apis:
raise AttributeError('No such API (%s)' % item)
api = self._apis[item](self)
setattr(self, item, api)
return api
class GoogleApiEndPoint(object):
_url = None
_methods = {}
def __init__(self, parent):
self._parent = parent
for method, decl in self._methods.items():
setattr(self, method, self._make_method(decl))
def request(self, method='GET', query=None, body=None):
return self._parent.request(self._url, method, query, body)
def _make_method(self, decl):
def proxy(**kwargs):
body = kwargs.get('body')
query = {}
if 'required' in decl:
for arg_name, arg_decl in decl['required'].items():
query[arg_name] = arg_decl(kwargs[arg_name])
if 'filter' in decl:
filter_count = 0
for arg_name, arg_decl in decl['filter'].items():
val = kwargs.get(arg_name)
if val is not None:
query[arg_name] = arg_decl(val)
filter_count += 1
if not decl.get('min_filters', 1) <= filter_count <= decl.get('max_filters', 1):
raise RuntimeError('must specify exactly one of %s' % ', '.join(decl['filter']))
if 'optional' in decl:
for arg_name, arg_decl in decl['optional'].items():
val = kwargs.get(arg_name)
if val is not None:
query[arg_name] = arg_decl(val)
return self.request(decl['method'], query, body)
return proxy
|
#!/usr/bin/env python
import os
import sys
# For coverage.
if __package__ is None:
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
from unittest import main, TestCase
import requests
import requests_mock
from iris_sdk.client import Client
from iris_sdk.models.account import Account
from iris_sdk.models.portout import PortOut
class ClassNotesUrlsTest(TestCase):
"""Test the Notes resource URI linking"""
@classmethod
def setUpClass(cls):
cls._client = Client("http://foo", "bar", "bar", "qux")
cls._account = Account(client=cls._client)
@classmethod
def tearDownClass(cls):
del cls._client
del cls._account
def test_notes_disconnects(self):
with requests_mock.Mocker() as m:
disc = self._account.disconnects.create({"order_id": "1"}, False)
m.get(self._client.config.url + disc.notes.get_xpath())
disc.notes.list()
def test_notes_orders(self):
with requests_mock.Mocker() as m:
ord = self._account.orders.create({"order_id": "2"}, False)
m.get(self._client.config.url + ord.notes.get_xpath())
ord.notes.list()
def test_notes_portins(self):
with requests_mock.Mocker() as m:
pin = self._account.portins.create({"order_id": "3"}, False)
m.get(self._client.config.url + pin.notes.get_xpath())
pin.notes.list()
def test_notes_portouts(self):
with requests_mock.Mocker() as m:
po = PortOut(self._account.portouts)
po.id = "4"
m.get(self._client.config.url + po.notes.get_xpath())
po.notes.list()
if __name__ == "__main__":
main()
|
import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
m_p = 1.67e-24 # g
sigma = 5.67e-5 #cgs
ev_ergs = 1.6e-12
solar_g = 1.989e33
G = 6.67e-8 # cgs
yr_sec = 3.156e7 #second
Mdot = 10e-4*(solar_g/yr_sec)
Rinit = 2.5
mvalues = np.linspace(0.01, 50, 2000)
def bb_luminosity(radius):
return 4*np.pi*(radius**2)*sigma*(3500**4)
def derivatives(mass, radius):
bb = max(bb_luminosity(radius*6.955e10), 3.846e33*(mass**3))
term1 = (2./3)*((radius*6.944e10)**2)/((mass*solar_g)**2)
term2 = -(0.25*Mdot*G)*(mass*solar_g)/(radius*6.955e10)
term3 = -bb
term4 = -3*Mdot*(mass*solar_g)/(radius*6.955e10)
term5 = (84.2*ev_ergs*Mdot)
return term1*(term2 + term3 + term4 + term5)
def other_derivs(mass, radius):
bb = max(bb_luminosity(radius*6.955e10), 3.846e33*(mass**3))
return bb - (0.25*G*Mdot)*((mass*solar_g)/(radius*6.955e10))
def tout_radius(M):
omega = 0.62246212
l = -0.42450044
kappa = -7.11727086
gamma = 0.32699690
mu = 0.02410413
nu = 0
eta = 0.94472050
o = -7.45345690
pi = -0.00186899
term1 = omega*(M**2.5) + l*(M**6.5) + kappa*(M**11) + gamma*(M**19) + mu*(M**19.5)
term2 = nu + eta*(M**2) + o*(M**8.5) + M**18.5 + pi*(M**19.5)
return 500*(term1/term2)
def tout_lum(M):
alpha = 0.397
beta = 8.527
gamma = 0.00026
delta = 5.433
sigma = 5.56
eta = 0.788
n = 0.0058
term1 = alpha*M**5.5 + beta*M**11
term2 = gamma + M**3 + delta*M**5 + sigma*M**7 + eta*M**8 + n*M**9.5
return term1/term2
radius = odeint(derivatives, Rinit, mvalues)
luminosity = odeint(other_derivs, Rinit, mvalues)
#plt.plot(mvalues, radius, label="This Model")
#plt.plot(mvalues, tout_radius(mvalues), label = "Tout1996")
#plt.xlabel('Mass (Solar Mass)', fontsize=16)
#plt.ylabel('Radius', fontsize=16)
#plt.legend()
#plt.show()
plt.plot(mvalues, luminosity)
plt.plot(mvalues, tout_lum(mvalues))
plt.xlabel('Mass (Solar Mass)', fontsize=16)
plt.ylabel('Luminosity', fontsize=16)
plt.ylim(0, 400000)
plt.show()
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Stephan Grunewald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace Sharpitecture.Creation
{
/// <summary>
/// Interface for an intermediate creation result.
/// Only when calling Product.get() will the underlying creational process be evaluated
/// </summary>
/// <typeparam name="TProduct"></typeparam>
public interface ICreationResult<TProduct>
{
/// <summary>
/// The result of a creational process.
/// </summary>
TProduct Product { get; }
}
}
|
//semestresreportmodel.ts
//
import {UserInfo} from './userinfo';
import {BaseConsultViewModel} from './baseconsultmodel';
import {DisplayEtudiant, DisplayEtudiantsArray} from './displayetudiant';
import {IDisplayEtudiant, IEtudiantEvent} from 'infodata';
//
export class SemestreReportBase extends BaseConsultViewModel<IDisplayEtudiant> {
//
private _all_data: IDisplayEtudiant[] = [];
//
constructor(info: UserInfo) {
super(info);
}// constructor
protected post_update_semestre(): Promise<boolean> {
return super.post_update_semestre().then((r) => {
if (!this.in_activate) {
return this.refreshAll();
} else {
return Promise.resolve(true);
}
});
}
protected is_refresh(): boolean {
return (this.semestreid !== null);
}
protected prepare_refresh(): void {
super.prepare_refresh();
this._all_data = [];
}
protected transform_data(pp: IEtudiantEvent[]): Promise<IDisplayEtudiant[]> {
let oRet: IDisplayEtudiant[] = [];
if ((pp !== undefined) && (pp !== null)) {
let grp: DisplayEtudiantsArray = new DisplayEtudiantsArray();
for (let p of pp) {
grp.add_event(p);
}
oRet = grp.get_etudiantdisplays();
}// pp
return Promise.resolve(oRet);
}// transformData
protected get_initial_events(): Promise<IEtudiantEvent[]> {
return Promise.resolve([]);
}
public refreshAll(): Promise<any> {
this.prepare_refresh();
if (!this.is_refresh()) {
return Promise.resolve(true);
}
let nc = this.itemsPerPage;
let self = this;
return this.get_initial_events().then((pp: IEtudiantEvent[]) => {
// let xx = self.filter_etudevents(pp);
return self.transform_data(pp);
}).then((zz: IDisplayEtudiant[]) => {
self._all_data = zz;
let nt = self._all_data.length;
let np = Math.floor(nt / nc);
if ((np * nc) < nt) {
++np;
self.pagesCount = np;
}
return self.refresh();
});
}// refreshAll
public refresh(): Promise<any> {
this.clear_error();
this.items = [];
if (!this.is_refresh()) {
return Promise.resolve(true);
}
let nbItems = this._all_data.length;
let nc = this.itemsPerPage;
let istart = (this.currentPage - 1) * nc;
if ((istart < 0) && (istart >= nbItems)) {
return Promise.resolve(true);
}
let iend = istart + nc - 1;
if (iend >= nbItems) {
iend = nbItems - 1;
}
if ((iend < 0) && (iend >= nbItems)) {
return Promise.resolve(true);
}
let oRet: IDisplayEtudiant[] = [];
let i = istart;
while (i <= iend) {
let p = this._all_data[i++];
oRet.push(p);
}// i
let self = this;
return this.retrieve_avatars(oRet).then((pp: IDisplayEtudiant[]) => {
self.items = pp;
return true;
})
}// refresh
}// class BaseEditViewModel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.