text
stringlengths 2
6.14k
|
|---|
#!/usr/bin/python
import os
try: import simplejson as json
except ImportError: import json
from decimal import Decimal
import copy
import bitcoinrpc.authproxy
import rules
CONFIG_PATH = os.path.expanduser(os.path.join("~", ".autosend", "config.json"))
BITCOIND_CONF = os.path.expanduser(os.path.join("~", ".bitcoin", "bitcoin.conf"))
def get_bitcoin_conf(path=BITCOIND_CONF):
cfg = {}
try:
with open(path, "r") as conf_file:
for line in conf_file:
line = line.rstrip().split('=', 1)
if len(line) != 2:
continue
cfg[line[0]] = line[1]
except IOError:
pass
return {
'user': cfg.get('rpcuser', 'bitcoinrpc'),
'pass': cfg.get('rpcpassword', ''),
'host': cfg.get('rpcconnect', '127.0.0.1'),
'port': int(cfg.get('rpcport', 8333)),
}
class Autosender(object):
def __init__(self, config_path=CONFIG_PATH):
self.config_path = config_path
self._bitcoind = None
self._config = None
def validate_sending_address(self, addr):
res = self.bitcoind.validateaddress(addr)
if not res['isvalid']:
raise RuntimeError("Invalid address: %s" % addr)
if not res['ismine']:
raise RuntimeError("Address is not in your wallet: %s" % addr)
def validate_address(self, addr):
if not self.bitcoind.validateaddress(addr)['isvalid']:
raise RuntimeError("Invalid address: %s" % addr)
@classmethod
def validate_proportion(cls, num):
if num < 0 or num > 1:
raise RuntimeError("Invalid decimal proportion: %s" % num)
def create_split(self, args):
if args.ADDRESS in self.config['rules']:
raise RuntimeError("A rule already exists for address '%s'."
" To redefine it, first delete it." % args.ADDRESS)
self.validate_sending_address(args.ADDRESS)
dests = [(a, Decimal(b)) for a, b in
[x.split(':') for x in args.OUTPUT_PROPORTION]]
for dest, amt in dests:
self.validate_address(dest)
self.validate_proportion(amt)
if args.fee < 0:
raise RuntimeError("Negative fee? What are you trying to pull?")
if args.minimum <= args.fee:
raise RuntimeError("Minimum balance to execute must be more than the fee!")
if sum(d[1] for d in dests) != 1:
raise RuntimeError("Proportions should add to 1!")
self.bitcoind.setaccount(args.ADDRESS, args.ADDRESS)
self.config['rules'][args.ADDRESS] = {
"action": "split",
"minimum": args.minimum,
"fee": args.fee,
"destinations": dests,
}
self.save_config()
def execute(self, args):
if args.ADDRESS:
addrs = args.ADDRESS
else:
addrs = self.config['rules'].keys()
for addr in addrs:
try:
rule = self.config['rules'][addr]
except KeyError:
print("WARNING: No rule defined to send from address %s (skipping)" %
(addr))
else:
RuleCls = rules.by_name(rule['action'])
RuleCls(addr, copy.deepcopy(rule)).execute(self.bitcoind)
def show_rules(self, args):
for addr, rule in self.config['rules'].iteritems():
rule = rules.by_name(rule['action'])(addr, copy.deepcopy(rule))
print(rule.description)
def delete(self, args):
try:
del self.config['rules'][args.ADDRESS]
except KeyError:
raise RuntimeError("No rule exists for address '%s'." % args.ADDRESS)
else:
self.save_config()
@property
def config(self):
if self._config is None:
try:
config_file = open(self.config_path, 'r')
except IOError:
self._config = {
'rules': {},
'bitcoind': get_bitcoin_conf()
}
else:
cfg = json.load(config_file, parse_float=Decimal)
config_file.close()
self._config = cfg
return self._config
def save_config(self):
try:
os.mkdir(os.path.dirname(self.config_path))
except OSError:
# already exists
pass
with open(self.config_path, 'w') as config_file:
json.dump(self.config, config_file)
def set_param(self, args):
if args.PARAMETER == 'bitcoind.user':
self.config['bitcoind']['user'] = args.VALUE
if args.PARAMETER == 'bitcoind.password':
self.config['bitcoind']['pass'] = args.VALUE
if args.PARAMETER == 'bitcoind.host':
self.config['bitcoind']['host'] = args.VALUE
if args.PARAMETER == 'bitcoind.port':
self.config['bitcoind']['port'] = int(args.VALUE)
self.save_config()
def get_param(self, args):
if args.PARAMETER == 'bitcoind.user':
print(self.config['bitcoind']['user'])
if args.PARAMETER == 'bitcoind.password':
print(self.config['bitcoind']['pass'])
if args.PARAMETER == 'bitcoind.host':
print(self.config['bitcoind']['host'])
if args.PARAMETER == 'bitcoind.port':
print(self.config['bitcoind']['port'])
@property
def bitcoind(self):
if self._bitcoind is None:
user = self.config['bitcoind']['user']
password = self.config['bitcoind']['pass']
host = self.config['bitcoind']['host']
port = self.config['bitcoind']['port']
rpc = "http://%s:%s@%s:%s" % (user, password, host, port)
self._bitcoind = bitcoinrpc.authproxy.AuthServiceProxy(rpc)
return self._bitcoind
|
using UnityEngine;
using System.Collections;
public class Kaiser5 : MessageBehaviour {
void OnMouseUpAsButton()
{
Messenger.SendToListeners(new ClickMessage(gameObject, "Scene5ClickMessage", "kaiser", 1));
}
}
|
<?php
/**
* This file is part of Noxgame
*
* @license http://www.gnu.org/licenses/gpl-3.0.txt
*
* Copyright (c) 2012-Present, mandalorien
* All rights reserved.
*=========================================================
_ _
| \ | |
| \| | _____ ____ _ __ _ _ __ ___ ___
| . ` |/ _ \ \/ / _` |/ _` | '_ ` _ \ / _ \
| |\ | (_) > < (_| | (_| | | | | | | __/
|_| \_|\___/_/\_\__, |\__,_|_| |_| |_|\___|
__/ |
|___/
*=========================================================
*
*/
function InsertBuildListScript ( $CallProgram ) {
global $lang;
$BuildListScript = "<script type=\"text/javascript\">\n";
$BuildListScript .= "<!--\n";
$BuildListScript .= "function t() {\n";
$BuildListScript .= " v = new Date();\n";
$BuildListScript .= " var blc = document.getElementById('blc');\n";
$BuildListScript .= " var timeout = 1;\n";
$BuildListScript .= " n = new Date();\n";
$BuildListScript .= " ss = pp;\n";
$BuildListScript .= " aa = Math.round( (n.getTime() - v.getTime() ) / 1000. );\n";
$BuildListScript .= " s = ss - aa;\n";
$BuildListScript .= " m = 0;\n";
$BuildListScript .= " h = 0;\n\n";
$BuildListScript .= " j = 0;\n\n";
$BuildListScript .= " if ( (ss + 3) < aa ) {\n";
$BuildListScript .= " blc.innerHTML = \"". $lang['completed'] ."<br>\" + \"<a href=". INDEX_BASE ."batiment&planet=\" + pl + \">". $lang['continue'] ."</a>\";\n";
$BuildListScript .= " if ((ss + 6) >= aa) {\n";
$BuildListScript .= " window.setTimeout('document.location.href=\"". INDEX_BASE ."batiment&planet=' + pl + '\";', 3500);\n";
$BuildListScript .= " }\n";
$BuildListScript .= " } else {\n";
$BuildListScript .= " if ( s < 0 ) {\n";
$BuildListScript .= " if (1) {\n";
$BuildListScript .= " blc.innerHTML = \"". $lang['completed'] ."<br>\" + \"<a href=". INDEX_BASE ."batiment&planet=\" + pl + \">". $lang['continue'] ."</a>\";\n";
$BuildListScript .= " window.setTimeout('document.location.href=\"". INDEX_BASE ."batiment&planet=' + pl + '\";', 2000);\n";
$BuildListScript .= " } else {\n";
$BuildListScript .= " timeout = 0;\n";
$BuildListScript .= " blc.innerHTML = \"". $lang['completed'] ."<br>\" + \"<a href=". INDEX_BASE ."batiment&planet=\" + pl + \">". $lang['continue'] ."</a>\";\n";
$BuildListScript .= " }\n";
$BuildListScript .= " } else {\n";
$BuildListScript .= " if ( s > 59) {\n";
$BuildListScript .= " m = Math.floor( s / 60);\n";
$BuildListScript .= " s = s - m * 60;\n";
$BuildListScript .= " }\n";
$BuildListScript .= " if ( m > 59) {\n";
$BuildListScript .= " h = Math.floor( m / 60);\n";
$BuildListScript .= " m = m - h * 60;\n";
$BuildListScript .= " }\n";
$BuildListScript .= " if ( h > 24) {\n";
$BuildListScript .= " j = Math.floor( h / 24);\n";
$BuildListScript .= " h = h - j * 24;\n";
$BuildListScript .= " }\n";
$BuildListScript .= " if ( s < 10 ) {\n";
$BuildListScript .= " s = \"0\" + s;\n";
$BuildListScript .= " }\n";
$BuildListScript .= " if ( m < 10 ) {\n";
$BuildListScript .= " m = \"0\" + m;\n";
$BuildListScript .= " }\n";
$BuildListScript .= " if (1) {\n";
if($_REQUEST['page']!='overview')
{
$BuildListScript .= " blc.innerHTML = j + \"j \" + h + \":\" + m + \":\" + s + \"<br><input class='stopbuild' type=submit name=cancel value=enlever />\";\n";
}
else
{
$BuildListScript .= " blc.innerHTML = j + \"j \" + h + \":\" + m + \":\" + s ;\n";
}
$BuildListScript .= " } else {\n";
$BuildListScript .= " blc.innerHTML = j + \"j \" + h + \":\" + m + \":\" + s + \"<br><a href=". INDEX_BASE ."batiment&listid=\" + pk + \"&cmd=\" + pm + \"&planet=\" + pl + \">". $lang['DelFirstQueue'] ."</a>\";\n";
$BuildListScript .= " }\n";
$BuildListScript .= " }\n";
$BuildListScript .= " pp = pp - 1;\n";
$BuildListScript .= " if (timeout == 1) {\n";
$BuildListScript .= " window.setTimeout(\"t();\", 999);\n";
$BuildListScript .= " }\n";
$BuildListScript .= " }\n";
$BuildListScript .= "}\n";
$BuildListScript .= "//-->\n";
$BuildListScript .= "</script>\n";
return $BuildListScript;
}
?>
|
import pandas as pd
from bokeh.embed import components
from bokeh.models.formatters import DatetimeTickFormatter, DEFAULT_DATETIME_FORMATS
from bokeh.plotting import figure, ColumnDataSource
from app import db
from app.decorators import data_quality
from app.main.data_quality_plots import data_quality_date_plot
@data_quality(name='hrdet_bias', caption='Mean HRDET Bias Background levels')
def hrdet_bias_plot(start_date, end_date):
"""Return a <div> element with a weather downtime plot.
The plot shows the downtime for the period between start_date (inclusive) and end_date (exclusive).
Params:
-------
start_date: date
Earliest date to include in the plot.
end_date: date
Earliest date not to include in the plot.
Return:
-------
str:
A <div> element with the weather downtime plot.
"""
title = "HRDET Bias Levels"
column = 'BkgdMean'
table = 'PipelineDataQuality_CCD'
logic = " and FileName like 'R%%' and Target_Name='BIAS'"
y_axis_label = 'Bias Background Mean (e)'
return data_quality_date_plot(start_date, end_date, title, column, table, logic=logic, y_axis_label=y_axis_label)
@data_quality(name='hrdet_vacuum_temp', caption='HRS HRDET Vacuum Temperature')
def hrdet_vacuum_temp_plot(start_date, end_date):
"""Return a <div> element with a HRS vacuum temperature plot.
The plot shows the HRS vacuum temperature for the period between start_date (inclusive) and end_date (exclusive).
Params:
-------
start_date: date
Earliest date to include in the plot.
end_date: date
Earliest date not to include in the plot.
Return:
-------
str:
A <div> element with the weather downtime plot.
"""
title = "HRDET Vacuum Temp"
y_axis_label = 'Vacuum Temp'
# creates your query
table = 'FitsHeaderHrs'
column = 'TEM_VAC'
logic = " and FileName like 'R%%'"
sql = "select UTStart, {column} from {table} join FileData using (FileData_Id) " \
" where UTStart > '{start_date}' and UTStart <'{end_date}' {logic}"\
.format(column=column, start_date=start_date, end_date=end_date,
table=table, logic=logic)
df = pd.read_sql(sql, db.engine)
source = ColumnDataSource(df)
# creates your plot
date_formats = DEFAULT_DATETIME_FORMATS()
date_formats['hours'] = ['%e %b %Y']
date_formats['days'] = ['%e %b %Y']
date_formats['months'] = ['%e %b %Y']
date_formats['years'] = ['%e %b %Y']
date_formatter = DatetimeTickFormatter(formats=date_formats)
p = figure(title=title,
x_axis_label='Date',
y_axis_label=y_axis_label,
x_axis_type='datetime')
p.scatter(source=source, x='UTStart', y=column)
p.xaxis[0].formatter = date_formatter
return p
@data_quality(name='hrdet_arc_wave', caption='HRS Arc stability')
def hrdet_arc_wave_plot(start_date, end_date):
"""Return a <div> element with a HRS arc stability plot.
The plot shows the HRS wavelenght as a function of pixel position for a set of time
Params:
-------
start_date: date
Earliest date to include in the plot.
end_date: date
Earliest date not to include in the plot.
Return:
-------
str:
A <div> element with the weather downtime plot.
"""
title = "HRDET Arc Stability"
y_axis_label = 'Pixel Position'
# creates your query
table = 'DQ_HrsArc'
column = 'x'
obsmode = 'LOW RESOLUTION'
wavelength = 6483.08
logic = " and FileName like 'R%%' and OBSMODE like '{obsmode}' and wavelength={wavelength}"\
.format(obsmode=obsmode, wavelength=wavelength)
sql = "select UTStart, {column} from {table} join FileData using (FileData_Id) " \
" where UTStart > '{start_date}' and UTStart <'{end_date}' {logic}"\
.format(column=column, start_date=start_date, end_date=end_date,
table=table, logic=logic)
print(sql)
df = pd.read_sql(sql, db.engine)
source = ColumnDataSource(df)
# creates your plot
date_formats = DEFAULT_DATETIME_FORMATS()
date_formats['hours'] = ['%e %b %Y']
date_formats['days'] = ['%e %b %Y']
date_formats['months'] = ['%e %b %Y']
date_formats['years'] = ['%e %b %Y']
date_formatter = DatetimeTickFormatter(formats=date_formats)
p = figure(title=title,
x_axis_label='Date',
y_axis_label=y_axis_label,
x_axis_type='datetime')
print(df['UTStart'], df['x'])
p.scatter(source=source, x='UTStart', y=column)
p.xaxis[0].formatter = date_formatter
return p
|
# (c) 2014, Kent R. Spillner <[email protected]>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
name: dict
version_added: "1.5"
short_description: returns key/value pair items from dictionaries
description:
- Takes dictionaries as input and returns a list with each item in the list being a dictionary with 'key' and 'value' as
keys to the previous dictionary's structure.
options:
_terms:
description:
- A list of dictionaries
required: True
"""
EXAMPLES = """
vars:
users:
alice:
name: Alice Appleworth
telephone: 123-456-7890
bob:
name: Bob Bananarama
telephone: 987-654-3210
tasks:
# with predefined vars
- name: Print phone records
debug:
msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
loop: "{{ lookup('dict', users) }}"
# with inline dictionary
- name: show dictionary
debug:
msg: "{{item.key}}: {{item.value}}"
with_dict: {a: 1, b: 2, c: 3}
# Items from loop can be used in when: statements
- name: set_fact when alice in key
set_fact:
alice_exists: true
loop: "{{ lookup('dict', users) }}"
when: "'alice' in item.key"
"""
RETURN = """
_list:
description:
- list of composed dictonaries with key and value
type: list
"""
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.common._collections_compat import Mapping
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
# NOTE: can remove if with_ is removed
if not isinstance(terms, list):
terms = [terms]
results = []
for term in terms:
# Expect any type of Mapping, notably hostvars
if not isinstance(term, Mapping):
raise AnsibleError("with_dict expects a dict")
results.extend(self._flatten_hash_to_list(term))
return results
|
/* ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 1998 Netscape Communications Corporation.
* Copyright (C) 2010 Apple Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* ***** END LICENSE BLOCK ***** */
gTestfile = 'ToInt-001.js';
/**
* Preferred Argument Conversion.
*
* Passing a JavaScript boolean to a Java method should prefer to call
* a Java method of the same name that expects a Java boolean.
*
*/
var SECTION = "Preferred argument conversion: JavaScript Object to int";
var VERSION = "1_4";
var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " +
SECTION;
startTest();
var TEST_CLASS = applet.createQAObject("com.netscape.javascript.qa.lc3.jsobject.JSObject_007");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new String() ) +''",
"'INT'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Boolean() ) +''",
"'INT'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Number() ) +''",
"'INT'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Date(0) ) +''",
"'INT'");
|
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.db.transaction import atomic
from django.utils.translation import ugettext_lazy as _
from shuup.admin.form_part import FormPartsViewMixin, SaveFormPartsMixin
from shuup.admin.modules.contacts.form_parts import (
CompanyContactBaseFormPart, ContactAddressesFormPart,
PersonContactBaseFormPart
)
from shuup.admin.toolbar import get_default_edit_toolbar
from shuup.admin.utils.urls import get_model_url
from shuup.admin.utils.views import CreateOrUpdateView
from shuup.apps.provides import get_provide_objects
from shuup.core.models import Contact, PersonContact
class ContactEditView(SaveFormPartsMixin, FormPartsViewMixin, CreateOrUpdateView):
model = Contact
template_name = "shuup/admin/contacts/edit.jinja"
context_object_name = "contact"
form_part_class_provide_key = "admin_contact_form_part"
def get_contact_type(self):
contact_type = self.request.GET.get("type", "")
if self.object.pk:
if type(self.object) is PersonContact:
contact_type = "person"
else:
contact_type = "company"
return contact_type
def get_form_part_classes(self):
form_part_classes = []
contact_type = self.get_contact_type()
if contact_type == "person":
form_part_classes.append(PersonContactBaseFormPart)
else:
form_part_classes.append(CompanyContactBaseFormPart)
form_part_classes += list(get_provide_objects(self.form_part_class_provide_key))
if self.object.pk:
form_part_classes.append(ContactAddressesFormPart)
return form_part_classes
@atomic
def form_valid(self, form):
return self.save_form_parts(form)
def get_toolbar(self):
toolbar = get_default_edit_toolbar(
self,
self.get_save_form_id(),
discard_url=(get_model_url(self.object) if self.object.pk else None)
)
for button in get_provide_objects("admin_contact_edit_toolbar_button"):
toolbar.append(button(self.object))
return toolbar
def get_context_data(self, **kwargs):
context = super(ContactEditView, self).get_context_data(**kwargs)
contact_type = self.get_contact_type()
context["contact_type"] = contact_type
if not self.object.pk:
context["title"] = _("New Company") if contact_type == "company" else _("New Contact")
return context
|
// Copyright (c) 2016 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.
#include <vector>
#include "base/time/time.h"
#include "net/cookies/cookie_store.h"
#include "base/memory/scoped_ptr.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_options.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace net {
namespace {
// Helper for testing BuildCookieLine
void MatchCookieLineToVector(
const std::string& line,
const std::vector<scoped_ptr<CanonicalCookie>>& cookies) {
// Test the std::vector<CanonicalCookie> variant
// ('CookieMonster::CookieList'):
std::vector<CanonicalCookie> list;
for (const auto& cookie : cookies)
list.push_back(*cookie);
EXPECT_EQ(line, CookieStore::BuildCookieLine(list));
// Test the std::vector<CanonicalCookie*> variant
// ('CookieMonster::CanonicalCookieVector' (yes, this is absurd)):
std::vector<CanonicalCookie*> ptr_list;
for (const auto& cookie : cookies)
ptr_list.push_back(cookie.get());
EXPECT_EQ(line, CookieStore::BuildCookieLine(ptr_list));
}
} // namespace
TEST(CookieStoreBaseTest, BuildCookieLine) {
std::vector<scoped_ptr<CanonicalCookie>> cookies;
GURL url("https://example.com/");
CookieOptions options;
base::Time now = base::Time::Now();
MatchCookieLineToVector("", cookies);
cookies.push_back(CanonicalCookie::Create(url, "A=B", now, options));
MatchCookieLineToVector("A=B", cookies);
// Nameless cookies are sent back without a prefixed '='.
cookies.push_back(CanonicalCookie::Create(url, "C", now, options));
MatchCookieLineToVector("A=B; C", cookies);
// Cookies separated by ';'.
cookies.push_back(CanonicalCookie::Create(url, "D=E", now, options));
MatchCookieLineToVector("A=B; C; D=E", cookies);
// BuildCookieLine doesn't reorder the list, it relies on the caller to do so.
cookies.push_back(CanonicalCookie::Create(
url, "F=G", now - base::TimeDelta::FromSeconds(1), options));
MatchCookieLineToVector("A=B; C; D=E; F=G", cookies);
// BuildCookieLine doesn't deduplicate.
cookies.push_back(CanonicalCookie::Create(
url, "D=E", now - base::TimeDelta::FromSeconds(2), options));
MatchCookieLineToVector("A=B; C; D=E; F=G; D=E", cookies);
}
} // namespace net
|
# -*- test-case-name: twisted.web.test.test_soap -*-
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""SOAP support for twisted.web.
Requires SOAPpy 0.10.1 or later.
API Stability: unstable
Maintainer: U{Itamar Shtull-Trauring<mailto:[email protected]}
Future plans:
SOAPContext support of some kind.
Pluggable method lookup policies.
"""
# SOAPpy
import SOAPpy
# twisted imports
from twisted.web import server, resource, client
from twisted.internet import defer
from twisted.python import log, failure
class SOAPPublisher(resource.Resource):
"""Publish SOAP methods.
By default, publish methods beginning with 'soap_'. If the method
has an attribute 'useKeywords', it well get the arguments passed
as keyword args.
"""
isLeaf = 1
# override to change the encoding used for responses
encoding = "UTF-8"
def lookupFunction(self, functionName):
"""Lookup published SOAP function.
Override in subclasses. Default behaviour - publish methods
starting with soap_, if they have true attribute useKeywords
they are expected to accept keywords.
@return: tuple (callable, useKeywords), or (None, None) if not found.
"""
function = getattr(self, "soap_%s" % functionName, None)
if function:
return function, getattr(function, "useKeywords", False)
else:
return None
def render(self, request):
"""Handle a SOAP command."""
data = request.content.read()
p, header, body, attrs = SOAPpy.parseSOAPRPC(data, 1, 1, 1)
methodName, args, kwargs, ns = p._name, p._aslist, p._asdict, p._ns
# deal with changes in SOAPpy 0.11
if callable(args):
args = args()
if callable(kwargs):
kwargs = kwargs()
function, useKeywords = self.lookupFunction(methodName)
if not function:
self._methodNotFound(request, methodName)
return server.NOT_DONE_YET
else:
if hasattr(function, "useKeywords"):
keywords = {}
for k, v in kwargs.items():
keywords[str(k)] = v
d = defer.maybeDeferred(function, **keywords)
else:
d = defer.maybeDeferred(function, *args)
d.addCallback(self._gotResult, request, methodName)
d.addErrback(self._gotError, request, methodName)
return server.NOT_DONE_YET
def _methodNotFound(self, request, methodName):
response = SOAPpy.buildSOAP(SOAPpy.faultType("%s:Client" % SOAPpy.NS.ENV_T,
"Method %s not found" % methodName),
encoding=self.encoding)
self._sendResponse(request, response, status=500)
def _gotResult(self, result, request, methodName):
if not isinstance(result, SOAPpy.voidType):
result = {"Result": result}
response = SOAPpy.buildSOAP(kw={'%sResponse' % methodName: result},
encoding=self.encoding)
self._sendResponse(request, response)
def _gotError(self, failure, request, methodName):
e = failure.value
if isinstance(e, SOAPpy.faultType):
fault = e
else:
fault = SOAPpy.faultType("%s:Server" % SOAPpy.NS.ENV_T, "Method %s failed." % methodName)
response = SOAPpy.buildSOAP(fault, encoding=self.encoding)
self._sendResponse(request, response, status=500)
def _sendResponse(self, request, response, status=200):
request.setResponseCode(status)
if self.encoding is not None:
mimeType = 'text/xml; charset="%s"' % self.encoding
else:
mimeType = "text/xml"
request.setHeader("Content-type", mimeType)
request.setHeader("Content-length", str(len(response)))
request.write(response)
request.finish()
class Proxy:
"""A Proxy for making remote SOAP calls.
Pass the URL of the remote SOAP server to the constructor.
Use proxy.callRemote('foobar', 1, 2) to call remote method
'foobar' with args 1 and 2, proxy.callRemote('foobar', x=1)
will call foobar with named argument 'x'.
"""
# at some point this should have encoding etc. kwargs
def __init__(self, url, namespace=None, header=None):
self.url = url
self.namespace = namespace
self.header = header
def _cbGotResult(self, result):
result = SOAPpy.parseSOAPRPC(result)
if hasattr(result, 'Result'):
return result.Result
elif len(result) == 1:
## SOAPpy 0.11.6 wraps the return results in a containing structure.
## This check added to make Proxy behaviour emulate SOAPProxy, which
## flattens the structure by default.
## This behaviour is OK because even singleton lists are wrapped in
## another singleton structType, which is almost always useless.
return result[0]
else:
return result
def callRemote(self, method, *args, **kwargs):
payload = SOAPpy.buildSOAP(args=args, kw=kwargs, method=method,
header=self.header, namespace=self.namespace)
return client.getPage(self.url, postdata=payload, method="POST",
headers={'content-type': 'text/xml',
'SOAPAction': method}
).addCallback(self._cbGotResult)
|
"""Feed generation functions."""
from flask import request
from werkzeug.contrib.atom import AtomFeed
from unidecode import unidecode
from app import APP, auth, ct_connect, models
from app.views import make_external
@APP.route('/feeds/whatsup.atom')
@auth.feed_authorized
def whatsup_recent_posts():
"""Return feed of latest posts."""
feed = AtomFeed('Recent WhatsUp Posts',
feed_url=request.url,
url=request.url_root)
posts = models.get_latest_whatsup_posts(15)
with ct_connect.session_scope() as ct_session:
for post in posts:
feed.add(post.subject, unicode(post.body),
content_type='text',
author='{} {}'.format(
unidecode(post.user.ct_data(ct_session).vorname),
unidecode(post.user.ct_data(ct_session).name)),
url=make_external('/whatsup/{}'.format(post.id)),
updated=post.pub_date)
return feed.get_response()
@APP.route('/feeds/whatsup-comments.atom')
@auth.feed_authorized
def whatsup_recent_comments():
"""Return feed of latest comments."""
feed = AtomFeed('Recent WhatsUp Comments',
feed_url=request.url,
url=request.url_root)
comments = models.get_latest_whatsup_comments(15)
with ct_connect.session_scope() as ct_session:
for comment in comments:
feed.add(
'Kommentar fuer "{}" von {} {}'.format(
comment.post.subject,
unidecode(comment.user.ct_data(ct_session).vorname),
unidecode(comment.user.ct_data(ct_session).name)),
unicode(comment.body),
content_type='text',
author='{} {}'.format(
unidecode(comment.user.ct_data(ct_session).vorname),
unidecode(comment.user.ct_data(ct_session).name)),
url=make_external('whatsup/{}#comment{}'.format(
comment.post.id, comment.id)),
updated=comment.pub_date)
return feed.get_response()
|
# encoding: utf-8
"""
Provides StylesPart and related objects
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import os
from ..opc.constants import CONTENT_TYPE as CT
from ..opc.packuri import PackURI
from ..opc.part import XmlPart
from ..oxml import parse_xml
from ..styles.styles import Styles
class StylesPart(XmlPart):
"""
Proxy for the styles.xml part containing style definitions for a document
or glossary.
"""
@classmethod
def default(cls, package):
"""
Return a newly created styles part, containing a default set of
elements.
"""
partname = PackURI('/word/styles.xml')
content_type = CT.WML_STYLES
element = parse_xml(cls._default_styles_xml())
return cls(partname, content_type, element, package)
@property
def styles(self):
"""
The |_Styles| instance containing the styles (<w:style> element
proxies) for this styles part.
"""
return Styles(self.element)
@classmethod
def _default_styles_xml(cls):
"""
Return a bytestream containing XML for a default styles part.
"""
path = os.path.join(
os.path.split(__file__)[0], '..', 'templates',
'default-styles.xml'
)
with open(path, 'rb') as f:
xml_bytes = f.read()
return xml_bytes
|
/**
* Plugin Tests. The testApp.html should have 36 watchers.
*
*/
var plugin = require('../index.js');
describe('protractor-watcher-plugin test', function () {
beforeEach(function () {
browser.driver.get('http://localhost:9000/testApp.html');
expect(element(by.binding('friends.length')).getText()).toEqual('10');
});
afterEach(function () {
var name = require.resolve('../index.js');
delete require.cache[name];
plugin = require('../index.js');
});
it('should stop plugin execution if test is already failed', function () {
plugin.postTest({ maxAllowedWatchers: 50 }, false).then(function (result) {
expect(result).toBeUndefined();
});
});
it('should use the default value for maxAllowedWatchers if no value is set in the configuration', function () {
plugin.postTest({}, true).then(function (result) {
expect(0).toBe(result.failedCount);
});
});
it('should success if maxAllowedWatchers is lower than number of watchers', function () {
plugin.postTest({ maxAllowedWatchers: 50 }, true).then(function (result) {
expect(0).toBe(result.failedCount);
});
});
it('should success if maxAllowedWatchers is equal to number of watchers', function () {
plugin.postTest({ maxAllowedWatchers: 36 }, true).then(function (result) {
expect(0).toBe(result.failedCount);
});
});
it('should success if url pattern is lower than number of watchers', function () {
var config = {
maxAllowedWatchers: 15,
urlPatterns: [{
urlPattern: '/testApp.html',
maxAllowedWatchers: 50
}]
};
plugin.postTest(config, true).then(function (result) {
expect(0).toBe(result.failedCount);
});
});
it('should use the default value for maxAllowedWatchers if no value is set for this url pattern', function () {
var config = {
maxAllowedWatchers: 15,
urlPatterns: [{
urlPattern: '/testApp.html'
}]
};
plugin.postTest(config, true).then(function (result) {
expect(0).toBe(result.failedCount);
});
});
it('should fail if maxAllowedWatchers is exceeded', function () {
plugin.postTest({ maxAllowedWatchers: 15 }, true).then(function (result) {
expect(1).toBe(result.failedCount);
});
});
it('should prompt an error message if maxAllowedWatchers is exceeded', function () {
var message = 'The maximum number of watchers [15] has been exceeded. ' +
'Number of watchers found: [36] ';
plugin.postTest({ maxAllowedWatchers: 15 }, true).then(function (result) {
expect(message).toBe(result.assertions.errorMsg);
});
});
it('should fail if url pattern exceeds number of watchers', function () {
var config = {
maxAllowedWatchers: 50,
urlPatterns: [{
urlPattern: '/testApp.html',
maxAllowedWatchers: 34
}]
};
plugin.postTest(config, true).then(function (result) {
expect(1).toBe(result.failedCount);
});
});
});
|
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums is None or len(nums) == 0:
return []
pos, zero = 0, 0
while pos < len(nums) - 1 and zero < len(nums):
if nums[pos] != 0:
pos += 1
zero += 1
else:
while zero < len(nums) - 1 and nums[zero] == 0:
zero += 1
nums[pos], nums[zero] = nums[zero], nums[pos]
pos += 1
zero += 1
return nums
class Solution1():
def moveZeroes(self, nums):
pos = 0
index = 0
while index < len(nums):
if nums[index] != 0:
nums[pos] = nums[index]
pos += 1
index += 1
while pos < len(nums):
nums[pos] = 0
pos += 1
if __name__ == "__main__":
sln = Solution1()
res = sln.moveZeroes([0,1,0,3,12])
print(res)
|
<?php
namespace Crm\Model;
use Zend\Db\Adapter\Adapter as DbAdapter;
use AppController;
class CustomerTicket
{
protected $app;
function __construct()
{
$this->app = new App;
}
public function connection()
{
$db = new DbAdapter(
array(
'driver' => 'Pdo',
'dsn' => 'pgsql:dbname=oss;host=10.100.0.37',
'username' => 'oss',
'password' => 'httoss',
)
);
return $db;
}
public function types()
{
$db = $this->connection();
$sql = "SELECT type FROM crm_otrs_ticket_summary GROUP BY type";
$stmt = $db->query($sql);
$results = $stmt->execute();
return $results;
}
public function ticketList($filter)
{
$sqlType = $this->app->filterTypeTicketList($filter);
$db = $this->connection();
$sql = "SELECT *
FROM crm_otrs_ticket_summary
WHERE ".
$filter['where'] .
$sqlType ;
$stmt = $db->query($sql);
$results = $stmt->execute();
return $results;
}
public function volumeCliente($filter)
{
$firstDate = $filter['filter']['firstDate'];
$lastDate = $filter['filter']['lastDate'];
$sqlType = $this->app->filterType($filter);
$db = $this->connection();
$sql = "SELECT
COUNT(*) as volume,
customer
FROM crm_otrs_ticket_summary
WHERE
status = 'closed successful' AND
closetime >= '$firstDate 00:00:00' AND
closetime <= '$lastDate 23:59:59'
$sqlType
GROUP BY customer
ORDER BY volume DESC
LIMIT 10
";
$stmt = $db->query($sql);
$results = $stmt->execute();
return $results;
}
public function volumeService($filter)
{
$firstDate = $filter['filter']['firstDate'];
$lastDate = $filter['filter']['lastDate'];
$sqlType = $this->app->filterType($filter);
$db = $this->connection();
$sql = "SELECT
COUNT(*) as volume,
service,
customer_name
FROM crm_otrs_ticket_summary
WHERE
status = 'closed successful' AND
closetime >= '$firstDate 00:00:00' AND
closetime <= '$lastDate 23:59:59'
$sqlType
GROUP BY service, customer_name
ORDER BY volume DESC
LIMIT 10
";
$stmt = $db->query($sql);
$results = $stmt->execute();
return $results;
}
public function volumeProduto($filter)
{
$firstDate = $filter['filter']['firstDate'];
$lastDate = $filter['filter']['lastDate'];
$sqlType = $this->app->filterType($filter);
$db = $this->connection();
$sql = "SELECT
COUNT(*) as volume,
product
FROM crm_otrs_ticket_summary
WHERE
status = 'closed successful' AND
closetime >= '$firstDate 00:00:00' AND
closetime <= '$lastDate 23:59:59' AND
product <> ''
$sqlType
GROUP BY product
";
$stmt = $db->query($sql);
$results = $stmt->execute();
return $results;
}
}
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
export default [
[
['ponoć', 'podne', 'ujutro', 'popodne', 'navečer', 'noću'],
,
],
,
[
'00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '04:00']
]
];
|
#!/usr/bin/env python
# coding: utf-8
from distutils.core import setup
import os
import setuplib
packages, package_data = setuplib.find_packages('simpleshop')
setup(name='simpleshop',
version=__import__('simpleshop').__version__,
description='A very basic shop for FeinCMS',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
author=u'Simon Bächler',
author_email='[email protected]',
url='http://github.com/sbaechler/simpleshop/',
license='BSD License',
platforms=['OS Independent'],
packages=packages,
package_data=package_data,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
],
)
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bearsoft.gui.grid.rendering;
import java.awt.Rectangle;
import javax.swing.JLabel;
/**
*
* @author Gala
*/
public class NonRepaintableLabel extends JLabel {
protected boolean repaintable;
public NonRepaintableLabel(boolean aRepaintable) {
super();
repaintable = aRepaintable;
}
@Override
public void repaint() {
if (repaintable) {
super.repaint();
}
}
@Override
public void repaint(Rectangle r) {
if (repaintable) {
super.repaint(r);
}
}
@Override
public void repaint(long tm) {
if (repaintable) {
super.repaint(tm);
}
}
@Override
public void repaint(int x, int y, int width, int height) {
if (repaintable) {
super.repaint(x, y, width, height);
}
}
@Override
public void repaint(long tm, int x, int y, int width, int height) {
if (repaintable) {
super.repaint(tm, x, y, width, height);
}
}
}
|
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, 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:
#
# * 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 Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER 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.
PKG = 'test_rosmaster'
NAME = 'test_ps_scope_down'
import sys
import rospy
import rostest
from param_server import ParamServerTestCase
class PsScopeDownTestCase(ParamServerTestCase):
def testScopeDown(self):
return self._testScopeDown()
if __name__ == '__main__':
rospy.init_node(NAME)
rostest.rosrun(PKG, NAME, PsScopeDownTestCase, sys.argv)
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Rackspace provisioner.
"""
from ._libcloud import monkeypatch, LibcloudProvisioner
from ._install import (
provision,
task_open_control_firewall,
)
from ._ssh import run_remotely
from ._effect import sequence
def provision_rackspace(node, package_source, distribution, variants):
"""
Provision flocker on this node.
:param LibcloudNode node: Node to provision.
:param PackageSource package_source: See func:`task_install_flocker`
:param bytes distribution: See func:`task_install_flocker`
:param set variants: The set of variant configurations to use when
provisioning
"""
commands = []
commands.append(run_remotely(
username='root',
address=node.address,
commands=sequence([
provision(
package_source=package_source,
distribution=node.distribution,
variants=variants,
),
# https://clusterhq.atlassian.net/browse/FLOC-1550
# This should be part of ._install.configure_cluster
task_open_control_firewall(node.distribution),
]),
))
return sequence(commands)
IMAGE_NAMES = {
'fedora-20': u'Fedora 20 (Heisenbug) (PVHVM)',
'centos-7': u'CentOS 7 (PVHVM)',
'ubuntu-14.04': u'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)'
}
def rackspace_provisioner(username, key, region, keyname):
"""
Create a LibCloudProvisioner for provisioning nodes on rackspace.
:param bytes username: The user to connect to rackspace with.
:param bytes key: The API key associated with the user.
:param bytes region: The rackspace region in which to launch the instance.
:param bytes keyname: The name of an existing ssh public key configured in
rackspace. The provision step assumes the corresponding private key is
available from an agent.
"""
# Import these here, so that this can be imported without
# installng libcloud.
from libcloud.compute.providers import get_driver, Provider
monkeypatch()
driver = get_driver(Provider.RACKSPACE)(
key=username,
secret=key,
region=region)
provisioner = LibcloudProvisioner(
driver=driver,
keyname=keyname,
image_names=IMAGE_NAMES,
create_node_arguments=lambda **kwargs: {
"ex_config_drive": "true",
},
provision=provision_rackspace,
default_size="performance1-8",
)
return provisioner
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.ui.spoon;
public class InstanceCreationException extends Exception {
private static final long serialVersionUID = -2151267602926525247L;
public InstanceCreationException() {
super();
}
public InstanceCreationException( final String message ) {
super( message );
}
public InstanceCreationException( final String message, final Throwable reas ) {
super( message, reas );
}
public InstanceCreationException( final Throwable reas ) {
super( reas );
}
}
|
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram
InlineQueryResultArticle"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
class InlineQueryResultArticle(InlineQueryResult):
"""This object represents a Telegram InlineQueryResultArticle.
Attributes:
id (str):
title (str):
input_message_content (:class:`telegram.InputMessageContent`):
reply_markup (:class:`telegram.ReplyMarkup`):
url (str):
hide_url (bool):
description (str):
thumb_url (str):
thumb_width (int):
thumb_height (int):
Deprecated: 4.0
message_text (str): Use :class:`InputTextMessageContent` instead.
parse_mode (str): Use :class:`InputTextMessageContent` instead.
disable_web_page_preview (bool): Use :class:`InputTextMessageContent` instead.
Args:
id (str): Unique identifier for this result, 1-64 Bytes
title (str):
reply_markup (:class:`telegram.ReplyMarkup`):
url (Optional[str]):
hide_url (Optional[bool]):
description (Optional[str]):
thumb_url (Optional[str]):
thumb_width (Optional[int]):
thumb_height (Optional[int]):
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self,
id,
title,
input_message_content,
reply_markup=None,
url=None,
hide_url=None,
description=None,
thumb_url=None,
thumb_width=None,
thumb_height=None,
**kwargs):
# Required
super(InlineQueryResultArticle, self).__init__('article', id)
self.title = title
self.input_message_content = input_message_content
# Optional
if reply_markup:
self.reply_markup = reply_markup
if url:
self.url = url
if hide_url:
self.hide_url = hide_url
if description:
self.description = description
if thumb_url:
self.thumb_url = thumb_url
if thumb_width:
self.thumb_width = thumb_width
if thumb_height:
self.thumb_height = thumb_height
@staticmethod
def de_json(data, bot):
data = super(InlineQueryResultArticle, InlineQueryResultArticle).de_json(data, bot)
data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'), bot)
data['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'), bot)
return InlineQueryResultArticle(**data)
|
from __future__ import print_function
from influx_poster import database_post
from threading import Thread
from time import sleep, time
import datetime
import csv
import subprocess
import sys
import os
import signal
class bluetoothManager_scale(Thread):
def __init__(self):
''' Constructor. '''
Thread.__init__(self)
self.exit = 0
def endBluetooth(self):
print("ending scale")
self.exit = 1
def run(self):
try:
print("started scale")
count = 0
tare = 0
tared = False
process = subprocess.Popen("exec /usr/bin/gatttool -b EB:3D:C2:2D:A5:F4 -t random --char-write-req -a 0x23 -n 0100 --listen", shell=True, stdout=subprocess.PIPE)
buffer = ""
for line in iter(process.stdout.readline, ''):
if(self.exit) :
print("attempting exit")
process.kill()
raise Exception("bluetooth ended")
if (count < 5) :
count = count + 1
else :
input = line[36:].replace(" ", "").strip()
buffer += input.decode('hex')
if(buffer.find('\n') > -1) :
output = buffer[:buffer.find('\n')]
try:
output = float(output.replace(",kg,", ""))
if(tared == False):
print("taring")
tare = output
print("tared")
tared = True
else:
value = abs(tare - output)
if(value > 5000):
tared = False
else:
tag = "scale"
dbpost = database_post(tag, value, "scale")
dbpost.start()
timestamp = datetime.datetime.now()
timestring = timestamp.strftime("%Y-%m-%d %H:%M:%S")
with open("/home/jzc/logs/scale.csv", "a") as csvfile:
showerwriter = csv.writer(csvfile, delimiter=',')
showerwriter.writerow([timestring, tag, value])
except ValueError as error:
print(repr(error))
continue
buffer = buffer[buffer.find('\n')+1:]
except Exception as error :
process.kill()
print(repr(error))
|
# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
#
# 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.
class Port(object):
number = None
def __init__(self, number, conf=None):
if conf is None:
conf = {}
self.number = number
self.name = conf.setdefault('name', str(number))
self.description = conf.setdefault('description', self.name)
self.enabled = conf.setdefault('enabled', True)
self.phys_up = False
self.permanent_learn = conf.setdefault('permanent_learn', False)
self.unicast_flood = conf.setdefault('unicast_flood', True)
def running(self):
return self.enabled and self.phys_up
def __eq__(self, other):
return hash(self) == hash(other)
def __hash__(self):
return hash(('Port', self.number))
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
return self.name
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Sat Mar 08 13:50:49 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class ejb.integration.factory.DAOFactoryImp</title>
<meta name="date" content="2014-03-08">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class ejb.integration.factory.DAOFactoryImp";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../ejb/integration/factory/DAOFactoryImp.html" title="class in ejb.integration.factory">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?ejb/integration/factory/class-use/DAOFactoryImp.html" target="_top">Frames</a></li>
<li><a href="DAOFactoryImp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class ejb.integration.factory.DAOFactoryImp" class="title">Uses of Class<br>ejb.integration.factory.DAOFactoryImp</h2>
</div>
<div class="classUseContainer">No usage of ejb.integration.factory.DAOFactoryImp</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../ejb/integration/factory/DAOFactoryImp.html" title="class in ejb.integration.factory">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?ejb/integration/factory/class-use/DAOFactoryImp.html" target="_top">Frames</a></li>
<li><a href="DAOFactoryImp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
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("WinForms-App")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WinForms-App")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("e4ad109a-8b5a-4e51-94a2-8634ce825634")]
// 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")]
|
# Copyright 2019 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.
from .attribute import Attribute
from .code_generator_info import CodeGeneratorInfo
from .composition_parts import WithCodeGeneratorInfo
from .composition_parts import WithComponent
from .composition_parts import WithDebugInfo
from .composition_parts import WithExposure
from .composition_parts import WithExtendedAttributes
from .constant import Constant
from .exposure import Exposure
from .ir_map import IRMap
from .make_copy import make_copy
from .operation import Operation
from .operation import OperationGroup
from .user_defined_type import UserDefinedType
class Namespace(UserDefinedType, WithExtendedAttributes, WithCodeGeneratorInfo,
WithExposure, WithComponent, WithDebugInfo):
"""https://heycam.github.io/webidl/#idl-namespaces"""
class IR(IRMap.IR, WithExtendedAttributes, WithCodeGeneratorInfo,
WithExposure, WithComponent, WithDebugInfo):
def __init__(self,
identifier,
is_partial,
attributes=None,
constants=None,
operations=None,
extended_attributes=None,
component=None,
debug_info=None):
assert isinstance(is_partial, bool)
assert attributes is None or isinstance(attributes, (list, tuple))
assert constants is None or isinstance(constants, (list, tuple))
assert operations is None or isinstance(operations, (list, tuple))
attributes = attributes or []
constants = constants or []
operations = operations or []
assert all(
isinstance(attribute, Attribute.IR) and attribute.is_readonly
and attribute.is_static for attribute in attributes)
assert all(
isinstance(constant, Constant.IR) for constant in constants)
assert all(
isinstance(operation, Operation.IR) and operation.identifier
and operation.is_static for operation in operations)
kind = (IRMap.IR.Kind.PARTIAL_NAMESPACE
if is_partial else IRMap.IR.Kind.NAMESPACE)
IRMap.IR.__init__(self, identifier=identifier, kind=kind)
WithExtendedAttributes.__init__(self, extended_attributes)
WithCodeGeneratorInfo.__init__(self)
WithExposure.__init__(self)
WithComponent.__init__(self, component=component)
WithDebugInfo.__init__(self, debug_info)
self.is_partial = is_partial
self.attributes = list(attributes)
self.constants = list(constants)
self.operations = list(operations)
self.operation_groups = []
def __init__(self, ir):
assert isinstance(ir, Namespace.IR)
assert not ir.is_partial
ir = make_copy(ir)
UserDefinedType.__init__(self, ir.identifier)
WithExtendedAttributes.__init__(self, ir.extended_attributes)
WithCodeGeneratorInfo.__init__(
self, CodeGeneratorInfo(ir.code_generator_info))
WithExposure.__init__(self, Exposure(ir.exposure))
WithComponent.__init__(self, components=ir.components)
WithDebugInfo.__init__(self, ir.debug_info)
self._attributes = tuple([
Attribute(attribute_ir, owner=self)
for attribute_ir in ir.attributes
])
self._constants = tuple([
Constant(constant_ir, owner=self) for constant_ir in ir.constants
])
self._operations = tuple([
Operation(operation_ir, owner=self)
for operation_ir in ir.operations
])
self._operation_groups = tuple([
OperationGroup(
operation_group_ir,
filter(lambda x: x.identifier == operation_group_ir.identifier,
self._operations),
owner=self) for operation_group_ir in ir.operation_groups
])
@property
def attributes(self):
"""Returns attributes."""
return self._attributes
@property
def operations(self):
"""Returns operations."""
return self._operations
@property
def operation_groups(self):
"""Returns a list of OperationGroups."""
return self._operation_groups
|
<?php
/**
* File containing the Content Search handler class
*
* @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
* @license http://ez.no/licenses/gnu_gpl GNU General Public License v2.0
* @version 2012.9
*/
namespace eZ\Publish\Core\Persistence\Solr\Content\Search\CriterionVisitor;
use eZ\Publish\Core\Persistence\Solr\Content\Search\CriterionVisitor,
eZ\Publish\SPI\Persistence\Content\Type\Handler as ContentTypeHandler,
eZ\Publish\Core\Persistence\Solr\Content\Search\FieldNameGenerator,
eZ\Publish\Core\Persistence\Solr\Content\Search\FieldRegistry;
/**
* Visits the Field criterion
*/
abstract class Field extends CriterionVisitor
{
/**
* Field registry
*
* @var \eZ\Publish\Core\Persistence\Solr\Content\Search\FieldRegistry
*/
protected $fieldRegistry;
/**
* Content type handler
*
* @var \eZ\Publish\SPI\Persistence\Content\Type\Handler
*/
protected $contentTypeHandler;
/**
* Field name generator
*
* @var FieldNameGenerator
*/
protected $nameGenerator;
/**
* Available field types
*
* @var array
*/
protected $fieldTypes;
/**
* Create from content type handler and field registry
*
* @param FieldRegistry $fieldRegistry
* @param ContentTypeHandler $contentTypeHandler
* @return void
*/
public function __construct( FieldRegistry $fieldRegistry, ContentTypeHandler $contentTypeHandler, FieldNameGenerator $nameGenerator )
{
$this->fieldRegistry = $fieldRegistry;
$this->contentTypeHandler = $contentTypeHandler;
$this->nameGenerator = $nameGenerator;
}
/**
* Get field type information
*
* @return void
*/
protected function getFieldTypes()
{
if ( $this->fieldTypes !== null )
{
return $this->fieldTypes;
}
foreach ( $this->contentTypeHandler->loadAllGroups() as $group )
{
foreach ( $this->contentTypeHandler->loadContentTypes( $group->id ) as $contentType )
{
foreach ( $contentType->fieldDefinitions as $fieldDefinition )
{
$fieldType = $this->fieldRegistry->getType( $fieldDefinition->fieldType );
foreach ( $fieldType->getIndexDefinition() as $name => $type )
{
$this->fieldTypes[$fieldDefinition->identifier][] =
$this->nameGenerator->getTypedName(
$this->nameGenerator->getName( $name, $fieldDefinition->identifier, $contentType->identifier ),
$type
);
}
}
}
}
return $this->fieldTypes;
}
}
|
#!/usr/bin/env python
# Taken from https://github.com/yudanta/capturein/blob/master/app/decorators/authdecorators.py
# With litle modification
from datetime import datetime
from functools import wraps
from flask import g, request, redirect, url_for
from app import app
from app.helpers.RestHelper import RestHelper
def token_required(method):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
#check token is valid or not
token = ''
if method == 'POST' and 'token' in request.form:
token = request.form['token']
if method == 'GET' and request.args.get('token') != None:
token = request.args.get('token')
if token == '' or token == None:
return RestHelper().build_response(412, 412, {}, 'Token required')
else:
#check
if token == app.config['ACCESS_TOKEN']:
return f(*args, **kwargs)
else:
return RestHelper().build_response(403, 403, {}, 'Unauthorized!')
return decorated_function
return decorator
|
/*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#ifndef __JUCE_DECIBELS_JUCEHEADER__
#define __JUCE_DECIBELS_JUCEHEADER__
//==============================================================================
/**
This class contains some helpful static methods for dealing with decibel values.
*/
class Decibels
{
public:
//==============================================================================
/** Converts a dBFS value to its equivalent gain level.
A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
decibel value lower than minusInfinityDb will return a gain of 0.
*/
template <typename Type>
static Type decibelsToGain (const Type decibels,
const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
{
return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
: Type();
}
/** Converts a gain level into a dBFS value.
A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
If the gain is 0 (or negative), then the method will return the value
provided as minusInfinityDb.
*/
template <typename Type>
static Type gainToDecibels (const Type gain,
const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
{
return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
: minusInfinityDb;
}
//==============================================================================
/** Converts a decibel reading to a string, with the 'dB' suffix.
If the decibel value is lower than minusInfinityDb, the return value will
be "-INF dB".
*/
template <typename Type>
static String toString (const Type decibels,
const int decimalPlaces = 2,
const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
{
String s;
if (decibels <= minusInfinityDb)
{
s = "-INF dB";
}
else
{
if (decibels >= Type())
s << '+';
s << String (decibels, decimalPlaces) << " dB";
}
return s;
}
private:
//==============================================================================
enum
{
defaultMinusInfinitydB = -100
};
Decibels(); // This class can't be instantiated, it's just a holder for static methods..
JUCE_DECLARE_NON_COPYABLE (Decibels);
};
#endif // __JUCE_DECIBELS_JUCEHEADER__
|
import random
import math
from TimeBar import TimeBar
from pylash.core import stage
from pylash.display import Sprite, Bitmap, BitmapData, Shape, TextField, TextFormatWeight, TextFormatAlign
from pylash.events import MouseEvent
class GameLayer(Sprite):
def __init__(self, bg):
super(GameLayer, self).__init__()
self.blockLayer = None
self.characters = (("我", "找"), ("王", "玉"), ("籍", "藉"), ("春", "舂"), ("龙", "尤"), ("已", "己"), ("巳", "已"))
# add background
bg = Bitmap(BitmapData(bg, 50, 50))
self.addChild(bg)
# start game
self.start()
def createTimeBar(self):
self.timeBar = TimeBar()
self.timeBar.x = stage.width - 70
self.timeBar.y = (stage.height - self.timeBar.height) / 2
self.addChild(self.timeBar)
def startLevel(self, char):
# get random position of target
targetX = random.randint(0, 9)
targetY = random.randint(0, 9)
self.blockLayer = Sprite()
self.blockLayer.x = 50
self.blockLayer.y = 50
self.blockLayer.alpha = 0.7
self.blockLayer.mouseChildren = False
self.addChild(self.blockLayer)
shapeLayer = Sprite()
self.blockLayer.addChild(shapeLayer)
txtLayer = Sprite()
self.blockLayer.addChild(txtLayer)
# create blocks with a character
for i in range(10):
for j in range(10):
block = Shape()
block.x = j * 50
block.y = i * 50
block.graphics.beginFill("#33CCFF")
block.graphics.lineStyle(5, "#0066FF")
block.graphics.drawRect(0, 0, 50, 50)
block.graphics.endFill()
shapeLayer.addChild(block)
txt = TextField()
txt.size = 20
txt.font = "Microsoft YaHei"
# when this block is target
if i == targetY and j == targetX:
txt.text = char[1]
block.isTarget = True
# when this block is not target
else:
txt.text = char[0]
block.isTarget = False
txt.x = block.x + (50 - txt.width) / 2
txt.y = block.y + (50 - txt.height) / 2
txtLayer.addChild(txt)
self.blockLayer.addEventListener(MouseEvent.MOUSE_UP, self.check)
def check(self, e):
global gameOver
clickX = math.floor(e.selfX / 50)
clickY = math.floor(e.selfY / 50)
shapeLayer = self.blockLayer.getChildAt(0)
b = shapeLayer.getChildAt(clickY * 10 + clickX)
if b.isTarget:
self.gameOver("win")
def gameOver(self, flag):
self.blockLayer.remove()
if flag == "win":
self.levelIndex += 1
if self.levelIndex >= len(self.characters):
self.addResultLayer("Level Clear!", "Time: %s" % int(self.timeBar.usedTime))
self.timeBar.remove()
else:
self.startLevel(self.characters[self.levelIndex])
elif flag == "lose":
self.addResultLayer("Time is Up!", "Level: %s" % (self.levelIndex))
self.timeBar.remove()
def addResultLayer(self, *text):
resultLayer = Sprite()
self.addChild(resultLayer)
for i in text:
txt = TextField()
txt.font = "Microsoft YaHei"
txt.text = i
txt.size = 40
txt.textAlign = TextFormatAlign.CENTER
txt.x = stage.width / 2
txt.y = resultLayer.height + 20
txt.textColor = "orangered"
txt.weight = TextFormatWeight.BOLD
resultLayer.addChild(txt)
# add a botton used for restart
restartBtn = Sprite()
restartBtn.graphics.beginFill("yellow")
restartBtn.graphics.lineStyle(3, "orangered")
restartBtn.graphics.drawRect(0, 0, 200, 60)
restartBtn.graphics.endFill()
restartBtn.x = (stage.width - restartBtn.width) / 2
restartBtn.y = resultLayer.height + 50
resultLayer.addChild(restartBtn)
restartTxt = TextField()
restartTxt.font = "Microsoft YaHei"
restartTxt.text = "Restart"
restartTxt.textColor = "orangered"
restartTxt.size = 30
restartTxt.x = (restartBtn.width - restartTxt.width) / 2
restartTxt.y = (restartBtn.height - restartTxt.height) / 2
restartBtn.addChild(restartTxt)
def restart(e):
self.start()
resultLayer.remove()
restartBtn.addEventListener(MouseEvent.MOUSE_UP, restart)
# make the result layer locate at vertical center
resultLayer.y = (stage.height - resultLayer.height) / 2
def start(self):
self.levelIndex = 0
# add time bar
self.createTimeBar()
# start level 1
self.startLevel(self.characters[0])
|
from epidag.factory import get_workshop
import epidag.factory.arguments as vld
from .trigger import *
from .behaviour import *
from .modbe import *
from .lifebe import *
from .publisher import *
__author__ = 'TimeWz667'
__all__ = ['PassiveModBehaviour', 'ActiveModBehaviour',
'TransitionTrigger', 'StateTrigger', 'StateEnterTrigger', 'StateExitTrigger',
'ExternalShock',
'FDShock', 'FDShockFast', 'DDShock', 'DDShockFast',
'WeightedSumShock', 'WeightedAvgShock', 'NetShock', 'NetWeightShock',
'SwitchOn', 'SwitchOff',
'Reincarnation', 'Cohort', 'LifeRate', 'LifeS', 'AgentImport',
'BirthAgeingDeathLeeCarter',
'StateTrack',
'register_behaviour']
StSpBeLibrary = get_workshop('StSpABM_BE')
def register_behaviour(tp, obj, args):
StSpBeLibrary.register(tp, obj, args, meta=['Name'])
register_behaviour('Cohort', Cohort, [vld.Options('s_death', 'states')])
StSpBeLibrary.register('Cohort', Cohort, [vld.Options('s_death', 'states')], meta=['Name'])
register_behaviour('Reincarnation', Reincarnation,
[vld.Options('s_death', 'states'), vld.Options('s_birth', 'states')])
register_behaviour('LifeRate', LifeRate,
[vld.Options('s_death', 'states'), vld.Options('s_birth', 'states'),
vld.PositiveFloat('rate'), vld.PositiveFloat('dt', opt=True, default=0.5)])
register_behaviour('LifeS', LifeS,
[vld.Options('s_death', 'states'), vld.Options('s_birth', 'states'),
vld.PositiveFloat('rate'), vld.PositiveFloat('cap'),
vld.PositiveFloat('dt', opt=True, default=0.5)])
register_behaviour('StateTrack', StateTrack,
[vld.Options('s_src', 'states')])
register_behaviour('ExternalShock', ExternalShock,
[vld.Options('t_tar', 'transitions')])
register_behaviour('FDShock', FDShock,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states')])
register_behaviour('FDShockFast', FDShockFast,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states'),
vld.PositiveFloat('dt', opt=True, default=0.5)])
register_behaviour('DDShock', DDShock,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states')])
register_behaviour('DDShockFast', DDShockFast,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states'),
vld.PositiveFloat('dt', opt=True, default=0.5)])
register_behaviour('SwitchOff', SwitchOff,
[vld.Options('t_tar', 'transitions'),
vld.Options('s_src', 'states'),
vld.Prob('prob')])
register_behaviour('SwitchOn', SwitchOn,
[vld.Options('t_tar', 'transitions'),
vld.Options('s_src', 'states'),
vld.Prob('prob')])
register_behaviour('WeightedSumShock', WeightedSumShock,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states'),
vld.ProbTab('weight'), vld.PositiveFloat('dt', opt=True, default=0.5)])
register_behaviour('WeightedAvgShock', WeightedAvgShock,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states'),
vld.ProbTab('weight'), vld.PositiveFloat('dt', opt=True, default=0.5)])
register_behaviour('NetShock', NetShock,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states'),
vld.Options('net', 'networks')])
register_behaviour('NetWeightShock', NetWeightShock,
[vld.Options('t_tar', 'transitions'), vld.Options('s_src', 'states'),
vld.Options('net', 'networks'), vld.ProbTab('weight')])
register_behaviour('AgentImport', AgentImport, [vld.Options('s_birth', 'states')])
register_behaviour('BirthAgeingDeathLeeCarter', BirthAgeingDeathLeeCarter,
[vld.Options('s_death', 'states'),
vld.Options('t_die', 'transitions'),
vld.Options('s_birth', 'states'),
vld.NotNull('dlc')])
register_behaviour('CohortLeeCarter', CohortLeeCarter,
[vld.Options('s_death', 'states'),
vld.Options('t_die', 'transitions'),
vld.NotNull('dlc')])
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Cutlass: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" async src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Cutlass
</div>
<div id="projectbrief">CUDA Templates for Linear Algebra Subroutines and Solvers</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.14 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacecutlass.html">cutlass</a></li><li class="navelem"><a class="el" href="namespacecutlass_1_1platform.html">platform</a></li><li class="navelem"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html">is_base_of_helper</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">cutlass::platform::is_base_of_helper< BaseT, DerivedT > Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html">cutlass::platform::is_base_of_helper< BaseT, DerivedT ></a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html#a5bf08859497e304ca353699ad6ac332b">check</a>(DerivedT *, T)</td><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html">cutlass::platform::is_base_of_helper< BaseT, DerivedT ></a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html#ae8896817cabf297437b3a073e693ffd2">check</a>(BaseT *, int)</td><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html">cutlass::platform::is_base_of_helper< BaseT, DerivedT ></a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html#ae096aa6c67f60d8d9c5a4b084118a8af">no</a> typedef</td><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html">cutlass::platform::is_base_of_helper< BaseT, DerivedT ></a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html#ac7e3ab73057682cc2eb6ed74c33e5eff">value</a></td><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html">cutlass::platform::is_base_of_helper< BaseT, DerivedT ></a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html#ac1cf3f804e7686213fd42c678cc6d669">yes</a> typedef</td><td class="entry"><a class="el" href="structcutlass_1_1platform_1_1is__base__of__helper.html">cutlass::platform::is_base_of_helper< BaseT, DerivedT ></a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Oct 26 2018 14:53:40 for Cutlass by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.14
</small></address>
</body>
</html>
|
from PyObjCTools.TestSupport import *
from Foundation import *
class TestNSPointerFunctions (TestCase):
def testConstants(self):
self.assertEqual(NSPointerFunctionsStrongMemory, (0 << 0))
self.assertEqual(NSPointerFunctionsZeroingWeakMemory, (1 << 0))
self.assertEqual(NSPointerFunctionsOpaqueMemory, (2 << 0))
self.assertEqual(NSPointerFunctionsMallocMemory, (3 << 0))
self.assertEqual(NSPointerFunctionsMachVirtualMemory, (4 << 0))
self.assertEqual(NSPointerFunctionsObjectPersonality, (0 << 8))
self.assertEqual(NSPointerFunctionsOpaquePersonality, (1 << 8))
self.assertEqual(NSPointerFunctionsObjectPointerPersonality, (2 << 8))
self.assertEqual(NSPointerFunctionsCStringPersonality, (3 << 8))
self.assertEqual(NSPointerFunctionsStructPersonality, (4 << 8))
self.assertEqual(NSPointerFunctionsIntegerPersonality, (5 << 8))
self.assertEqual(NSPointerFunctionsCopyIn, (1 << 16))
@min_os_level('10.8')
def testConstants10_8(self):
self.assertEqual(NSPointerFunctionsWeakMemory, 5<<0)
def testPropType(self):
o = NSPointerFunctions.alloc().initWithOptions_(0)
v = o.usesStrongWriteBarrier()
self.assertTrue((v is True) or (v is False) )
self.assertArgIsBOOL(o.setUsesStrongWriteBarrier_, 0)
self.assertArgIsBOOL(o.setUsesWeakReadAndWriteBarriers_, 0)
v = o.usesWeakReadAndWriteBarriers()
self.assertTrue((v is True) or (v is False) )
if __name__ == "__main__":
main()
|
$('#section').on('click', '[id$="Empty"]', function(event) {
event.preventDefault();
var match = /(.+)Empty/.exec($(event.target).closest('.unwell').attr('id'));
var id = match[1];
var emptyId = match[0];
$('#'+id).trigger('addrow');
$('#'+emptyId).addClass('hidden');
return false;
});
$('#section').on('submit', 'form[name="formItem"]', function(e) {
e.preventDefault();
var form = $(this),
btn = form.find('.btn-primary'),
valid = isFormValid(form);
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
if($(e).val() == "Select an option"){
valid = false;
showPermanentError(form, "Please select a valid action.");
}
});
if (valid) {
btn.button('loading');
resetAlert($('#section'));
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize()
}).always(function() {
btn.button('reset');
}).done(function(data, textStatus, jqXHR) {
showSuccess(form, "Saved");
window.location.hash = "#config/portal_module/"+form.find('input[name="id"]').val()+"/read"
}).fail(function(jqXHR) {
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(form, status_msg);
});
}
});
$('#section').on('click', '.delete-portal-module', function(e){
e.preventDefault();
var button = $(e.target);
button.button('loading');
$.ajax({
type: 'GET',
url: button.attr('href'),
}).always(function() {
}).done(function(data, textStatus, jqXHR) {
showSuccess(button.closest('.table'), "Deleted");
button.closest('tr').remove();
}).fail(function(jqXHR) {
button.button('reset');
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(button.closest('.table'), status_msg);
});
return false;
});
$('#section').on('click', '.expand', function(e){
e.preventDefault();
$(e.target).hide(function(){
$($(e.target).attr('data-expand')).slideDown();
});
return false;
});
$('#section').on('change', '#actions select[name$=".type"]', function(event) {
var type_input = $(event.currentTarget);
updateActionMatchInput(type_input,false);
});
$('#section').on('click', '#actionsContainer a[href="#add"]', function(event) {
setTimeout(initActionMatchInput, 3000);
});
function initActionMatchInput() {
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
updateActionMatchInput($(e),true);
});
}
function updateActionMatchInput(type_input, keep) {
var match_input = type_input.next();
var type_value = type_input.val();
var match_input_template_id = '#' + type_value + "_action_match";
var match_input_template = $(match_input_template_id);
if ( match_input_template.length == 0 ) {
match_input_template = $('#default_action_match');
}
if ( match_input_template.length ) {
changeInputFromTemplate(match_input, match_input_template, keep);
if (type_value == "switch") {
type_input.next().typeahead({
source: searchSwitchesGenerator($('#section h2')),
minLength: 2,
items: 11,
matcher: function(item) { return true; }
});
}
}
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Thu Oct 23 20:37:10 CEST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.richfaces.view.facelets.html.BehaviorsTagHandlerDelegateFactoryImpl (RichFaces Distribution Assembler 4.5.0.Final API)</title>
<meta name="date" content="2014-10-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.richfaces.view.facelets.html.BehaviorsTagHandlerDelegateFactoryImpl (RichFaces Distribution Assembler 4.5.0.Final API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/richfaces/view/facelets/html/BehaviorsTagHandlerDelegateFactoryImpl.html" title="class in org.richfaces.view.facelets.html">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>RichFaces Distribution Assembler 4.5.0.Final</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/richfaces/view/facelets/html/class-use/BehaviorsTagHandlerDelegateFactoryImpl.html" target="_top">Frames</a></li>
<li><a href="BehaviorsTagHandlerDelegateFactoryImpl.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.richfaces.view.facelets.html.BehaviorsTagHandlerDelegateFactoryImpl" class="title">Uses of Class<br>org.richfaces.view.facelets.html.BehaviorsTagHandlerDelegateFactoryImpl</h2>
</div>
<div class="classUseContainer">No usage of org.richfaces.view.facelets.html.BehaviorsTagHandlerDelegateFactoryImpl</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/richfaces/view/facelets/html/BehaviorsTagHandlerDelegateFactoryImpl.html" title="class in org.richfaces.view.facelets.html">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>RichFaces Distribution Assembler 4.5.0.Final</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/richfaces/view/facelets/html/class-use/BehaviorsTagHandlerDelegateFactoryImpl.html" target="_top">Frames</a></li>
<li><a href="BehaviorsTagHandlerDelegateFactoryImpl.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All Rights Reserved.</small></p>
</body>
</html>
|
from mock import MagicMock, ANY
from ecomaps.model import Analysis
from ecomaps.services.tests.base import BaseTest
from ecomaps.services.analysis import AnalysisService
from ecomaps.model import Dataset
import os
__author__ = 'Chirag Mistry (Tessella)'
class AnalysisServiceTest(BaseTest):
sample_analysis = None
def setUp(self):
super(AnalysisServiceTest, self).setUp()
self.sample_analysis = Analysis()
self.sample_analysis.name = 'Test User'
self.sample_analysis.user_id = 1
self.sample_analysis.point_data_dataset_id = 2
self.sample_analysis.coverage_dataset_ids = ['1_LandCover','3_LandCover']
self.sample_analysis.parameters = []
self.sample_analysis.id = 12
self.sample_analysis.input_hash = 12345
self.sample_analysis.model_id = 1
self.sample_analysis.description = 'Analysis for testing purposes'
results_dataset = Dataset()
results_dataset.type = 'Result'
results_dataset.viewable_by_user_id = 1
results_dataset.name = 'Example Results Dataset 1'
self.sample_analysis.result_dataset = results_dataset
def test_create_analysis(self):
# Important - don't instantiate the mock class,
# as the session creation function in the service
# will do that for us
self._mock_session.add = MagicMock()
self._mock_session.commit = MagicMock()
time_indicies = {}
analysis_service = AnalysisService(self._mock_session)
analysis_service.create(self.sample_analysis.name,
self.sample_analysis.point_data_dataset_id,
self.sample_analysis.coverage_dataset_ids,
self.sample_analysis.user_id,
self.sample_analysis.unit_of_time,
self.sample_analysis.random_group,
self.sample_analysis.model_variable,
self.sample_analysis.data_type,
self.sample_analysis.model_id,
self.sample_analysis.description,
self.sample_analysis.input_hash,
time_indicies)
self._mock_session.add.assert_called_once_with(ANY)
self._mock_session.commit.assert_called_once_with()
def test_publish_analysis(self):
mock_query_result = MagicMock()
mock_query_result.one = MagicMock(return_value=self.sample_analysis)
mock_query = MagicMock()
mock_query.filter = MagicMock()
mock_query.filter.return_value = mock_query_result
self._mock_session.query = MagicMock()
self._mock_session.query.return_value = mock_query
analysis_service = AnalysisService(self._mock_session)
analysis_service.publish_analysis(self.sample_analysis.id)
self.assertEqual(self.sample_analysis.viewable_by, None)
self.assertEqual(self.sample_analysis.result_dataset.viewable_by_user_id, None)
def test_get_ncdf_file(self):
url = 'http://localhost:8080/thredds/dodsC/testAll/LCM2007_GB_1K_DOM_TAR.nc'
analysis_service = AnalysisService()
results_file = analysis_service.get_netcdf_file(url)
# Check HTTP status code of the object returned:
# 200 indicates a successful request.
self.assertEqual(results_file.getcode(), 200)
def test_delete_private_analysis(self):
mock_query_result = MagicMock()
mock_query_result.one = MagicMock(return_value=self.sample_analysis)
mock_query = MagicMock()
mock_query.filter = MagicMock()
mock_query.filter.return_value = mock_query_result
self._mock_session.query = MagicMock()
self._mock_session.query.return_value = mock_query
analysis_service = AnalysisService(self._mock_session)
analysis_service.delete_private_analysis(self.sample_analysis.id)
self.assertEqual(self.sample_analysis.deleted, True)
|
import weakref
from textwrap import dedent
from kinko.types import Record, StringType, IntType, ListType, Func, TypeRef
from kinko.typedef import load_types
from .base import TestCase, TYPE_EQ_PATCHER
class TestTypeDefinition(TestCase):
ctx = [TYPE_EQ_PATCHER]
def test(self):
src = """
type func
Fn [String Integer] String
type Foo
Record
:name String
:type Integer
type Bar
Record
:name String
:foo-list (List Foo)
type Baz
Record
:name String
:type Integer
:bar Bar
"""
src = dedent(src).strip() + '\n'
func_type = Func[[StringType, IntType], StringType]
FooType = Record[{'name': StringType, 'type': IntType}]
BarType = Record[{'name': StringType,
'foo-list': ListType[TypeRef['Foo']]}]
BarType.__items__['foo-list'].__item_type__.__ref__ = \
weakref.ref(FooType)
BazType = Record[{'name': StringType, 'type': IntType,
'bar': TypeRef['Bar']}]
BazType.__items__['bar'].__ref__ = weakref.ref(BarType)
self.assertEqual(
load_types(src),
{
'func': func_type,
'Foo': FooType,
'Bar': BarType,
'Baz': BazType,
},
)
|
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <[email protected]>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef _U2_DOCUMENTFOLDERS_H_
#define _U2_DOCUMENTFOLDERS_H_
#include <QStringList>
#include <U2Core/U2OpStatus.h>
#include <U2Core/U2Type.h>
namespace U2 {
class GObject;
class Folder;
class DocumentFoldersUpdate {
public:
DocumentFoldersUpdate();
DocumentFoldersUpdate(const U2DbiRef &dbiRef, U2OpStatus &os);
QStringList folders; // all folders
QHash<U2DataId, QString> objectIdFolders; // objectId -> path
QHash<U2Object, QString> u2objectFolders; // U2Object -> path
};
/**
* The auxiliary class for encapsulating object <-> folder info
*/
class FolderObjectTreeStorage {
public:
bool hasObject(const U2DataId &id) const;
GObject * getObject(const U2DataId &id) const;
void addObject(GObject *obj, const QString &path);
void removeObject(GObject *obj, const QString &path);
void moveObject(GObject *obj, const QString &oldPath, const QString &newPath);
QString getObjectFolder(GObject *obj) const;
QList<GObject*> getObjectsNatural(const QString &path) const;
const DocumentFoldersUpdate & getLastUpdate() const;
// objects from DB which have IDs from the `ids` list won't be affected by merging procedure
// pass an empty set as `ids` to unset the filter
void setIgnoredObjects(const QSet<U2DataId> &ids);
void addIgnoredObject(const U2DataId &id);
// folders from DB which have paths from the `paths` list won't be affected by merging procedure
// pass an empty set as `paths` to unset the filter
void setIgnoredFolders(const QSet<QString> &paths);
void addIgnoredFolder(const QString &path);
void excludeFromObjFilter(const QSet<U2DataId> &ids);
void excludeFromFolderFilter(const QSet<QString> &paths);
bool isObjectIgnored(const U2DataId &id) const;
bool isFolderIgnored(const QString &path) const;
protected:
void setLastUpdate(const DocumentFoldersUpdate &value);
const QStringList & allFolders() const;
void addFolderToStorage(const QString &path); // insert sorted
void removeFolderFromStorage(const QString &path);
bool hasFolderInfo(const U2DataId &id) const;
bool hasFolderInfo(GObject *obj) const;
QString getFolderByObjectId(const U2DataId &id) const;
/** Returns the insertion pos */
static int insertSorted(const QString &value, QStringList &list);
private:
/**
* Four structures:
* 1) lastUpdate.objectIdFolders
* 2) objectsIds
* 3) objectFolders
* 4) folderObjects
* can be only simultaneously modified! Support the consistency for them!
*/
DocumentFoldersUpdate lastUpdate;
QHash<U2DataId, GObject*> objectsIds; // objectId -> GObject
QHash<GObject*, QString> objectFolders; // GObject -> path
QHash<QString, QList<GObject *> > folderObjects; // path -> GObject
// these objects and folders won't be affected during merge
QSet<U2DataId> ignoredObjects;
QSet<QString> ignoredPaths;
};
class DocumentFolders : public FolderObjectTreeStorage {
public:
DocumentFolders();
void init(Document *doc, U2OpStatus &os);
bool hasFolder(const QString &path) const;
Folder * getFolder(const QString &path) const;
void addFolder(const QString &path);
void removeFolder(const QString &path);
void renameFolder(const QString &oldPath, const QString &newPath);
int getNewFolderRowInParent(const QString &path) const;
int getNewObjectRowInParent(GObject *obj, const QString &parentPath) const;
QList<Folder*> getSubFolders(const QString &path) const;
QList<GObject*> getObjects(const QString &path) const;
QStringList getAllSubFolders(const QString &path) const;
static QString getParentFolder(const QString &path);
private:
QStringList calculateSubFoldersNames(const QString &parentPath) const;
QList<Folder*> & cacheSubFoldersNames(const QString &parentPath, const QStringList &subFoldersNames) const;
void onFolderAdded(const QString &path); // updates caches
void onFolderRemoved(Folder *folder); // updates caches
QList<Folder*> getSubFoldersNatural(const QString &path) const; // without recycle bin rules
void addFolderToCache(const QString &path);
private:
Document *doc;
mutable QHash<QString, Folder *> foldersMap; // path -> Folder
mutable QHash<QString, bool> hasCachedSubFolders;
mutable QHash<QString, QStringList> cachedSubFoldersNames; // sorted
mutable QHash<QString, QList<Folder *> > cachedSubFolders;
};
} // U2
#endif // _U2_DOCUMENTFOLDERS_H_
|
import * as Constants from '../constants/following_constants';
function fetchingHelper ( state = {
isFetching: false,
following: []
}, action ) {
switch ( action.type ) {
case Constants.REQUEST_FOLLOWING:
return Object.assign( {}, state, {
isFetching: true
});
case Constants.RECEIVE_FOLLOWING:
return Object.assign( {}, state, {
isFetching: false,
following: action.followingList
});
default:
return state
}
}
function compareHelper ( first, second ) {
let compareArr = [];
for ( let i = 0; i < first.length; i++ ) {
if ( !( second.includes( first[i] ) ) ) {
compareArr.push( first[i] );
}
}
return compareArr;
}
function errorHelper ( userObj = {}, action ) {
switch ( action.type ) {
case Constants.TWITTER_ERROR:
return Object.assign( {}, userObj, {
isFetching: false,
error: true
});
default:
return userObj
}
};
const followingHelpers = {
fetching: fetchingHelper,
compare: compareHelper,
error: errorHelper
}
export default followingHelpers;
|
//
// FileStream_POSIX.h
//
// Library: Foundation
// Package: Streams
// Module: FileStream
//
// Definition of the FileStreamBuf, FileInputStream and FileOutputStream classes.
//
// Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Foundation_FileStream_POSIX_INCLUDED
#define Foundation_FileStream_POSIX_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/BufferedBidirectionalStreamBuf.h"
#include <istream>
#include <ostream>
namespace Poco {
class Foundation_API FileStreamBuf: public BufferedBidirectionalStreamBuf
/// This stream buffer handles Fileio
{
public:
FileStreamBuf();
/// Creates a FileStreamBuf.
~FileStreamBuf();
/// Destroys the FileStream.
void open(const std::string& path, std::ios::openmode mode);
/// Opens the given file in the given mode.
bool close();
/// Closes the File stream buffer. Returns true if successful,
/// false otherwise.
std::streampos seekoff(std::streamoff off, std::ios::seekdir dir, std::ios::openmode mode = std::ios::in | std::ios::out);
/// Change position by offset, according to way and mode.
std::streampos seekpos(std::streampos pos, std::ios::openmode mode = std::ios::in | std::ios::out);
/// Change to specified position, according to mode.
protected:
enum
{
BUFFER_SIZE = 4096
};
int readFromDevice(char* buffer, std::streamsize length);
int writeToDevice(const char* buffer, std::streamsize length);
private:
std::string _path;
int _fd;
std::streamoff _pos;
};
} // namespace Poco
#endif // Foundation_FileStream_WIN32_INCLUDED
|
import urlparse
import os, sys,re
tools_dir = os.environ.get('TOOLSDIR')
lib_path = os.path.abspath(tools_dir)
sys.path.append(lib_path)
from msc_utils_parsing import *
from msc_apps import *
from pending import *
import tempfile
sys.path.append(os.path.abspath("../lib"))
from stats_backend import StatsBackend
error_codez= {
'-1': 'Exception thrown. Contact a developer.',
'-2': 'Server is in safe mode. Contact a developer.',
'-3': 'Unexpected type. Contact a developer.',
'-5': 'Invalid address or key. Contact a developer.',
'-7': 'Out of memory. Contact a developer.',
'-8': 'Invalid parameter. Contact a developer.',
'-20': 'Database error. Contact a developer.',
'-22': 'Error parsing transaction. Contact a developer.',
'-25': 'General error. Contact a developer.',
'-26': 'Transaction rejected by the network. Contact a developer.',
'-27': 'Transaction already in chain. Contact a developer.',
'1': 'Transaction malformed. Contact a developer.',
'16': 'Transaction was invalid. Contact a developer.',
'65': 'Transaction sent was under dust limit. Contact a developer.',
'66': 'Transaction did not meet fees. Contact a developer.',
'69.2': 'Your hair is on fire. Contact a stylist.'
}
def pushtx_response(response_dict):
expected_fields=['signedTransaction']
for field in expected_fields:
if not response_dict.has_key(field):
return (None, 'No field '+field+' in response dict '+str(response_dict))
if len(response_dict[field]) != 1:
return (None, 'Multiple values for field '+field)
signed_tx=response_dict['signedTransaction'][0]
response=pushtxnode(signed_tx)
if "NOTOK" not in response:
insertpending(signed_tx)
print signed_tx,'\n', response
return (response, None)
def pushtxnode(signed_tx):
import commands, json
signed_tx = re.sub(r'\W+', '', signed_tx) #check alphanumeric
#output=commands.getoutput('bitcoind sendrawtransaction ' + str(signed_tx) )
output=sendrawtransaction(str(signed_tx))
ret=re.findall('{.+',str(output))
if 'code' in ret[0]:
try:
output=json.loads(ret[0])
except TypeError:
output=ret[0]
except ValueError:
#reverse the single/double quotes and strip leading u in output to make it json compatible
output=json.loads(ret[0].replace("'",'"').replace('u"','"'))
response_status='NOTOK'
try:
response=json.dumps({"status":response_status, "pushed": error_codez[ str(output['code']) ], "message": output['message'], "code": output['code'] })
except KeyError, e:
response=json.dumps({"status":response_status, "pushed": str(e), "message": output['message'], "code": output['code'] })
else:
response_status='OK'
response=json.dumps({"status":response_status, "pushed": 'success', "tx": output['result'] })
print response
return response
def pushtx(signed_tx):
info(signed_tx)
f = tempfile.NamedTemporaryFile(mode='r+b',prefix='signedtx-', delete=False, dir='/var/lib/omniwallet/tmptx')
f.write(signed_tx)
f.close()
# validate tx first
ret=validate_tx(f.name)
if ret != None:
return ret
# broadcast
ret=broadcast_tx(f.name)
if ret != None:
return ret
else:
stats = StatsBackend()
stats.increment("amount_of_transactions")
return 'success'
def pushtx_handler(environ, start_response):
return general_handler(environ, start_response, pushtx_response)
|
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
http = require('http'),
path = require('path');
var app = express();
var MongoStore = require('connect-mongo')(express);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
store: new MongoStore({
host: 'localhost',
db: 'face-sessions',
collection: 'sessions',
}),
key: 'faces',
secret: '1234567890QWERTY',
cookie: {
path: '/',
maxAge: 172800000
}
}));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// GETS
app.get('/', routes.index);
app.get('/addface', routes.faces.addface);
app.get('/faces', routes.faces.index);
app.get('/myface', routes.faces.myface);
app.get('/theirface/:id', routes.faces.theirface);
app.get('/up', routes.faces.up);
// POSTS
// app.post('/books', routes.books.create);
app.post('/faces', routes.faces.save);
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
|
/* Copyright (c) Daniel Doubrovkine, All Rights Reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package com.sun.jna.platform.win32;
import junit.framework.TestCase;
import com.sun.jna.Native;
/**
* @author dblock[at]dblock[dot]org
*/
public class Crypt32UtilTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(Crypt32UtilTest.class);
}
public void testCryptProtectUnprotectData() {
byte[] data = new byte[2];
data[0] = 42;
data[1] = 12;
byte[] protectedData = Crypt32Util.cryptProtectData(data);
byte[] unprotectedData = Crypt32Util.cryptUnprotectData(protectedData);
assertEquals(data.length, unprotectedData.length);
assertEquals(data[0], unprotectedData[0]);
assertEquals(data[1], unprotectedData[1]);
}
public void testCryptProtectUnprotectMachineKey() {
String s = "Hello World";
byte[] data = Native.toByteArray(s);
byte[] protectedData = Crypt32Util.cryptProtectData(data,
WinCrypt.CRYPTPROTECT_LOCAL_MACHINE | WinCrypt.CRYPTPROTECT_UI_FORBIDDEN);
byte[] unprotectedData = Crypt32Util.cryptUnprotectData(protectedData,
WinCrypt.CRYPTPROTECT_LOCAL_MACHINE);
String unprotectedString = Native.toString(unprotectedData);
assertEquals(s, unprotectedString);
}
}
|
# coding: UTF-8
from __future__ import unicode_literals
import json
from datetime import datetime
from openpyxl import Workbook
import pytz
from xlsx_to_nosql import XlsxReader
UTC = pytz.utc
def test_instantiate():
reader = XlsxReader(filepath='src/tests/test-data/content.xlsx')
assert isinstance(reader.workbook, Workbook)
assert isinstance(reader.workbook.sheetnames, list)
assert reader.workbook.sheetnames == ['Films', 'Books']
assert reader.name == 'content.xlsx'
assert reader.db
assert repr(reader) == '<XlsxReader: content.xlsx>'
assert isinstance(reader.collections, dict)
def test_extract_as_python():
reader = XlsxReader(filepath='src/tests/test-data/content.xlsx')
expected_data = {
'Films': [
{
'row': 1,
'Film': 'Interstellar',
'Directed by': 'Christopher Nolan',
'Starring': ['Matthew McConaughey', 'Anne Hathaway'],
'Release date': datetime(2014, 10, 26, 0, 0, tzinfo=UTC),
'Running time': 169,
'Box office': 672700000,
},
],
'Books': [
{
'row': 1,
'Book': 'Northern Lights',
'Author': 'Philip Pullman',
'Publication date': datetime(1995, 7, 1, 0, 0, tzinfo=UTC),
'ISBN': '0-590-54178-1',
}
],
'_columns': [{
'Films': [
'Film', 'Directed by', 'Starring',
'Release date', 'Running time', 'Box office'
],
'Books': [
'Book', 'Author', 'Publication date', 'ISBN'
],
}]
}
assert expected_data == reader.data
def test_to_json():
reader = XlsxReader(filepath='src/tests/test-data/content.xlsx')
expected_json = '''{
"Films": [
{
"Directed by": "Christopher Nolan",
"Starring": ["Matthew McConaughey", "Anne Hathaway"],
"Running time": 169,
"Box office": 672700000,
"Release date": "2014-10-26T00:00:00+00:00",
"Film": "Interstellar",
"row": 1
}
],
"Books": [
{
"Author": "Philip Pullman",
"Book": "Northern Lights",
"ISBN": "0-590-54178-1",
"Publication date": "1995-07-01T00:00:00+00:00",
"row": 1
}
],
"_columns": [{
"Films": [
"Film", "Directed by", "Starring",
"Release date", "Running time", "Box office"
],
"Books": [
"Book", "Author", "Publication date", "ISBN"
]
}]
}'''
assert json.loads(expected_json) == json.loads(reader.to_json())
def test_db():
reader = XlsxReader(filepath='src/tests/test-data/content.xlsx')
films = reader.db.collection('Films')
books = reader.db.collection('Books')
columns = reader.db.collection('_columns')
assert len(films.all()) == 1
assert films.fetch(0) == {
'__id': 0,
'Film': 'Interstellar',
'Directed by': 'Christopher Nolan',
'Starring': ['Matthew McConaughey', 'Anne Hathaway'],
'Release date': '2014-10-26T00:00:00+00:00',
'Running time': 169,
'Box office': 672700000,
}
assert len(books.all()) == 1
assert books.fetch(0) == {
'__id': 0,
'Book': 'Northern Lights',
'Author': 'Philip Pullman',
'Publication date': '1995-07-01T00:00:00+00:00',
'ISBN': '0-590-54178-1',
}
assert len(columns.all()) == 1
assert columns.fetch(0) == {
'__id': 0,
'Films': [
'Film', 'Directed by', 'Starring',
'Release date', 'Running time', 'Box office'
],
'Books': [
'Book', 'Author', 'Publication date', 'ISBN'
],
}
|
/** A dummy source for no data. */
builder.datasource.none = {};
builder.datasource.register(builder.datasource.none);
builder.datasource.none.id = "none";
builder.datasource.none.name = _t('no_source');
builder.datasource.none.fetchRows = function(config, script, callback, failure) {
callback([{}]);
};
builder.datasource.none.showConfigDialog = function(callback) {
callback({});
};
builder.datasource.none.hideConfigDialog = function() {};
if (builder && builder.loader && builder.loader.loadNextMainScript) { builder.loader.loadNextMainScript(); }
|
//========================== Open Steamworks ================================
//
// This file is part of the Open Steamworks project. All individuals associated
// with this project do not claim ownership of the contents
//
// The code, comments, and all related files, projects, resources,
// redistributables included with this project are Copyright Valve Corporation.
// Additionally, Valve, the Valve logo, Half-Life, the Half-Life logo, the
// Lambda logo, Steam, the Steam logo, Team Fortress, the Team Fortress logo,
// Opposing Force, Day of Defeat, the Day of Defeat logo, Counter-Strike, the
// Counter-Strike logo, Source, the Source logo, and Counter-Strike Condition
// Zero are trademarks and or registered trademarks of Valve Corporation.
// All other trademarks are property of their respective owners.
//
//=============================================================================
#ifndef ISTEAMFRIENDS004_H
#define ISTEAMFRIENDS004_H
#ifdef _WIN32
#pragma once
#endif
#include "SteamTypes.h"
#include "FriendsCommon.h"
class ISteamFriends004
{
public:
// returns the local players name - guaranteed to not be NULL.
// this is the same name as on the users community profile page
// this is stored in UTF-8 format
// like all the other interface functions that return a char *, it's important that this pointer is not saved
// off; it will eventually be free'd or re-allocated
virtual const char *GetPersonaName() = 0;
// sets the player name, stores it on the server and publishes the changes to all friends who are online
virtual void SetPersonaName( const char *pchPersonaName ) = 0;
// gets the status of the current user
virtual EPersonaState GetPersonaState() = 0;
// friend iteration
// takes a set of k_EFriendFlags, and returns the number of users the client knows about who meet that criteria
// then GetFriendByIndex() can then be used to return the id's of each of those users
virtual int GetFriendCount( EFriendFlags eFriendFlags ) = 0;
// returns the steamID of a user
// iFriend is a index of range [0, GetFriendCount())
// iFriendsFlags must be the same value as used in GetFriendCount()
// the returned CSteamID can then be used by all the functions below to access details about the user
virtual CSteamID GetFriendByIndex( int iFriend, EFriendFlags eFriendFlags ) = 0;
// returns a relationship to a user
virtual EFriendRelationship GetFriendRelationship( CSteamID steamIDFriend ) = 0;
// returns the current status of the specified user
// this will only be known by the local user if steamIDFriend is in their friends list; on the same game server; in a chat room or lobby; or in a small group with the local user
virtual EPersonaState GetFriendPersonaState( CSteamID steamIDFriend ) = 0;
// returns the name another user - guaranteed to not be NULL.
// same rules as GetFriendPersonaState() apply as to whether or not the user knowns the name of the other user
// note that on first joining a lobby, chat room or game server the local user will not known the name of the other users automatically; that information will arrive asyncronously
virtual const char *GetFriendPersonaName( CSteamID steamIDFriend ) = 0;
// gets the avatar of the current user, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set
virtual int GetFriendAvatar( CSteamID steamIDFriend, int eAvatarSize ) = 0;
// returns true if the friend is actually in a game
virtual bool GetFriendGamePlayed( CSteamID steamIDFriend, uint64 *pulGameID, uint32 *punGameIP, uint16 *pusGamePort, uint16 *pusQueryPort ) = 0;
// accesses old friends names - returns an empty string when their are no more items in the history
virtual const char *GetFriendPersonaNameHistory( CSteamID steamIDFriend, int iPersonaName ) = 0;
// returns true if the specified user meets any of the criteria specified in iFriendFlags
// iFriendFlags can be the union (binary or, |) of one or more k_EFriendFlags values
virtual bool HasFriend( CSteamID steamIDFriend, EFriendFlags eFriendFlags ) = 0;
// clan (group) iteration and access functions
virtual int GetClanCount() = 0;
virtual CSteamID GetClanByIndex( int iClan ) = 0;
virtual const char *GetClanName( CSteamID steamIDClan ) = 0;
// iterators for getting users in a chat room, lobby, game server or clan
// note that large clans that cannot be iterated by the local user
// steamIDSource can be the steamID of a group, game server, lobby or chat room
virtual int GetFriendCountFromSource( CSteamID steamIDSource ) = 0;
virtual CSteamID GetFriendFromSourceByIndex( CSteamID steamIDSource, int iFriend ) = 0;
// returns true if the local user can see that steamIDUser is a member or in steamIDSource
virtual bool IsUserInSource( CSteamID steamIDUser, CSteamID steamIDSource ) = 0;
// User is in a game pressing the talk button (will suppress the microphone for all voice comms from the Steam friends UI)
virtual void SetInGameVoiceSpeaking( CSteamID steamIDUser, bool bSpeaking ) = 0;
// activates the game overlay, with an optional dialog to open
// valid options are "Friends", "Community", "Players", "Settings", "LobbyInvite", "OfficialGameGroup"
virtual void ActivateGameOverlay( const char *pchDialog ) = 0;
};
#endif // ISTEAMFRIENDS004_H
|
#!/usr/bin/python
# Copyright (c) 2014 Wladmir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory that is passed as an
argument:
nodes_main.txt
nodes_test.txt
These files must consist of lines in the format
<ip>
<ip>:<port>
[<ipv6>]
[<ipv6>]:<port>
<onion>.onion
0xDDBBCCAA (IPv4 little-endian old pnSeeds format)
The output will be two data structures with the peers in binary format:
static SeedSpec6 pnSeed6_main[]={
...
}
static SeedSpec6 pnSeed6_test[]={
...
}
These should be pasted into `src/chainparamsseeds.h`.
'''
from __future__ import print_function, division
from base64 import b32decode
from binascii import a2b_hex
import sys, os
import re
# ipv4 in ipv6 prefix
pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff])
# tor-specific ipv6 prefix
pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43])
def name_to_ipv6(addr):
if len(addr)>6 and addr.endswith('.onion'):
vchAddr = b32decode(addr[0:-6], True)
if len(vchAddr) != 16-len(pchOnionCat):
raise ValueError('Invalid onion %s' % s)
return pchOnionCat + vchAddr
elif '.' in addr: # IPv4
return pchIPv4 + bytearray((int(x) for x in addr.split('.')))
elif ':' in addr: # IPv6
sub = [[], []] # prefix, suffix
x = 0
addr = addr.split(':')
for i,comp in enumerate(addr):
if comp == '':
if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end
continue
x += 1 # :: skips to suffix
assert(x < 2)
else: # two bytes per component
val = int(comp, 16)
sub[x].append(val >> 8)
sub[x].append(val & 0xff)
nullbytes = 16 - len(sub[0]) - len(sub[1])
assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0))
return bytearray(sub[0] + ([0] * nullbytes) + sub[1])
elif addr.startswith('0x'): # IPv4-in-little-endian
return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:])))
else:
raise ValueError('Could not parse address %s' % addr)
def parse_spec(s, defaultport):
match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
if match: # ipv6
host = match.group(1)
port = match.group(2)
elif s.count(':') > 1: # ipv6, no port
host = s
port = ''
else:
(host,_,port) = s.partition(':')
if not port:
port = defaultport
else:
port = int(port)
host = name_to_ipv6(host)
return (host,port)
def process_nodes(g, f, structname, defaultport):
g.write('static SeedSpec6 %s[] = {\n' % structname)
first = True
for line in f:
comment = line.find('#')
if comment != -1:
line = line[0:comment]
line = line.strip()
if not line:
continue
if not first:
g.write(',\n')
first = False
(host,port) = parse_spec(line, defaultport)
hoststr = ','.join(('0x%02x' % b) for b in host)
g.write(' {{%s}, %i}' % (hoststr, port))
g.write('\n};\n')
def main():
if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef BECOIN_CHAINPARAMSSEEDS_H\n')
g.write('#define BECOIN_CHAINPARAMSSEEDS_H\n')
g.write('/**\n')
g.write(' * List of fixed seed nodes for the becoin network\n')
g.write(' * AUTOGENERATED by contrib/seeds/generate-seeds.py\n')
g.write(' *\n')
g.write(' * Each line contains a 16-byte IPv6 address and a port.\n')
g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n')
g.write(' */\n')
with open(os.path.join(indir,'nodes_main.txt'),'r') as f:
process_nodes(g, f, 'pnSeed6_main', 2333)
g.write('\n')
with open(os.path.join(indir,'nodes_test.txt'),'r') as f:
process_nodes(g, f, 'pnSeed6_test', 12333)
g.write('#endif // BECOIN_CHAINPARAMSSEEDS_H\n')
if __name__ == '__main__':
main()
|
using System;
using System.Collections.Generic;
#if DOUBLE
using Real = System.Double;
#elif NETSTANDARD2_1
using Real = System.Single;
using Math = System.MathF;
#else
using Real = System.Single;
using Math = KelpNet.MathF;
#endif
namespace KelpNet
{
#if !DOUBLE
[Serializable]
public class AdaDelta<T> : Optimizer<T> where T : unmanaged, IComparable<T>
{
public T Rho;
public T Epsilon;
private List<T[]> msg = new List<T[]>();
private List<T[]> msdx = new List<T[]>();
public AdaDelta(T? rho = null, T? epsilon = null)
{
this.Rho = rho??(TVal<T>)0.95;
this.Epsilon = epsilon??(TVal<T>)1e-6;
switch (this)
{
case AdaDelta<float> adaDeltaF:
adaDeltaF.Update = () => OptimizerF.Update(adaDeltaF);
adaDeltaF.UpdateFunctionParameters = (i) => AdaDeltaF.UpdateFunctionParameters(adaDeltaF.msg[i], adaDeltaF.msdx[i], adaDeltaF.Rho, adaDeltaF.Epsilon, adaDeltaF.FunctionParameters[i]);
break;
case AdaDelta<double> adaDeltaD:
adaDeltaD.Update = () => OptimizerD.Update(adaDeltaD);
adaDeltaD.UpdateFunctionParameters = (i) => AdaDeltaD.UpdateFunctionParameters(adaDeltaD.msg[i], adaDeltaD.msdx[i], adaDeltaD.Rho, adaDeltaD.Epsilon, adaDeltaD.FunctionParameters[i]);
break;
}
}
protected override void AddFunctionParameters(NdArray<T>[] functionParameters)
{
foreach (NdArray<T> functionParameter in functionParameters)
{
this.msg.Add(new T[functionParameter.Data.Length]);
this.msdx.Add(new T[functionParameter.Data.Length]);
}
}
}
#endif
#if DOUBLE
public static class AdaDeltaD
#else
public static class AdaDeltaF
#endif
{
public static void UpdateFunctionParameters(Real[] msg, Real[] msdx, Real rho, Real epsilon, NdArray<Real> functionParameter)
{
for (int i = 0; i < functionParameter.Data.Length; i++)
{
Real grad = functionParameter.Grad[i];
msg[i] *= rho;
msg[i] += (1 - rho) * grad * grad;
Real dx = Math.Sqrt((msdx[i] + epsilon) / (msg[i] + epsilon)) * grad;
msdx[i] *= rho;
msdx[i] += (1 - rho) * dx * dx;
functionParameter.Data[i] -= dx;
}
}
}
}
|
<?php
class docController extends Controller
{
public function indexAction()
{
$m = M("document");
$m2 = M('docType');
$list_type = $m2->find();
$types = array();
foreach ($list_type as $value) {
$types[$value['id']] = $value['name'];
}
$list = $m->find();
$this->assign('list',$list);
$this->assign('types',$types);
$this->assignPage('main','doc_list');
$this->display();
}
public function addAction()
{
//echo "string";
$m = M("docType");
$type_list = $m->find();
$this->assign('type_list',$type_list);
$this->assignPage('main','doc_add');
$this->display();
}
public function insertAction()
{
$m = M('document');
$m->create();
$m->set('created_at',DATETIME);
$result = $m->insert();
if($result !== false)
{
$id = $m->getInsertId();
if(isset($_POST['files']) && !empty($_POST['files']))
{
$m2 = M('docAttach');
$m2->set('document_id',$id)->update(array_map('intval', $_POST['files']) );
}
$this->to(null,'index');
}
}
public function editAction()
{
$m = M("document");
$id = (int)$_GET['id'];
$data = $m->findone($id);
$m2 = M('docType');
$list_type = $m2->find();
$types = array();
foreach ($list_type as $value) {
$types[$value['id']] = $value['name'];
}
$m3 = M('docAttach');
$list_attach = $m3->where("document_id='{$id}'")->find();
$this->assign('attachs',$list_attach);
$this->assign('types',$types);
$this->assign('data',$data);
$this->assignPage('main','doc_edit');
$this->display();
}
public function updateAction()
{
if(!isset($_POST['published'])) $_POST['published'] = 0;
$id = (int)$_POST['id'];
$m = M('document');
$m->create();
$result = $m->update($id);
if(false !== $result)
{
$m2 = M('docAttach');
//$m2->delete(array_map('intval', $_POST['files']));
if(isset($_POST['files']) && !empty($_POST['files']))
$m2->set('document_id',$id)->update(array_map('intval', $_POST['files']));
}
$this->to(null,'index');
}
public function deleteAction()
{
$m = M('document');
$m->delete((int)$_GET['id']);
$this->to(null,'index');
}
}
|
// /**
// * Created by ben on 11/6/15.
// */
// 'use strict';
import { Logger } from '../src/Logger';
import { expect } from 'chai';
import { ILoggerOptions } from '../src/ILoggerOptions';
import * as fs from 'fs';
import * as path from 'path';
describe('LOGGER', function () {
it('logs to file', function (done) {
var logger = new Logger({
name: 'bunyanlog.test'
} as ILoggerOptions);
logger.error('hello world');
var logFile = 'bunyanlog.test.log';
fs.stat(path.join('./logs/', logFile), function (error, stats) {
expect(error).to.equal(null);
expect(stats.isFile()).to.equal(true);
done();
});
});
});
|
""" Tests for editing descriptors"""
import unittest
import os
import logging
from mock import Mock
from pkg_resources import resource_string
from xmodule.editing_module import TabsEditingDescriptor
from xblock.field_data import DictFieldData
from xblock.fields import ScopeIds
from xmodule.tests import get_test_descriptor_system
log = logging.getLogger(__name__)
class TabsEditingDescriptorTestCase(unittest.TestCase):
""" Testing TabsEditingDescriptor"""
def setUp(self):
super(TabsEditingDescriptorTestCase, self).setUp()
system = get_test_descriptor_system()
system.render_template = Mock(return_value="<div>Test Template HTML</div>")
self.tabs = [
{
'name': "Test_css",
'template': "tabs/codemirror-edit.html",
'current': True,
'css': {
'scss': [resource_string(__name__,
'../../test_files/test_tabseditingdescriptor.scss')],
'css': [resource_string(__name__,
'../../test_files/test_tabseditingdescriptor.css')]
}
},
{
'name': "Subtitles",
'template': "video/subtitles.html",
},
{
'name': "Settings",
'template': "tabs/video-metadata-edit-tab.html"
}
]
TabsEditingDescriptor.tabs = self.tabs
self.descriptor = system.construct_xblock_from_class(
TabsEditingDescriptor,
field_data=DictFieldData({}),
scope_ids=ScopeIds(None, None, None, None),
)
def test_get_css(self):
"""test get_css"""
css = self.descriptor.get_css()
test_files_dir = os.path.dirname(__file__).replace('xmodule/tests', 'test_files')
test_css_file = os.path.join(test_files_dir, 'test_tabseditingdescriptor.scss')
with open(test_css_file) as new_css:
added_css = new_css.read()
self.assertEqual(css['scss'].pop(), added_css)
self.assertEqual(css['css'].pop(), added_css)
def test_get_context(self):
""""test get_context"""
rendered_context = self.descriptor.get_context()
self.assertListEqual(rendered_context['tabs'], self.tabs)
|
from nose.tools import assert_equal
from tui.protocol import generate_checktextformatrequest, \
parse_checktextformatrequest, \
generate_checktextformatresponse, \
parse_checktextformatresponse, \
generate_getscreeninforequest, \
parse_getscreeninforequest, \
generate_getscreeninforesponse, \
parse_getscreeninforesponse, \
generate_initsessionrequest, \
parse_initsessionrequest, \
generate_initsessionresponse, \
parse_initsessionresponse, \
generate_closesessionrequest, \
parse_closesessionrequest, \
generate_closesessionresponse, \
parse_closesessionresponse, \
generate_displayscreenrequest, \
parse_displayscreenrequest, \
generate_displayscreenresponse, \
parse_displayscreenresponse
def test_checktextformatrequest():
text = 'AAAFVTGERGERFGREGREJGIERJGIERJGJEROIJJEIOJGOIJERIOGJEROIGJ'
assert_equal(text,
parse_checktextformatrequest(generate_checktextformatrequest(text)))
def test_checktextformatresponse():
ret = 0
width = 300
height = 25
last_index = 63
assert_equal((ret, width, height, last_index),
parse_checktextformatresponse(
generate_checktextformatresponse(ret, width, height, last_index)))
def test_getscreeninforequest():
orientation = 1
nbentryfields = 5
assert_equal((orientation, nbentryfields),
parse_getscreeninforequest(
generate_getscreeninforequest(orientation, nbentryfields)))
def test_getscreeninforesponse():
params = (0,
8,
8,
8,
8,
2,
3,
5,
(255, 128, 0),
200,
70,
(
('OK', 100, 25, True, True),
('Cancel', 100, 1000, True, False),
('Next', 300, 220, False, True),
('Prev', 20, 25, True, False),
('Back', 80, 250, False, False),
('Forward', 90, 25, False, True)
)
)
assert_equal(params,
parse_getscreeninforesponse(generate_getscreeninforesponse(*params)))
def test_initsessionrequest():
parse_initsessionrequest(generate_initsessionrequest())
def test_initsessionresponse():
ret = 0
assert_equal(ret,
parse_initsessionresponse(generate_initsessionresponse(ret)))
def test_closesessionrequest():
parse_closesessionrequest(generate_closesessionrequest())
def test_closesessionresponse():
ret = 0
assert_equal(ret,
parse_closesessionresponse(generate_closesessionresponse(ret)))
def test_displayscreenrequest():
orientation = 1
labelimage = ('PNGDATAxcvlksdlkjsdlfjslkjf', 320, 200)
btnimage = ('PNGDATAxcvlksdlkjsdlfjslkjf', 320, 200)
emptyimage = ('', 0, 0)
label = ('LABEL TEXT', 5, 5, (128, 255, 128), labelimage, 0, 0)
buttons = (
('OK', emptyimage),
('Cancel', emptyimage),
('Next', emptyimage),
('Prev', emptyimage),
('Back', btnimage),
('FWD', emptyimage),
)
requestedbuttons = (False, True, True, False, True, False)
closetuisession = True
entryfields = (
('Your name', 1, 2, 3, 4),
('Password', 2, 3, 4, 5)
)
params = (orientation,
label,
buttons,
requestedbuttons,
closetuisession,
entryfields)
assert_equal(params,
parse_displayscreenrequest(
generate_displayscreenrequest(*params)))
def test_displayscreenresponse():
ret = 0
button = 2
entryfields = ('aaAAadjjidjqjiwjfioewjiofjewoifjweoifjewiofejwoifejwioefw',
'djqiwjdiqwodjicjwun23',
'420')
params = (ret, button, entryfields)
assert_equal(params,
parse_displayscreenresponse(
generate_displayscreenresponse(*params)))
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Avanzosc - Avanced Open Source Consulting
# Copyright (C) 2011 - 2013 Avanzosc <http://www.avanzosc.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
import mrp_bom_ext
import mrp_production_ext
import stock_move_ext
|
import { Nullable } from "../types";
import { Camera } from "../Cameras/camera";
import { Effect } from "../Materials/effect";
import { PostProcess, PostProcessOptions } from "./postProcess";
import { Engine } from "../Engines/engine";
import { Constants } from "../Engines/constants";
import "../Shaders/depthOfFieldMerge.fragment";
/**
* Options to be set when merging outputs from the default pipeline.
*/
export class DepthOfFieldMergePostProcessOptions {
/**
* The original image to merge on top of
*/
public originalFromInput: PostProcess;
/**
* Parameters to perform the merge of the depth of field effect
*/
public depthOfField?: {
circleOfConfusion: PostProcess;
blurSteps: Array<PostProcess>;
};
/**
* Parameters to perform the merge of bloom effect
*/
public bloom?: {
blurred: PostProcess;
weight: number;
};
}
/**
* The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
*/
export class DepthOfFieldMergePostProcess extends PostProcess {
/**
* Gets a string identifying the name of the class
* @returns "DepthOfFieldMergePostProcess" string
*/
public getClassName(): string {
return "DepthOfFieldMergePostProcess";
}
/**
* Creates a new instance of DepthOfFieldMergePostProcess
* @param name The name of the effect.
* @param originalFromInput Post process which's input will be used for the merge.
* @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
* @param blurSteps Blur post processes from low to high which will be mixed with the original image.
* @param options The required width/height ratio to downsize to before computing the render pass.
* @param camera The camera to apply the render pass to.
* @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
* @param engine The engine which the post process will be applied. (default: current engine)
* @param reusable If the post process can be reused on the same frame. (default: false)
* @param textureType Type of textures used when performing the post process. (default: 0)
* @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
*/
constructor(name: string, originalFromInput: PostProcess, circleOfConfusion: PostProcess, private blurSteps: Array<PostProcess>, options: number | PostProcessOptions, camera: Nullable<Camera>, samplingMode?: number, engine?: Engine, reusable?: boolean, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT, blockCompilation = false) {
super(name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true);
this.onApplyObservable.add((effect: Effect) => {
effect.setTextureFromPostProcess("textureSampler", originalFromInput);
effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
blurSteps.forEach((step, index) => {
effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
});
});
if (!blockCompilation) {
this.updateEffect();
}
}
/**
* Updates the effect with the current post process compile time values and recompiles the shader.
* @param defines Define statements that should be added at the beginning of the shader. (default: null)
* @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
* @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
* @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
* @param onCompiled Called when the shader has been compiled.
* @param onError Called if there is an error when compiling a shader.
*/
public updateEffect(defines: Nullable<string> = null, uniforms: Nullable<string[]> = null, samplers: Nullable<string[]> = null, indexParameters?: any,
onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void) {
if (!defines) {
defines = "";
defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
}
super.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError);
}
}
|
from django.contrib import admin
from django.utils.timesince import timesince
from . import models
class StatusListFilter(admin.SimpleListFilter):
title = 'status'
parameter_name = 'status'
def lookups(self, request, model_admin):
return (
('good', 'Good'),
('fair', 'Fair'),
('poor', 'Poor'),
('unknown', 'Unknown'),
)
def queryset(self, request, queryset):
if self.value():
return queryset.filter(status=self.value())
@admin.register(models.Domain)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'owner', )
list_filter = ('owner', )
search_fields = ('name', )
@admin.register(models.DomainCheck)
class DomainCheckAdmin(admin.ModelAdmin):
list_display = (
'domain', 'path', 'protocol', 'method', 'is_active',
'status', 'last_checked', )
list_filter = ('protocol', 'method', StatusListFilter, 'is_active', )
search_fields = ('domain__name', )
actions = ('run_check', 'mark_inactive', )
def get_queryset(self, request):
return super().get_queryset(request).status()
def status(self, obj):
return obj.status.title()
status.admin_order_field = 'success_rate'
def last_checked(self, obj):
if obj.last_check:
return '{} ago'.format(timesince(obj.last_check))
else:
return 'Never'
last_checked.admin_order_field = 'last_check'
def run_check(self, request, queryset):
for item in queryset:
item.run_check()
run_check.short_description = 'Run the domain check'
def mark_inactive(self, request, queryset):
ids = queryset.values_list('pk', flat=True)
count = self.model.objects.filter(pk__in=ids).update(is_active=False)
message = '{count} domain{plural} made inactive.'.format(
count=count, plural=' was' if count == 1 else 's were')
self.message_user(request, message)
mark_inactive.short_description = 'Make checks inactive'
@admin.register(models.CheckResult)
class CheckResultAdmin(admin.ModelAdmin):
date_hierarchy = 'checked_on'
list_display = ('domain_check', 'status_code', )
list_filter = ('checked_on', )
|
/***************************************************************************
* Copyright (C) 2014 by Serge Poltavski *
* [email protected] *
* *
* 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/> *
***************************************************************************/
#include <cmath>
#include <cstdlib>
#define CATCH_CONFIG_MAIN
#include "catch/include/catch.hpp"
#include "iso226.h"
bool cmp(double d1, double d2, double delta = 0.02) {
if(abs(d1 - d2) < delta)
return true;
return false;
}
TEST_CASE( "phon2spl", "phon2spl test" )
{
double res = 0;
REQUIRE(iso226_phon2spl(80, 1000, &res) == 0);
CHECK(cmp(res, 80));
REQUIRE(iso226_phon2spl(70, 1000, &res) == 0);
CHECK(cmp(res, 70));
REQUIRE(iso226_phon2spl(60, 1000, &res) == 0);
CHECK(cmp(res, 60));
REQUIRE(iso226_phon2spl(50, 1000, &res) == 0);
CHECK(cmp(res, 50));
REQUIRE(iso226_phon2spl(40, 1000, &res) == 0);
CHECK(cmp(res, 40));
REQUIRE(iso226_phon2spl(30, 1000, &res) == 0);
CHECK(cmp(res, 30));
REQUIRE(iso226_phon2spl(20, 1000, &res) == 0);
CHECK(cmp(res, 20));
for(int freq = 20; freq <= 12500; freq++) {
REQUIRE(iso226_phon2spl(20, freq, &res) == 0);
}
for(int freq = -20; freq < 20; freq++) {
REQUIRE_FALSE(iso226_phon2spl(20, freq, &res) == 0);
}
for(int freq = 12501; freq < 13000; freq++) {
REQUIRE_FALSE(iso226_phon2spl(20, freq, &res) == 0);
}
}
TEST_CASE( "spl2phon", "spl2phon test" ) {
double res = 0;
REQUIRE(iso226_spl2phon(80, 1000, &res) == 0);
CHECK(cmp(res, 80));
REQUIRE(iso226_spl2phon(70, 1000, &res) == 0);
CHECK(cmp(res, 70));
REQUIRE(iso226_spl2phon(60, 1000, &res) == 0);
CHECK(cmp(res, 60));
REQUIRE(iso226_spl2phon(50, 1000, &res) == 0);
CHECK(cmp(res, 50));
REQUIRE(iso226_spl2phon(40, 1000, &res) == 0);
CHECK(cmp(res, 40));
REQUIRE(iso226_spl2phon(30, 1000, &res) == 0);
CHECK(cmp(res, 30));
REQUIRE(iso226_spl2phon(20, 1000, &res) == 0);
CHECK(cmp(res, 20));
}
TEST_CASE( "<=>", "<=> test" ) {
double res0 = 0;
double res1 = 0;
REQUIRE(iso226_phon2spl(80, 1000, &res0) == 0);
REQUIRE(iso226_spl2phon(res0, 1000, &res1) == 0);
CHECK(cmp(res0, res0));
for(int freq = 20; freq <= 12500; freq += 2) {
for(int phon = 20; phon <= 80; phon += 2) {
REQUIRE(iso226_phon2spl(phon, freq, &res0) == 0);
REQUIRE(iso226_spl2phon(res0, freq, &res1) == 0);
CHECK(cmp(res0, res0, 0.015));
}
}
}
TEST_CASE( "error", "error test" ) {
for(int i = -1; i < 8; i++) {
CHECK(iso226_strerror(i) != NULL);
}
}
TEST_CASE( "phon2sone", "phon2sone test" ) {
double sone;
REQUIRE(iso226_phon2sone(40, &sone) == 0);
CHECK(cmp(sone, 1));
REQUIRE(iso226_phon2sone(50, &sone) == 0);
CHECK(cmp(sone, 2));
REQUIRE(iso226_phon2sone(60, &sone) == 0);
CHECK(cmp(sone, 4));
REQUIRE(iso226_phon2sone(70, &sone) == 0);
CHECK(cmp(sone, 8));
REQUIRE(iso226_phon2sone(80, &sone) == 0);
CHECK(cmp(sone, 16));
REQUIRE(iso226_phon2sone(90, &sone) == 0);
CHECK(cmp(sone, 32));
REQUIRE_FALSE(iso226_phon2sone(40, 0) == 0);
REQUIRE_FALSE(iso226_phon2sone(10, &sone) == 0);
}
TEST_CASE( "sone2phon", "sone2phon test" ) {
double phon;
REQUIRE(iso226_sone2phon(1, &phon) == 0);
CHECK(cmp(phon, 40));
REQUIRE(iso226_sone2phon(2, &phon) == 0);
CHECK(cmp(phon, 50));
REQUIRE(iso226_sone2phon(4, &phon) == 0);
CHECK(cmp(phon, 60));
REQUIRE(iso226_sone2phon(8, &phon) == 0);
CHECK(cmp(phon, 70));
REQUIRE(iso226_sone2phon(16, &phon) == 0);
CHECK(cmp(phon, 80));
REQUIRE(iso226_sone2phon(32, &phon) == 0);
CHECK(cmp(phon, 90));
REQUIRE_FALSE(iso226_sone2phon(1, 0) == 0);
REQUIRE_FALSE(iso226_sone2phon(0, &phon) == 0);
}
|
import {
Component, AfterViewInit, ChangeDetectorRef, OnDestroy,
Input
} from '@angular/core';
import { VariantSearchService } from '../../../services/variant-search-service';
import { VariantTrackService } from '../../../services/genome-browser/variant-track-service';
import { TranscriptTrackService } from '../../../services/genome-browser/transcript-track-service';
import { environment } from '../../../../environments/environment';
import { Variant } from '../../../model/variant';
import { Subscription } from 'rxjs/Subscription';
import { ElasticGeneSearch } from '../../../services/autocomplete/elastic-gene-search-service';
import { EnsemblService } from '../../../services/ensembl-service';
import * as tnt from 'tnt.genome';
const MAX_REGION_SIZE = 100000;
const MIN_REGION_SIZE = 100;
@Component({
selector: 'app-genome-browser',
templateUrl: './genome-browser.component.html',
styleUrls: ['./genome-browser.component.css'],
providers: [TranscriptTrackService]
})
export class GenomeBrowserComponent implements AfterViewInit, OnDestroy {
@Input() width: number;
genomeBrowser: any;
transcriptsShown = false;
variants: Variant[];
subscription: Subscription;
ensemblSupported = true;
locked = false;
constructor(private searchService: VariantSearchService,
private variantTrackService: VariantTrackService,
private transcriptTrackService: TranscriptTrackService,
private elastic: ElasticGeneSearch,
private ensembl: EnsemblService,
cd: ChangeDetectorRef) {
this.variants = searchService.variants;
this.subscription = searchService.results.subscribe(v => {
this.variants = v.variants;
});
}
ngAfterViewInit(): void {
this.ensembl.healthCheck()
.then(() => {
this.ensemblSupported = true;
})
.catch(() => {
this.ensemblSupported = false;
});
this.drawBoard();
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
drawBoard() {
const that = this;
const end = this.searchService.lastQuery.end - this.searchService.lastQuery.start < MIN_REGION_SIZE ?
this.searchService.lastQuery.start + MIN_REGION_SIZE : this.searchService.lastQuery.end;
this.genomeBrowser = tnt.genome()
.species('human')
.chr(this.searchService.lastQuery.chromosome)
.from(this.searchService.lastQuery.start).to(end)
.zoom_out(MAX_REGION_SIZE)
.width(this.width)
.max_coord(this.elastic.getChromosome(this.searchService.lastQuery.chromosome).toPromise());
const rest = this.genomeBrowser.rest();
rest.domain(environment.ensemblDomain);
rest.protocol(environment.ensemblProtocol);
this.genomeBrowser.zoom_in(MIN_REGION_SIZE);
const sequenceData = tnt.track.data.genome.sequence().limit(200);
const sequenceDataFunction = tnt.track.data.async()
.retriever(function (loc: any) {
const track = this;
return sequenceData.retriever().call(this, loc).then(function (sequence: string[]) {
if (sequence.length <= 0) {
track.height(0);
} else {
track.height(20);
}
that.genomeBrowser.tracks(that.genomeBrowser.tracks());
return sequence;
});
});
const sequenceTrack = tnt.track()
.height(20)
.color('white')
.display(tnt.track.feature.genome.sequence())
.data(sequenceDataFunction);
this.transcriptTrackService.init(this.genomeBrowser);
this.genomeBrowser
.add_track(sequenceTrack)
.add_track(this.variantTrackService.trackLabel)
.add_track(this.variantTrackService.track);
this.genomeBrowser(document.getElementById('genome-browser'));
this.genomeBrowser.start();
}
showTranscripts() {
const tracks: any[] = this.genomeBrowser.tracks();
this.genomeBrowser.tracks(tracks.concat([this.transcriptTrackService.trackLabel, this.transcriptTrackService.track]));
this.transcriptsShown = true;
}
hideTranscripts() {
const tracks = this.genomeBrowser.tracks();
tracks.pop();
tracks.pop();
this.genomeBrowser.tracks(tracks);
this.transcriptsShown = false;
}
toggleTranscripts() {
this.transcriptsShown ? this.hideTranscripts() : this.showTranscripts();
}
forward() {
this.genomeBrowser.scroll(0.5);
}
backward() {
this.genomeBrowser.scroll(-0.5);
}
zoomOut() {
const range = this.genomeBrowser.to() - this.genomeBrowser.from();
if (range > MAX_REGION_SIZE) {
return;
}
this.genomeBrowser.zoom(0.5);
}
zoomIn() {
const range = this.genomeBrowser.to() - this.genomeBrowser.from();
if (range < MIN_REGION_SIZE) {
return;
}
this.genomeBrowser.zoom(2);
}
lock(event: Event) {
this.genomeBrowser.allow_drag(false);
this.locked = true;
}
unlock(event: Event) {
this.locked = false;
this.genomeBrowser.allow_drag(true);
}
wheeling(event: WheelEvent) {
if (this.locked) {
document.getElementById('main-scroll').scrollTop = document.getElementById('main-scroll').scrollTop + event.deltaY;
}
}
}
|
/*
* Copyright (C) 2015 - 2016 Gracjan Orzechowski
*
* This file is part of GWatchD
*
* GWatchD is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 GWatchD; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QEventLoop>
#include <QSystemSemaphore>
#include "jobsrunner.h"
JobsRunner::JobsRunner(JobsLoader *loader, Logger *logger, QObject *parent) : QObject(parent)
{
this->m_loader = loader;
this->m_logger = logger;
}
void JobsRunner::run(QString name, QStringList entries)
{
name = name.toLower();
Job *job = this->m_loader->getLoadedJobs().value(name);
if(!job) {
this->m_logger->debug(QString("Job %1 not found").arg(name));
return;
}
QObject *jobObject = dynamic_cast<QObject*>(job);
QEventLoop loop;
connect(jobObject, SIGNAL(finished(int)), &loop, SLOT(quit()));
if(entries.isEmpty()) {
entries = job->getEntries();
}
foreach(Entry entry, entries) {
QFileInfo info(entry);
if(info.isDir() && !entry.endsWith("/")) {
entry.append("/");
}
this->m_logger->debug("Running job with arg: " + entry);
job->run(entry);
}
loop.exec();
}
void JobsRunner::run(QString name, Entry entry)
{
this->run(name, QStringList() << entry);
}
void JobsRunner::run(QString name, Predefine predefine)
{
name = name.toLower();
Job *job = this->m_loader->getLoadedJobs().value(name);
if(!job) {
this->m_logger->debug(QString("Job %1 not found").arg(name));
return;
}
QObject *jobObject = dynamic_cast<QObject*>(job);
QEventLoop loop;
connect(jobObject, SIGNAL(finished(int)), &loop, SLOT(quit()));
this->m_logger->debug("Running job with arg: " + predefine);
job->run(predefine);
QSystemSemaphore semaphore("" + name + ":" + predefine);
loop.exec();
semaphore.release();
}
void JobsRunner::runAll(QString data)
{
foreach(Job *job, this->m_loader->getLoadedJobs().values()) {
this->m_logger->debug("Running job with arg: " + data);
job->run(Entry(data));
}
}
|
---
layout: post
title: histeria com o Natal
date: 2009-11-25 17:37:28.000000000 +00:00
type: post
published: true
status: publish
categories: []
tags: []
meta:
spaces_3b4c7ab08b2559d7e6deed6ee4bb7aaa_permalink: http://cid-bdfcf232da5f8179.users.api.live.net/Users(-4756660806184107655)/Blogs('BDFCF232DA5F8179!102')/Entries('BDFCF232DA5F8179!1483')?authkey=hSbGhYtz7bY%24
author:
login: fmcarvalho
email: [email protected]
display_name: fmcarvalho
first_name: ''
last_name: ''
---
<div id="msgcns!BDFCF232DA5F8179!1483" class="bvMsg">
<div>
<p style="margin:0;"><font face="Times New Roman" color="#000000" size="3">Irrita-me este sentimento generalizado de histeria com o Natal em que todos ficam excitados a pensar nas 2 semanas de trabalho, em que fingirão que trabalham… e eu aqui a ver tanta coisa por fazer…</font></p>
</div>
</div>
|
#!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
"""
This module provide function to plot the speed control info from log csv file
"""
import math
import sys
import numpy as np
import tkFileDialog
from process import get_start_index
from process import preprocess
from process import process
class Plotter(object):
"""
plot the speed info
"""
def __init__(self, filename):
"""
init the speed info
"""
np.set_printoptions(precision=3)
self.file = open('result.csv', 'a')
self.file_one = open(filename + ".result", 'w')
def process_data(self, filename):
"""
load the file and preprocess th data
"""
self.data = preprocess(filename)
self.tablecmd, self.tablespeed, self.tableacc, self.speedsection, self.accsection, self.timesection = process(
self.data)
def save_data(self):
"""
"""
for i in range(len(self.tablecmd)):
for j in range(len(self.tablespeed[i])):
self.file.write("%s, %s, %s\n" %
(self.tablecmd[i], self.tablespeed[i][j],
self.tableacc[i][j]))
self.file_one.write("%s, %s, %s\n" %
(self.tablecmd[i], self.tablespeed[i][j],
self.tableacc[i][j]))
def main():
"""
demo
"""
if len(sys.argv) == 2:
# get the latest file
file_path = sys.argv[1]
else:
file_path = tkFileDialog.askopenfilename(
initialdir="/home/caros/.ros",
filetypes=(("csv files", ".csv"), ("all files", "*.*")))
plotter = Plotter(file_path)
plotter.process_data(file_path)
plotter.save_data()
print 'save result to:', file_path + ".result"
if __name__ == '__main__':
main()
|
<?php
use PoP\Root\Facades\Translation\TranslationAPIFacade;
class GD_URE_Module_Processor_ProfileFormGroups extends PoP_Module_Processor_FormComponentGroupsBase
{
public const MODULE_URE_FORMINPUTGROUP_MEMBERPRIVILEGES = 'ure-forminputgroup-memberprivileges';
public const MODULE_URE_FORMINPUTGROUP_MEMBERTAGS = 'ure-forminputgroup-membertags';
public const MODULE_URE_FORMINPUTGROUP_MEMBERSTATUS = 'ure-forminputgroup-memberstatus';
public const MODULE_URE_FILTERINPUTGROUP_MEMBERPRIVILEGES = 'ure-filterinputgroup-memberprivileges';
public const MODULE_URE_FILTERINPUTGROUP_MEMBERTAGS = 'ure-filterinputgroup-membertags';
public const MODULE_URE_FILTERINPUTGROUP_MEMBERSTATUS = 'ure-filterinputgroup-memberstatus';
public function getModulesToProcess(): array
{
return array(
[self::class, self::MODULE_URE_FORMINPUTGROUP_MEMBERPRIVILEGES],
[self::class, self::MODULE_URE_FORMINPUTGROUP_MEMBERTAGS],
[self::class, self::MODULE_URE_FORMINPUTGROUP_MEMBERSTATUS],
[self::class, self::MODULE_URE_FILTERINPUTGROUP_MEMBERPRIVILEGES],
[self::class, self::MODULE_URE_FILTERINPUTGROUP_MEMBERTAGS],
[self::class, self::MODULE_URE_FILTERINPUTGROUP_MEMBERSTATUS],
);
}
public function getLabelClass(array $module)
{
$ret = parent::getLabelClass($module);
switch ($module[1]) {
case self::MODULE_URE_FILTERINPUTGROUP_MEMBERPRIVILEGES:
case self::MODULE_URE_FILTERINPUTGROUP_MEMBERTAGS:
case self::MODULE_URE_FILTERINPUTGROUP_MEMBERSTATUS:
$ret .= ' col-sm-2';
break;
}
return $ret;
}
public function getFormcontrolClass(array $module)
{
$ret = parent::getFormcontrolClass($module);
switch ($module[1]) {
case self::MODULE_URE_FILTERINPUTGROUP_MEMBERPRIVILEGES:
case self::MODULE_URE_FILTERINPUTGROUP_MEMBERTAGS:
case self::MODULE_URE_FILTERINPUTGROUP_MEMBERSTATUS:
$ret .= ' col-sm-10';
break;
}
return $ret;
}
public function getComponentSubmodule(array $module)
{
$components = array(
self::MODULE_URE_FORMINPUTGROUP_MEMBERPRIVILEGES => [GD_URE_Module_Processor_ProfileMultiSelectFormInputs::class, GD_URE_Module_Processor_ProfileMultiSelectFormInputs::MODULE_URE_FORMINPUT_MEMBERPRIVILEGES],
self::MODULE_URE_FORMINPUTGROUP_MEMBERTAGS => [GD_URE_Module_Processor_ProfileMultiSelectFormInputs::class, GD_URE_Module_Processor_ProfileMultiSelectFormInputs::MODULE_URE_FORMINPUT_MEMBERTAGS],
self::MODULE_URE_FORMINPUTGROUP_MEMBERSTATUS => [GD_URE_Module_Processor_SelectFormInputs::class, GD_URE_Module_Processor_SelectFormInputs::MODULE_URE_FORMINPUT_MEMBERSTATUS],
self::MODULE_URE_FILTERINPUTGROUP_MEMBERPRIVILEGES => [GD_URE_Module_Processor_ProfileMultiSelectFilterInputs::class, GD_URE_Module_Processor_ProfileMultiSelectFilterInputs::MODULE_URE_FILTERINPUT_MEMBERPRIVILEGES],
self::MODULE_URE_FILTERINPUTGROUP_MEMBERTAGS => [GD_URE_Module_Processor_ProfileMultiSelectFilterInputs::class, GD_URE_Module_Processor_ProfileMultiSelectFilterInputs::MODULE_URE_FILTERINPUT_MEMBERTAGS],
self::MODULE_URE_FILTERINPUTGROUP_MEMBERSTATUS => [GD_URE_Module_Processor_ProfileMultiSelectFilterInputs::class, GD_URE_Module_Processor_ProfileMultiSelectFilterInputs::MODULE_URE_FILTERINPUT_MEMBERSTATUS],
);
if ($component = $components[$module[1]] ?? null) {
return $component;
}
return parent::getComponentSubmodule($module);
}
public function getInfo(array $module, array &$props)
{
switch ($module[1]) {
case self::MODULE_URE_FORMINPUTGROUP_MEMBERSTATUS:
return TranslationAPIFacade::getInstance()->__('Status "Active" if the user is truly your member, or "Rejected" otherwise. Rejected users will not appear as your community\'s members, or contribute content.');
case self::MODULE_URE_FORMINPUTGROUP_MEMBERPRIVILEGES:
return TranslationAPIFacade::getInstance()->__('"Contribute content" will add the member\'s content to your profile.', 'ure-popprocessors');
case self::MODULE_URE_FORMINPUTGROUP_MEMBERTAGS:
return TranslationAPIFacade::getInstance()->__('What is the type of relationship from this member to your community.', 'ure-popprocessors');
}
return parent::getInfo($module, $props);
}
}
|
#!/usr/bin/env python
#
# Copyright 2007,2010,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, gr_unittest
import blocks_swig as blocks
import math
class test_max(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_001(self):
src_data = (0,0.2,-0.3,0,12,0)
expected_result = (float(max(src_data)),)
src = gr.vector_source_f(src_data)
s2v = blocks.stream_to_vector(gr.sizeof_float, len(src_data))
op = blocks.max_ff(len(src_data))
dst = gr.vector_sink_f()
self.tb.connect(src, s2v, op, dst)
self.tb.run()
result_data = dst.data()
self.assertEqual(expected_result, result_data)
def test_002(self):
src_data=(-100,-99,-98,-97,-96,-1)
expected_result = (float(max(src_data)),)
src = gr.vector_source_f(src_data)
s2v = blocks.stream_to_vector(gr.sizeof_float, len(src_data))
op = blocks.max_ff(len(src_data))
dst = gr.vector_sink_f()
self.tb.connect(src, s2v, op, dst)
self.tb.run()
result_data = dst.data()
self.assertEqual(expected_result, result_data)
if __name__ == '__main__':
gr_unittest.run(test_max, "test_max.xml")
|
// { dg-do compile }
// { dg-options "-std=gnu++0x" }
// { dg-require-cstdint "" }
// { dg-require-gthreads "" }
// 2008-03-18 Benjamin Kosnik <[email protected]>
// Copyright (C) 2008-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <mutex>
void test01()
{
// Check for required typedefs
typedef std::recursive_mutex test_type;
typedef test_type::native_handle_type type;
}
|
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.
from sos.report.plugins import Plugin, IndependentPlugin
import re
class Dlm(Plugin, IndependentPlugin):
short_desc = 'DLM (Distributed lock manager)'
plugin_name = "dlm"
profiles = ("cluster", )
packages = ("cman", "dlm", "pacemaker")
option_list = [
("lockdump", "capture lock dumps for DLM", "slow", False),
]
def setup(self):
self.add_copy_spec([
"/etc/sysconfig/dlm"
])
self.add_cmd_output([
"dlm_tool log_plock",
"dlm_tool dump",
"dlm_tool ls -n"
])
if self.get_option("lockdump"):
self.do_lockdump()
def do_lockdump(self):
dlm_tool = "dlm_tool ls"
result = self.collect_cmd_output(dlm_tool)
if result["status"] != 0:
return
lock_exp = r'^name\s+([^\s]+)$'
lock_re = re.compile(lock_exp, re.MULTILINE)
for lockspace in lock_re.findall(result["output"]):
self.add_cmd_output(
"dlm_tool lockdebug -svw '%s'" % lockspace,
suggest_filename="dlm_locks_%s" % lockspace
)
# vim: et ts=4 sw=4
|
# Copyright 2015 Internap.
#
# 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 logging
from fake_switches.command_processing.shell_session import \
ShellSession
from fake_switches.brocade.command_processor.piping import \
PipingProcessor
from fake_switches.brocade.brocade_core import BrocadeSwitchCore
from fake_switches.dell.command_processor.default import \
DellDefaultCommandProcessor
from fake_switches.terminal import LoggingTerminalController
class DellSwitchCore(BrocadeSwitchCore):
def launch(self, protocol, terminal_controller):
self.last_connection_id += 1
self.logger = logging.getLogger("fake_switches.dell.%s.%s.%s" % (self.switch_configuration.name, self.last_connection_id, protocol))
command_processor = DellDefaultCommandProcessor(
switch_configuration=self.switch_configuration,
terminal_controller=LoggingTerminalController(self.logger, terminal_controller),
piping_processor=PipingProcessor(self.logger),
logger=self.logger)
return DellShellSession(command_processor)
class DellShellSession(ShellSession):
def handle_unknown_command(self, line):
self.command_processor.terminal_controller.write(" ^\n")
self.command_processor.terminal_controller.write("% Invalid input detected at '^' marker.\n")
self.command_processor.terminal_controller.write("\n")
|
#include "pch.h"
/*
#include <uc_dev/gx/geo/indexed_geometry_factory.h>
#include <uc_dev/mem/alloc.h>
#include <uc_dev/gx/dx12/cmd/upload_queue.h>
#include <uc_dev/gx/dx12/gpu/resource_create_context.h>
#include <uc_dev/gx/dx12/gpu/buffer.h>
namespace uc
{
namespace gx
{
namespace geo
{
indexed_geometry create_indexed_geometry(gx::dx12::gpu_resource_create_context* rc, gx::dx12::gpu_upload_queue* upload_queue, const void* __restrict positions, size_t positions_size, const void* __restrict indices, size_t indices_size)
{
indexed_geometry r;
auto sp = mem::align<256>(positions_size);
auto si = mem::align<256>(indices_size);
r.m_buffer = std::move(gx::dx12::create_buffer(rc, static_cast<uint32_t>(sp + si)));
r.m_vertex_count = static_cast<uint32_t>(positions_size / indexed_geometry::position_stride);
r.m_index_count = static_cast<uint32_t>(indices_size / indexed_geometry::index_stride);
upload_queue->upload_buffer_gather(r.m_buffer.get(), positions, sp, positions_size, indices, si, indices_size);
return r;
}
parametrized_geometry create_parametrized_geometry(gx::dx12::gpu_resource_create_context* rc, gx::dx12::gpu_upload_queue* upload_queue, const void* __restrict positions, size_t positions_size, const void* __restrict indices, size_t indices_size, const void* __restrict uv, size_t uv_size)
{
parametrized_geometry r;
auto sp = mem::align<256>(positions_size);
auto si = mem::align<256>(indices_size);
auto su = mem::align<256>(uv_size);
r.m_buffer = std::move(gx::dx12::create_buffer(rc, static_cast<uint32_t>(sp + si + su)));
r.m_vertex_count = static_cast<uint32_t>(positions_size / parametrized_geometry::position_stride);
r.m_index_count = static_cast<uint32_t>(indices_size / parametrized_geometry::index_stride);
upload_queue->upload_buffer_gather(r.m_buffer.get(), positions, sp, positions_size, indices, si, indices_size, uv, su, uv_size);
return r;
}
multi_material_geometry create_multi_material_geometry(gx::dx12::gpu_resource_create_context* rc, gx::dx12::gpu_upload_queue* upload_queue, gsl::span<const gsl::byte> positions, gsl::span<const gsl::byte> indices, gsl::span<const gsl::byte> uv, const lip::reloc_array<lip::primitive_range>& ranges)
{
multi_material_geometry r;
auto sp = mem::align<256>(positions.size());
auto si = mem::align<256>(indices.size());
auto su = mem::align<256>(uv.size());
r.m_ranges.reserve(ranges.size());
for (auto i : ranges)
{
primitive_range range(i.m_begin, i.m_end);
r.m_ranges.push_back(std::move(range));
}
r.m_buffer = std::move(gx::dx12::create_buffer(rc, static_cast<uint32_t>(sp + si + su)));
r.m_vertex_count = static_cast<uint32_t>(positions.size() / multi_material_geometry::position_stride);
r.m_index_count = static_cast<uint32_t>(indices.size() / multi_material_geometry::index_stride);
upload_queue->upload_buffer_gather(r.m_buffer.get(), positions.data(), sp, positions.size(), indices.data(), si, indices.size(), uv.data(), su, uv.size());
return r;
}
skinned_geometry create_skinned_geometry(gx::dx12::gpu_resource_create_context* rc, gx::dx12::gpu_upload_queue* upload_queue, gsl::span<const gsl::byte> positions, gsl::span<const gsl::byte> indices, gsl::span<const gsl::byte> uv, gsl::span<const gsl::byte> blend_weight, gsl::span<const gsl::byte> blend_indices, const lip::reloc_array<lip::primitive_range>& ranges)
{
skinned_geometry r;
auto sp = mem::align<256>(positions.size());
auto si = mem::align<256>(indices.size());
auto su = mem::align<256>(uv.size());
auto sbw = mem::align<256>(blend_weight.size());
auto sbi = mem::align<256>(blend_indices.size());
r.m_ranges.reserve(ranges.size());
for (auto i : ranges)
{
primitive_range range(i.m_begin, i.m_end);
r.m_ranges.push_back(std::move(range));
}
r.m_buffer = std::move(gx::dx12::create_buffer(rc, static_cast<uint32_t>(sp + si + su + sbw + sbi)));
r.m_vertex_count = static_cast<uint32_t>(positions.size() / skinned_geometry::position_stride);
r.m_index_count = static_cast<uint32_t>(indices.size() / skinned_geometry::index_stride);
upload_queue->upload_buffer_gather(r.m_buffer.get(), positions.data(), sp, positions.size(), indices.data(), si, indices.size(), uv.data(), su, uv.size(), blend_weight.data(), sbw, blend_weight.size(), blend_indices.data(), sbi, blend_indices.size());
return r;
}
}
}
}
*/
|
//// [augmentedTypesFunction.ts]
// function then var
function y1() { } // error
var y1 = 1; // error
// function then function
function y2() { } // error
function y2() { } // error
function y2a() { } // error
var y2a = () => { } // error
// function then class
function y3() { } // error
class y3 { } // error
function y3a() { } // error
class y3a { public foo() { } } // error
// function then enum
function y4() { } // error
enum y4 { One } // error
// function then internal module
function y5() { }
module y5 { } // ok since module is not instantiated
function y5a() { }
module y5a { var y = 2; } // should be an error
function y5b() { }
module y5b { export var y = 3; } // should be an error
function y5c() { }
module y5c { export interface I { foo(): void } } // should be an error
// function then import, messes with other errors
//function y6() { }
//import y6 = require('');
//// [augmentedTypesFunction.js]
// function then var
function y1() { } // error
var y1 = 1; // error
// function then function
function y2() { } // error
function y2() { } // error
function y2a() { } // error
var y2a = function () { }; // error
// function then class
function y3() { } // error
var y3 = (function () {
function y3() {
}
return y3;
}()); // error
function y3a() { } // error
var y3a = (function () {
function y3a() {
}
y3a.prototype.foo = function () { };
return y3a;
}()); // error
// function then enum
function y4() { } // error
var y4;
(function (y4) {
y4[y4["One"] = 0] = "One";
})(y4 || (y4 = {})); // error
// function then internal module
function y5() { }
function y5a() { }
var y5a;
(function (y5a) {
var y = 2;
})(y5a || (y5a = {})); // should be an error
function y5b() { }
var y5b;
(function (y5b) {
y5b.y = 3;
})(y5b || (y5b = {})); // should be an error
function y5c() { }
// function then import, messes with other errors
//function y6() { }
//import y6 = require('');
|
// TypeScript Version: 2.1
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdPersonOutline extends React.Component<IconBaseProps, any> { }
|
package bndtools.perspective;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.progress.IProgressConstants;
import org.eclipse.ui.texteditor.templates.TemplatesView;
import bndtools.PartConstants;
public class BndPerspective implements IPerspectiveFactory {
private static final String BNDTOOLS_PACKAGE_EXPLORER = "bndtools.PackageExplorer";
public static final String ID_PROJECT_EXPLORER = "org.eclipse.ui.navigator.ProjectExplorer"; //$NON-NLS-1$
public static final String VIEW_ID_JUNIT_RESULTS = "org.eclipse.jdt.junit.ResultView";
private static final String VIEW_ID_CONSOLE = "org.eclipse.ui.console.ConsoleView";
private static final String VIEW_ID_SEARCH = "org.eclipse.search.ui.views.SearchView";
@Override
public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
IFolderLayout leftFolder = layout.createFolder("left", IPageLayout.LEFT, 0.25f, editorArea);
leftFolder.addView(BNDTOOLS_PACKAGE_EXPLORER);
// leftFolder.addView(JavaUI.ID_PACKAGES);
leftFolder.addView(JavaUI.ID_TYPE_HIERARCHY);
layout.addView(PartConstants.VIEW_ID_REPOSITORIES, IPageLayout.BOTTOM, 0.66f, "left");
IFolderLayout outputFolder = layout.createFolder("bottom", IPageLayout.BOTTOM, 0.75f, editorArea);
outputFolder.addView(IPageLayout.ID_PROBLEM_VIEW);
outputFolder.addView(JavaUI.ID_JAVADOC_VIEW);
outputFolder.addView(PartConstants.VIEW_ID_IMPORTSEXPORTS);
outputFolder.addPlaceholder(VIEW_ID_SEARCH);
outputFolder.addPlaceholder(VIEW_ID_CONSOLE);
outputFolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
outputFolder.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
outputFolder.addPlaceholder(VIEW_ID_JUNIT_RESULTS);
IFolderLayout outlineFolder = layout.createFolder("right", IPageLayout.RIGHT, (float) 0.75, editorArea); //$NON-NLS-1$
outlineFolder.addView(IPageLayout.ID_OUTLINE);
outlineFolder.addPlaceholder(TemplatesView.ID);
layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
layout.addActionSet(JavaUI.ID_ACTION_SET);
layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
layout.addActionSet("bndtools.actions");
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
// views - java
layout.addShowViewShortcut(VIEW_ID_JUNIT_RESULTS);
layout.addShowViewShortcut(JavaUI.ID_PACKAGES);
layout.addShowViewShortcut(JavaUI.ID_TYPE_HIERARCHY);
layout.addShowViewShortcut(JavaUI.ID_SOURCE_VIEW);
layout.addShowViewShortcut(JavaUI.ID_JAVADOC_VIEW);
// views - search
layout.addShowViewShortcut(VIEW_ID_SEARCH);
// views - debugging
layout.addShowViewShortcut(VIEW_ID_CONSOLE);
// views - standard workbench
layout.addShowViewShortcut(PartConstants.VIEW_ID_IMPORTSEXPORTS);
layout.addShowViewShortcut(PartConstants.VIEW_ID_REPOSITORIES);
layout.addShowViewShortcut(PartConstants.VIEW_ID_JPM);
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
layout.addShowViewShortcut(IPageLayout.ID_PROJECT_EXPLORER);
layout.addShowViewShortcut(ID_PROJECT_EXPLORER);
// new actions - Java project creation wizard
layout.addNewWizardShortcut(PartConstants.WIZARD_ID_NEWPROJECT);
layout.addNewWizardShortcut(PartConstants.WIZARD_ID_NEWWORKSPACE);
layout.addNewWizardShortcut(PartConstants.WIZARD_ID_NEWBNDRUN);
layout.addNewWizardShortcut(PartConstants.WIZARD_ID_NEWWRAPPROJECT);
layout.addNewWizardShortcut(PartConstants.WIZARD_ID_NEWBND);
layout.addNewWizardShortcut(PartConstants.WIZARD_ID_NEWBLUEPRINT_XML);
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewEnumCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewAnnotationCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
layout.addPerspectiveShortcut("org.eclipse.debug.ui.DebugPerspective");
layout.addPerspectiveShortcut("org.eclipse.jdt.ui.JavaPerspective");
}
}
|
# -*- coding: utf-8 -*-
#
# Copyright 2019 Spotify AB
#
# 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.
#
"""
These are the unit tests for the BigQueryLoadAvro class.
"""
import unittest
import avro
import avro.schema
from luigi.contrib.bigquery_avro import BigQueryLoadAvro
class BigQueryAvroTest(unittest.TestCase):
def test_writer_schema_method_existence(self):
schema_json = """
{
"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "null"]}
]
}
"""
avro_schema = avro.schema.Parse(schema_json)
reader = avro.io.DatumReader(avro_schema, avro_schema)
actual_schema = BigQueryLoadAvro._get_writer_schema(reader)
self.assertEqual(actual_schema, avro_schema,
"writer(s) avro_schema attribute not found")
# otherwise AttributeError is thrown
|
# 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 os
import fixtures
from nova.tests.unit.virt.libvirt.volume import test_volume
from nova.virt.libvirt.volume import scality
class LibvirtScalityVolumeDriverTestCase(
test_volume.LibvirtVolumeBaseTestCase):
def test_libvirt_scality_driver(self):
tempdir = self.useFixture(fixtures.TempDir()).path
TEST_MOUNT = os.path.join(tempdir, 'fake_mount')
TEST_CONFIG = os.path.join(tempdir, 'fake_config')
TEST_VOLDIR = 'volumes'
TEST_VOLNAME = 'volume_name'
TEST_CONN_INFO = {
'data': {
'sofs_path': os.path.join(TEST_VOLDIR, TEST_VOLNAME)
}
}
TEST_VOLPATH = os.path.join(TEST_MOUNT,
TEST_VOLDIR,
TEST_VOLNAME)
open(TEST_CONFIG, "w+").close()
os.makedirs(os.path.join(TEST_MOUNT, 'sys'))
def _access_wrapper(path, flags):
if path == '/sbin/mount.sofs':
return True
else:
return os.access(path, flags)
self.stubs.Set(os, 'access', _access_wrapper)
self.flags(scality_sofs_config=TEST_CONFIG,
scality_sofs_mount_point=TEST_MOUNT,
group='libvirt')
driver = scality.LibvirtScalityVolumeDriver(self.fake_conn)
driver.connect_volume(TEST_CONN_INFO, self.disk_info)
device_path = os.path.join(TEST_MOUNT,
TEST_CONN_INFO['data']['sofs_path'])
self.assertEqual(device_path,
TEST_CONN_INFO['data']['device_path'])
conf = driver.get_config(TEST_CONN_INFO, self.disk_info)
tree = conf.format_dom()
self._assertFileTypeEquals(tree, TEST_VOLPATH)
|
/*
* Copyright (C) 2015 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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/>.
*
*/
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "utils.h"
#include "cleanup-funcs.h"
void die(const char *msg, ...)
{
int saved_errno = errno;
va_list va;
va_start(va, msg);
vfprintf(stderr, msg, va);
va_end(va);
if (errno != 0) {
fprintf(stderr, ": %s\n", strerror(saved_errno));
} else {
fprintf(stderr, "\n");
}
exit(1);
}
bool error(const char *msg, ...)
{
va_list va;
va_start(va, msg);
vfprintf(stderr, msg, va);
va_end(va);
return false;
}
struct sc_bool_name {
const char *text;
bool value;
};
static const struct sc_bool_name sc_bool_names[] = {
{"yes", true},
{"no", false},
{"1", true},
{"0", false},
{"", false},
};
/**
* Convert string to a boolean value.
*
* The return value is 0 in case of success or -1 when the string cannot be
* converted correctly. In such case errno is set to indicate the problem and
* the value is not written back to the caller-supplied pointer.
**/
static int str2bool(const char *text, bool * value)
{
if (value == NULL) {
errno = EFAULT;
return -1;
}
if (text == NULL) {
*value = false;
return 0;
}
for (int i = 0; i < sizeof sc_bool_names / sizeof *sc_bool_names; ++i) {
if (strcmp(text, sc_bool_names[i].text) == 0) {
*value = sc_bool_names[i].value;
return 0;
}
}
errno = EINVAL;
return -1;
}
/**
* Get an environment variable and convert it to a boolean.
*
* Supported values are those of str2bool(), namely "yes", "no" as well as "1"
* and "0". All other values are treated as false and a diagnostic message is
* printed to stderr.
**/
static bool getenv_bool(const char *name)
{
const char *str_value = getenv(name);
bool value;
if (str2bool(str_value, &value) < 0) {
if (errno == EINVAL) {
fprintf(stderr,
"WARNING: unrecognized value of environment variable %s (expected yes/no or 1/0)\n",
name);
return false;
} else {
die("cannot convert value of environment variable %s to a boolean", name);
}
}
return value;
}
bool sc_is_debug_enabled()
{
return getenv_bool("SNAP_CONFINE_DEBUG");
}
void debug(const char *msg, ...)
{
if (sc_is_debug_enabled()) {
va_list va;
va_start(va, msg);
fprintf(stderr, "DEBUG: ");
vfprintf(stderr, msg, va);
fprintf(stderr, "\n");
va_end(va);
}
}
void write_string_to_file(const char *filepath, const char *buf)
{
debug("write_string_to_file %s %s", filepath, buf);
FILE *f = fopen(filepath, "w");
if (f == NULL)
die("fopen %s failed", filepath);
if (fwrite(buf, strlen(buf), 1, f) != 1)
die("fwrite failed");
if (fflush(f) != 0)
die("fflush failed");
if (fclose(f) != 0)
die("fclose failed");
}
int sc_nonfatal_mkpath(const char *const path, mode_t mode)
{
// If asked to create an empty path, return immediately.
if (strlen(path) == 0) {
return 0;
}
// We're going to use strtok_r, which needs to modify the path, so we'll
// make a copy of it.
char *path_copy __attribute__ ((cleanup(sc_cleanup_string))) = NULL;
path_copy = strdup(path);
if (path_copy == NULL) {
return -1;
}
// Open flags to use while we walk the user data path:
// - Don't follow symlinks
// - Don't allow child access to file descriptor
// - Only open a directory (fail otherwise)
const int open_flags = O_NOFOLLOW | O_CLOEXEC | O_DIRECTORY;
// We're going to create each path segment via openat/mkdirat calls instead
// of mkdir calls, to avoid following symlinks and placing the user data
// directory somewhere we never intended for it to go. The first step is to
// get an initial file descriptor.
int fd __attribute__ ((cleanup(sc_cleanup_close))) = AT_FDCWD;
if (path_copy[0] == '/') {
fd = open("/", open_flags);
if (fd < 0) {
return -1;
}
}
// strtok_r needs a pointer to keep track of where it is in the string.
char *path_walker = NULL;
// Initialize tokenizer and obtain first path segment.
char *path_segment = strtok_r(path_copy, "/", &path_walker);
while (path_segment) {
// Try to create the directory. It's okay if it already existed, but
// return with error on any other error. Reset errno before attempting
// this as it may stay stale (errno is not reset if mkdirat(2) returns
// successfully).
errno = 0;
if (mkdirat(fd, path_segment, mode) < 0 && errno != EEXIST) {
return -1;
}
// Open the parent directory we just made (and close the previous one
// (but not the special value AT_FDCWD) so we can continue down the
// path.
int previous_fd = fd;
fd = openat(fd, path_segment, open_flags);
if (previous_fd != AT_FDCWD && close(previous_fd) != 0) {
return -1;
}
if (fd < 0) {
return -1;
}
// Obtain the next path segment.
path_segment = strtok_r(NULL, "/", &path_walker);
}
return 0;
}
|
'use strict';
function QuizHardCtrl($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
}
angular.module('hackyRacesApp')
.controller('QuizHardCtrl', QuizHardCtrl);
|
#!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from os.path import join, dirname
import glob
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
from numpy.distutils.misc_util import get_info as get_misc_info
from numpy.distutils.system_info import get_info as get_sys_info
from distutils.sysconfig import get_python_inc
config = Configuration('spatial', parent_package, top_path)
config.add_data_dir('tests')
# qhull
qhull_src = list(glob.glob(join(dirname(__file__), 'qhull',
'src', '*.c')))
inc_dirs = [get_python_inc()]
if inc_dirs[0] != get_python_inc(plat_specific=1):
inc_dirs.append(get_python_inc(plat_specific=1))
inc_dirs.append(get_numpy_include_dirs())
cfg = dict(get_sys_info('lapack_opt'))
cfg.setdefault('include_dirs', []).extend(inc_dirs)
def get_qhull_misc_config(ext, build_dir):
# Generate a header file containing defines
config_cmd = config.get_config_cmd()
defines = []
if config_cmd.check_func('open_memstream', decl=True, call=True):
defines.append(('HAVE_OPEN_MEMSTREAM', '1'))
target = join(dirname(__file__), 'qhull_misc_config.h')
with open(target, 'w') as f:
for name, value in defines:
f.write('#define {0} {1}\n'.format(name, value))
config.add_extension('qhull',
sources=['qhull.c'] + qhull_src + [get_qhull_misc_config],
**cfg)
# cKDTree
ckdtree_src = ['query.cxx',
'build.cxx',
'globals.cxx',
'cpp_exc.cxx',
'query_pairs.cxx',
'count_neighbors.cxx',
'query_ball_point.cxx',
'query_ball_tree.cxx',
'sparse_distances.cxx']
ckdtree_src = [join('ckdtree', 'src', x) for x in ckdtree_src]
ckdtree_headers = ['ckdtree_decl.h',
'cpp_exc.h',
'ckdtree_methods.h',
'cpp_utils.h',
'rectangle.h',
'distance.h',
'distance_box.h',
'ordered_pair.h']
ckdtree_headers = [join('ckdtree', 'src', x) for x in ckdtree_headers]
ckdtree_dep = ['ckdtree.cxx'] + ckdtree_headers + ckdtree_src
config.add_extension('ckdtree',
sources=['ckdtree.cxx'] + ckdtree_src,
depends=ckdtree_dep,
include_dirs=inc_dirs + [join('ckdtree','src')])
# _distance_wrap
config.add_extension('_distance_wrap',
sources=[join('src', 'distance_wrap.c')],
depends=[join('src', 'distance_impl.h')],
include_dirs=[get_numpy_include_dirs()],
extra_info=get_misc_info("npymath"))
config.add_extension('_voronoi',
sources=['_voronoi.c'])
config.add_extension('_hausdorff',
sources=['_hausdorff.c'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer="SciPy Developers",
author="Anne Archibald",
maintainer_email="[email protected]",
description="Spatial algorithms and data structures",
url="https://www.scipy.org",
license="SciPy License (BSD Style)",
**configuration(top_path='').todict()
)
|
class Translation(object):
"""
A class whose instances represent complete translations (with optional comments)
as they can be found in .strings-localization-files.
"""
# INITIALIZER #
def __init__(self, language_code, comment, key, translation):
if key is None:
raise ValueError('Tried to create an instance of Translation with None as key! '
'This is likely a programming-error in nslocapysation :(')
if translation is None:
raise ValueError('Tried to create an instance of Translation with None as translation. '
'Instead, an instance of IncompleteTranslation should be created. '
'This is likely a programming-error in nslocapysation :(')
self._language_code = language_code
self._comment = comment
self._key = key
self._translation = translation
# MAGIC #
def __str__(self):
result = ''
has_comment = self.comment is not None
if has_comment:
result += '\n' + self.comment + '\n'
result += ('"{key}" = "{translation}";'
''.format(key=self.key,
translation=self.translation))
if has_comment:
result += '\n'
return result
def __hash__(self):
return (hash(self.language_code) ^
hash(self.key) ^
hash(self.translation))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return (self.language_code == other.language_code and
self.key == other.key and
self.translation == other.translation)
def __ne__(self, other):
return not self.__eq__(other=other)
# PROPERTIES #
@property
def language_code(self):
return self._language_code
@property
def comment(self):
return self._comment
@property
def key(self):
return self._key
@property
def translation(self):
return self._translation
|
/**
* Copyright (C) 2015 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.
*/
package io.fabric8.kubernetes.client;
import io.fabric8.kubernetes.api.model.scheduling.DoneablePriorityClass;
import io.fabric8.kubernetes.api.model.scheduling.PriorityClass;
import io.fabric8.kubernetes.api.model.scheduling.PriorityClassList;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.fabric8.kubernetes.client.dsl.SchedulingAPIGroupDSL;
import io.fabric8.kubernetes.client.dsl.internal.PriorityClassOperationsImpl;
import okhttp3.OkHttpClient;
public class SchedulingAPIGroupClient extends BaseClient implements SchedulingAPIGroupDSL {
public SchedulingAPIGroupClient(OkHttpClient httpClient, final Config config) throws KubernetesClientException {
super(httpClient, config);
}
@Override
public MixedOperation<PriorityClass, PriorityClassList, DoneablePriorityClass, Resource<PriorityClass, DoneablePriorityClass>> priorityClass() {
return new PriorityClassOperationsImpl(httpClient, getConfiguration(), null);
}
}
|
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2013 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# See http://www.gnu.org/licenses/ for more information.
"""
Displays any widget as a tooltip.
"""
from PyQt5.QtCore import QEvent, QObject, QTimer, Qt
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QApplication
__all__ = ['hide', 'show']
# the currently displayed widget
_widget = None
# the timer to hide (connected later)
_timer = QTimer(singleShot=True)
# the event handler (setup later)
_handler = None
def hide():
"""Hide the currently displayed widget (if any)."""
global _widget
if _widget:
_widget.hide()
_widget = None
QApplication.instance().removeEventFilter(_handler)
def show(widget, pos=None, timeout=10000):
"""Show the widget at position."""
if pos is None:
pos = QCursor.pos()
global _widget
if _widget:
if _widget is not widget:
_widget.hide()
else:
global _handler
if _handler is None:
_handler = EventHandler()
QApplication.instance().installEventFilter(_handler)
# where to display the tooltip
screen = QApplication.desktop().availableGeometry(pos)
x = pos.x() + 2
y = pos.y() + 20
if x + widget.width() > screen.x() + screen.width():
x -= 4 + widget.width()
if y + widget.height() > screen.y() + screen.height():
y -= 24 + widget.height()
if y < screen.y():
y = screen.y()
if x < screen.x():
x = screen.x()
widget.move(x, y)
if widget.windowFlags() & Qt.ToolTip != Qt.ToolTip:
widget.setWindowFlags(Qt.ToolTip)
widget.ensurePolished()
widget.show()
_widget = widget
_timer.start(timeout)
_hideevents = {
QEvent.KeyPress,
QEvent.KeyRelease,
QEvent.Leave,
QEvent.WindowActivate,
QEvent.WindowDeactivate,
QEvent.MouseButtonPress,
QEvent.MouseButtonRelease,
QEvent.MouseButtonDblClick,
QEvent.FocusIn,
QEvent.FocusOut,
QEvent.Wheel,
QEvent.MouseMove,
}
class EventHandler(QObject):
def eventFilter(self, obj, ev):
if ev.type() in _hideevents:
hide()
return False
# setup
_timer.timeout.connect(hide)
|
#!/usr/bin/env python
#
# An example that presents CAPTCHA tests in a web environment
# and gives the user a chance to solve them. Run it, optionally
# specifying a port number on the command line, then point your web
# browser at the given URL.
#
from Captcha.Visual import Tests
from Captcha import Factory
import BaseHTTPServer, urlparse, sys
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
scheme, host, path, parameters, query, fragment = urlparse.urlparse(self.path)
# Split the path into segments
pathSegments = path.split('/')[1:]
# Split the query into key-value pairs
args = {}
for pair in query.split("&"):
if pair.find("=") >= 0:
key, value = pair.split("=", 1)
args.setdefault(key, []).append(value)
else:
args[pair] = []
# A hack so it works with a proxy configured for VHostMonster :)
if pathSegments[0] == "vhost":
pathSegments = pathSegments[3:]
if pathSegments[0] == "":
self.handleRootPage(args.get('test', Tests.__all__)[0])
elif pathSegments[0] == "images":
self.handleImagePage(pathSegments[1])
elif pathSegments[0] == "solutions":
self.handleSolutionPage(pathSegments[1], args['word'][0])
else:
self.handle404()
def handle404(self):
self.send_response(404)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write("<html><body><h1>No such resource</h1></body></html>")
def handleRootPage(self, testName):
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
test = self.captchaFactory.new(getattr(Tests, testName))
# Make a list of tests other than the one we're using
others = []
for t in Tests.__all__:
if t != testName:
others.append('<li><a href="/?test=%s">%s</a></li>' % (t,t))
others = "\n".join(others)
self.wfile.write("""<html>
<head>
<title>PyCAPTCHA Example</title>
</head>
<body>
<h1>PyCAPTCHA Example</h1>
<p>
<b>%s</b>:
%s
</p>
<p><img src="/images/%s"/></p>
<p>
<form action="/solutions/%s" method="get">
Enter the word shown:
<input type="text" name="word"/>
</form>
</p>
<p>
Or try...
<ul>
%s
</ul>
</p>
</body>
</html>
""" % (test.__class__.__name__, test.__doc__, test.id, test.id, others))
def handleImagePage(self, id):
test = self.captchaFactory.get(id)
if not test:
return self.handle404()
self.send_response(200)
self.send_header("Content-Type", "image/jpeg")
self.end_headers()
test.render().save(self.wfile, "JPEG")
def handleSolutionPage(self, id, word):
test = self.captchaFactory.get(id)
if not test:
return self.handle404()
if not test.valid:
# Invalid tests will always return False, to prevent
# random trial-and-error attacks. This could be confusing to a user...
result = "Test invalidated, try another test"
elif test.testSolutions([word]):
result = "Correct"
else:
result = "Incorrect"
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write("""<html>
<head>
<title>PyCAPTCHA Example</title>
</head>
<body>
<h1>PyCAPTCHA Example</h1>
<h2>%s</h2>
<p><img src="/images/%s"/></p>
<p><b>%s</b></p>
<p>You guessed: %s</p>
<p>Possible solutions: %s</p>
<p><a href="/">Try again</a></p>
</body>
</html>
""" % (test.__class__.__name__, test.id, result, word, ", ".join(test.solutions)))
def main(port):
print "Starting server at http://localhost:%d/" % port
handler = RequestHandler
handler.captchaFactory = Factory()
BaseHTTPServer.HTTPServer(('', port), RequestHandler).serve_forever()
if __name__ == "__main__":
# The port number can be specified on the command line, default is 8080
if len(sys.argv) >= 2:
port = int(sys.argv[1])
else:
port = 8080
main(port)
### The End ###
|
#include "Result.h"
#include "Result.mh"
#include "Result.ic"
#include "Result.mc"
BEGIN_PAFCORE
Result::Result(Type* type, bool constant, Passing passing)
: Metadata(0)
{
m_type = type;
m_constant = constant;
m_passing = passing;
}
bool Result::get_isConstant() const
{
return m_constant;
}
Type* Result::get_type() const
{
return m_type;
}
bool Result::get_byValue() const
{
return by_value == m_passing;
}
bool Result::get_byRef() const
{
return by_ref == m_passing;
}
bool Result::get_byPtr() const
{
return by_ptr == m_passing;
}
bool Result::get_byNew() const
{
return by_new == m_passing;
}
bool Result::get_byNewArray() const
{
return by_new_array == m_passing;
}
END_PAFCORE
|
/* DMCS -- Distributed Nonmonotonic Multi-Context Systems.
* Copyright (C) 2009, 2010 Minh Dao-Tran, Thomas Krennwallner
*
* This file is part of DMCS.
*
* DMCS 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.
*
* DMCS 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 DMCS. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file NoSBACtxSortingStrategy.h
* @author Minh Dao-Tran <[email protected]>
* @date Wed Jul 14 9:36:21 2010
*
* @brief
*
*
*/
#ifndef NO_SBA_CTX_SORTING_STRATEGY_H
#define NO_SBA_CTX_SORTING_STRATEGY_H
#include "ContextSortingStrategy.h"
#include "Match.h"
namespace dmcs {
class NoSBACtxSortingStrategy : public ContextSortingStrategy
{
public:
// IteratorListPtr == shared_ptr of list of iterators of a MatchTableIteratorVec
NoSBACtxSortingStrategy(IteratorListPtr list_to_sort_, CountVecPtr sba_count_,
std::size_t dfs_level_)
: ContextSortingStrategy(list_to_sort_, dfs_level_),
sba_count(sba_count_)
{ }
void calculateQuality()
{
#ifdef DEBUG
std::cerr << TABS(dfs_level) << "Calculating qualities:" << std::endl;
#endif
for (IteratorList::const_iterator it = list_to_sort->begin(); it != list_to_sort->end(); ++it)
{
// the quality takes the number of schematic bridge atoms in a
// potential neighbor into account. Furthermore, the quality
// of the match also counts. With this setting, can sort
// according to 2 criteria in one shot:
// + Firstly, sort contexts wrt. their numbers of schematic
// bridge atoms, increasingly
// + Then, the contexts with the same numbers of schematic
// bridge atoms are sorted decreasingly according to the
// quality of the respective match. Note that the quality of a
// match is in [0,1]
ContextID cid = (**it)->tarCtx;
float q_it = (*sba_count)[cid];
#ifdef DEBUG
std::cerr << TABS(dfs_level) << cid << ", " << q_it << std::endl;
#endif
quality->insert( std::pair<MatchTableIteratorVec::iterator, float>(*it, q_it) );
}
}
private:
CountVecPtr sba_count;
};
} // namespace dmcs
#endif // NO_SBA_CTX_SORTING_STRATEGY_H
// Local Variables:
// mode: C++
// End:
|
# -*- coding: utf-8 -*-
"""
Server for picture synchronization
"""
from socketserver import TCPServer, BaseRequestHandler
from .remote_log import REMOTE_LOG as log
class PhotoTCPHandler(BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
try:
self.server.put(
self.data.decode(encoding="utf-8", errors="strict"))
except UnicodeError:
pass
class PhotoServer(TCPServer):
""" Class that represents our TCP server"""
def __init__(self, address, port, queue):
self._queue = queue
log.debug(
'Binding the listening socket to address %(address)s and port %(port)s',
{'address': address,
'port': port})
super(PhotoServer, self).__init__((address, port), PhotoTCPHandler)
def put(self, data):
""" Method used to put data into the queue """
log.debug('Received the following data from the network: %s', data)
self._queue.put(data)
|
var Parrot;
(function (Parrot) {
(function (Lexer) {
(function (TokenType) {
TokenType[TokenType["Start"] = 0] = "Start";
TokenType[TokenType["Identifier"] = 1] = "Identifier";
TokenType[TokenType["QuotedStringLiteral"] = 2] = "QuotedStringLiteral";
TokenType[TokenType["StringLiteral"] = 3] = "StringLiteral";
TokenType[TokenType["OpenBracket"] = 4] = "OpenBracket";
TokenType[TokenType["CloseBracket"] = 5] = "CloseBracket";
TokenType[TokenType["OpenParenthesis"] = 6] = "OpenParenthesis";
TokenType[TokenType["CloseParenthesis"] = 7] = "CloseParenthesis";
TokenType[TokenType["Comma"] = 8] = "Comma";
TokenType[TokenType["OpenBrace"] = 9] = "OpenBrace";
TokenType[TokenType["CloseBrace"] = 10] = "CloseBrace";
TokenType[TokenType["GreaterThan"] = 11] = "GreaterThan";
TokenType[TokenType["Plus"] = 12] = "Plus";
TokenType[TokenType["Whitespace"] = 13] = "Whitespace";
TokenType[TokenType["StringLiteralPipe"] = 14] = "StringLiteralPipe";
TokenType[TokenType["CommentLine"] = 15] = "CommentLine";
TokenType[TokenType["CommentStart"] = 16] = "CommentStart";
TokenType[TokenType["CommentEnd"] = 17] = "CommentEnd";
TokenType[TokenType["Equal"] = 18] = "Equal";
TokenType[TokenType["At"] = 19] = "At";
TokenType[TokenType["Caret"] = 20] = "Caret";
})(Lexer.TokenType || (Lexer.TokenType = {}));
var TokenType = Lexer.TokenType;
})(Parrot.Lexer || (Parrot.Lexer = {}));
var Lexer = Parrot.Lexer;
})(Parrot || (Parrot = {}));
//# sourceMappingURL=tokenType.js.map
|
/*
* Mark Benjamin 6th March 2019
* Copyright (c) 2019 Mark Benjamin
*/
#ifndef FASTRL_DOMAIN_SINGLEAGENT_CARTPOLE_STATES_CART_POLE_FULL_STATE_HPP
#define FASTRL_DOMAIN_SINGLEAGENT_CARTPOLE_STATES_CART_POLE_FULL_STATE_HPP
class CartPoleFullState {
};
#endif //FASTRL_DOMAIN_SINGLEAGENT_CARTPOLE_STATES_CART_POLE_FULL_STATE_HPP
|
from django.db import models
class CountyInmate(models.Model):
"""
Model that represents a Cook County Jail inmate.
"""
jail_id = models.CharField(max_length=15, primary_key=True)
person_id = models.CharField(max_length=64, null=True)
race = models.CharField(max_length=4, null=True, blank=True)
last_seen_date = models.DateTimeField(auto_now=True)
booking_date = models.DateField(null=True)
discharge_date_earliest = models.DateTimeField(null=True)
discharge_date_latest = models.DateTimeField(null=True)
gender = models.CharField(max_length=1, null=True, blank=True)
height = models.IntegerField(null=True, blank=True)
weight = models.IntegerField(null=True, blank=True)
age_at_booking = models.IntegerField(null=True, blank=True)
bail_status = models.CharField(max_length=50, null=True)
bail_amount = models.IntegerField(null=True, blank=True)
in_jail = models.BooleanField(default=True)
def __unicode__(self):
return self.jail_id
class Meta:
ordering = ['-jail_id']
class CourtDate(models.Model):
"""
Model that represents an inmate's next court date.
"""
inmate = models.ForeignKey('CountyInmate', related_name='court_dates')
location = models.ForeignKey('CourtLocation', related_name='court_dates')
date = models.DateField()
class Meta:
ordering = ['date']
get_latest_by = 'date'
class CourtLocation(models.Model):
"""
Model that represents a unique court location (court house and room).
"""
location = models.TextField()
location_name = models.CharField(max_length=20, null=True)
branch_name = models.CharField(max_length=60, null=True)
room_number = models.IntegerField(null=True, blank=True)
address = models.CharField(max_length=100, null=True)
city = models.CharField(max_length=30, null=True)
state = models.CharField(max_length=3, null=True)
zip_code = models.IntegerField(null=True, blank=True)
class HousingHistory(models.Model):
"""
Model that represents an inmate's housing location on a given date.
"""
inmate = models.ForeignKey('CountyInmate', related_name='housing_history')
housing_location = models.ForeignKey('HousingLocation', related_name='housing_history')
housing_date_discovered = models.DateField(null=True)
class Meta:
ordering = ['housing_date_discovered']
get_latest_by = 'housing_date_discovered'
class HousingLocation(models.Model):
"""
Model that represents a housing unit in the jail.
"""
housing_location = models.CharField(max_length=40, primary_key=True)
division = models.CharField(max_length=4)
sub_division = models.CharField(max_length=20)
sub_division_location = models.CharField(max_length=20)
in_jail = models.BooleanField(default=True)
in_program = models.CharField(max_length=60)
def __unicode__(self):
return self.housing_location
class ChargesHistory(models.Model):
inmate = models.ForeignKey('CountyInmate', related_name='charges_history')
charges = models.TextField(null=True)
charges_citation = models.TextField(null=True)
date_seen = models.DateField(null=True)
class InmateSummaries(models.Model):
"""
Model that displays count of inmates in system by date
"""
date = models.DateField(null=False)
current_inmate_count = models.IntegerField(null=False, blank=False)
class DailyPopulationCounts(models.Model):
"""
Population counts by day.
"""
booking_date = models.DateField(null=True)
total = models.IntegerField(default=0)
female_as = models.IntegerField(default=0)
female_b = models.IntegerField(default=0)
female_bk = models.IntegerField(default=0)
female_in = models.IntegerField(default=0)
female_lb = models.IntegerField(default=0)
female_lw = models.IntegerField(default=0)
female_lt = models.IntegerField(default=0)
female_w = models.IntegerField(default=0)
female_wh = models.IntegerField(default=0)
male_as = models.IntegerField(default=0)
male_b = models.IntegerField(default=0)
male_bk = models.IntegerField(default=0)
male_in = models.IntegerField(default=0)
male_lb = models.IntegerField(default=0)
male_lw = models.IntegerField(default=0)
male_lt = models.IntegerField(default=0)
male_w = models.IntegerField(default=0)
male_wh = models.IntegerField(default=0)
class Meta:
ordering = ['booking_date']
class DailyBookingsCounts(models.Model):
"""
Bookings counts by day.
"""
booking_date = models.DateField(null=True)
total = models.IntegerField(default=0)
female_as = models.IntegerField(default=0)
female_b = models.IntegerField(default=0)
female_bk = models.IntegerField(default=0)
female_in = models.IntegerField(default=0)
female_lb = models.IntegerField(default=0)
female_lw = models.IntegerField(default=0)
female_lt = models.IntegerField(default=0)
female_w = models.IntegerField(default=0)
female_wh = models.IntegerField(default=0)
female_minors = models.IntegerField(default=0)
male_as = models.IntegerField(default=0)
male_b = models.IntegerField(default=0)
male_bk = models.IntegerField(default=0)
male_in = models.IntegerField(default=0)
male_lb = models.IntegerField(default=0)
male_lw = models.IntegerField(default=0)
male_lt = models.IntegerField(default=0)
male_w = models.IntegerField(default=0)
male_wh = models.IntegerField(default=0)
male_minors = models.IntegerField(default=0)
class Meta:
ordering = ['booking_date']
|
import { WorkflowInstance, WorkflowStatus, ExecutionPointer, EventSubscription } from "../models";
import { WorkflowBase, IPersistenceProvider, IQueueProvider, IDistributedLockProvider, IWorkflowExecutor, ILogger } from "../abstractions";
export interface IWorkflowHost {
start(): Promise<void>;
stop();
startWorkflow(id: string, version: number, data: any): Promise<string>;
registerWorkflow<TData>(workflow: new () => WorkflowBase<TData>);
publishEvent(eventName: string, eventKey: string, eventData: any, eventTime: Date): Promise<void>;
suspendWorkflow(id: string): Promise<boolean>;
resumeWorkflow(id: string): Promise<boolean>;
terminateWorkflow(id: string): Promise<boolean>;
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
/**
* This package contains the implementation classes for NetworkManagementClient.
* Network Client.
*/
package com.microsoft.azure.management.network.v2018_07_01.implementation;
|
"""
__author__ = 'Christopher Fagiani'
"""
from disqusclient import Disqusclient
import json
import sys, argparse, dateutil.parser
from datetime import datetime, timedelta
def main(args):
"""This program will download all the posts for a speific Disqus forum for a specific time interval
(specified in hours on the command line)
All data is written to a single output file as a well-formed JSON array.
"""
gather_data(args.forum,args.interval,args.outputFile,args.key)
def gather_data(forum,interval, outputFile, apiKey):
"""Performs the actual work of downloading the data and writing the output file
"""
stop_date = datetime.utcnow() - timedelta(hours=int(interval))
with open(outputFile,'w') as out_file:
cursor = None
last_date = None
out_file.write("[")
api_client = Disqusclient(apiKey)
posts, cursor = process_batch(api_client,forum,None,stop_date)
write_results(posts,out_file,True)
while cursor is not None:
posts, cursor = process_batch(api_client,forum,cursor,stop_date)
write_results(posts,out_file)
out_file.write("]")
def write_results(data, out_file, first=False):
"""Writes the results to the file
"""
for item in data:
if not first:
out_file.write(",\n")
else:
first = False
out_file.write(json.dumps(item))
def process_batch(apiClient, forum, cursor,stop_date):
"""Fetches a single batch of posts and checks the last date to see if we should stop processing
this method returns the list of posts and the cursor string
"""
last_date = None
posts,cursor = apiClient.fetch_posts(forum,cursor,True)
if len(posts) > 0:
last_date = dateutil.parser.parse(posts[-1]['date'])
if last_date is None or last_date < stop_date:
cursor = None
return posts,cursor
if __name__ == "__main__":
argparser = argparse.ArgumentParser(description="Download all posts from a Disqus forum for a specific interval")
argparser.add_argument("-i","--interval", metavar='intervalHours',default="24",help='interval in hours',dest='interval')
argparser.add_argument("-f","--forum", metavar='forumName',required=True,help='forum name',dest='forum')
argparser.add_argument("-k","--key", metavar='key',required=True,help='public key for api',dest='key')
argparser.add_argument("-o","--output", metavar='outputFile',required=True,help='output file',dest='outputFile')
main(argparser.parse_args())
|
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_oam_oam_constraint import TapiOamOamConstraint # noqa: F401,E501
from tapi_server.models.tapi_oam_oam_service_end_point import TapiOamOamServiceEndPoint # noqa: F401,E501
from tapi_server import util
class TapiOamUpdateoamserviceInput(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
"""
def __init__(self, oam_constraint=None, service_id=None, state=None, end_point=None): # noqa: E501
"""TapiOamUpdateoamserviceInput - a model defined in OpenAPI
:param oam_constraint: The oam_constraint of this TapiOamUpdateoamserviceInput. # noqa: E501
:type oam_constraint: TapiOamOamConstraint
:param service_id: The service_id of this TapiOamUpdateoamserviceInput. # noqa: E501
:type service_id: str
:param state: The state of this TapiOamUpdateoamserviceInput. # noqa: E501
:type state: str
:param end_point: The end_point of this TapiOamUpdateoamserviceInput. # noqa: E501
:type end_point: List[TapiOamOamServiceEndPoint]
"""
self.openapi_types = {
'oam_constraint': TapiOamOamConstraint,
'service_id': str,
'state': str,
'end_point': List[TapiOamOamServiceEndPoint]
}
self.attribute_map = {
'oam_constraint': 'oam-constraint',
'service_id': 'service-id',
'state': 'state',
'end_point': 'end-point'
}
self._oam_constraint = oam_constraint
self._service_id = service_id
self._state = state
self._end_point = end_point
@classmethod
def from_dict(cls, dikt) -> 'TapiOamUpdateoamserviceInput':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The tapi.oam.updateoamservice.Input of this TapiOamUpdateoamserviceInput. # noqa: E501
:rtype: TapiOamUpdateoamserviceInput
"""
return util.deserialize_model(dikt, cls)
@property
def oam_constraint(self):
"""Gets the oam_constraint of this TapiOamUpdateoamserviceInput.
:return: The oam_constraint of this TapiOamUpdateoamserviceInput.
:rtype: TapiOamOamConstraint
"""
return self._oam_constraint
@oam_constraint.setter
def oam_constraint(self, oam_constraint):
"""Sets the oam_constraint of this TapiOamUpdateoamserviceInput.
:param oam_constraint: The oam_constraint of this TapiOamUpdateoamserviceInput.
:type oam_constraint: TapiOamOamConstraint
"""
self._oam_constraint = oam_constraint
@property
def service_id(self):
"""Gets the service_id of this TapiOamUpdateoamserviceInput.
none # noqa: E501
:return: The service_id of this TapiOamUpdateoamserviceInput.
:rtype: str
"""
return self._service_id
@service_id.setter
def service_id(self, service_id):
"""Sets the service_id of this TapiOamUpdateoamserviceInput.
none # noqa: E501
:param service_id: The service_id of this TapiOamUpdateoamserviceInput.
:type service_id: str
"""
self._service_id = service_id
@property
def state(self):
"""Gets the state of this TapiOamUpdateoamserviceInput.
none # noqa: E501
:return: The state of this TapiOamUpdateoamserviceInput.
:rtype: str
"""
return self._state
@state.setter
def state(self, state):
"""Sets the state of this TapiOamUpdateoamserviceInput.
none # noqa: E501
:param state: The state of this TapiOamUpdateoamserviceInput.
:type state: str
"""
self._state = state
@property
def end_point(self):
"""Gets the end_point of this TapiOamUpdateoamserviceInput.
none # noqa: E501
:return: The end_point of this TapiOamUpdateoamserviceInput.
:rtype: List[TapiOamOamServiceEndPoint]
"""
return self._end_point
@end_point.setter
def end_point(self, end_point):
"""Sets the end_point of this TapiOamUpdateoamserviceInput.
none # noqa: E501
:param end_point: The end_point of this TapiOamUpdateoamserviceInput.
:type end_point: List[TapiOamOamServiceEndPoint]
"""
self._end_point = end_point
|
# -*- coding: utf-8 -*-
#
# computingunit.py
#
# Copyright (C) 2010 Antoine Mercadal <[email protected]>
# Copyright (C) 2013 Nicolas Ochem <[email protected]>
# This file is part of ArchipelProject
# http://archipelproject.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from archipelcentralagentplatformrequest.scorecomputing import TNBasicPlatformScoreComputing
class TNDefaultComputingUnit (TNBasicPlatformScoreComputing):
### Initialization
def __init__(self):
"""
Initialize the TNBasicPlatformScoreComputing.
"""
TNBasicPlatformScoreComputing.__init__(self)
self.required_stats = [ { "major":"memory", "minor":"free" } ]
## Plugin implementation
@staticmethod
def plugin_info():
"""
Return informations about the plugin.
@rtype: dict
@return: dictionary contaning plugin informations
"""
plugin_friendly_name = "Platform Request Default Score Computing Unit"
plugin_identifier = "defaultcomputingunit"
plugin_configuration_section = None
plugin_configuration_tokens = []
return { "common-name" : plugin_friendly_name,
"identifier" : plugin_identifier,
"configuration-section" : plugin_configuration_section,
"configuration-tokens" : plugin_configuration_tokens }
### Score computing
def score(self, database, limit=10):
"""
Perform the score. The highest is the score, the highest chance
you got to perform the action. If you want to decline
the performing of the action, return 0.0 or None. the max score
you can return is 1.0 (so basically see it as a percentage).
@type limit: integer
@param limit: the number of potential hypervisors to suggest
@rtype: list
@return: scores of the top hypervisors
"""
# stat1 is the free ram available, we divide it by 256GB of ram to get a first score, the highest ram the better;
# 1/(1+num_vm) gives us another score based on the number of vms running, the less the better;
# but we have to perform an union to take into account the case of hypervisors with no vms
# we multiply these 2 scores to get the final score.
hyp_list = []
rows = database.execute("select hypervisors.jid, 1.0/(1+count(vms.uuid))*(hypervisors.stat1/256000000.0) as score_vms\
from hypervisors join vms on hypervisors.jid=vms.hypervisor\
where hypervisors.status='Online'\
union\
select hypervisors.jid, (hypervisors.stat1/256000000.0) as score_vms\
from hypervisors left outer join vms on hypervisors.jid=vms.hypervisor\
where hypervisors.status='Online'\
and vms.uuid is null \
order by score_vms asc \
limit %s;" % limit)
for row in rows:
hyp_list.append({"jid":row[0], "score":row[1]})
return hyp_list
|
function editItem (id) {
$("#"+id+"edit").hide('fast', function() {
console.log("edit button is hidden")
});
$("#"+id+"text").hide('fast', function() {
console.log("text is hidden")
});
$("#"+id+"qtext").hide('fast', function() {
console.log("quantity text is hidden")
});
var itemText = $("#"+id+"text").text();
$("#"+id+"input").attr('placeholder', itemText);
//puts the current text in as placeholder in input box
var quantityText = $("#"+id+"qtext").text();
$("#"+id+"qinput").attr('placeholder', quantityText);
$("#"+id+"qinput").show('fast', function() {
//animation occured
});
$("#"+id+"input").show('fast', function() {
//animation occured
});
$("#"+id+"check").show('fast', function() {
//animation occured
});
};
function renameItem (id) {
var newText = $("#"+id+"input").val();
var newqText = $("#"+id+"qinput").val();
console.log($("#"+id+"input").val());
$("#"+id+"text").text(newText);
$("#"+id+"qtext").text(newqText);
//variables for new quantity and new text
$("#"+id+"input").hide('fast', function() {
//text input box hidden
});
$("#"+id+"qinput").hide('fast', function() {
//quantity input box hidden
});
$("#"+id+"text").show('fast', function() {
//shows item text
});
$("#"+id+"qtext").show('fast', function() {
//shows item quantity again
});
$("#"+id+"check").hide('fast', function() {
//hides check button
});
$("#"+id+"edit").show('fast', function() {
//animation occured
});
};
//add list item button
function addItemBtn() {
$('#')
$('#add-list-item').show('fast', function() {
});
console.log ('add item clicked')
}
function editTodo (id) {
$("#"+id+"edit").hide('fast', function() {
console.log("edit button is hidden")
});
$("#"+id+"text").hide('fast', function() {
console.log("text is hidden")
});
var itemText = $("#"+id+"text").text();
$("#"+id+"input").attr('placeholder', itemText);
//puts the current text in as placeholder in input box
$("#"+id+"input").show('fast', function() {
//animation occured
});
$("#"+id+"check").show('fast', function() {
//animation occured
});
};
function renameTodo (id) {
var newText = $("#"+id+"input").val();
console.log($("#"+id+"input").val());
$("#"+id+"text").text(newText);
//variables for new text
$("#"+id+"input").hide('fast', function() {
//text input box hidden
});
$("#"+id+"text").show('fast', function() {
//shows item text
});
$("#"+id+"check").hide('fast', function() {
//hides check button
});
$("#"+id+"edit").show('fast', function() {
//animation occured
});
};
//add list item button
function addTodoBtn() {
$('#')
$('#add-todo-item').show('fast', function() {
});
console.log ('add item clicked')
}
|
import os
import shutil
import tempfile
import argparse
import sys
from cStringIO import StringIO
from contextlib import contextmanager
from nose.plugins.skip import SkipTest
from mock import Mock
import netlib.tutils
from libmproxy import utils, controller
from libmproxy.models import (
ClientConnection, ServerConnection, Error, HTTPRequest, HTTPResponse, HTTPFlow
)
from libmproxy.console.flowview import FlowView
from libmproxy.console import ConsoleState
def _SkipWindows():
raise SkipTest("Skipped on Windows.")
def SkipWindows(fn):
if os.name == "nt":
return _SkipWindows
else:
return fn
def tflow(client_conn=True, server_conn=True, req=True, resp=None, err=None):
"""
@type client_conn: bool | None | libmproxy.proxy.connection.ClientConnection
@type server_conn: bool | None | libmproxy.proxy.connection.ServerConnection
@type req: bool | None | libmproxy.protocol.http.HTTPRequest
@type resp: bool | None | libmproxy.protocol.http.HTTPResponse
@type err: bool | None | libmproxy.protocol.primitives.Error
@return: bool | None | libmproxy.protocol.http.HTTPFlow
"""
if client_conn is True:
client_conn = tclient_conn()
if server_conn is True:
server_conn = tserver_conn()
if req is True:
req = netlib.tutils.treq()
if resp is True:
resp = netlib.tutils.tresp()
if err is True:
err = terr()
if req:
req = HTTPRequest.wrap(req)
if resp:
resp = HTTPResponse.wrap(resp)
f = HTTPFlow(client_conn, server_conn)
f.request = req
f.response = resp
f.error = err
f.reply = controller.DummyReply()
return f
def tclient_conn():
"""
@return: libmproxy.proxy.connection.ClientConnection
"""
c = ClientConnection.from_state(dict(
address=dict(address=("address", 22), use_ipv6=True),
clientcert=None
))
c.reply = controller.DummyReply()
return c
def tserver_conn():
"""
@return: libmproxy.proxy.connection.ServerConnection
"""
c = ServerConnection.from_state(dict(
address=dict(address=("address", 22), use_ipv6=True),
state=[],
source_address=dict(address=("address", 22), use_ipv6=True),
cert=None
))
c.reply = controller.DummyReply()
return c
def terr(content="error"):
"""
@return: libmproxy.protocol.primitives.Error
"""
err = Error(content)
return err
def tflowview(request_contents=None):
m = Mock()
cs = ConsoleState()
if request_contents is None:
flow = tflow()
else:
flow = tflow(req=netlib.tutils.treq(request_contents))
fv = FlowView(m, cs, flow)
return fv
def get_body_line(last_displayed_body, line_nb):
return last_displayed_body.contents()[line_nb + 2]
@contextmanager
def tmpdir(*args, **kwargs):
orig_workdir = os.getcwd()
temp_workdir = tempfile.mkdtemp(*args, **kwargs)
os.chdir(temp_workdir)
yield temp_workdir
os.chdir(orig_workdir)
shutil.rmtree(temp_workdir)
class MockParser(argparse.ArgumentParser):
"""
argparse.ArgumentParser sys.exits() by default.
Make it more testable by throwing an exception instead.
"""
def error(self, message):
raise Exception(message)
def raises(exc, obj, *args, **kwargs):
"""
Assert that a callable raises a specified exception.
:exc An exception class or a string. If a class, assert that an
exception of this type is raised. If a string, assert that the string
occurs in the string representation of the exception, based on a
case-insenstivie match.
:obj A callable object.
:args Arguments to be passsed to the callable.
:kwargs Arguments to be passed to the callable.
"""
try:
obj(*args, **kwargs)
except Exception as v:
if isinstance(exc, basestring):
if exc.lower() in str(v).lower():
return
else:
raise AssertionError(
"Expected %s, but caught %s" % (
repr(str(exc)), v
)
)
else:
if isinstance(v, exc):
return
else:
raise AssertionError(
"Expected %s, but caught %s %s" % (
exc.__name__, v.__class__.__name__, str(v)
)
)
raise AssertionError("No exception raised.")
@contextmanager
def capture_stderr(command, *args, **kwargs):
out, sys.stderr = sys.stderr, StringIO()
command(*args, **kwargs)
yield sys.stderr.getvalue()
sys.stderr = out
test_data = utils.Data(__name__)
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import threading
from openstack.common import local
from openstack.common import test
class Dict(dict):
"""Make weak referencable object."""
pass
class LocalStoreTestCase(test.BaseTestCase):
v1 = Dict(a='1')
v2 = Dict(a='2')
v3 = Dict(a='3')
def setUp(self):
super(LocalStoreTestCase, self).setUp()
# NOTE(mrodden): we need to make sure that local store
# gets imported in the current python context we are
# testing in (eventlet vs normal python threading) so
# we test the correct type of local store for the current
# threading model
reload(local)
def test_thread_unique_storage(self):
"""Make sure local store holds thread specific values."""
expected_set = []
local.store.a = self.v1
def do_something():
local.store.a = self.v2
expected_set.append(getattr(local.store, 'a'))
def do_something2():
local.store.a = self.v3
expected_set.append(getattr(local.store, 'a'))
t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something2)
t1.start()
t2.start()
t1.join()
t2.join()
expected_set.append(getattr(local.store, 'a'))
self.assertTrue(self.v1 in expected_set)
self.assertTrue(self.v2 in expected_set)
self.assertTrue(self.v3 in expected_set)
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/LatinExtendedB.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* 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.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold"],{384:[676,14,553,-28,516],392:[576,14,568,30,574],400:[686,4,610,38,587],402:[706,155,500,0,498],405:[676,10,797,14,767],409:[691,0,533,12,533],410:[676,0,291,24,265],411:[666,0,536,60,526],414:[473,205,559,21,539],416:[732,19,778,35,788],417:[505,14,554,25,576],421:[673,205,550,10,515],426:[689,228,446,25,421],427:[630,218,347,18,331],429:[691,12,371,19,389],431:[810,19,796,16,836],432:[596,14,600,16,626],442:[450,237,441,9,415],443:[688,0,515,27,492],446:[541,10,527,78,449],448:[740,0,186,60,126],449:[740,0,313,60,253],450:[740,0,445,39,405],451:[691,13,333,81,251],496:[704,203,333,-57,335],506:[972,0,722,9,689],507:[923,14,500,25,488],508:[923,0,1000,4,951],509:[713,14,722,33,694],510:[923,74,778,35,743],511:[713,92,500,25,476],567:[461,203,333,-57,260]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Bold/LatinExtendedB.js");
|
//// [constructSignatureAssignabilityInInheritance5.ts]
// checking subtype relations for function types as it relates to contextual signature instantiation
// same as subtypingWithConstructSignatures2 just with an extra level of indirection in the inheritance chain
class Base { foo: string; }
class Derived extends Base { bar: string; }
class Derived2 extends Derived { baz: string; }
class OtherDerived extends Base { bing: string; }
interface A { // T
// M's
a: new (x: number) => number[];
a2: new (x: number) => string[];
a3: new (x: number) => void;
a4: new (x: string, y: number) => string;
a5: new (x: (arg: string) => number) => string;
a6: new (x: (arg: Base) => Derived) => Base;
a7: new (x: (arg: Base) => Derived) => (r: Base) => Derived;
a8: new (x: (arg: Base) => Derived, y: (arg2: Base) => Derived) => (r: Base) => Derived;
a9: new (x: (arg: Base) => Derived, y: (arg2: Base) => Derived) => (r: Base) => Derived;
a10: new (...x: Derived[]) => Derived;
a11: new (x: { foo: string }, y: { foo: string; bar: string }) => Base;
a12: new (x: Array<Base>, y: Array<Derived2>) => Array<Derived>;
a13: new (x: Array<Base>, y: Array<Derived>) => Array<Derived>;
a14: new (x: { a: string; b: number }) => Object;
}
interface B extends A {
a: new <T>(x: T) => T[];
}
// S's
interface I extends B {
// N's
a: new <T>(x: T) => T[]; // ok, instantiation of N is a subtype of M, T is number
a2: new <T>(x: T) => string[]; // ok
a3: new <T>(x: T) => T; // ok since Base returns void
a4: new <T, U>(x: T, y: U) => T; // ok, instantiation of N is a subtype of M, T is string, U is number
a5: new <T, U>(x: (arg: T) => U) => T; // ok, U is in a parameter position so inferences can be made
a6: new <T extends Base, U extends Derived>(x: (arg: T) => U) => T; // ok, same as a5 but with object type hierarchy
a7: new <T extends Base, U extends Derived>(x: (arg: T) => U) => (r: T) => U; // ok
a8: new <T extends Base, U extends Derived>(x: (arg: T) => U, y: (arg2: T) => U) => (r: T) => U; // ok
a9: new <T extends Base, U extends Derived>(x: (arg: T) => U, y: (arg2: { foo: string; bing: number }) => U) => (r: T) => U; // ok, same as a8 with compatible object literal
a10: new <T extends Derived>(...x: T[]) => T; // ok
a11: new <T extends Base>(x: T, y: T) => T; // ok
a12: new <T extends Array<Base>>(x: Array<Base>, y: T) => Array<Derived>; // ok, less specific parameter type
a13: new <T extends Array<Derived>>(x: Array<Base>, y: T) => T; // ok, T = Array<Derived>, satisfies constraint, contextual signature instantiation succeeds
a14: new <T>(x: { a: T; b: T }) => T; // ok, best common type yields T = {} but that's satisfactory for this signature
}
//// [constructSignatureAssignabilityInInheritance5.js]
// checking subtype relations for function types as it relates to contextual signature instantiation
// same as subtypingWithConstructSignatures2 just with an extra level of indirection in the inheritance chain
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Base = (function () {
function Base() {
}
return Base;
}());
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Derived;
}(Base));
var Derived2 = (function (_super) {
__extends(Derived2, _super);
function Derived2() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Derived2;
}(Derived));
var OtherDerived = (function (_super) {
__extends(OtherDerived, _super);
function OtherDerived() {
return _super !== null && _super.apply(this, arguments) || this;
}
return OtherDerived;
}(Base));
|
package org.codehaus.plexus.archiver.zip;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.codehaus.plexus.archiver.UnixStat;
import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes;
import org.codehaus.plexus.components.io.attributes.SimpleResourceAttributes;
import org.codehaus.plexus.components.io.functions.InputStreamTransformer;
import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier;
import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResource;
import org.codehaus.plexus.components.io.resources.ClosingInputStream;
import org.codehaus.plexus.components.io.resources.PlexusIoResource;
import javax.annotation.Nonnull;
public class ZipResource extends AbstractPlexusIoResource
implements ResourceAttributeSupplier
{
private final org.apache.commons.compress.archivers.zip.ZipFile zipFile;
private final ZipArchiveEntry entry;
private final InputStreamTransformer streamTransformer;
private PlexusIoResourceAttributes attributes;
public ZipResource( ZipFile zipFile, ZipArchiveEntry entry, InputStreamTransformer streamTransformer )
{
super(entry.getName(),getLastModofied( entry), entry.isDirectory() ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : entry.getSize() ,
!entry.isDirectory(), entry.isDirectory(), true);
this.zipFile = zipFile;
this.entry = entry;
this.streamTransformer = streamTransformer;
}
private static long getLastModofied( ZipArchiveEntry entry )
{
long l = entry.getLastModifiedDate().getTime();
return l == -1 ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : l;
}
public synchronized PlexusIoResourceAttributes getAttributes()
{
int mode = -1;
if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_UNIX)
{
mode = entry.getUnixMode();
if ((mode & UnixStat.FILE_FLAG) == UnixStat.FILE_FLAG) {
mode = mode & ~UnixStat.FILE_FLAG;
} else {
mode = mode & ~UnixStat.DIR_FLAG;
}
}
if ( attributes == null )
{
attributes = new SimpleResourceAttributes(null, null,null,null, mode);
}
return attributes;
}
public synchronized void setAttributes( PlexusIoResourceAttributes attributes )
{
this.attributes = attributes;
}
public URL getURL()
throws IOException
{
return null;
}
@Nonnull
public InputStream getContents()
throws IOException
{
final InputStream inputStream = zipFile.getInputStream( entry );
return new ClosingInputStream( streamTransformer.transform( this, inputStream ), inputStream);
}
}
|
<?php
/**
* Declares AlreadyExistsException.php
*
* origin: M
*
* @author Malte Stenzel
* @copyright 2007 - 2012 ICANS GmbH
*/
namespace Icans\Platforms\CoffeeKittyBundle\Exception;
use Icans\Platforms\CoffeeKittyBundle\Api\Exception\CoffeeKittyExceptionInterface;
/**
* Implements the AlreadyExistsException
*
* @author Malte Stenzel ([email protected])
*/
class AlreadyExistsException extends \RuntimeException implements CoffeeKittyExceptionInterface
{
}
|
<?php
/**
* This file is part of mermshaus/Pdf.
*
* mermshaus/Pdf is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* mermshaus/Pdf 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 mermshaus/Pdf. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2013 Marc Ermshaus <http://www.ermshaus.org/>
*/
namespace mermshaus\Tests\Pdf\Parser;
use mermshaus\Pdf\Parser\CrossReferenceTable;
use mermshaus\Pdf\Parser\CrossReferenceTableEntry;
use mermshaus\Pdf\Parser\ObjectRepository;
use mermshaus\Pdf\Parser\PdfStream;
use mermshaus\Pdf\Parser\StreamDecoder;
use PHPUnit_Framework_TestCase;
class StreamDecoderTest extends PHPUnit_Framework_TestCase
{
public function testFilterCombinations()
{
$dataHex = '48 65 6c 6c 6f 20 57 6f 72 6c 64 21>';
$dataHexFlate = gzcompress($dataHex);
$streamObjectTemplate = <<<EOT
1 0 obj
<<
/Length %s
/Filter [ /FlateDecode /ASCIIHexDecode ]
>>
stream
%s
endstream
endobj
EOT;
$streamObject = sprintf(
$streamObjectTemplate,
strlen($dataHexFlate),
$dataHexFlate
);
$streamData = 'data://text/plain;base64,' . base64_encode($streamObject);
$handle = fopen($streamData, 'rb');
$pdfStream = new PdfStream($handle);
$crossReferenceTable = new CrossReferenceTable();
$crossReferenceTable[] = new CrossReferenceTableEntry(1, 0, 0, 'n');
$objectRepository = new ObjectRepository($pdfStream, $crossReferenceTable);
$pdfStreamObject = $objectRepository->getObjectByIdAndRevision(1, 0)->getValue();
$streamDecoder = new StreamDecoder($pdfStream);
$dataDecoded = $streamDecoder->decodeStream($pdfStreamObject);
$this->assertEquals($dataDecoded, 'Hello World!');
}
}
|
"""
Django settings for ingenia project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0fbu(m#v%cjzvmuckl4^k7ng4t7py_^zojam1r(c6l*uunzim3'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pedidos',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'ingenia.urls'
WSGI_APPLICATION = 'ingenia.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
|
from animerecommendersystem.utils import utils_functions
from animerecommendersystem.recommender_systems import FuzzyClusteringRS
from animerecommendersystem.utils import definitions
from animerecommendersystem.data_processing import user_cluster_matrix
import numpy as np
import webbrowser
import timeit
import json
import os
import io
BASE_ANIME_LINK = "https://myanimelist.net/anime/"
BASE_USER_LINK = "https://myanimelist.net/animelist/"
def print_html_page(user, recommendations, utility):
header = u"""<html><head><title>Anime Recommendation System</title></head>"""
title = u"""<body><b><font size="6"><center>
Recommendations for user <a href="%s">%s</a>
</center></font></b>""" % (BASE_USER_LINK + user, user)
footer = u"""</body></html>"""
s = ""
counter = 1
for r in recommendations:
t = utility[r[0]]
link = BASE_ANIME_LINK + str(int(r[0]))
s += u"""<center>
<div class="riga">
<div class="colonna-1">
<p><img src="%s"></p>
<br>
%d - <a href="%s">%s</a>
</div>
</div>
</center>
<br><br><br>""" % (t[1], counter, link, t[0])
counter += 1
message = header + title + s + footer
filename = 'rec.html'
f = io.open(filename, 'w', encoding='utf-8')
f.write(message)
f.close()
webbrowser.open_new_tab(filename)
if __name__ == '__main__':
if (not os.path.exists(definitions.USER_CLUSTER_DICT)) or \
(not os.path.exists(definitions.USER_CLUSTER_MATRIX)) or \
(not os.path.exists(definitions.USER_CLUSTER_INDICES)):
user_cluster_matrix.save_user_cluster_matrix()
users_anime_lists = utils_functions.load_json_file(definitions.JSON_USER_FILE)
with open(definitions.UTILITY_FILE, 'r') as fp:
utility = json.load(fp)
users_clusters_dict = np.load(definitions.USER_CLUSTER_DICT).item()
users_clusters_matrix = np.load(definitions.USER_CLUSTER_MATRIX)
users_clusters_indices = np.load(definitions.USER_CLUSTER_INDICES).item()
fcrs = FuzzyClusteringRS.FuzzyCluseringRS(users_anime_lists, users_clusters_matrix,
users_clusters_dict, users_clusters_indices)
e1 = np.random.randint(len(users_clusters_indices.keys()))
print "[Username examples: %s , %s]" % ('RaiZero',
users_clusters_indices[e1])
user = raw_input("Insert username: ")
start = timeit.default_timer()
recommendations = fcrs.get_recommendations(user)
req_time = timeit.default_timer() - start
print "------------------------------------------------------------"
print "Required time to get recommendations = " + str(req_time)
print_html_page(user, recommendations, utility)
|
"""
Django settings for pycontw2016 project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from os.path import abspath, dirname, join, exists
from django.contrib.messages import constants as messages
from django.core.urlresolvers import reverse_lazy
# Build paths inside the project like this: join(BASE_DIR, "directory")
BASE_DIR = dirname(dirname(dirname(abspath(__file__))))
# Use Django templates using the new Django 1.8 TEMPLATES settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
join(BASE_DIR, 'templates'),
# insert more TEMPLATE_DIRS here
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request',
'core.context_processors.google_analytics',
],
'debug': True,
},
},
]
# Use 12factor inspired environment variables or from a file
import environ
env = environ.Env()
# Ideally move env file should be outside the git repo
# i.e. BASE_DIR.parent.parent
env_file = join(dirname(__file__), 'local.env')
if exists(env_file):
environ.Env.read_env(str(env_file))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
ALLOWED_HOSTS = []
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
# Raises ImproperlyConfigured exception if DATABASE_URL not in
# os.environ
'default': env.db(),
}
# Application definition
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
THIRD_PARTY_APPS = (
'django_extensions',
'crispy_forms',
'compressor',
)
LOCAL_APPS = (
'core',
'proposals',
'users',
)
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# Enable Postgres-specific things if we are using it.
if 'postgres' in DATABASES['default']['ENGINE']:
INSTALLED_APPS += ('postgres',)
MIDDLEWARE_CLASSES = (
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'core.middlewares.LocaleFallbackMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'pycontw2016.urls'
WSGI_APPLICATION = 'pycontw2016.wsgi.application'
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en'
LANGUAGES = [
('zh-hant', 'Traditional Chinese'),
('en-us', 'English (US)'),
]
FALLBACK_LANGUAGE_PREFIXES = {
'zh': 'zh-hant',
'en': 'en-us',
}
from django.conf import locale
if 'en-us' not in locale.LANG_INFO:
locale.LANG_INFO['en-us'] = {
'bidi': False,
'code': 'en-us',
'name': 'English (US)',
'name_local': 'English (US)',
}
# Path to the local .po and .mo files
LOCALE_PATHS = (
join(BASE_DIR, 'locale'),
)
USE_TZ = True
TIME_ZONE = 'UTC'
# Message tag setup.
# https://docs.djangoproject.com/es/1.9/ref/contrib/messages/#message-tags
MESSAGE_TAGS = {
messages.ERROR: 'danger',
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = join(BASE_DIR, 'assets')
STATICFILES_DIRS = [join(BASE_DIR, 'static')]
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_ROOT = join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LIBSASS_SOURCEMAPS = True
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
# URL settings.
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
LOGIN_REDIRECT_URL = reverse_lazy('user_dashboard')
# Third-party app and custom settings.
AUTH_USER_MODEL = 'users.User'
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
CRISPY_TEMPLATE_PACK = 'bootstrap3'
WERKZEUG_DEBUG = env.bool('WERKZEUG_DEBUG', default=True)
GA_TRACK_ID = None
SLACK_WEBHOOK_URL = env.str('SLACK_WEBHOOK_URL', default=None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.