text
stringlengths 2
6.14k
|
|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.digysoft.netbeans.sketch;
import processing.core.PApplet;
/**
*
* @author root
*/
public class AbstractSketch extends PApplet {
public int hexrgb(String hex){
return 0;
}
}
|
#! /usr/bin/python
'''
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
'''
class Solution:
# @return an integer
def minDistance(self, word1, word2):
size1 = len(word1)
size2 = len(word2)
if size1 == 0:
return size2
elif size2 == 0:
return size1
dp_array = [ [0] * (size2 + 1) for index in range(size1 + 1) ]
dp_array[0][0] = 0 if word1[0] == word2[0] else 1
for index in range(size1 + 1):
dp_array[index][0] = index
for index in range(size2 + 1):
dp_array[0][index] = index
for index1 in range(1, size1+1):
for index2 in range(1, size2+1):
if word1[index1 - 1] == word2[index2 - 1]:
dp_array[index1][index2] = dp_array[index1-1][index2-1]
else:
dp_array[index1][index2] = min([dp_array[index1-1][index2-1], dp_array[index1-1][index2], dp_array[index1][index2-1]]) + 1
return dp_array[-1][-1]
if __name__ == '__main__':
solution = Solution()
print solution.minDistance("pneumonoultramicroscopicsilicovolcanoconiosis", "ultramicroscopically")
|
#ifndef _BCM2835_MAILBOX_H
#define _BCM2835_MAILBOX_H
#include <stdint.h>
#define MAILBOX_BASE 0x2000B880
#define MAILBOX_POLL 0x10
#define MAILBOX_SENDER 0x14
#define MAILBOX_STATUS 0x18
#define MAILBOX_CONFIG 0x1C
#define MAILBOX_WRITE 0x20
#define EMMC_CLOCK_ID 0x01
#define UART_CLOCK_ID 0x02
#define ARM_CLOCK_ID 0x03
#define CORE_CLOCK_ID 0x04
#define V3D_CLOCK_ID 0x05
#define H264_CLOCK_ID 0x06
#define ISP_CLOCK_ID 0x07
#define SDRAM_CLOCK_ID 0x08
#define PIXEL_CLOCK_ID 0x09
#define PWM_CLOCK_ID 0x0A
#define MAILBOX_ARM_TO_VC 8
#define MAILBOX_SUCCESS 0x80000000
#define MAILBOX_TIMEOUT 100
/*
* Synchronously write to the mailbox.
* uint32_t data.
* uint8_t channel.
*/
void mailbox_write(uint32_t data, uint8_t channel);
/*
* Synchronously read from the mailbox.
* uint8_t channel.
*
* Returns:
* uint32_t.
*/
uint32_t mailbox_read(uint8_t channel);
#endif /* _BCM2835_MAILBOX_H */
|
//
// detail/tss_ptr.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_TSS_PTR_HPP
#define ASIO_DETAIL_TSS_PTR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_HAS_THREADS)
# include "asio/detail/null_tss_ptr.hpp"
#elif defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION)
# include "asio/detail/keyword_tss_ptr.hpp"
#elif defined(ASIO_WINDOWS)
# include "asio/detail/win_tss_ptr.hpp"
#elif defined(ASIO_HAS_PTHREADS)
# include "asio/detail/posix_tss_ptr.hpp"
#else
# error Only Windows and POSIX are supported!
#endif
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename T>
class tss_ptr
#if !defined(ASIO_HAS_THREADS)
: public null_tss_ptr<T>
#elif defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION)
: public keyword_tss_ptr<T>
#elif defined(ASIO_WINDOWS)
: public win_tss_ptr<T>
#elif defined(ASIO_HAS_PTHREADS)
: public posix_tss_ptr<T>
#endif
{
public:
void operator=(T* value)
{
#if !defined(ASIO_HAS_THREADS)
null_tss_ptr<T>::operator=(value);
#elif defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION)
keyword_tss_ptr<T>::operator=(value);
#elif defined(ASIO_WINDOWS)
win_tss_ptr<T>::operator=(value);
#elif defined(ASIO_HAS_PTHREADS)
posix_tss_ptr<T>::operator=(value);
#endif
}
};
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_DETAIL_TSS_PTR_HPP
|
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import time
Test.Summary = '''
regex_revalidate plugin test, reload epoch state on ats start
'''
# Test description:
# Ensures that that the regex revalidate config file is loaded,
# then epoch times from the state file are properly merged.
Test.SkipUnless(
Condition.PluginExists('regex_revalidate.so')
)
Test.ContinueOnFail = False
# configure origin server
server = Test.MakeOriginServer("server")
# Define ATS and configure
ts = Test.MakeATSProcess("ts", command="traffic_manager")
# **testname is required**
testName = "regex_revalidate_state"
# default root
request_header_0 = {"headers":
"GET / HTTP/1.1\r\n" +
"Host: www.example.com\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": "",
}
response_header_0 = {"headers":
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
"Cache-Control: max-age=300\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": "xxx",
}
server.addResponse("sessionlog.json", request_header_0, response_header_0)
reval_conf_path = os.path.join(ts.Variables.CONFIGDIR, 'reval.conf')
reval_state_path = os.path.join(Test.Variables.RUNTIMEDIR, 'reval.state')
# Configure ATS server
ts.Disk.plugin_config.AddLine(
f"regex_revalidate.so -d -c reval.conf -l reval.log -f {reval_state_path}"
)
sep = ' '
# rule with no initial state
path0_regex = "path0"
path0_expiry = str(time.time() + 90).split('.')[0]
path0_type = "STALE"
path0_rule = sep.join([path0_regex, path0_expiry, path0_type])
path1_regex = "path1"
path1_epoch = str(time.time() - 50).split('.')[0]
path1_expiry = str(time.time() + 600).split('.')[0]
path1_type = "MISS"
path1_rule = sep.join([path1_regex, path1_expiry, path1_type])
# Create gold files
gold_path_good = reval_state_path + ".good"
ts.Disk.File(gold_path_good, typename="ats:config").AddLines([
sep.join([path0_regex, "``", path0_expiry, path0_type]),
sep.join([path1_regex, path1_epoch, path1_expiry, path1_type]),
])
# It seems there's no API for negative gold file matching
'''
gold_path_bad = reval_state_path + ".bad"
ts.Disk.File(gold_path_bad, typename="ats:config").AddLines([
sep.join([path0_regex, path1_epoch, path0_expiry, path0_type]),
sep.join([path1_regex, path1_epoch, path1_expiry, path1_type]),
])
'''
# Create a state file, second line will be discarded and not merged
ts.Disk.File(reval_state_path, typename="ats:config").AddLines([
sep.join([path1_regex, path1_epoch, path1_expiry, path1_type]),
sep.join(["dummy", path1_epoch, path1_expiry, path1_type]),
])
# Write out reval.conf file
ts.Disk.File(reval_conf_path, typename="ats:config").AddLines([
path0_rule, path1_rule,
])
ts.chownForATSProcess(reval_state_path)
ts.Disk.remap_config.AddLine(
f"map http://ats/ http://127.0.0.1:{server.Variables.Port}"
)
# minimal configuration
ts.Disk.records_config.update({
'proxy.config.diags.debug.enabled': 1,
'proxy.config.diags.debug.tags': 'regex_revalidate',
'proxy.config.http.wait_for_cache': 1,
})
# This TestRun creates the state file so it exists when the ts process's Setup
# logic is run so that it can be chowned at that point.
tr = Test.AddTestRun("Populate the regex_revalidate state file")
tr.Processes.Default.Command = f'touch {reval_state_path}'
# Start ATS and evaluate the new state file
tr = Test.AddTestRun("Initial load, state merged")
ps = tr.Processes.Default
ps.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
# Note the ready condition: wait for ATS to modify the contents
# of the file from dummy to path1.
ps.StartBefore(Test.Processes.ts, ready=When.FileContains(reval_state_path, "path0"))
ps.Command = 'cat ' + reval_state_path
ps.ReturnCode = 0
ps.Streams.stdout.Content = Testers.GoldFile(gold_path_good)
tr.StillRunningAfter = ts
|
package com.vdurmont.vdmail.dto;
import org.joda.time.DateTime;
public class SessionDTO extends EntityDTO {
private String token;
private DateTime expirationDate;
private UserDTO user;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public DateTime getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(DateTime expirationDate) {
this.expirationDate = expirationDate;
}
public UserDTO getUser() {
return user;
}
public void setUser(UserDTO user) {
this.user = user;
}
}
|
# -*- coding: utf-8 -*-
"""
Attracting components.
"""
# Copyright (C) 2004-2013 by
# Aric Hagberg <[email protected]>
# Dan Schult <[email protected]>
# Pieter Swart <[email protected]>
# All rights reserved.
# BSD license.
import networkx as nx
from networkx.utils.decorators import not_implemented_for
__authors__ = "\n".join(['Christopher Ellison'])
__all__ = ['number_attracting_components',
'attracting_components',
'is_attracting_component',
'attracting_component_subgraphs',
]
@not_implemented_for('undirected')
def attracting_components(G):
"""Generates a list of attracting components in `G`.
An attracting component in a directed graph `G` is a strongly connected
component with the property that a random walker on the graph will never
leave the component, once it enters the component.
The nodes in attracting components can also be thought of as recurrent
nodes. If a random walker enters the attractor containing the node, then
the node will be visited infinitely often.
Parameters
----------
G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns
-------
attractors : generator of list
The list of attracting components, sorted from largest attracting
component to smallest attracting component.
See Also
--------
number_attracting_components
is_attracting_component
attracting_component_subgraphs
"""
scc = list(nx.strongly_connected_components(G))
cG = nx.condensation(G, scc)
for n in cG:
if cG.out_degree(n) == 0:
yield scc[n]
@not_implemented_for('undirected')
def number_attracting_components(G):
"""Returns the number of attracting components in `G`.
Parameters
----------
G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns
-------
n : int
The number of attracting components in G.
See Also
--------
attracting_components
is_attracting_component
attracting_component_subgraphs
"""
n = len(list(attracting_components(G)))
return n
@not_implemented_for('undirected')
def is_attracting_component(G):
"""Returns True if `G` consists of a single attracting component.
Parameters
----------
G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns
-------
attracting : bool
True if `G` has a single attracting component. Otherwise, False.
See Also
--------
attracting_components
number_attracting_components
attracting_component_subgraphs
"""
ac = list(attracting_components(G))
if len(ac[0]) == len(G):
attracting = True
else:
attracting = False
return attracting
@not_implemented_for('undirected')
def attracting_component_subgraphs(G, copy=True):
"""Generates a list of attracting component subgraphs from `G`.
Parameters
----------
G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns
-------
subgraphs : list
A list of node-induced subgraphs of the attracting components of `G`.
copy : bool
If copy is True, graph, node, and edge attributes are copied to the
subgraphs.
See Also
--------
attracting_components
number_attracting_components
is_attracting_component
"""
for ac in attracting_components(G):
if copy:
yield G.subgraph(ac).copy()
else:
yield G.subgraph(ac)
|
package org.batfish.specifier.parboiled;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.specifier.NameNodeSpecifier;
import org.batfish.specifier.NameRegexNodeSpecifier;
import org.batfish.specifier.NodeSpecifier;
import org.batfish.specifier.RoleNameNodeSpecifier;
import org.batfish.specifier.SpecifierContext;
import org.batfish.specifier.TypesNodeSpecifier;
import org.parboiled.errors.InvalidInputError;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
/** An {@link NodeSpecifier} that resolves based on the AST generated by {@link Parser}. */
@ParametersAreNonnullByDefault
public final class ParboiledNodeSpecifier implements NodeSpecifier {
@ParametersAreNonnullByDefault
private final class NodeAstNodeToNodes implements NodeAstNodeVisitor<Set<String>> {
private final SpecifierContext _ctxt;
NodeAstNodeToNodes(SpecifierContext ctxt) {
_ctxt = ctxt;
}
@Override
public Set<String> visitDifferenceNodeAstNode(DifferenceNodeAstNode differenceNodeAstNode) {
return Sets.difference(
differenceNodeAstNode.getLeft().accept(this),
differenceNodeAstNode.getRight().accept(this));
}
@Override
public Set<String> visitIntersectionNodeAstNode(
IntersectionNodeAstNode intersectionNodeAstNode) {
return Sets.intersection(
intersectionNodeAstNode.getLeft().accept(this),
intersectionNodeAstNode.getRight().accept(this));
}
@Override
public Set<String> visitNameNodeAstNode(NameNodeAstNode nameNodeAstNode) {
return new NameNodeSpecifier(nameNodeAstNode.getName()).resolve(_ctxt);
}
@Override
public Set<String> visitNameRegexNodeAstNode(NameRegexNodeAstNode nameRegexNodeAstNode) {
return new NameRegexNodeSpecifier(nameRegexNodeAstNode.getPattern()).resolve(_ctxt);
}
@Override
public Set<String> visitRoleNodeAstNode(RoleNodeAstNode roleNodeAstNode) {
// Because we changed the input on June 8 2019 from (role, dim) to (dim, role), we
// first interpret the user input as (dim, role) if the dim exists. Otherwise, we interpret
// it is as (role, dim)
if (_ctxt.getNodeRoleDimension(roleNodeAstNode.getDimensionName()).isPresent()) {
return new RoleNameNodeSpecifier(
roleNodeAstNode.getRoleName(), roleNodeAstNode.getDimensionName())
.resolve(_ctxt);
} else if (_ctxt.getNodeRoleDimension(roleNodeAstNode.getRoleName()).isPresent()) {
return new RoleNameNodeSpecifier(
roleNodeAstNode.getDimensionName(), roleNodeAstNode.getRoleName())
.resolve(_ctxt);
}
throw new NoSuchElementException(
"Node role dimension " + roleNodeAstNode.getDimensionName() + " does not exist.");
}
@Override
public Set<String> visitTypeNodeAstNode(TypeNodeAstNode typeNodeAstNode) {
return new TypesNodeSpecifier(ImmutableSet.of(typeNodeAstNode.getDeviceType()))
.resolve(_ctxt);
}
@Override
public Set<String> visitUnionNodeAstNode(UnionNodeAstNode unionNodeAstNode) {
return Sets.union(
unionNodeAstNode.getLeft().accept(this), unionNodeAstNode.getRight().accept(this));
}
}
private final NodeAstNode _ast;
ParboiledNodeSpecifier(NodeAstNode ast) {
_ast = ast;
}
/**
* Returns an {@link NodeSpecifier} based on {@code input} which is parsed as {@link
* Grammar#NODE_SPECIFIER}.
*
* @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
*/
public static ParboiledNodeSpecifier parse(String input) {
return new ParboiledNodeSpecifier(getAst(input));
}
static NodeAstNode getAst(String input) {
ParsingResult<AstNode> result =
new ReportingParseRunner<AstNode>(Parser.instance().getInputRule(Grammar.NODE_SPECIFIER))
.run(input);
if (!result.parseErrors.isEmpty()) {
throw new IllegalArgumentException(
ParserUtils.getErrorString(
input,
Grammar.NODE_SPECIFIER,
(InvalidInputError) result.parseErrors.get(0),
Parser.ANCHORS));
}
AstNode ast = ParserUtils.getAst(result);
checkArgument(
ast instanceof NodeAstNode, "Unexpected AST for nodeSpec input '%s': '%s'", input, ast);
return (NodeAstNode) ast;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ParboiledNodeSpecifier)) {
return false;
}
return Objects.equals(_ast, ((ParboiledNodeSpecifier) o)._ast);
}
@Override
public int hashCode() {
return Objects.hashCode(_ast);
}
@Override
public Set<String> resolve(SpecifierContext ctxt) {
return _ast.accept(new NodeAstNodeToNodes(ctxt));
}
}
|
<?php
namespace RectorPrefix20210615;
if (\class_exists('Tx_Extbase_Persistence_Exception_InvalidClass')) {
return;
}
class Tx_Extbase_Persistence_Exception_InvalidClass
{
}
\class_alias('Tx_Extbase_Persistence_Exception_InvalidClass', 'Tx_Extbase_Persistence_Exception_InvalidClass', \false);
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using Org.Apache.REEF.Utilities.Logging;
namespace Org.Apache.REEF.Tang.Util
{
public sealed class MonotonicHashMap<T, U> : Dictionary<T, U>
{
private static readonly Logger LOGGER = Logger.GetLogger(typeof(MonotonicHashMap<T, U>));
public new void Add(T key, U value)
{
U old;
TryGetValue(key, out old);
if (old != null)
{
var ex = new ArgumentException("Attempt to re-add: [" + key + "] old value: " + old + " new value " + value);
Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
}
base.Add(key, value);
}
public void AddAll(IDictionary<T, U> m)
{
foreach (T t in m.Keys)
{
if (ContainsKey(t))
{
U old;
m.TryGetValue(t, out old);
Add(t, old); // guaranteed to throw.
}
}
foreach (T t in m.Keys)
{
U old;
m.TryGetValue(t, out old);
Add(t, old);
}
}
public bool IsEmpty()
{
return Count == 0;
}
public U Get(T key)
{
U val;
TryGetValue(key, out val);
return val;
}
public new void Clear()
{
throw new NotSupportedException();
}
public new bool Remove(T key)
{
throw new NotSupportedException();
}
}
}
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 OpenStack Foundation
#
# 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.
#
"""nvp_net_binding
Revision ID: 1341ed32cc1e
Revises: 4692d074d587
Create Date: 2013-02-26 01:28:29.182195
"""
# revision identifiers, used by Alembic.
revision = '1341ed32cc1e'
down_revision = '4692d074d587'
# Change to ['*'] if this migration applies to all plugins
migration_for_plugins = [
'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2',
'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin',
'neutron.plugins.vmware.plugin.NsxPlugin',
'neutron.plugins.vmware.plugin.NsxServicePlugin'
]
from alembic import op
import sqlalchemy as sa
from neutron.db import migration
new_type = sa.Enum('flat', 'vlan', 'stt', 'gre', 'l3_ext',
name='nvp_network_bindings_binding_type')
old_type = sa.Enum('flat', 'vlan', 'stt', 'gre',
name='nvp_network_bindings_binding_type')
def upgrade(active_plugins=None, options=None):
if not migration.should_run(active_plugins, migration_for_plugins):
return
op.alter_column('nvp_network_bindings', 'tz_uuid',
name='phy_uuid',
existing_type=sa.String(36),
existing_nullable=True)
migration.alter_enum('nvp_network_bindings', 'binding_type', new_type,
nullable=False)
def downgrade(active_plugins=None, options=None):
if not migration.should_run(active_plugins, migration_for_plugins):
return
op.alter_column('nvp_network_bindings', 'phy_uuid',
name='tz_uuid',
existing_type=sa.String(36),
existing_nullable=True)
migration.alter_enum('nvp_network_bindings', 'binding_type', old_type,
nullable=False)
|
#Utilities for normalization/denormalization
def normalizedOrdinal(lowData,highData,lowNormalized,highNormalized,value):
dataRange = highData - lowData
realDataPercentage = value/dataRange
width = highNormalized - lowNormalized
widthDistance = realDataPercentage * width
return lowNormalized + widthDistance
def deNormalizeOrdinal(lowData,highData,lowNormalized,highNormalized,normalizedValue):
widthDistance = normalizedValue - lowNormalized
widthPercentage = widthDistance / (highNormalized - lowNormalized)
cataegoryNumber = (highData - lowData) * widthPercentage
return cataegoryNumber
def normalizedQuantitative(lowData,highData,lowNormalized,highNormalized,value):
dataRange = highData - lowData
normalizedRange = highNormalized - lowNormalized
dRange = value - lowData
dPct = dRange / dataRange
dNorm = normalizedRange * dPct
return lowNormalized + dNorm
def deNormalizeQuantitative(lowData,highData,lowNormalized,highNormalized,normalizedValue):
distanceFromLowerBound = normalizedValue - lowNormalized
dRange = distanceFromLowerBound/(highNormalized-lowNormalized)
distanceActual = dRange * (highData-lowData)
distanceRelative = lowData + distanceActual
return distanceRelative
################ UNIT TEST ######################################
def unit_test():
normalizedValue = normalizedOrdinal(0.0,14.0,-1.0,1.0,7.0)
print("Normalized Value is " + str(normalizedValue))
print(deNormalizeOrdinal(0.0,14.0,-1.0,1.0,normalizedValue))
x = normalizedQuantitative(100.0,4000.0,-1.0,1.0,1000.0)
print(deNormalizeQuantitative(100.0,4000.0,-1.0,1.0,x))
unit_test()
|
//
// ShopCartLogicViewModel.h
// RAC_Demo
//
// Created by ld on 17/1/10.
// Copyright © 2017年 ld. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <ReactiveObjC.h>
#define kShopCartLogicViewModelUpdateUI @"kShopCartLogicViewModelUpdateUI"
#import "ShopCartModel.h"
@interface ShopCartLogicViewModel : NSObject
//初始化方法
+(instancetype)logicViewModel:(UITableView *)tableView tableViewDelegate:(id) tableViewDelegate inVC:(UIViewController *)viewController;
//注册view的方法
-(void)registerReuseHeaderView:(NSString *)viewNames fromNib:(BOOL)fromNib;
-(void)registerReuseFooterView:(NSString *)viewNames fromNib:(BOOL)fromNib;
-(void)registerReuseCell:(NSString *)cellNames fromNib:(BOOL)fromNib;
//获取数据的方法
-(ShopCartCellModel *)cellModel:(NSIndexPath *)indexPath;
-(BOOL)sectionEdit:(NSIndexPath *)indexPath;
-(void)getDatas;
//刷新UI
-(void)updateSectionUI:(NSInteger)section;
//事件处理方法
-(void)cellSelectedClick:(NSIndexPath *)indexPath;
-(void)sectionSelectedClick:(NSInteger)section;
-(void)sectionEditBtnClick:(NSInteger)section;
-(void)allEditBtnClick:(UIButton *)btn;
-(void)allSelectedClick:(UIButton *)btn;
-(void)deleteCellByClick:(NSIndexPath *)indexPath;
-(void)deleteSelectedCell;
-(void)cellAddBtnClick:(NSIndexPath *)indexPath;
-(void)cellMinusBtnClick:(NSIndexPath *)indexPath;
-(void)cellTextFieldEndEdit:(NSIndexPath *)indexPath value:(NSInteger)value;
//需要保存的值
@property (nonatomic,weak,readonly) UITableView * tableView;
@property (nonatomic,weak,readonly) UIViewController * viewController;
@property (nonatomic,weak,readonly) id tableViewDelegate;
@property (nonatomic,copy,readonly) NSString * cellReuseID;
@property (nonatomic,copy,readonly) NSString * sectionHeaderReuseID;
@property (nonatomic,copy,readonly) NSString * sectionFooterReuseID;
@property (nonatomic,strong,readonly) ShopCartModel * shopCartModel;
@end
|
"""Start the arcyd instance for the current directory, if not already going."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdcmd_start
#
# Public Functions:
# getFromfilePrefixChars
# setupParser
# process
#
# -----------------------------------------------------------------------------
# (this contents block is generated, edits will be lost)
# =============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import abdi_startstop
def getFromfilePrefixChars():
return None
def setupParser(parser):
parser.add_argument(
'--foreground',
'-f',
action='store_true',
help="supply this argument to run arcyd interactively in the "
"foreground")
parser.add_argument(
'--no-loop',
action='store_true',
help="supply this argument to only process each repo once then exit")
def process(args):
logging.getLogger().setLevel(logging.DEBUG)
abdi_startstop.start_arcyd(daemonize=not args.foreground,
loop=not args.no_loop)
# -----------------------------------------------------------------------------
# Copyright (C) 2014-2015 Bloomberg Finance L.P.
#
# 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.
# ------------------------------ END-OF-FILE ----------------------------------
|
import unittest
import time
import glob
from benchmark import WebPage, STRESS_PATH
localhost = "http://localhost:80"
#localhost = "http://adslabs.org/bumblebee/"
class Test(unittest.TestCase):
def test_load_page(self):
"""Simple test to ensure a basic load works."""
myPage = WebPage(localhost)
myPage.pageLoad()
try:
self.assertEqual("Bumblebee discovery", myPage.title)
self.assertTrue(myPage.load_time > 0)
except Exception:
myPage.log_fail(Exception)
finally:
myPage.quit()
def test_load_page_config(self):
"""Simple test that all the config parameters parse correctly."""
config = {
"headless": True,
"fire_bug": False,
"net_export": False,
"fake_input": False,
"net_export_output": "{0}/har".format(STRESS_PATH),
}
myPage = WebPage(localhost, config=config)
try:
self.assertTrue("fake_input" not in myPage.config)
except Exception:
myPage.log_fail(Exception)
finally:
myPage.quit()
def test_query_author(self):
success_text = ""
config = {"headless": True, "fire_bug": False, "net_export": False}
myPage = WebPage(localhost, config=config)
myPage.pageLoad(wait={"type": "CLASS_NAME", "value": "q"})
#myPage.logger.info("waiting...")
#time.sleep(1)
#class_identify = "list-of-things"
#class_identify = "col-sm-5"
#class_identify = "col-sm-4 col-xs-5 s-top-row-col identifier s-identifier"
#class_identify = "col-sm-12 results-list s-results-list list-unstyled s-display-block"
#class_identify = "sr-only"
#class_identify = "//*[contains(@class, \"results-list\")]"
#class_identify = "li.col-sm-12.results-list"
class_identify = "s-results-title"
element = myPage.sendQuery(query="Elliott", wait={"type": "CLASS_NAME", "value": class_identify})
try:
self.assertTrue("Elliott" in myPage.page_source)
except Exception:
myPage.log_fail(Exception)
finally:
myPage.quit()
# def test_har_parse(self):
#
# myPage = WebPage(localhost)
# har_text = myPage.parse_har("./test.har")
#
# self.assertTrue("1418045210512398" in har_text)
def test_har_nofiles(self):
import os
har_file_made = False
config = {"headless": True, "fire_bug": True, "net_export": True}
myPage = WebPage(localhost, config=config)
glob_re = "{0}/localhost+20??-??-??+??-??-??.har".format(myPage.har_output)
file_list = glob.glob(glob_re)
for file_indv in file_list:
myPage.logger.info(file_indv)
os.remove(file_indv)
number_before = len(glob.glob(glob_re))
try:
myPage.pageLoad(wait={"type": "CLASS_NAME", "value": "q"})
har_file_made = myPage.har_file_made
except Exception:
myPage.log_fail(Exception)
finally:
myPage.quit()
number_after = len(glob.glob(glob_re))
simple_check = number_after > number_before
self.assertTrue(simple_check & har_file_made)
def test_har_filecheck(self):
har_file_made = False
config = {"headless": True, "fire_bug": True, "net_export": True}
myPage = WebPage(localhost, config=config)
glob_re = "{0}/localhost+20??-??-??+??-??-??.har".format(myPage.har_output)
number_before = len(glob.glob(glob_re))
try:
myPage.pageLoad(wait={"type": "CLASS_NAME", "value": "q"})
har_file_made = myPage.har_file_made
except Exception:
myPage.log_fail(Exception)
finally:
myPage.quit()
number_after = len(glob.glob(glob_re))
simple_check = number_after > number_before
self.assertTrue(simple_check & har_file_made)
def test_har_output(self):
config = {"headless": True, "fire_bug": True, "net_export": True}
myPage = WebPage(localhost, config=config)
glob_re = "{0}/localhost+20??-??-??+??-??-??.har".format(myPage.har_output)
number_before = len(glob.glob(glob_re))
number_after = number_before
myPage.pageLoad(wait={"type": "CLASS_NAME", "value": "q"})
myPage.logger.info("Waiting for har output file...")
timer, timeout = 0, 30
while number_before == number_after:
number_after = len(glob.glob(glob_re))
time.sleep(1)
timer += 1
myPage.logger.info("... {0} seconds [{1}]".format(timer, timeout))
# Timeout
if timer == timeout: break
myPage.logger.info("Investigating output folder: {0}".format(glob_re))
try:
self.assertTrue(number_after > number_before)
except Exception:
myPage.log_fail(Exception)
finally:
myPage.quit()
|
def migrate_up(manager):
manager.execute_script(ADD_COLUMN_SQL)
manager.execute_script(ALTER_VIEWS_UP_SQL)
def migrate_down(manager):
manager.execute_script(DROP_COLUMN_SQL)
manager.execute_script(ALTER_VIEWS_DOWN_SQL)
ADD_COLUMN_SQL = """\
ALTER TABLE tests ADD COLUMN started_time datetime NULL;
"""
DROP_COLUMN_SQL = """\
ALTER TABLE tests DROP started_time;
"""
ALTER_VIEWS_UP_SQL = """\
ALTER VIEW test_view AS
SELECT tests.test_idx,
tests.job_idx,
tests.test,
tests.subdir,
tests.kernel_idx,
tests.status,
tests.reason,
tests.machine_idx,
tests.started_time AS test_started_time,
tests.finished_time AS test_finished_time,
jobs.tag AS job_tag,
jobs.label AS job_label,
jobs.username AS job_username,
jobs.queued_time AS job_queued_time,
jobs.started_time AS job_started_time,
jobs.finished_time AS job_finished_time,
machines.hostname AS machine_hostname,
machines.machine_group,
machines.owner AS machine_owner,
kernels.kernel_hash,
kernels.base AS kernel_base,
kernels.printable AS kernel_printable,
status.word AS status_word
FROM tests
INNER JOIN jobs ON jobs.job_idx = tests.job_idx
INNER JOIN machines ON machines.machine_idx = jobs.machine_idx
INNER JOIN kernels ON kernels.kernel_idx = tests.kernel_idx
INNER JOIN status ON status.status_idx = tests.status;
-- perf_view (to make life easier for people trying to mine performance data)
ALTER VIEW perf_view AS
SELECT tests.test_idx,
tests.job_idx,
tests.test,
tests.subdir,
tests.kernel_idx,
tests.status,
tests.reason,
tests.machine_idx,
tests.started_time AS test_started_time,
tests.finished_time AS test_finished_time,
jobs.tag AS job_tag,
jobs.label AS job_label,
jobs.username AS job_username,
jobs.queued_time AS job_queued_time,
jobs.started_time AS job_started_time,
jobs.finished_time AS job_finished_time,
machines.hostname AS machine_hostname,
machines.machine_group,
machines.owner AS machine_owner,
kernels.kernel_hash,
kernels.base AS kernel_base,
kernels.printable AS kernel_printable,
status.word AS status_word,
iteration_result.iteration,
iteration_result.attribute AS iteration_key,
iteration_result.value AS iteration_value
FROM tests
INNER JOIN jobs ON jobs.job_idx = tests.job_idx
INNER JOIN machines ON machines.machine_idx = jobs.machine_idx
INNER JOIN kernels ON kernels.kernel_idx = tests.kernel_idx
INNER JOIN status ON status.status_idx = tests.status
INNER JOIN iteration_result ON iteration_result.test_idx = tests.kernel_idx;
"""
ALTER_VIEWS_DOWN_SQL = """\
ALTER VIEW test_view AS
SELECT tests.test_idx,
tests.job_idx,
tests.test,
tests.subdir,
tests.kernel_idx,
tests.status,
tests.reason,
tests.machine_idx,
tests.finished_time AS test_finished_time,
jobs.tag AS job_tag,
jobs.label AS job_label,
jobs.username AS job_username,
jobs.queued_time AS job_queued_time,
jobs.started_time AS job_started_time,
jobs.finished_time AS job_finished_time,
machines.hostname AS machine_hostname,
machines.machine_group,
machines.owner AS machine_owner,
kernels.kernel_hash,
kernels.base AS kernel_base,
kernels.printable AS kernel_printable,
status.word AS status_word
FROM tests
INNER JOIN jobs ON jobs.job_idx = tests.job_idx
INNER JOIN machines ON machines.machine_idx = jobs.machine_idx
INNER JOIN kernels ON kernels.kernel_idx = tests.kernel_idx
INNER JOIN status ON status.status_idx = tests.status;
-- perf_view (to make life easier for people trying to mine performance data)
ALTER VIEW perf_view AS
SELECT tests.test_idx,
tests.job_idx,
tests.test,
tests.subdir,
tests.kernel_idx,
tests.status,
tests.reason,
tests.machine_idx,
tests.finished_time AS test_finished_time,
jobs.tag AS job_tag,
jobs.label AS job_label,
jobs.username AS job_username,
jobs.queued_time AS job_queued_time,
jobs.started_time AS job_started_time,
jobs.finished_time AS job_finished_time,
machines.hostname AS machine_hostname,
machines.machine_group,
machines.owner AS machine_owner,
kernels.kernel_hash,
kernels.base AS kernel_base,
kernels.printable AS kernel_printable,
status.word AS status_word,
iteration_result.iteration,
iteration_result.attribute AS iteration_key,
iteration_result.value AS iteration_value
FROM tests
INNER JOIN jobs ON jobs.job_idx = tests.job_idx
INNER JOIN machines ON machines.machine_idx = jobs.machine_idx
INNER JOIN kernels ON kernels.kernel_idx = tests.kernel_idx
INNER JOIN status ON status.status_idx = tests.status
INNER JOIN iteration_result ON iteration_result.test_idx = tests.kernel_idx;
"""
|
from flask_me_example import app
app.debug = True
SECRET_KEY = 'random-secret-key'
SESSION_COOKIE_NAME = 'psa_session'
DEBUG = False
MONGODB_SETTINGS = {'DB': 'psa_db'}
DEBUG_TB_INTERCEPT_REDIRECTS = False
SESSION_PROTECTION = 'strong'
SOCIAL_AUTH_LOGIN_URL = '/'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/done/'
SOCIAL_AUTH_USER_MODEL = 'flask_me_example.models.user.User'
SOCIAL_AUTH_AUTHENTICATION_BACKENDS = (
'social.backends.open_id.OpenIdAuth',
'social.backends.google.GoogleOpenId',
'social.backends.google.GoogleOAuth2',
'social.backends.google.GoogleOAuth',
'social.backends.twitter.TwitterOAuth',
'social.backends.yahoo.YahooOpenId',
'social.backends.stripe.StripeOAuth2',
'social.backends.persona.PersonaAuth',
'social.backends.facebook.FacebookOAuth2',
'social.backends.facebook.FacebookAppOAuth2',
'social.backends.yahoo.YahooOAuth',
'social.backends.angel.AngelOAuth2',
'social.backends.behance.BehanceOAuth2',
'social.backends.bitbucket.BitbucketOAuth',
'social.backends.box.BoxOAuth2',
'social.backends.linkedin.LinkedinOAuth',
'social.backends.github.GithubOAuth2',
'social.backends.foursquare.FoursquareOAuth2',
'social.backends.instagram.InstagramOAuth2',
'social.backends.live.LiveOAuth2',
'social.backends.vk.VKOAuth2',
'social.backends.dailymotion.DailymotionOAuth2',
'social.backends.disqus.DisqusOAuth2',
'social.backends.dropbox.DropboxOAuth',
'social.backends.evernote.EvernoteSandboxOAuth',
'social.backends.fitbit.FitbitOAuth',
'social.backends.flickr.FlickrOAuth',
'social.backends.livejournal.LiveJournalOpenId',
'social.backends.soundcloud.SoundcloudOAuth2',
'social.backends.lastfm.LastFmAuth',
'social.backends.thisismyjam.ThisIsMyJamOAuth1',
'social.backends.stocktwits.StocktwitsOAuth2',
'social.backends.tripit.TripItOAuth',
'social.backends.clef.ClefOAuth2',
'social.backends.twilio.TwilioAuth',
'social.backends.xing.XingOAuth',
'social.backends.yandex.YandexOAuth2',
'social.backends.podio.PodioOAuth2',
'social.backends.reddit.RedditOAuth2',
)
|
/*
* This file is part of the L2J Global project.
*
* 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/>.
*/
package com.l2jglobal.gameserver.model.conditions;
import com.l2jglobal.gameserver.model.actor.L2Character;
import com.l2jglobal.gameserver.model.items.L2Item;
import com.l2jglobal.gameserver.model.items.L2Weapon;
import com.l2jglobal.gameserver.model.skills.Skill;
/**
* The Class ConditionTargetUsesWeaponKind.
* @author mkizub
*/
public class ConditionTargetUsesWeaponKind extends Condition
{
private final int _weaponMask;
/**
* Instantiates a new condition target uses weapon kind.
* @param weaponMask the weapon mask
*/
public ConditionTargetUsesWeaponKind(int weaponMask)
{
_weaponMask = weaponMask;
}
@Override
public boolean testImpl(L2Character effector, L2Character effected, Skill skill, L2Item item)
{
if (effected == null)
{
return false;
}
final L2Weapon weapon = effected.getActiveWeaponItem();
if (weapon == null)
{
return false;
}
return (weapon.getItemType().mask() & _weaponMask) != 0;
}
}
|
#!/usr/bin/python
#
# hershey-jhf-fix-linebreaks.py - fix linebreaks in .jhf Hershey font files
# Copyright (C) 2013 Kamal Mostafa <[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 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.
#
import sys
output = ''
def hershey_val(character):
return ord(character) - ord('R')
def read_hershey_glyph(f):
line = ''
while ( line == '' ):
line = f.readline()
if (not line) or line == '\x1a': # eof
return False
line = line.rstrip()
# read a Hershey format line
glyphnum = int(line[0:5]) # glyphnum (junk in some .jhf files)
nverts = int(line[5:8]) - 1
leftpos = hershey_val(line[8])
rightpos = hershey_val(line[9])
vertchars = line[10:]
nvertchars = len(vertchars)
# join split lines in the Hershey data
while ( nverts * 2 > nvertchars ):
nextline = f.readline().rstrip()
line += nextline
vertchars += nextline
nvertchars = len(vertchars)
if ( nverts * 2 != nvertchars ):
print >> sys.stderr, "hershey2olfont: Hershey format parse error (nvertchars=%d not %d)" % (nvertchars, nverts*2)
sys.exit(1)
# emit the fixed (joined) line
global output
output += "%s\n" % line
return True
#
# main
#
if ( len(sys.argv) != 3 ):
print >> sys.stderr, "usage: hershey-jhf-fix-linebreaks.py in.jhf out.jhf (same filename is ok)"
sys.exit(1)
hershey_in = sys.argv[1]
hershey_out = sys.argv[2]
with open(hershey_in) as f:
while read_hershey_glyph(f):
pass
f.close()
fd = open(hershey_out,"w")
fd.write(output)
fd.close()
|
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Security
{
using System.Diagnostics;
using Caching;
using Microsoft.Xrm.Client.Caching;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Sdk.Client;
using Services;
internal class ApplicationCachingCrmEntitySecurityProvider : CachingCrmEntitySecurityProvider
{
public ApplicationCachingCrmEntitySecurityProvider(
ICacheSupportingCrmEntitySecurityProvider underlyingProvider,
ICrmEntitySecurityCacheInfoFactory cacheInfoFactory)
: base(underlyingProvider, cacheInfoFactory) { }
public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
var info = CacheInfoFactory.GetCacheInfo(context, entity, right);
if (!info.IsCacheable)
{
return UnderlyingProvider.TryAssert(context, entity, right, dependencies);
}
Stopwatch stopwatch = null;
return ObjectCacheManager.Get(info.Key,
cache =>
{
stopwatch = Stopwatch.StartNew();
var value = UnderlyingProvider.TryAssert(context, entity, right, dependencies);
stopwatch.Stop();
return value;
},
(cache, value) =>
{
if (dependencies.IsCacheable)
{
cache.Insert(info.Key, value, dependencies);
if (stopwatch != null)
{
cache.AddCacheItemTelemetry(info.Key, new CacheItemTelemetry { Duration = stopwatch.Elapsed });
}
}
});
}
}
}
|
/*
* DesktopSessionServersOverlay.hpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef DESKTOP_SESSION_SERVERS_OVERLAY_HPP
#define DESKTOP_SESSION_SERVERS_OVERLAY_HPP
#include <QJsonObject>
#include <QJsonValue>
#include <QNetworkCookie>
#include <QObject>
#include <boost/optional.hpp>
#include <boost/signals2.hpp>
#include <shared_core/FilePath.hpp>
namespace rstudio {
namespace core {
class Error;
}
}
namespace rstudio {
namespace desktop {
class DesktopSessionServers;
DesktopSessionServers& sessionServers();
class SessionServerSettings;
SessionServerSettings& sessionServerSettings();
class SessionServerPathMapping
{
public:
SessionServerPathMapping(const std::string& localPath,
const std::string& remotePath) :
localPath_(localPath),
remotePath_(remotePath)
{
}
bool empty() { return localPath_.empty() || remotePath_.empty(); }
const std::string& localPath() const { return localPath_; }
const std::string& remotePath() const { return remotePath_; }
void setLocalPath(const std::string& localPath) { localPath_ = localPath; }
void setRemotePath(const std::string& remotePath) { remotePath_ = remotePath; }
QJsonObject toJson() const;
static SessionServerPathMapping fromJson(const QJsonObject& pathMappingJson);
private:
SessionServerPathMapping() {}
std::string localPath_;
std::string remotePath_;
};
class SessionServer
{
public:
SessionServer(const std::string& name,
const std::string& url,
bool isDefault = false,
bool allowPathMapping = false,
const std::vector<SessionServerPathMapping>& pathMappings = {}) :
name_(name),
url_(url),
isDefault_(isDefault),
allowPathMapping_(allowPathMapping),
pathMappings_(pathMappings)
{
}
SessionServer(const SessionServer& other) = default;
const std::string& name() const { return name_; }
const std::string& url() const { return url_; }
const std::string& label() const;
bool isDefault() const { return isDefault_; }
bool allowPathMapping() const { return allowPathMapping_; }
std::vector<SessionServerPathMapping> pathMappings() const { return pathMappings_; }
QJsonObject toJson() const;
static SessionServer fromJson(const QJsonObject& sessionServerJson);
bool cookieBelongs(const QNetworkCookie& cookie) const;
void setName(const std::string& name) { name_ = name; }
void setUrl(const std::string& url) { url_ = url; }
void setIsDefault(bool isDefault) { isDefault_ = isDefault; }
void setAllowPathMapping(bool allow) { allowPathMapping_ = allow; }
void setPathMappings(const std::vector<SessionServerPathMapping>& mappings) { pathMappings_ = mappings; }
core::Error test();
bool operator==(const SessionServer& other) const
{
return name_ == other.name_ &&
url_ == other.url_;
}
private:
SessionServer() :
isDefault_(false) {}
std::string name_;
std::string url_;
bool isDefault_;
bool allowPathMapping_;
std::vector<SessionServerPathMapping> pathMappings_;
};
struct LaunchLocationResult
{
int dialogResult;
boost::optional<SessionServer> sessionServer;
};
class DesktopSessionServers : public QObject
{
Q_OBJECT
public:
DesktopSessionServers();
void showSessionServerOptionsDialog(QWidget* parent = nullptr);
LaunchLocationResult showSessionLaunchLocationDialog();
void setPendingSessionServerReconnect(const SessionServer& server);
boost::optional<SessionServer> getPendingSessionServerReconnect();
Q_SIGNALS:
public:
private:
boost::optional<SessionServer> pendingSessionServerReconnect_;
};
enum class SessionLocation
{
Ask,
Locally,
Server
};
enum class CloseServerSessions
{
Ask,
Always,
Never
};
enum class ConfigSource
{
Admin,
User
};
class SessionServerSettings
{
public:
const std::vector<SessionServer>& servers() const { return servers_; }
SessionLocation sessionLocation() const { return sessionLocation_; }
CloseServerSessions closeServerSessionsOnExit() const { return closeServerSessionsOnExit_; }
ConfigSource configSource() const;
void save(const std::vector<SessionServer>& servers,
SessionLocation sessionLocation,
CloseServerSessions closeServerSessionsOnExit);
boost::signals2::scoped_connection addSaveHandler(const boost::function<void(void)>& onSave);
private:
friend SessionServerSettings& sessionServerSettings();
SessionServerSettings();
std::vector<SessionServer> servers_;
SessionLocation sessionLocation_;
CloseServerSessions closeServerSessionsOnExit_;
core::FilePath optionsFile_;
boost::signals2::signal<void()> onSaveSignal_;
};
} // namespace desktop
} // namespace rstudio
#endif // DESKTOP_SESSION_SERVERS_OVERLAY_HPP
|
import logging
import re
import lxml.etree as ET
_account_alias_pattern = re.compile("Account: *([^(]+) *\(([0-9]+)\)")
_account_without_alias_pattern = re.compile("Account: *\(?([0-9]+)\)?")
def account_aliases(session, username, password, auth_method, saml_response, config):
alias_response = session.post(
'https://signin.aws.amazon.com/saml',
verify=config.ssl_verification,
headers={
'Accept-Language': 'en',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'text/plain, */*; q=0.01',
},
auth=None,
data={
'SAMLResponse': saml_response,
}
)
logging.debug(u'''Request:
* url: {}
* headers: {}
Response:
* status: {}
* headers: {}
* body: {}
'''.format('https://signin.aws.amazon.com/saml',
alias_response.request.headers,
alias_response.status_code,
alias_response.headers,
alias_response.text))
html_response = ET.fromstring(alias_response.text, ET.HTMLParser())
accounts = {}
account_element_query = './/div[@class="saml-account-name"]'
for account_element in html_response.iterfind(account_element_query):
logging.debug(u'Found SAML account name: {}'.format(account_element.text))
m = _account_alias_pattern.search(account_element.text)
if m is not None:
accounts[m.group(2)] = m.group(1).strip()
if m is None:
m = _account_without_alias_pattern.search(account_element.text)
if m is not None:
accounts[m.group(1)] = m.group(0).strip()
return accounts
|
# 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.
"""Output formatters for JSON.
"""
import json
from . import base
from cliff import columns
class JSONFormatter(base.ListFormatter, base.SingleFormatter):
def add_argument_group(self, parser):
group = parser.add_argument_group(title='json formatter')
group.add_argument(
'--noindent',
action='store_true',
dest='noindent',
help='whether to disable indenting the JSON'
)
def emit_list(self, column_names, data, stdout, parsed_args):
items = []
for item in data:
items.append(
{n: (i.machine_readable()
if isinstance(i, columns.FormattableColumn)
else i)
for n, i in zip(column_names, item)}
)
indent = None if parsed_args.noindent else 2
json.dump(items, stdout, indent=indent)
stdout.write('\n')
def emit_one(self, column_names, data, stdout, parsed_args):
one = {
n: (i.machine_readable()
if isinstance(i, columns.FormattableColumn)
else i)
for n, i in zip(column_names, data)
}
indent = None if parsed_args.noindent else 2
json.dump(one, stdout, indent=indent)
|
# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# 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
#
# https://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.
from __future__ import absolute_import
import sys
from google.api_core.protobuf_helpers import get_messages
from google.cloud.talent_v4beta1.proto import application_pb2
from google.cloud.talent_v4beta1.proto import application_service_pb2
from google.cloud.talent_v4beta1.proto import common_pb2
from google.cloud.talent_v4beta1.proto import company_pb2
from google.cloud.talent_v4beta1.proto import company_service_pb2
from google.cloud.talent_v4beta1.proto import completion_service_pb2
from google.cloud.talent_v4beta1.proto import event_pb2
from google.cloud.talent_v4beta1.proto import event_service_pb2
from google.cloud.talent_v4beta1.proto import filters_pb2
from google.cloud.talent_v4beta1.proto import histogram_pb2
from google.cloud.talent_v4beta1.proto import job_pb2
from google.cloud.talent_v4beta1.proto import job_service_pb2
from google.cloud.talent_v4beta1.proto import profile_pb2
from google.cloud.talent_v4beta1.proto import profile_service_pb2
from google.cloud.talent_v4beta1.proto import tenant_pb2
from google.cloud.talent_v4beta1.proto import tenant_service_pb2
from google.longrunning import operations_pb2
from google.protobuf import any_pb2
from google.protobuf import duration_pb2
from google.protobuf import empty_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import wrappers_pb2
from google.rpc import status_pb2
from google.type import date_pb2
from google.type import latlng_pb2
from google.type import money_pb2
from google.type import postal_address_pb2
from google.type import timeofday_pb2
_shared_modules = [
operations_pb2,
any_pb2,
duration_pb2,
empty_pb2,
field_mask_pb2,
timestamp_pb2,
wrappers_pb2,
status_pb2,
date_pb2,
latlng_pb2,
money_pb2,
postal_address_pb2,
timeofday_pb2,
]
_local_modules = [
application_pb2,
application_service_pb2,
common_pb2,
company_pb2,
company_service_pb2,
completion_service_pb2,
event_pb2,
event_service_pb2,
filters_pb2,
histogram_pb2,
job_pb2,
job_service_pb2,
profile_pb2,
profile_service_pb2,
tenant_pb2,
tenant_service_pb2,
]
names = []
for module in _shared_modules: # pragma: NO COVER
for name, message in get_messages(module).items():
setattr(sys.modules[__name__], name, message)
names.append(name)
for module in _local_modules:
for name, message in get_messages(module).items():
message.__module__ = "google.cloud.talent_v4beta1.types"
setattr(sys.modules[__name__], name, message)
names.append(name)
__all__ = tuple(sorted(names))
|
import unittest
"""
Given n daily price quotes for a stock, we need to calculate span of stock's price for
all n days.
The Span S[i] of the stock's price on a given day i is defined as the maximum number of
consecutive days just before day i, for which price of stock on that day is less than
or equal to price of stock on day i.
Input: prices = {100, 80, 60, 70, 60, 75, 85}
Output: spans = {1, 1, 1, 2, 1, 4, 6}
"""
"""
Approach:
1. When computing span for day i, say the price of stock on that day is prices[i].
2. We need to find the first day j to left of i such that prices[j] > prices[i].
3. Then span for day i will be j - i. If there is no such day j, then span for day i is i + 1.
4. We use a stack to store indices. When we are at day i, we keep removing indices from stack
till we find an index j on stack for which prices[j] > prices[i].
5. We then push i on stack.
"""
def stock_span(prices):
spans = [0] * len(prices)
spans[0] = 1
stack = [0]
for i in range(1, len(prices)):
while len(stack) > 0 and prices[stack[-1]] <= prices[i]:
stack.pop()
spans[i] = (i + 1) if len(stack) == 0 else i - stack[-1]
stack.append(i)
return spans
class TestStockSpan(unittest.TestCase):
def test_stock_span(self):
prices = [100, 80, 60, 70, 60, 75, 85]
self.assertEqual(stock_span(prices), [1, 1, 1, 2, 1, 4, 6])
prices = [10, 4, 5, 90, 120, 80]
self.assertEqual(stock_span(prices), [1, 1, 2, 4, 5, 1])
|
export const PAGES_MENU = [
{
path: 'pages',
children: [
{
path: 'dashboard',
data: {
menu: {
title: 'general.menu.dashboard',
icon: 'ion-android-home',
selected: false,
expanded: false,
order: 0
}
}
},
{
path: 'browse',
data: {
menu: {
title: 'general.menu.browse',
icon: 'ion-android-home',
selected: false,
expanded: false,
order: 0
}
}
},
{
path: 'add',
data: {
menu: {
title: 'general.menu.add',
icon: 'ion-android-home',
selected: false,
expanded: false,
order: 0
}
}
}
]
}
];
|
# Copyright 2017, 2019 The Meson development team
# 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.
from . import ExtensionModule
from .. import mesonlib
from ..mesonlib import typeslistify
from ..interpreterbase import FeatureNew, noKwargs
from ..interpreter import InvalidCode
import os
class KeyvalModule(ExtensionModule):
@FeatureNew('Keyval Module', '0.55.0')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.snippets.add('load')
def _load_file(self, path_to_config):
result = dict()
try:
with open(path_to_config) as f:
for line in f:
if '#' in line:
comment_idx = line.index('#')
line = line[:comment_idx]
line = line.strip()
try:
name, val = line.split('=', 1)
except ValueError:
continue
result[name.strip()] = val.strip()
except IOError as e:
raise mesonlib.MesonException('Failed to load {}: {}'.format(path_to_config, e))
return result
@noKwargs
def load(self, interpreter, state, args, kwargs):
sources = typeslistify(args, (str, mesonlib.File))
if len(sources) != 1:
raise InvalidCode('load takes only one file input.')
s = sources[0]
is_built = False
if isinstance(s, mesonlib.File):
is_built = is_built or s.is_built
s = s.absolute_path(interpreter.environment.source_dir, interpreter.environment.build_dir)
else:
s = os.path.join(interpreter.environment.source_dir, s)
if s not in interpreter.build_def_files and not is_built:
interpreter.build_def_files.append(s)
return self._load_file(s)
def initialize(*args, **kwargs):
return KeyvalModule(*args, **kwargs)
|
int main(int argc, const char * argv[]) {
if(argc < 1) {
__builtin_unreachable();
}
return *argv[0];
}
|
<?php
/**
* Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace FacebookAds\Object\Fields;
use FacebookAds\Enum\AbstractEnum;
/**
* This class is auto-genereated.
*
* For any issues or feature requests related to this class, please let us know
* on github and we'll fix in our codegen framework. We'll not be able to accept
* pull request for this class.
*
*/
class TargetingGeoLocationMarketFields extends AbstractEnum {
const COUNTRY = 'country';
const KEY = 'key';
const MARKET_TYPE = 'market_type';
const NAME = 'name';
public function getFieldTypes() {
return array(
'country' => 'string',
'key' => 'string',
'market_type' => 'string',
'name' => 'string',
);
}
}
|
/*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.sdk;
import com.salesforce.dva.argus.sdk.ArgusHttpClient.ArgusResponse;
import com.salesforce.dva.argus.sdk.ArgusService.EndpointService;
import com.salesforce.dva.argus.sdk.entity.PrincipalUser;
import java.io.IOException;
import java.math.BigInteger;
/**
* Provides methods to manipulate users.
*
* @author Tom Valine ([email protected])
*/
public class UserService extends EndpointService {
//~ Static fields/initializers *******************************************************************************************************************
private static final String RESOURCE = "/users";
//~ Constructors *********************************************************************************************************************************
/**
* Creates a new UserService object.
*
* @param client The HTTP client for use by the service.
*/
UserService(ArgusHttpClient client) {
super(client);
}
//~ Methods **************************************************************************************************************************************
/**
* Returns the information for the specified user.
*
* @param id The ID of the user to retrieve information for.
*
* @return The information for the specified user.
*
* @throws IOException If the server cannot be reached.
*/
public PrincipalUser getUser(BigInteger id) throws IOException {
String requestUrl = RESOURCE + "/id/" + id.toString();
ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.GET, requestUrl, null);
assertValidResponse(response, requestUrl);
return fromJson(response.getResult(), PrincipalUser.class);
}
/**
* Returns the information for the specified user.
*
* @param username The username to retrieve information for.
*
* @return The information for the specified user.
*
* @throws IOException If the server cannot be reached.
*/
public PrincipalUser getUser(String username) throws IOException {
String requestUrl = RESOURCE + "/username/" + username;
ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.GET, requestUrl, null);
assertValidResponse(response, requestUrl);
return fromJson(response.getResult(), PrincipalUser.class);
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
|
// Type definitions for @feathersjs/errors 3.3
// Project: https://feathersjs.com
// Definitions by: Jan Lohage <https://github.com/j2L4e>
// RazzM13 <https://github.com/RazzM13>
// Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript
// TypeScript Version: 2.2
export interface FeathersErrorJSON {
readonly name: string;
readonly message: string;
readonly code: number;
readonly className: string;
readonly data: any;
readonly errors: any;
}
export class FeathersError extends Error {
readonly code: number;
readonly className: string;
readonly data: any;
readonly errors: any;
constructor(msg: string | Error, name: string, code: number, className: string, data: any);
toJSON(): FeathersErrorJSON;
}
export class BadRequest extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class NotAuthenticated extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class PaymentError extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class Forbidden extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class NotFound extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class MethodNotAllowed extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class NotAcceptable extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class Timeout extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class Conflict extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class LengthRequired extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class Unprocessable extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class TooManyRequests extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class GeneralError extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class NotImplemented extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class BadGateway extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export class Unavailable extends FeathersError {
constructor(msg?: string | Error, data?: any);
}
export interface Errors {
FeathersError: FeathersError;
BadRequest: BadRequest;
NotAuthenticated: NotAuthenticated;
PaymentError: PaymentError;
Forbidden: Forbidden;
NotFound: NotFound;
MethodNotAllowed: MethodNotAllowed;
NotAcceptable: NotAcceptable;
Timeout: Timeout;
Conflict: Conflict;
LengthRequired: LengthRequired;
Unprocessable: Unprocessable;
TooManyRequests: TooManyRequests;
GeneralError: GeneralError;
NotImplemented: NotImplemented;
BadGateway: BadGateway;
Unavailable: Unavailable;
}
export function convert(error: any): FeathersError;
export const types: Errors;
export const errors: Errors;
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Xabaril.EntityFrameworkCoreStore.Entities;
using Xabaril.EntityFrameworkCoreStore.Options;
namespace Xabaril.EntityFrameworkCoreStore.EntityConfigurations
{
public class ActivatorParameterEntityConfiguration : IEntityTypeConfiguration<ActivatorParameter>
{
private readonly StoreOptions storeOptions;
public ActivatorParameterEntityConfiguration(StoreOptions storeOptions)
{
this.storeOptions = storeOptions;
}
public void Configure(EntityTypeBuilder<ActivatorParameter> builder)
{
builder.ToTable(storeOptions.ActivatorParameters);
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).ValueGeneratedOnAdd();
builder.Property(x => x.ActivatorType).HasMaxLength(500).IsRequired();
builder.Property(x => x.Value).HasMaxLength(200).IsRequired();
builder.Property(x => x.Name).HasMaxLength(200).IsRequired();
}
}
}
|
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
def __init__(self):
CharSetGroupProber.__init__(self)
self._mProbers = [ \
SingleByteCharSetProber(Win1251CyrillicModel),
SingleByteCharSetProber(Koi8rModel),
SingleByteCharSetProber(Latin5CyrillicModel),
SingleByteCharSetProber(MacCyrillicModel),
SingleByteCharSetProber(Ibm866Model),
SingleByteCharSetProber(Ibm855Model),
SingleByteCharSetProber(Latin7GreekModel),
SingleByteCharSetProber(Win1253GreekModel),
SingleByteCharSetProber(Latin5BulgarianModel),
SingleByteCharSetProber(Win1251BulgarianModel),
SingleByteCharSetProber(Latin2HungarianModel),
SingleByteCharSetProber(Win1250HungarianModel),
SingleByteCharSetProber(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset()
|
package org.mymoney.accountservice.web.rest.vm;
import ch.qos.logback.classic.Logger;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* View Model object for storing a Logback logger.
*/
public class LoggerVM {
private String name;
private String level;
public LoggerVM(Logger logger) {
this.name = logger.getName();
this.level = logger.getEffectiveLevel().toString();
}
@JsonCreator
public LoggerVM() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
@Override
public String toString() {
return "LoggerVM{" +
"name='" + name + '\'' +
", level='" + level + '\'' +
'}';
}
}
|
/*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2007-2011, Code Aurora Forum. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/stddef.h>
#include <linux/spinlock.h>
#include <mach/clk.h>
#include <mach/socinfo.h>
#include "proc_comm.h"
#include "clock.h"
#include "clock-pcom.h"
#include <mach/socinfo.h>
struct clk_pcom {
unsigned count;
bool always_on;
};
static struct clk_pcom pcom_clocks[P_NR_CLKS] = {
[P_EBI1_CLK] = { .always_on = true },
[P_PBUS_CLK] = { .always_on = true },
};
static DEFINE_SPINLOCK(pc_clk_lock);
/*
* glue for the proc_comm interface
*/
int pc_clk_enable(unsigned id)
{
int rc;
unsigned long flags;
struct clk_pcom *clk = &pcom_clocks[id];
if (clk->always_on)
return 0;
spin_lock_irqsave(&pc_clk_lock, flags);
if (clk->count == 0) {
rc = msm_proc_comm(PCOM_CLKCTL_RPC_ENABLE, &id, NULL);
if (rc < 0)
goto unlock;
else if ((int)id < 0) {
rc = -EINVAL;
goto unlock;
} else
rc = 0;
}
clk->count++;
unlock:
spin_unlock_irqrestore(&pc_clk_lock, flags);
return rc;
}
void pc_clk_disable(unsigned id)
{
unsigned long flags;
struct clk_pcom *clk = &pcom_clocks[id];
if (clk->always_on)
return;
spin_lock_irqsave(&pc_clk_lock, flags);
if (WARN_ON(clk->count == 0))
goto out;
clk->count--;
if (clk->count == 0)
msm_proc_comm(PCOM_CLKCTL_RPC_DISABLE, &id, NULL);
out:
spin_unlock_irqrestore(&pc_clk_lock, flags);
}
void pc_clk_auto_off(unsigned id)
{
unsigned long flags;
struct clk_pcom *clk = &pcom_clocks[id];
spin_lock_irqsave(&pc_clk_lock, flags);
if (clk->count == 0)
msm_proc_comm(PCOM_CLKCTL_RPC_DISABLE, &id, NULL);
spin_unlock_irqrestore(&pc_clk_lock, flags);
}
int pc_clk_reset(unsigned id, enum clk_reset_action action)
{
int rc;
if (action == CLK_RESET_ASSERT)
rc = msm_proc_comm(PCOM_CLKCTL_RPC_RESET_ASSERT, &id, NULL);
else
rc = msm_proc_comm(PCOM_CLKCTL_RPC_RESET_DEASSERT, &id, NULL);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_rate(unsigned id, unsigned rate)
{
/* The rate _might_ be rounded off to the nearest KHz value by the
* remote function. So a return value of 0 doesn't necessarily mean
* that the exact rate was set successfully.
*/
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_SET_RATE, &id, &rate);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_min_rate(unsigned id, unsigned rate)
{
int rc;
bool ignore_error = (cpu_is_msm7x27() && id == P_EBI1_CLK &&
rate >= INT_MAX);
rc = msm_proc_comm(PCOM_CLKCTL_RPC_MIN_RATE, &id, &rate);
if (rc < 0)
return rc;
else if (ignore_error)
return 0;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_max_rate(unsigned id, unsigned rate)
{
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_MAX_RATE, &id, &rate);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_flags(unsigned id, unsigned flags)
{
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_SET_FLAGS, &id, &flags);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
unsigned pc_clk_get_rate(unsigned id)
{
if (msm_proc_comm(PCOM_CLKCTL_RPC_RATE, &id, NULL))
return 0;
else
return id;
}
unsigned pc_clk_is_enabled(unsigned id)
{
if (msm_proc_comm(PCOM_CLKCTL_RPC_ENABLED, &id, NULL))
return 0;
else
return id;
}
long pc_clk_round_rate(unsigned id, unsigned rate)
{
/* Not really supported; pc_clk_set_rate() does rounding on it's own. */
return rate;
}
struct clk_ops clk_ops_remote = {
.enable = pc_clk_enable,
.disable = pc_clk_disable,
.auto_off = pc_clk_auto_off,
.reset = pc_clk_reset,
.set_rate = pc_clk_set_rate,
.set_min_rate = pc_clk_set_min_rate,
.set_max_rate = pc_clk_set_max_rate,
.set_flags = pc_clk_set_flags,
.get_rate = pc_clk_get_rate,
.is_enabled = pc_clk_is_enabled,
.round_rate = pc_clk_round_rate,
};
int pc_clk_set_rate2(unsigned id, unsigned rate)
{
return pc_clk_set_rate(id, rate / 2);
}
int pc_clk_set_min_rate2(unsigned id, unsigned rate)
{
return pc_clk_set_min_rate(id, rate / 2);
}
unsigned pc_clk_get_rate2(unsigned id)
{
return pc_clk_get_rate(id) * 2;
}
struct clk_ops clk_ops_pcom_div2 = {
.enable = pc_clk_enable,
.disable = pc_clk_disable,
.auto_off = pc_clk_auto_off,
.reset = pc_clk_reset,
.set_rate = pc_clk_set_rate2,
.set_min_rate = pc_clk_set_min_rate2,
.set_flags = pc_clk_set_flags,
.get_rate = pc_clk_get_rate2,
.is_enabled = pc_clk_is_enabled,
.round_rate = pc_clk_round_rate,
};
|
##
# elo.py
# provides implementation of ELO algorithm to determine
# change in fitness given a malicious act of nature.
##
K_FACTOR = 50 # weighting factor. The larger the more significant a match
# ^ in chess it's usually 15-16 for grandmasters and 32 for weak players
BETA = 400
class ResultType:
WIN = 1
LOSE = 2
DRAW = 3
'''
Returns a tuple (newELOYou, newELOThem)
example usage:
(2100NewElo, 2000NewElo) = get_elos_for_result(2100, 2000, ResultType.LOSE)
'''
def get_elos_for_result(eloYou, eloOpponent, result):
# get expected values
expectedYou = 1. / (1.+10.**(float(eloOpponent - eloYou)/BETA))
expectedThem = 1 - expectedYou # 1. / (1+10**((eloYou - eloOpponent)/BETA))
# actual scores
if result == ResultType.WIN:
actualYou = 1
elif result == ResultType.LOSE:
actualYou = 0
else:
actualYou = 0.5
actualThem = 1. - actualYou
newELOYou = eloYou + K_FACTOR * (actualYou - expectedYou)
newELOOpponent = eloOpponent + K_FACTOR * (actualThem - expectedThem)
return (newELOYou, newELOOpponent)
'''
Test to make sure elo calculated correctly given constants
'''
def test_elos():
def eloTuplesEqual(tupleA, tupleB):
return abs(tupleA[0] - tupleB[0]) <= 1 and abs(tupleA[1] - tupleB[1]) <= 1
assert eloTuplesEqual(get_elos_for_result(1200, 1200, ResultType.DRAW), (1200, 1200))
assert eloTuplesEqual(get_elos_for_result(800, 1400, ResultType.DRAW), (823, 1377))
assert eloTuplesEqual(get_elos_for_result(200, 2000, ResultType.WIN), (249, 1951))
assert eloTuplesEqual(get_elos_for_result(2100, 2000, ResultType.WIN), (2117, 1983))
assert eloTuplesEqual(get_elos_for_result(2100, 2000, ResultType.LOSE), (2067, 2033))
print "tests pass"
#test_elos()
|
/**
* @fileoverview Options configuration for optionator.
* @author idok
*/
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var optionator = require('optionator');
var pkg = require('../package.json');
var reactDOMSupport = require('./reactDOMSupport');
var reactNativeSupport = require('./reactNativeSupport');
//------------------------------------------------------------------------------
// Initialization and Public Interface
//------------------------------------------------------------------------------
// exports 'parse(args)', 'generateHelp()', and 'generateHelpForOption(optionName)'
module.exports = optionator({
prepend: `${ pkg.name } v${ pkg.version }
${ pkg.description }
Usage:
$ rt <filename> [<filename> ...] [<args>]`,
concatRepeatedArrays: true,
mergeRepeatedObjects: true,
options: [{
heading: 'Options'
}, {
option: 'help',
alias: 'h',
type: 'Boolean',
description: 'Show help.'
}, {
option: 'color',
alias: 'c',
default: 'true',
type: 'Boolean',
description: 'Use colors in output.'
}, {
option: 'modules',
alias: 'm',
default: 'none',
type: 'String',
description: 'Use output modules. (amd|commonjs|none|es6|typescript|jsrt)'
}, {
option: 'name',
alias: 'n',
type: 'String',
description: 'When using globals, the name for the variable. The default is the [file name]RT, when using amd, the name of the module'
}, {
option: 'dry-run',
alias: 'd',
default: 'false',
type: 'Boolean',
description: 'Run compilation without creating an output file, used to check if the file is valid'
}, {
option: 'force',
alias: 'r',
default: 'false',
type: 'Boolean',
description: 'Force creation of output. skip file check.'
}, {
option: 'format',
alias: 'f',
type: 'String',
default: 'stylish',
//enum: ['stylish', 'json'],
description: 'Use a specific output format. (stylish|json)'
}, {
option: 'target-version',
alias: 't',
type: 'String',
default: reactDOMSupport.default,
description: `'React version to generate code for (${ Object.keys(reactDOMSupport).join(', ') })'`
}, {
option: 'list-target-version',
type: 'Boolean',
default: 'false',
description: 'Show list of target versions'
}, {
option: 'version',
alias: 'v',
type: 'Boolean',
description: 'Outputs the version number.'
}, {
option: 'stack',
alias: 'k',
type: 'Boolean',
description: 'Show stack trace on errors.'
}, {
option: 'react-import-path',
default: 'react/addons',
type: 'String',
description: 'Dependency path for importing React.'
}, {
option: 'lodash-import-path',
default: 'lodash',
type: 'String',
description: 'Dependency path for importing lodash.'
}, {
option: 'native',
alias: 'rn',
type: 'Boolean',
description: 'Renders react native templates.'
}, {
option: 'flow',
type: 'Boolean',
description: 'Add /* @flow */ to the top of the generated file'
}, {
option: 'native-target-version',
alias: 'rnv',
type: 'String',
default: reactNativeSupport.default,
description: `'React native version to generate code for (${ Object.keys(reactNativeSupport).join(', ') })'`
}]
});
|
/*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Searching across all cocalc projects via various criteria
*/
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="http://gmpg.org/xfn/11" rel="profile">
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
About · Antonio Scatoloni
</title>
<!-- CSS -->
<link rel="stylesheet" href="/public/css/poole.css">
<link rel="stylesheet" href="/public/css/syntax.css">
<link rel="stylesheet" href="/public/css/ascatox.css">
<link rel="stylesheet" href="/public/font-awesome/css/font-awesome.min.css">
<!-- Fonts -->
<link href='http://fonts.googleapis.com/css?family=PT+Serif:400,700italic,700,400italic' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css' />
<!-- Icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="public/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="public/favicon.ico">
<!-- RSS -->
<link rel="alternate" type="application/atom+xml" title="Antonio Scatoloni" href="/atom.xml">
</head>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-77141714-1', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
<body>
<div class="container content">
<header class="masthead">
<h3 class="masthead-title">
<img src="/assets/ascatox.jpg">
<a href="/" title="Home">Antonio Scatoloni</a>
<small><a href="http://www.antonioscatoloni.it/">About</a></small>
<small><a href="/archive">Archive</a></small>
<small><a href="/tag">Tags</a></small>
<small><a href="/atom.xml">Feed</a></small>
</h3>
<div class="social-icons">
<a href="https://twitter.com/ascatox"><i class="fa fa-twitter"></i></a>
<a href="https://github.com/ascatox"><i class="fa fa-github"></i></a>
<a href="https://www.linkedin.com/in/antonioscatoloni"><i class="fa fa-linkedin-square"></i></a>
</div>
</header>
<main>
<div class="page">
<h1 class="page-title">About</h1>
<p class="message">
Hey there! This page is included as an example. Feel free to customize it for your own use upon downloading. Carry on!
</p>
<p>In the novel, <em>The Strange Case of Dr. Jekyll and Mr. Hyde</em>, Mr. Poole is Dr. Jekyll’s virtuous and loyal butler. Similarly, Poole is an upstanding and effective butler that helps you build Jekyll themes. It’s made by <a href="https://twitter.com/mdo">@mdo</a>.</p>
<p>There are currently two themes built on Poole:</p>
<ul>
<li><a href="http://hyde.getpoole.com">Hyde</a></li>
<li><a href="http://lanyon.getpoole.com">Lanyon</a></li>
</ul>
<p>Learn more and contribute on <a href="https://github.com/poole">GitHub</a>.</p>
<h2 id="setup">Setup</h2>
<p>Some fun facts about the setup of this project include:</p>
<ul>
<li>Built for <a href="http://jekyllrb.com">Jekyll</a></li>
<li>Developed on GitHub and hosted for free on <a href="https://pages.github.com">GitHub Pages</a></li>
<li>Coded with <a href="http://sublimetext.com">Sublime Text 2</a>, an amazing code editor</li>
<li>Designed and developed while listening to music like <a href="https://soundcloud.com/maddecent/sets/blood-bros-series">Blood Bros Trilogy</a></li>
</ul>
<p>Have questions or suggestions? Feel free to <a href="https://github.com/poole/poole/issues/new">open an issue on GitHub</a> or <a href="https://twitter.com/mdo">ask me on Twitter</a>.</p>
<p>Thanks for reading!</p>
</div>
</main>
<footer class="footer">
<p>
© Antonio Scatoloni Weblog made with <a href="http://jekyllrb.com/">Jekyll</a>, under <a href="https://creativecommons.org/licenses/by-nc/3.0/">CC BY-NC</a>.
</p>
</footer>
</div>
</body>
</html>
|
import unittest
import mock
from cloudshell.networking.apply_connectivity.models.connectivity_result import ConnectivityErrorResponse
from cloudshell.networking.apply_connectivity.models.connectivity_result import ConnectivitySuccessResponse
class TestConnectivitySuccessResponse(unittest.TestCase):
def test_init(self):
"""Check that __init__ nethod will set up object with correct params"""
action = mock.MagicMock()
result_string = "info message"
# act
response = ConnectivitySuccessResponse(action=action, result_string=result_string)
# verify
self.assertEqual(response.type, action.type)
self.assertEqual(response.actionId, action.actionId)
self.assertIsNone(response.errorMessage)
self.assertEqual(response.updatedInterface, action.actionTarget.fullName)
self.assertEqual(response.infoMessage, result_string)
self.assertTrue(response.success)
class TestConnectivityErrorResponse(unittest.TestCase):
def test_init(self):
"""Check that __init__ nethod will set up object with correct params"""
action = mock.MagicMock()
err_string = "error message"
# act
response = ConnectivityErrorResponse(action=action, error_string=err_string)
# verify
self.assertEqual(response.type, action.type)
self.assertEqual(response.actionId, action.actionId)
self.assertIsNone(response.infoMessage)
self.assertEqual(response.updatedInterface, action.actionTarget.fullName)
self.assertEqual(response.errorMessage, err_string)
self.assertFalse(response.success)
|
define(['underscore','backbone','text!./results.tmpl','text!./item.tmpl'
,'text!../config.json'],
function(_,Backbone,template,itemtemplate,config) {
return {
type:"Backbone",
resize:function() {
var that=this;
var texts=$("div.mainview");
var parentheight=texts.height();
var space=parseInt(this.options.space)||0;
if (!parentheight) parentheight=this.$el.parent().parent().height();
this.$el.css("height", (parentheight) +"px");
this.$el.unbind('scroll');
this.$el.bind("scroll", function() {
if (that.$el.scrollTop()+ that.$el.innerHeight()+3> that.$el[0].scrollHeight) {
if (that.displayed+10>that.results.length && that.displayed<that.totalslot) {
that.sandbox.emit("more","",that.results.length);
} else {
that.loadscreenful();
}
}
});
},
moreresult:function(data) {
this.results=this.results.concat(data);
this.loadscreenful();
},
loadscreenful:function() {
var screenheight=this.$el.innerHeight();
var $listgroup=this.$el.find(".results");
var startheight=$listgroup.height();
if (this.displayed>=this.results.length) return;
var now=this.displayed||0;
var H=0;
for (var i=now;i<this.results.length;i++ ) {
newitem=_.template(itemtemplate,this.results[i]);
$listgroup.append(newitem); // this is slow to get newitem height()
if ($listgroup.height()-startheight>screenheight) break;
}
this.displayed=i+1;
},
render: function (data) {
if (!data) return;
this.results=[];
this.displayed=0;
this.results=data;
this.$el.html(template);
this.resize();
this.loadscreenful();
},
totalslot:function(count,hitcount) {
var that=this;//totalslot might come later
setTimeout(function(){
that.totalslot=count;
that.$el.find("#totalslot").html(count);
that.$el.find("#totalhits").html(hitcount);
},500)
},
initialize: function() {
this.config=JSON.parse(config);
this.db=this.config.db;
$(window).resize( _.bind(this.resize,this) );
this.sandbox.on("newresult",this.render,this);
this.sandbox.on("moreresult",this.moreresult,this);
this.sandbox.on("totalslot",this.totalslot,this);
}
}
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var jshint = require("jshint").JSHINT;
var RcLoader = require("rcloader");
var stripJsonComments = require("strip-json-comments");
var loaderUtils = require("loader-utils");
var fs = require("fs");
// setup RcLoader
var rcLoader = new RcLoader(".jshintrc", null, {
loader: function(path) {
return path;
}
});
function loadRcConfig(callback){
var sync = typeof callback !== "function";
if(sync){
var path = rcLoader.for(this.resourcePath);
if(typeof path !== "string") {
// no .jshintrc found
return {};
} else {
this.addDependency(path);
var file = fs.readFileSync(path, "utf8");
return JSON.parse(stripJsonComments(file));
}
}
else {
rcLoader.for(this.resourcePath, function(err, path) {
if(typeof path !== "string") {
// no .jshintrc found
return callback(null, {});
}
this.addDependency(path);
fs.readFile(path, "utf8", function(err, file) {
var options;
if(!err) {
try {
options = JSON.parse(stripJsonComments(file));
}
catch(e) {
err = e;
}
}
callback(err, options);
});
}.bind(this));
}
}
function jsHint(input, options) {
// copy options to own object
if(this.options.jshint) {
for(var name in this.options.jshint) {
options[name] = this.options.jshint[name];
}
}
// copy query into options
var query = loaderUtils.parseQuery(this.query);
for(var name in query) {
options[name] = query[name];
}
// copy globals from options
var globals = {};
if(options.globals) {
if(Array.isArray(options.globals)) {
options.globals.forEach(function(g) {
globals[g] = true;
}, this);
} else {
for(var g in options.globals)
globals[g] = options.globals[g];
}
delete options.globals;
}
// move flags
var emitErrors = options.emitErrors;
delete options.emitErrors;
var failOnHint = options.failOnHint;
delete options.failOnHint;
// custom reporter
var reporter = options.reporter;
delete options.reporter;
// module system globals
globals.require = true;
globals.module = true;
globals.exports = true;
globals.global = true;
globals.process = true;
globals.define = true;
var source = input.split(/\r\n?|\n/g);
var result = jshint(source, options, globals);
var errors = jshint.errors;
if(!result) {
if(reporter) {
reporter.call(this, errors);
} else {
var hints = [];
if(errors) errors.forEach(function(error) {
if(!error) return;
var message = " " + error.reason + " @ line " + error.line + " char " + error.character + "\n " + error.evidence;
hints.push(message);
}, this);
var message = hints.join("\n\n");
var emitter = emitErrors ? this.emitError : this.emitWarning;
if(emitter)
emitter("jshint results in errors\n" + message);
else
throw new Error("Your module system doesn't support emitWarning. Update availible? \n" + message);
}
}
if(failOnHint && !result)
throw new Error("Module failed in cause of jshint error.");
}
module.exports = function(input, map) {
this.cacheable && this.cacheable();
var callback = this.async();
if(!callback) {
// load .jshintrc synchronously
var config = loadRcConfig.call(this);
jsHint.call(this, input, config);
return input;
}
// load .jshintrc asynchronously
loadRcConfig.call(this, function(err, config) {
if(err) return callback(err);
try {
jsHint.call(this, input, config);
}
catch(e) {
return callback(e);
}
callback(null, input, map);
}.bind(this));
}
|
__author__ = 'v-lshen'
from Utils import *
from RpcStream import *
class Clientlet:
@staticmethod
def build_address(argv1, argv2):
return Native.dsn_address_build(argv1, argv2)
@staticmethod
def call_async(evt, callback_owner, callback, hash = 0, delay_milliseconds = 0, timer_interval_milliseconds = 0):
global function_dict
function_dict[id(callback)] = callback
if(timer_interval_milliseconds == 0):
task = Native.dsn_task_create(evt, id(callback), hash, id(callback_owner))
else:
task = Native.dsn_task_create_timer(evt, id(callback), hash, timer_interval_milliseconds, id(callback_owner))
Native.dsn_task_call(task, delay_milliseconds)
return task
@staticmethod
def rpc_call_async(code, server, request, callback_owner, callback, reply_hash):
global function_dict
function_dict[id(callback)] = callback
msg = Native.dsn_msg_create_request(code, 0, 0)
Native.marshall(msg, request)
task = Native.dsn_rpc_create_response_task(msg, id(callback), reply_hash, id(callback_owner))
Native.dsn_rpc_call(server, task)
@staticmethod
def rpc_call_sync(code, server, request, ss):
msg = Native.dsn_msg_create_request(code, 0, 0)
Native.marshall(msg, request)
resp = Native.dsn_rpc_call_wait(server, msg, ss.value)
return resp
@staticmethod
def concel_task(task, cleanup):
return Native.dsn_task_cancel(task, cleanup)
|
/* eslint no-undef: "off" */
/* eslint import/no-extraneous-dependencies: "off" */
/* eslint-disable no-console */
process.env.NODE_ENV = 'development'; // this assures React is built in development mode and that the Babel prod config doesn't apply.
const express = require('express');
const webpack = require('webpack');
const open = require('open');
const path = require('path');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const fs = require('fs');
const config = require('../webpack.config');
const port = 60782;
const host = 'localhost';
const app = express();
const compiler = webpack(config);
const middleware = webpackDevMiddleware(compiler, {
contentBase: `http://${host}:${port}`,
quiet: false,
noInfo: false,
hot: true,
publicPath: config.output.publicPath,
stats: {
assets: true,
colors: true,
version: false,
hash: false,
timings: true,
chunks: false,
chunkModules: false
}
});
app.use(middleware);
app.use(webpackHotMiddleware(compiler));
const content = fs.readFileSync(path.join( __dirname, '../src/index.html'), 'utf-8');
const newValue = content.replace(/(?:<%(.*)%>)/g, '').replace(/(<link (?:.*)>)/g, '').replace(/src=""/g, 'src="/js/vendor.bundle.js"></script><script type="text/javascript" src="/js/bundle.js"');
app.get('*', (req, res) => {
res.send(newValue);
});
app.listen(port, function(err) {
if (err) {
console.log(err);
} else {
open(`http://${host}:${port}`);
}
});
|
/***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
* $Id$
*
* Copyright (C) 2006 Dan Everton
*
* 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
#include <SDL.h>
#include "config.h"
#include "button.h"
#include "buttonmap.h"
int key_to_button(int keyboard_button)
{
int new_btn = BUTTON_NONE;
switch (keyboard_button)
{
case SDLK_KP4:
case SDLK_LEFT:
new_btn = BUTTON_LEFT;
break;
case SDLK_KP6:
case SDLK_RIGHT:
new_btn = BUTTON_RIGHT;
break;
case SDLK_KP8:
case SDLK_UP:
new_btn = BUTTON_UP;
break;
case SDLK_KP2:
case SDLK_DOWN:
new_btn = BUTTON_DOWN;
break;
case SDLK_KP_PLUS:
case SDLK_F8:
new_btn = BUTTON_ON;
break;
case SDLK_KP_ENTER:
case SDLK_RETURN:
case SDLK_a:
new_btn = BUTTON_OFF;
break;
case SDLK_KP_DIVIDE:
case SDLK_F1:
new_btn = BUTTON_REC;
break;
case SDLK_KP5:
case SDLK_SPACE:
new_btn = BUTTON_SELECT;
break;
case SDLK_KP_PERIOD:
case SDLK_INSERT:
new_btn = BUTTON_MODE;
break;
}
return new_btn;
}
struct button_map bm[] = {
#if defined (IRIVER_H120) || defined (IRIVER_H100)
{ SDLK_KP_DIVIDE, 46, 162, 13, "Record" },
{ SDLK_KP_PLUS, 327, 36, 16, "Play" },
{ SDLK_KP_ENTER, 330, 99, 18, "Stop" },
{ SDLK_KP_PERIOD, 330, 163, 18, "AB" },
{ SDLK_KP5, 186, 227, 27, "5" },
{ SDLK_KP8, 187, 185, 19, "8" },
{ SDLK_KP4, 142, 229, 23, "4" },
{ SDLK_KP6, 231, 229, 22, "6" },
{ SDLK_KP2, 189, 272, 28, "2" },
/* Remote Buttons */
{ SDLK_KP_ENTER, 250, 404, 20, "Stop" },
{ SDLK_SPACE, 285, 439, 29, "Space" },
{ SDLK_h, 336, 291, 24, "Hold" },
#elif defined (IRIVER_H300)
{ SDLK_KP_PLUS, 56, 335, 20, "Play" },
{ SDLK_KP8, 140, 304, 29, "Up" },
{ SDLK_KP_DIVIDE, 233, 331, 23, "Record" },
{ SDLK_KP_ENTER, 54, 381, 24, "Stop" },
{ SDLK_KP4, 100, 353, 17, "Left" },
{ SDLK_KP5, 140, 351, 19, "Navi" },
{ SDLK_KP6, 185, 356, 19, "Right" },
{ SDLK_KP_PERIOD, 230, 380, 20, "AB" },
{ SDLK_KP2, 142, 402, 24, "Down" },
{ SDLK_KP_ENTER, 211, 479, 21, "Stop" },
{ SDLK_KP_PLUS, 248, 513, 29, "Play" },
#endif
{ 0, 0, 0, 0, "None" }
};
|
import re
import string
import numpy
import os
if __name__ == '__main__':
# for each case
path=os.getcwd()
#print path
chpath=str(path)+"\\..\\results\\parfsGIA\hound.opteron\ERS"
#replace chpath=str(path)+"\\..\\results\\parfsGIA\hound.opteron\WPT"
os.chdir(chpath)
#print os.getcwd()
prefix="parfsGIA_ERS_betterconfig_P"
#replace prefix="parfsGIA_WPT_betterconfig_P"
# for each #cores
totalfilename = str('Total_'+prefix[0:25]+'.csv')
outputFile = open(totalfilename, 'w')
try:
# remove ParetoSize, add uniqueFoundPoints to check overlapping ratio
# outputFile.writelines('Cores'+','+'FoundPoints'+','+'UniqueFoundPoints'+','+'SatCalls'+','+'Time'+'\n')
outputFile.writelines('Cores'+','+'Time'+'\n')
finally:
outputFile.close()
# change for xeon/opteron
#for i in [4, 6, 8, 10, 12]:
for i in [4, 8, 16]:
# initiate a set of lists for collecting all data from ParentFile and ChildFiles
summary = []
inputParentFile = open(str(prefix+str(i)+'.csv'))
inputParentList = inputParentFile.readlines()
for m in range(len(inputParentList)):
summary.append([])
m = 0
for inputParentLine in inputParentList:
#print inputParentLine
#print re.split(',| ', str(inputParentLine))
summary[m] = re.split(',| ', str(inputParentLine))
summary[m].remove('\n')
# #cores, #foundPoints/#unsatCalls, #SizeFront, TotalTime, #satcalls
# set #SizeFront = 0
summary[m][0]=string.atoi(summary[m][0])
summary[m][1]=string.atoi(summary[m][1])
summary[m][2]=string.atoi(summary[m][2])
# this time is the record in parent subprocess, which should be choose min in each group and then choose max in all groups
# update it below
summary[m][3]=0.0
# for WPT seconds -> minutes
#summary[m][3]=string.atof(summary[m][3])/60
summary[m].append(0)
#print summary[m]
m += 1
# create group id, e.g. P4 has two groups for the two partitions
group = []
for k in range(i/2):
group.append([])
for k in range(i/2):
for m in range(len(inputParentList)):
group[k].append([])
#print group
# choose min values in child files and update them to groups
for j in range(0, i):
inputChildFile = open(str(prefix+str(i)+'C'+str(j)+'.csv'))
inputChildList = inputChildFile.readlines()
m = 0
for inputChildLine in inputChildList:
# fix a running problem on Sharcnet
if m == len(inputParentList):
break
tmpChildLineList = re.split(',| ', str(inputChildLine))
tmpChildLineList.remove('\n')
# get time
time_subprocess = string.atof(tmpChildLineList[4])
# for WPT seconds -> minutes
#time_subprocess = string.atof(tmpChildLineList[4])/60
if len(group[j/2][m]) == 0 :
group[j/2][m].append(time_subprocess)
else:
if time_subprocess < group[j/2][m][0] :
group[j/2][m][0] = time_subprocess
m += 1
#print group
# choose max value in each group and update to parent file
for m in range(len(inputParentList)):
for k in range(i/2):
time_subgroup = group[k][m][0]
if time_subgroup > summary[m][3]:
summary[m][3] = time_subgroup
# #print summary
arr = numpy.array(summary)
meanList = numpy.mean(arr, axis=0)
print meanList[3]
stdList = numpy.std(arr, axis=0)
print stdList[3]
outputFile = open(totalfilename, 'a')
try:
# outputFile.writelines('Cores'+','+'FoundPoints(UnSatCalls-1)'+','+'UniqueFoundPoints'+','+'SatCalls'+','+'Time'+'\n')
for m in range(10):
outputFile.writelines(str(summary[m][0])+','+str(summary[m][3])+'\n')
# outputFile.writelines(str(summary[m][0])+','+str(summary[m][1])+','+str(summary[m][2])+','+str(summary[m][4])+','+str(summary[m][3])+'\n')
# outputFile.writelines(str(meanList[0])+','+str(meanList[2])+','+str(meanList[1])+','+str(meanList[4])+','+str(meanList[3])+'\n')
# outputFile.writelines(str(stdList[0])+','+str(stdList[2])+','+str(stdList[1])+','+str(stdList[4])+','+str(stdList[3])+'\n')
finally:
outputFile.close()
print "Done"
|
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// 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/>.
// Scintilla source code edit control
/** @file ScintillaBase.h
** Defines an enhanced subclass of Editor with calltips, autocomplete and context menu.
**/
// Copyright 1998-2002 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef SCINTILLABASE_H
#define SCINTILLABASE_H
/**
*/
class ScintillaBase : public Editor {
// Private so ScintillaBase objects can not be copied
ScintillaBase(const ScintillaBase &) : Editor() {}
ScintillaBase &operator=(const ScintillaBase &) { return *this; }
protected:
/** Enumeration of commands and child windows. */
enum {
idCallTip=1,
idAutoComplete=2,
idcmdUndo=10,
idcmdRedo=11,
idcmdCut=12,
idcmdCopy=13,
idcmdPaste=14,
idcmdDelete=15,
idcmdSelectAll=16
};
bool displayPopupMenu;
Menu popup;
AutoComplete ac;
CallTip ct;
int listType; ///< 0 is an autocomplete list
SString userListSelected; ///< Receives listbox selected string
#ifdef SCI_LEXER
int lexLanguage;
const LexerModule *lexCurrent;
PropSet props;
enum {numWordLists=6};
WordList *keyWordLists[numWordLists+1];
void SetLexer(uptr_t wParam);
void SetLexerLanguage(const char *languageName);
void Colourise(int start, int end);
#endif
ScintillaBase();
virtual ~ScintillaBase();
virtual void Initialise() = 0;
virtual void Finalise() = 0;
virtual void RefreshColourPalette(Palette &pal, bool want);
virtual void AddCharUTF(char *s, unsigned int len, bool treatAsDBCS=false);
void Command(int cmdId);
virtual void CancelModes();
virtual int KeyCommand(unsigned int iMessage);
void AutoCompleteStart(int lenEntered, const char *list);
void AutoCompleteCancel();
void AutoCompleteMove(int delta);
void AutoCompleteChanged(char ch=0);
void AutoCompleteCompleted(char fillUp='\0');
void AutoCompleteMoveToCurrentWord();
static void AutoCompleteDoubleClick(void* p);
virtual void CreateCallTipWindow(PRectangle rc) = 0;
virtual void AddToPopUp(const char *label, int cmd=0, bool enabled=true) = 0;
void ContextMenu(Point pt);
virtual void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt);
virtual void NotifyStyleToNeeded(int endStyleNeeded);
public:
// Public so scintilla_send_message can use it
virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
};
#endif
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Angle_MVC6_Angular_Seed.Models.ManageViewModels
{
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DiarMe</title>
<link rel="icon" href="<?php echo base_url() ?>img/logo.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="<?php echo base_url() ?>img/logo.ico" type="image/x-icon"/>
<link rel="stylesheet" href="<?php echo base_url() ?>css/bootstrap.min.css"/>
<script src="<?php echo base_url() ?>js/jquery.min.js"></script>
<script src="<?php echo base_url() ?>js/bootstrap.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url() ?>css/style.css">
</head>
<body>
<div class="form">
<img src="<?php echo base_url() ?>img/logo.png"/>
<!-- BEGIN FORMULAR INREGISTRARE -->
<?php $attributes = array('class' => 'register-form');
echo form_open('user/register_user', $attributes); ?>
<label for="username">Username</label>
<input type="text" id="username" name="username" required/>
<label for="password">Password</label>
<input type="password" id="password" name="password" required/>
<label for="password_conf">Confirm password</label>
<input id="password_conf" name="password_conf" type="password" required/>
<label for="email">Email</label>
<input type="email" id="email" name="email" required/>
<button>Sign Up</button>
<p class="message">Already registered? <a href="#">Sign In</a></p>
<?php echo form_close(); ?>
<!-- END FORMULAR INREGISTRARE -->
<!-- BEGIN FORMULAR RESETARe -->
<?php $attributes = array('class' => 'forgot-password');
echo form_open('forgot_password_C/reset_password', $attributes) ?>
<label>Type your email</label>
<input type="email" name="email" id="email"/>
<button>Reset password</button>
<p class="message2">Remembered your password? <a href="#">Sign In</a></p>
<?php echo form_close(); ?>
<!-- END FORMULAR RESETARE -->
<!-- BEGIN FORMULAR LOGARE -->
<?php $attributes = array('class' => 'login-form');
echo form_open('user/login', $attributes); ?>
<input type="text" placeholder="Username" name="username" id="username"/>
<input type="password" placeholder="Password" name="password" id="password "/>
<button>Login</button>
<?php echo '<span style="color:red;font-size:19px">' . validation_errors() . '</span>' ?>
<p class="message">Not registered? <a href="#" id="create">Create an account</a></p>
<p class="message2">Forgot your password? <a href="#" id="reset">Reset password</a></p>
<?php echo form_close(); ?>
<!-- END FORMULAR LOGARE -->
</div>
<script>
$('.message a').click(function () {
$('.login-form').animate({height: "toggle", opacity: "toggle"}, "slow");
$('.register-form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
$('.message2 a').click(function () {
$('.forgot-password').animate({height: "toggle", opacity: "toggle"}, "slow");
$('.login-form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
var viewportHeight = $(window).height();
var formHeight = $('.form').height();
var element = $('.form');
$('#height').text(viewportHeight);
element.css('margin-top', (viewportHeight - formHeight) / 4 + 'px');
$(window).resize(function () {
var viewportHeight = $(window).height();
var formHeight = $('.form').height();
var element = $('.form');
element.css('margin-top', (viewportHeight - formHeight) / 4 + 'px');
});
</script>
</body>
</html>
|
// Libraries
import React, {FunctionComponent} from 'react'
import {connect} from 'react-redux'
import {Config, Table} from '@influxdata/giraffe'
import {flatMap} from 'lodash'
// Components
import EmptyGraphMessage from 'src/shared/components/EmptyGraphMessage'
import GraphLoadingDots from 'src/shared/components/GraphLoadingDots'
import ThresholdMarkers from 'src/shared/components/ThresholdMarkers'
// Utils
import {getFormatter, filterNoisyColumns} from 'src/shared/utils/vis'
// Constants
import {VIS_THEME} from 'src/shared/constants'
import {INVALID_DATA_COPY} from 'src/shared/copy/cell'
// Types
import {RemoteDataState, CheckViewProperties, TimeZone, Check} from 'src/types'
import {updateTimeMachineCheck} from 'src/timeMachine/actions'
import {useCheckYDomain} from 'src/alerting/utils/vis'
const X_COLUMN = '_time'
const Y_COLUMN = '_value'
interface DispatchProps {
updateTimeMachineCheck: typeof updateTimeMachineCheck
}
interface OwnProps {
table: Table
check: Partial<Check>
fluxGroupKeyUnion: string[]
loading: RemoteDataState
timeZone: TimeZone
viewProperties: CheckViewProperties
children: (config: Config) => JSX.Element
}
type Props = OwnProps & DispatchProps
const CheckPlot: FunctionComponent<Props> = ({
updateTimeMachineCheck,
table,
check,
fluxGroupKeyUnion,
loading,
children,
timeZone,
viewProperties: {colors},
}) => {
const thresholds = check && check.type === 'threshold' ? check.thresholds : []
const [yDomain, onSetYDomain, onResetYDomain] = useCheckYDomain(
table.getColumn(Y_COLUMN, 'number'),
thresholds
)
const columnKeys = table.columnKeys
const isValidView =
columnKeys.includes(X_COLUMN) && columnKeys.includes(Y_COLUMN)
if (!isValidView) {
return <EmptyGraphMessage message={INVALID_DATA_COPY} />
}
const groupKey = [...fluxGroupKeyUnion, 'result']
const xFormatter = getFormatter(table.getColumnType(X_COLUMN), {
timeZone,
trimZeros: false,
})
const yFormatter = getFormatter(table.getColumnType(Y_COLUMN), {
timeZone,
trimZeros: false,
})
const legendColumns = filterNoisyColumns(
[...groupKey, X_COLUMN, Y_COLUMN],
table
)
const thresholdValues = flatMap(thresholds, (t: any) => [
t.value,
t.minValue,
t.maxValue,
]).filter(t => t !== undefined)
const yTicks = thresholdValues.length ? thresholdValues : null
const config: Config = {
...VIS_THEME,
table,
legendColumns,
yTicks,
yDomain,
onSetYDomain,
onResetYDomain,
valueFormatters: {
[X_COLUMN]: xFormatter,
[Y_COLUMN]: yFormatter,
},
layers: [
{
type: 'line',
x: X_COLUMN,
y: Y_COLUMN,
fill: groupKey,
interpolation: 'linear',
colors,
},
{
type: 'custom',
render: ({yScale, yDomain}) => (
<ThresholdMarkers
key="custom"
thresholds={thresholds || []}
onSetThresholds={thresholds => updateTimeMachineCheck({thresholds})}
yScale={yScale}
yDomain={yDomain}
/>
),
},
],
}
return (
<div className="time-series-container time-series-container--alert-check">
{loading === RemoteDataState.Loading && <GraphLoadingDots />}
{children(config)}
</div>
)
}
const mdtp: DispatchProps = {
updateTimeMachineCheck: updateTimeMachineCheck,
}
export default connect<{}, DispatchProps, {}>(
null,
mdtp
)(CheckPlot)
|
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de https://trad.spip.net/tradlang_module/revisions?lang_cible=oc_ni_la
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// D
'diff_para_ajoute' => 'Paragraf apondut',
'diff_para_deplace' => 'Paragraf desplaçat',
'diff_para_supprime' => 'Paragraf suprimit',
'diff_texte_ajoute' => 'Tèxt apondut',
'diff_texte_deplace' => 'Tèxt apondut',
'diff_texte_supprime' => 'Tèxt suprimit',
// I
'info_historique' => 'Revisions:',
'info_historique_lien' => 'Afichar l’istoric dei modificacions',
'info_historique_titre' => 'Seguiment dei revisions',
// V
'version_initiale' => 'Version iniciala'
);
?>
|
from wutu_compiler.utils.test import *
from wutu_compiler.core.common import *
from wutu_compiler.core.controller import *
from wutu_compiler.core.snippet import *
from wutu_compiler.utils.common import *
class CompilerTests(object):
def test_service(self):
mod = Module()
mod.__name__ = "test_module"
stream = StringIO()
create_base(stream)
mod.create_service(stream)
result = get_data(stream)
expected = """
"""
def test_string_argument(self):
stream = create_stream()
add_variable(stream, "test", "hello")
result = get_data(stream).strip()
excepted = "var test = \"hello\";"
assert excepted == result
def test_int_argument(self):
stream = create_stream()
add_variable(stream, "test", 123)
result = get_data(stream).strip()
excepted = "var test = 123;"
assert excepted == result
def test_module(self):
mod = Module()
mod.__name__ = "test_module"
stream = StringIO()
create_base(stream)
mod.create_service(stream)
assert validate_js(get_data(stream))
class GrammarTests(object):
def test_string(self):
from core.grammar import String
str = String("test")
assert "\"test\"" == str.compile()
def test_number(self):
from core.grammar import Number
num = Number(42)
assert "42" == num.compile()
def test_simple_declaration(self):
from core.grammar import String, SimpleDeclare, Expression
assert "var foo = \"bar\";" == SimpleDeclare("foo", String("bar"), True).compile()
def test_function(self):
from core.grammar import Function, String, SimpleDeclare, Expression
fun = Function(["name"], [SimpleDeclare("hello_str", String("Hello, "))], Expression("hello_str + \" \" + name"))
expected = """
function(name){
hello_str = "Hello, ";
return hello_str + " " + name;
}
"""
assert expected == fun.compile()
def test_provider(self):
from core.grammar import Provider, String
http = Provider("$http")
result = http.get(String("http://google.com").compile())
expected = "$http.get(\"http://google.com\")"
assert expected == result
http.url = "my_url_generator()"
assert ["$http.url = my_url_generator();"] == http.assignments
def test_promise(self):
from core.grammar import Provider, Function, SimpleDeclare, String, Expression
http = Provider("$http")
result = http.get(String("http://google.com").compile()).resolve(Function(["result"],
body=[SimpleDeclare("$scope.test", Expression("result.data"))]))
expected = """
$http.get("http://google.com").then(function(result){
$scope.test = result.data;
});
"""
assert expected == result
def test_object(self):
from core.grammar import Object, String
obj = Object()
obj.add_member("something", String("test"))
result = obj.compile()
expected = "{ \"something\": \"test\" }"
assert expected == result
def test_unwrap(self):
from core.grammar import Function, Promise, Provider, String, unwraps
http = Provider("$http")
promise = http.get(String("http://google.com").compile())
result = Function([], *unwraps(promise)).compile()
expected = """
function(){
var result = [];
if(result != undefined){
$http.get("http://google.com").then(function(response){
angular.forEach(response.data,
function(val){
result.push(val);
})
});
}
else {
return $http.get("http://google.com").then(function(response){
return response.data;
});
}
return result;
}
"""
assert expected == result
class SnippetsTests(object):
def test_local_variable(self):
expected = "var foo = \"bar\";"
result = compile_snippet("variable.html", local=True, name="foo", value="bar")
assert expected == str(result)
def test_local_variable_without_assign(self):
expected = "var test;"
result = compile_snippet("variable.html", local=True, name="test")
assert expected == str(result)
def test_fn_as_variable(self):
expected = "helloMsg = alert(\"Hello, world!\");"
fn_snippet = compile_snippet("function_call.html", name="alert", params=["\"Hello, world!\""])
result = compile_snippet("variable.html", name="helloMsg", value=fn_snippet)
assert expected == str(result)
def test_fn_block(self):
expected = """
function hello(name){
hello_str = "Hello, ";
return hello_str + " " + name;
}
"""
fn_block = compile_snippet("block.html",
statements=[compile_snippet("variable.html", name="hello_str", value="Hello, ")],
returns="hello_str + \" \" + name"
)
result = compile_snippet("function_define.html",
name="hello",
params=["name"],
content=fn_block)
assert expected == str(result)
|
"""Classes that define commission models"""
from abc import ABCMeta, abstractmethod
DEFAULT_MINIMUM_COST_PER_ORDER = 5.0
class AbstractCommissionModel(metaclass=ABCMeta):
"""
Abstract Commission Model interface.
Commission models define how much commission should be charged extra to a
portfolio per order or trade.
"""
@abstractmethod
def calculate(self, order, execution_price):
"""
Calculate the amount of commission to charge to an :class:``Order`` as
the result of a :class:``Trade``.
:param order: the :py:class:`~order.Order` to charge the commission to.
:type order: Order
:param float execution_price: The cost per share.
:return: amount to charge
:rtype: float or None
"""
raise (NotImplementedError('calculate must be overridden'))
class PerOrderCommissionModel(AbstractCommissionModel):
"""
Calculates commission for a :py:class:`~order.Trade` on a per order basis,
so if there is multiple `trade`s created from one `order` commission
will only be charged once.
"""
def __init__(self, cost=DEFAULT_MINIMUM_COST_PER_ORDER):
"""
:param float cost: The flat cost charged per order.
"""
self.cost = float(cost)
def calculate(self, order, execution_price):
"""
If the order hasn't paid any commission then pay the fixed commission.
"""
if order.commission == 0.0:
return self.cost
else:
return 0
|
# -*- coding: utf-8 -*-
# daemon/__init__.py
# Part of ‘python-daemon’, an implementation of PEP 3143.
#
# Copyright © 2009–2015 Ben Finney <[email protected]>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Apache License, version 2.0 as published by the
# Apache Software Foundation.
# No warranty expressed or implied. See the file ‘LICENSE.ASF-2’ for details.
""" Library to implement a well-behaved Unix daemon process.
This library implements the well-behaved daemon specification of
:pep:`3143`, “Standard daemon process library”.
A well-behaved Unix daemon process is tricky to get right, but the
required steps are much the same for every daemon program. A
`DaemonContext` instance holds the behaviour and configured
process environment for the program; use the instance as a context
manager to enter a daemon state.
Simple example of usage::
import daemon
from spam import do_main_program
with daemon.DaemonContext():
do_main_program()
Customisation of the steps to become a daemon is available by
setting options on the `DaemonContext` instance; see the
documentation for that class for each option.
"""
from __future__ import (absolute_import, unicode_literals)
from .daemon import DaemonContext
# Local variables:
# coding: utf-8
# mode: python
# End:
# vim: fileencoding=utf-8 filetype=python :
|
#!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
# Credits######################################################
# Coded by: Juan Funes ([email protected])
# Audited by: Vauxoo C.A.
#############################################################################
# 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 openerp.osv import osv, fields
from openerp.tools.translate import _
class account_journal(osv.Model):
_inherit = 'account.journal'
_columns = {
'active': fields.boolean('Active', help="Field indicating whether the journal is active")
}
_defaults = {
'active': True,
}
|
#include <asf.h>
#include "settings.h"
void process_settings(struct mysettingsstruct *settings)
{
}
|
<div class="device-list-item" data-bind="attr: {'data-uuid': uuid}">
<span class="fa fa-video-camera"></span>
<span data-bind="text: name"></span>
</div>
|
from flask import Blueprint, render_template, abort, flash, redirect, url_for
from flask.ext.login import login_required, current_user, login_user, logout_user
import speakeasy
from speakeasy import bcrypt
from speakeasy.database import User
from speakeasy.views.utils import menu, site_config
from speakeasy.forms import LoginForm
import datetime
auth = Blueprint('auth', __name__,
template_folder='templates')
@auth.route('/login', methods = ['GET'])
def login():
form = LoginForm()
return render_template('login.html', title='Login', form=form, menu=menu(), site_config=site_config())
@auth.route('/logout')
def logout():
logout_user()
flash("You are now logged out.")
return redirect(url_for('index'))
@auth.route('/authenticate', methods = ['POST'])
def authenticate():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None:
flash("Error, incorrect username or password")
return render_template('login.html', title='Login', form=form, menu=menu(), site_config=site_config())
if bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
flash('Login was successful for %s' % (repr(user.display_name)))
return redirect("/index")
else:
flash("Error, incorrect username or password")
return render_template('login.html', title='Login', form=form, menu=menu(), site_config=site_config())
else:
flash("Error, incorrect username or password")
return render_template('login.html', title='Login', form=form, menu=(), site_config=site_config())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main server script for a pyqode.python backend. You can directly use this
script in your application if it fits your needs or use it as a starting point
for writing your own server.
::
usage: server.py [-h] [-s [SYSPATH [SYSPATH ...]]] port
positional arguments:
port the local tcp port to use to run the server
optional arguments:
-h, --help show this help message and exit
-s [SYSPATH [SYSPATH ...]], --syspath [SYSPATH [SYSPATH ...]]
"""
import argparse
import sys
if __name__ == '__main__':
"""
Server process' entry point
"""
# setup argument parser and parse command line args
parser = argparse.ArgumentParser()
parser.add_argument("port", help="the local tcp port to use to run "
"the server")
parser.add_argument('-s', '--syspath', nargs='*')
args = parser.parse_args()
# add user paths to sys.path
if args.syspath:
for path in args.syspath:
print('append path %s to sys.path' % path)
sys.path.append(path)
from pyqode.core import backend
from pyqode.python.backend.workers import JediCompletionProvider
# setup completion providers
backend.CodeCompletionWorker.providers.append(JediCompletionProvider())
backend.CodeCompletionWorker.providers.append(
backend.DocumentWordsProvider())
# starts the server
backend.serve_forever(args)
|
// Components
export { Article } from "./Article"
export { Artwork } from "./Sections/Artwork"
export { Authors } from "./Sections/Authors"
export { Caption } from "./Sections/Caption"
export { Embed } from "./Sections/Embed"
export { FullscreenViewer } from "./Sections/FullscreenViewer/FullscreenViewer"
export { Header } from "./Header/Header"
export { InstantArticleEmailSignup } from "./Email/InstantArticleEmailSignup"
export { Image } from "./Sections/Image"
export { ImageCollection } from "./Sections/ImageCollection"
export { ImageSetPreview } from "./Sections/ImageSetPreview"
export {
ImageSetPreviewClassic,
} from "./Sections/ImageSetPreview/ImageSetPreviewClassic"
export { Nav } from "./Nav/Nav"
export { SeriesLayout } from "./Layouts/SeriesLayout"
export { Text } from "./Sections/Text"
export { Video } from "./Sections/Video"
export { VideoLayout } from "./Layouts/VideoLayout"
export { VideoCover } from "./Video/VideoCover"
export { VideoAbout } from "./Video/VideoAbout"
export { PartnerInline } from "./Partner/PartnerInline"
export { PartnerBlock } from "./Partner/PartnerBlock"
export {
RelatedArticlesCanvas,
} from "./RelatedArticles/Canvas/RelatedArticlesCanvas"
export {
RelatedArticlesPanel,
} from "./RelatedArticles/Panel/RelatedArticlesPanel"
// Icon SVGs
export { IconArtist } from "./Icon/IconArtist"
export { IconBlockquote } from "./Icon/IconBlockquote"
export { IconClearFormatting } from "./Icon/IconClearFormatting"
export { IconDrag } from "./Icon/IconDrag"
export { IconEditEmbed } from "./Icon/IconEditEmbed"
export { IconEditImages } from "./Icon/IconEditImages"
export { IconEditSection } from "./Icon/IconEditSection"
export { IconEditText } from "./Icon/IconEditText"
export { IconEditVideo } from "./Icon/IconEditVideo"
export { IconHamburger } from "./Icon/IconHamburger"
export { IconHeroImage } from "./Icon/IconHeroImage"
export { IconHeroVideo } from "./Icon/IconHeroVideo"
export { IconImageFullscreen } from "./Icon/IconImageFullscreen"
export { IconImageSet } from "./Icon/IconImageSet"
export { IconLayoutFullscreen } from "./Icon/IconLayoutFullscreen"
export { IconLayoutSplit } from "./Icon/IconLayoutSplit"
export { IconLayoutText } from "./Icon/IconLayoutText"
export { IconLayoutBasic } from "./Icon/IconLayoutBasic"
export { IconLink } from "./Icon/IconLink"
export { IconOrderedList } from "./Icon/IconOrderedList"
export { IconVideoPlay } from "./Icon/IconVideoPlay"
export { IconRemove } from "./Icon/IconRemove"
export { IconUnorderedList } from "./Icon/IconUnorderedList"
export { IconLock } from "./Icon/IconLock"
// FIXME: Refactor out SizeMe; see https://github.com/ctrlplusb/react-sizeme#server-side-rendering
import sizeMe from "react-sizeme"
sizeMe.noPlaceholders = true
// Constants
import * as AllConstants from "./Constants"
export const Constants = AllConstants
|
<h2>{{$noti->title}}</h2>
@if($noti->type_link=="imagen")
<img src="{{$noti->link}}">
@else
<?php $video_id = array_reverse(explode('=',$noti->link))[0]; ?>
<iframe width="560" height="315" src="https://www.youtube.com/embed/{{$video_id}}?autoplay=0&controls=1&showinfo=0" frameborder="0" allowfullscreen=""></iframe>
@endif
<h4>{{$noti->content}}</h4>
<h6>Promix.mx</h6>
|
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tape = require( 'tape' );
var tryRequire = require( '@stdlib/utils/try-require' );
// VARIABLES //
var TODO = tryRequire( resolve( __dirname, './../lib/native.js' ) );
var opts = {
'skip': ( TODO instanceof Error )
};
// TESTS //
tape( 'main export is a function', opts, function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof TODO, 'function', 'main export is a function' );
t.end();
});
// TODO: add tests
|
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-13 13:24
from typing import Union, Optional
from transformers import BertTokenizerFast, TensorType, BatchEncoding, BertJapaneseTokenizer as _BertJapaneseTokenizer
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import TextInput, PreTokenizedInput, EncodedInput, TruncationStrategy
class BertJapaneseTokenizer(_BertJapaneseTokenizer):
# We may need to customize character level tokenization to handle English words and URLs
pass
class BertJapaneseTokenizerFast(BertTokenizerFast):
def encode_plus(
self,
text: Union[TextInput, PreTokenizedInput, EncodedInput],
text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
stride: int = 0,
is_split_into_words: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) -> BatchEncoding:
"""
Tokenize and prepare for the model a sequence or a pair of sequences.
.. warning::
This method is deprecated, ``__call__`` should be used instead.
Args:
text (:obj:`str`, :obj:`List[str]` or :obj:`List[int]` (the latter only for not-fast tokenizers)):
The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
``tokenize`` method) or a list of integers (tokenized string ids using the ``convert_tokens_to_ids``
method).
text_pair (:obj:`str`, :obj:`List[str]` or :obj:`List[int]`, `optional`):
Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
the ``tokenize`` method) or a list of integers (tokenized string ids using the
``convert_tokens_to_ids`` method).
"""
text = list(text)
is_split_into_words = True
encoding = BertJapaneseTokenizer.encode_plus(self,
text,
text_pair,
add_special_tokens,
padding,
truncation,
max_length,
stride,
is_split_into_words,
pad_to_multiple_of,
return_tensors,
return_token_type_ids,
return_attention_mask,
return_overflowing_tokens,
return_special_tokens_mask,
return_offsets_mapping,
return_length,
verbose,
**kwargs
)
offsets = encoding.encodings[0].offsets
fixed_offsets = [(b + i, e + i) for i, (b, e) in enumerate(offsets)]
# TODO: This doesn't work with rust tokenizers
encoding.encodings[0].offsets.clear()
encoding.encodings[0].offsets.extend(fixed_offsets)
return encoding
|
/* ************************************************************************
APPUDO CLI Creator
https://www.appudo.com
Copyright: 2018 Appudo UG (haftungsbeschränkt), https://www.appudo.com
License: MIT License, https://opensource.org/licenses/MIT
Authors: [email protected]
************************************************************************ */
qx.Class.define("appudo_cli_creator.view.desktop.OperationChainItem",
{
extend : qx.ui.form.ListItem,
construct : function(label, icon, nodeData)
{
this.base(arguments, label, icon);
this.setNodeData(nodeData !== undefined ? nodeData : null);
},
properties :
{
nodeData :
{
event : "changeNodeData",
nullable : true
}
}
});
|
#!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""
Organizaţia Internaţională a Aviaţiei Civile propune un alfabet în care
fiecărei litere îi este asignat un cuvânt pentru a evita problemele în
înțelegerea mesajelor critice.
Pentru a se păstra un istoric al conversațiilor s-a decis transcrierea lor
conform următoarelor reguli:
- fiecare cuvânt este scris pe o singură linie
- literele din alfabet sunt separate de o virgulă
Următoarea sarcină ți-a fost asignată:
Scrie un program care să primească un fișier ce conține mesajul
ce trebuie transmis și generează un fișier numit mesaj.icao ce
va conține mesajul scris folosin alfabetul ICAO.
Mai jos găsiți un dicționar ce conține o versiune a alfabetului ICAO:
"""
ICAO = {
'a': 'alfa', 'b': 'bravo', 'c': 'charlie', 'd': 'delta', 'e': 'echo',
'f': 'foxtrot', 'g': 'golf', 'h': 'hotel', 'i': 'india', 'j': 'juliett',
'k': 'kilo', 'l': 'lima', 'm': 'mike', 'n': 'november', 'o': 'oscar',
'p': 'papa', 'q': 'quebec', 'r': 'romeo', 's': 'sierra', 't': 'tango',
'u': 'uniform', 'v': 'victor', 'w': 'whiskey', 'x': 'x-ray', 'y': 'yankee',
'z': 'zulu'
}
def icao(mesaj):
"""Encodes a message to ICAO"""
encoded = ""
for item in mesaj:
if item.isalpha():
encoded += ICAO[item.lower()] + " "
if item == ' ':
encoded += '\n'
print encoded
if __name__ == "__main__":
icao("Mesajul ce trebuie transmis")
|
from vsg import parser
class shift_operator(parser.keyword):
'''
unique_id = shift_operator : shift_operator
'''
def __init__(self, sString):
parser.keyword.__init__(self, sString)
class sll(shift_operator):
'''
unique_id = shift_operator : sll
'''
def __init__(self, sString):
shift_operator.__init__(self, sString)
class srl(shift_operator):
'''
unique_id = shift_operator : srl
'''
def __init__(self, sString):
shift_operator.__init__(self, sString)
class sla(shift_operator):
'''
unique_id = shift_operator : sla
'''
def __init__(self, sString):
shift_operator.__init__(self, sString)
class sra(shift_operator):
'''
unique_id = shift_operator : sra
'''
def __init__(self, sString):
shift_operator.__init__(self, sString)
class rol(shift_operator):
'''
unique_id = shift_operator : rol
'''
def __init__(self, sString):
shift_operator.__init__(self, sString)
class ror(shift_operator):
'''
unique_id = shift_operator : ror
'''
def __init__(self, sString):
shift_operator.__init__(self, sString)
|
/* -*- c++ -*- */
/*
* Copyright 2007 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 this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <mb_gettid.h>
#define NEED_STUB
#if defined(HAVE_SYS_SYSCALL_H) && defined(HAVE_UNISTD_H)
#include <sys/syscall.h>
#include <unistd.h>
#if defined(SYS_gettid)
#undef NEED_STUB
int mb_gettid()
{
return syscall(SYS_gettid);
}
#endif
#endif
#if defined(NEED_STUB)
int
mb_gettid()
{
return 0;
}
#endif
|
"""
Test the user api's partition extensions.
"""
from collections import defaultdict
import pytest
from django.test import TestCase
from mock import patch
from six.moves import range
from openedx.core.djangoapps.user_api.partition_schemes import RandomUserPartitionScheme, UserPartitionError
from common.djangoapps.student.tests.factories import UserFactory
from xmodule.partitions.partitions import Group, UserPartition
from xmodule.partitions.tests.test_partitions import PartitionTestCase
class MemoryCourseTagAPI(object):
"""
An implementation of a user service that uses an in-memory dictionary for storage
"""
def __init__(self):
self._tags = defaultdict(dict)
def get_course_tag(self, __, course_id, key):
"""Sets the value of ``key`` to ``value``"""
return self._tags[course_id].get(key)
def set_course_tag(self, __, course_id, key, value):
"""Gets the value of ``key``"""
self._tags[course_id][key] = value
class BulkCourseTags(object):
@classmethod
def is_prefetched(self, course_id): # lint-amnesty, pylint: disable=bad-classmethod-argument, unused-argument
return False
@pytest.mark.django_db
class TestRandomUserPartitionScheme(PartitionTestCase):
"""
Test getting a user's group out of a partition
"""
MOCK_COURSE_ID = "mock-course-id"
def setUp(self):
super(TestRandomUserPartitionScheme, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# Patch in a memory-based user service instead of using the persistent version
course_tag_api = MemoryCourseTagAPI()
self.user_service_patcher = patch(
'openedx.core.djangoapps.user_api.partition_schemes.course_tag_api', course_tag_api
)
self.user_service_patcher.start()
self.addCleanup(self.user_service_patcher.stop)
# Create a test user
self.user = UserFactory.create()
def test_get_group_for_user(self):
# get a group assigned to the user
group1_id = RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, self.user_partition)
# make sure we get the same group back out every time
for __ in range(10):
group2_id = RandomUserPartitionScheme.get_group_for_user(
self.MOCK_COURSE_ID,
self.user,
self.user_partition
)
assert group1_id == group2_id
def test_get_group_for_user_with_assign(self):
"""
Make sure get_group_for_user returns None if no group is already
assigned to a user instead of assigning/creating a group automatically
"""
# We should not get any group because assign is False which will
# protect us from automatically creating a group for user
group = RandomUserPartitionScheme.get_group_for_user(
self.MOCK_COURSE_ID, self.user, self.user_partition, assign=False
)
assert group is None
# We should get a group automatically assigned to user
group = RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, self.user_partition)
assert group is not None
def test_empty_partition(self):
empty_partition = UserPartition(
self.TEST_ID,
'Test Partition',
'for testing purposes',
[],
scheme=RandomUserPartitionScheme
)
# get a group assigned to the user
with self.assertRaisesRegex(UserPartitionError, "Cannot assign user to an empty user partition"):
RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, empty_partition)
def test_user_in_deleted_group(self):
# get a group assigned to the user - should be group 0 or 1
old_group = RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, self.user_partition)
assert old_group.id in [0, 1]
# Change the group definitions! No more group 0 or 1
groups = [Group(3, 'Group 3'), Group(4, 'Group 4')]
user_partition = UserPartition(self.TEST_ID, 'Test Partition', 'for testing purposes', groups)
# Now, get a new group using the same call - should be 3 or 4
new_group = RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, user_partition)
assert new_group.id in [3, 4]
# We should get the same group over multiple calls
new_group_2 = RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, user_partition)
assert new_group == new_group_2
def test_change_group_name(self):
# Changing the name of the group shouldn't affect anything
# get a group assigned to the user - should be group 0 or 1
old_group = RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, self.user_partition)
assert old_group.id in [0, 1]
# Change the group names
groups = [Group(0, 'Group 0'), Group(1, 'Group 1')]
user_partition = UserPartition(
self.TEST_ID,
'Test Partition',
'for testing purposes',
groups,
scheme=RandomUserPartitionScheme
)
# Now, get a new group using the same call
new_group = RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, user_partition)
assert old_group.id == new_group.id
class TestExtension(TestCase):
"""
Ensure that the scheme extension is correctly plugged in (via entry point
in setup.py)
"""
def test_get_scheme(self):
assert UserPartition.get_scheme('random') == RandomUserPartitionScheme
with self.assertRaisesRegex(UserPartitionError, 'Unrecognized scheme'):
UserPartition.get_scheme('other')
|
/*
* jinclude.h
*
* Copyright (C) 1991-1994, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file exists to provide a single place to fix any problems with
* including the wrong system include files. (Common problems are taken
* care of by the standard jconfig symbols, but on really weird systems
* you may have to edit this file.)
*
* NOTE: this file is NOT intended to be included by applications using the
* JPEG library. Most applications need only include jpeglib.h.
*/
/* Include auto-config file to find out which system include files we need. */
#include "jconfig.h" /* auto configuration options */
#define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
/*
* We need the NULL macro and size_t typedef.
* On an ANSI-conforming system it is sufficient to include <stddef.h>.
* Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
* pull in <sys/types.h> as well.
* Note that the core JPEG library does not require <stdio.h>;
* only the default error handler and data source/destination modules do.
* But we must pull it in because of the references to FILE in jpeglib.h.
* You can remove those references if you want to compile without <stdio.h>.
*/
#ifdef HAVE_STDDEF_H
#include <stddef.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef NEED_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <stdio.h>
/*
* We need memory copying and zeroing functions, plus strncpy().
* ANSI and System V implementations declare these in <string.h>.
* BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
* Some systems may declare memset and memcpy in <memory.h>.
*
* NOTE: we assume the size parameters to these functions are of type size_t.
* Change the casts in these macros if not!
*/
#ifdef NEED_BSD_STRINGS
#include <strings.h>
#define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
#define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
#else /* not BSD, assume ANSI/SysV string lib */
#include <string.h>
#define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
#define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
#endif
/*
* In ANSI C, and indeed any rational implementation, size_t is also the
* type returned by sizeof(). However, it seems there are some irrational
* implementations out there, in which sizeof() returns an int even though
* size_t is defined as long or unsigned long. To ensure consistent results
* we always use this SIZEOF() macro in place of using sizeof() directly.
*/
#define SIZEOF(object) ((size_t) sizeof(object))
/*
* The modules that use fread() and fwrite() always invoke them through
* these macros. On some systems you may need to twiddle the argument casts.
* CAUTION: argument order is different from underlying functions!
*/
#define JFREAD(file,buf,sizeofbuf) \
((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
#define JFWRITE(file,buf,sizeofbuf) \
((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
|
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code 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.
Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "tools/edit_gui_common.h"
#include "../../sys/win32/win_local.h"
#include "MaterialEditor.h"
#include "MEMainFrame.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
MEMainFrame* meMainFrame = NULL;
CFont* materialEditorFont = NULL;
/**
* Initializes the material editor tool.
*/
void MaterialEditorInit( void ) {
InitPropTree(win32.hInstance);
com_editors = EDITOR_MATERIAL;
Sys_GrabMouseCursor( false );
InitAfx();
InitCommonControls();
// Initialize OLE libraries
if (!AfxOleInit())
{
return;
}
AfxEnableControlContainer();
NONCLIENTMETRICS info;
info.cbSize = sizeof(info);
::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(info), &info, 0);
LOGFONT lf;
memset(&lf, 0, sizeof (LOGFONT));
CWindowDC dc(NULL);
lf.lfCharSet = (BYTE)GetTextCharsetInfo(dc.GetSafeHdc(), NULL, 0);
lf.lfHeight = info.lfMenuFont.lfHeight;
lf.lfWeight = info.lfMenuFont.lfWeight;
lf.lfItalic = info.lfMenuFont.lfItalic;
// check if we should use system font
_tcscpy(lf.lfFaceName, info.lfMenuFont.lfFaceName);
materialEditorFont = new CFont;
materialEditorFont->CreateFontIndirect(&lf);
// To create the main window, this code creates a new frame window
// object and then sets it as the application's main window object
meMainFrame = new MEMainFrame;
// create and load the frame with its resources
meMainFrame->LoadFrame(IDR_ME_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL);
// hide the doom window by default
::ShowWindow ( win32.hWnd, SW_HIDE );
// The one and only window has been initialized, so show and update it
meMainFrame->ShowWindow(SW_SHOW);
meMainFrame->UpdateWindow();
}
/**
* Called every frame by the doom engine to allow the material editor to process messages.
*/
void MaterialEditorRun( void ) {
MSG *msg = AfxGetCurrentMessage();
while( ::PeekMessage(msg, NULL, NULL, NULL, PM_NOREMOVE) ) {
// pump message
if ( !AfxGetApp()->PumpMessage() ) {
}
}
}
/**
* Called by the doom engine when the material editor needs to be destroyed.
*/
void MaterialEditorShutdown( void ) {
delete meMainFrame;
delete materialEditorFont;
meMainFrame = NULL;
}
/**
* Allows the doom engine to reflect console output to the material editors console.
*/
void MaterialEditorPrintConsole( const char *msg ) {
if(com_editors & EDITOR_MATERIAL)
meMainFrame->PrintConsoleMessage(msg);
}
/**
* Returns the handle to the main Material Editor Window
*/
HWND GetMaterialEditorWindow() {
return meMainFrame->GetSafeHwnd();
}
/**
* Simple about box for the material editor.
*/
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
enum { IDD = IDD_ME_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
};
/**
* Constructor for the about box.
*/
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) {
}
/**
* Called by the MFC framework to exchange data with the window controls.
*/
void CAboutDlg::DoDataExchange(CDataExchange* pDX) {
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { RouterLink } from './src/directives/router_link';
import { RouterLinkActive } from './src/directives/router_link_active';
import { RouterOutlet } from './src/directives/router_outlet';
export { ExtraOptions } from './src/common_router_providers';
export { Route, RouterConfig } from './src/config';
export { CanActivate, CanDeactivate } from './src/interfaces';
export { Event, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router, RoutesRecognized } from './src/router';
export { RouterOutletMap } from './src/router_outlet_map';
export { provideRouter } from './src/router_providers';
export { ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from './src/router_state';
export { PRIMARY_OUTLET, Params } from './src/shared';
export { DefaultUrlSerializer, UrlPathWithParams, UrlSerializer, UrlTree } from './src/url_tree';
export declare const ROUTER_DIRECTIVES: (typeof RouterOutlet | typeof RouterLink | typeof RouterLinkActive)[];
|
#!/usr/bin/env node
// WebSocket vs. Socket.IO example - common backend - from:
// https://github.com/rsp/node-websocket-vs-socket.io
// Copyright (c) 2015, 2016 Rafał Pocztarski
// Released under MIT License (Expat) - see:
// https://github.com/rsp/node-websocket-vs-socket.io/blob/master/LICENSE.md
/*eslint-disable no-loop-func*/
var path = require('path');
var express = require('express');
var log = function (m) {
console.error(new Date().toISOString()+' '+this.pre+m);
}
console.error("node-websocket-vs-socket.io\n"
+"WebSocket vs. Socket.IO on Node.js with Express.js - see:\n"
+"https://github.com/rsp/node-websocket-vs-socket.io#readme\n"
+"Copyright (c) 2015, 2016 Rafał Pocztarski\n"
+"Released under MIT License (Expat) - see:\n"
+"https://github.com/rsp/node-websocket-vs-socket.io/blob/master/LICENSE.md\n");
// WebSocket:
var ws = {app: express(), pre: "websocket app: ", log: log};
ws.ws = require('express-ws')(ws.app);
ws.app.get('/', (req, res) => {
ws.log('express connection - sending html');
res.sendFile(path.join(__dirname, 'ws.html'));
});
ws.app.ws('/', (s, req) => {
ws.log('incoming websocket connection');
for (var t = 0; t < 3; t++)
setTimeout(() => {
ws.log('sending message to client');
s.send(ws.pre+'message from server', ()=>{});
}, 1000*t);
});
ws.app.listen(3001, () =>
ws.log('listening on http://localhost:3001/'));
ws.log('starting server');
// Socket.IO:
var si = {app: express(), pre: "socket.io app: ", log: log};
si.http = require('http').Server(si.app);
si.io = require('socket.io')(si.http);
si.app.get('/', (req, res) => {
si.log('express connection - sending html');
res.sendFile(path.join(__dirname, 'si.html'));
});
si.app.get('/forced', (req, res) => {
si.log('express connection - sending html');
res.sendFile(path.join(__dirname, 'si-forced.html'));
});
si.io.on('connection', s => {
si.log('incoming socket.io connection');
for (var t = 0; t < 3; t++)
setTimeout(() => {
si.log('sending message to client');
s.emit('message', si.pre+'message from server');
}, 1000*t);
});
si.http.listen(3002, () =>
si.log('listening on http://localhost:3002/'));
si.log('starting server');
|
/*
* Copyright 2012-2015 MarkLogic Corporation
*
* 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 com.marklogic.client.admin.config.support;
/**
* Marker for geospatial index configurations.
* Maps to geo-elem-pair|geo-attr|geo-elem
* in the Search API options schema.
* Not actually in use.
*/
public interface GeospatialIndex {}
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 proto # type: ignore
from google.cloud.automl_v1beta1.types import classification
__protobuf__ = proto.module(
package="google.cloud.automl.v1beta1",
manifest={
"TextClassificationDatasetMetadata",
"TextClassificationModelMetadata",
"TextExtractionDatasetMetadata",
"TextExtractionModelMetadata",
"TextSentimentDatasetMetadata",
"TextSentimentModelMetadata",
},
)
class TextClassificationDatasetMetadata(proto.Message):
r"""Dataset metadata for classification.
Attributes:
classification_type (google.cloud.automl_v1beta1.types.ClassificationType):
Required. Type of the classification problem.
"""
classification_type = proto.Field(
proto.ENUM, number=1, enum=classification.ClassificationType,
)
class TextClassificationModelMetadata(proto.Message):
r"""Model metadata that is specific to text classification.
Attributes:
classification_type (google.cloud.automl_v1beta1.types.ClassificationType):
Output only. Classification type of the
dataset used to train this model.
"""
classification_type = proto.Field(
proto.ENUM, number=3, enum=classification.ClassificationType,
)
class TextExtractionDatasetMetadata(proto.Message):
r"""Dataset metadata that is specific to text extraction """
class TextExtractionModelMetadata(proto.Message):
r"""Model metadata that is specific to text extraction.
Attributes:
model_hint (str):
Indicates the scope of model use case.
- ``default``: Use to train a general text extraction
model. Default value.
- ``health_care``: Use to train a text extraction model
that is tuned for healthcare applications.
"""
model_hint = proto.Field(proto.STRING, number=3,)
class TextSentimentDatasetMetadata(proto.Message):
r"""Dataset metadata for text sentiment.
Attributes:
sentiment_max (int):
Required. A sentiment is expressed as an integer ordinal,
where higher value means a more positive sentiment. The
range of sentiments that will be used is between 0 and
sentiment_max (inclusive on both ends), and all the values
in the range must be represented in the dataset before a
model can be created. sentiment_max value must be between 1
and 10 (inclusive).
"""
sentiment_max = proto.Field(proto.INT32, number=1,)
class TextSentimentModelMetadata(proto.Message):
r"""Model metadata that is specific to text sentiment. """
__all__ = tuple(sorted(__protobuf__.manifest))
|
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay = int(self.pay * (1 + percent))
def __repr__(self):
return '[Person: %s, %s]' % (self.name, self.pay)
class Manager:
def __init__(self, name, pay):
self.person = Person(name, 'mgr', pay) # Embed a Person object
def giveRaise(self, percent, bonus=.10):
self.person.giveRaise(percent + bonus) # Intercept and delegate
def __getattr__(self, attr):
return getattr(self.person, attr) # Delegate all other attrs
def __repr__(self):
return str(self.person) # Must overload again (in 3.X)
if __name__ == '__main__':
bob = Person('Bob Smith')
sue = Person('Sue Jones', job='dev', pay=100000)
print(bob)
print(sue)
print(bob.lastName(), sue.lastName())
sue.giveRaise(.10)
print(sue)
tom = Manager('Tom Jones', 50000) # Job name not needed:
tom.giveRaise(.10) # Implied/set by class
print(tom.lastName())
print(tom)
|
/* Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
package org.LK8000;
import android.util.Log;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import static android.opengl.GLES11.*;
import android.opengl.GLUtils;
/**
* Utilities for dealing with #Bitmap objects and OpenGL.
*/
final class BitmapUtil {
private static final String TAG = "LK8000";
public static int validateTextureSize(int i) {
return NativeView.validateTextureSize(i);
}
/**
* Initialize the current texture and load the specified Bitmap into
* it.
*/
private static boolean loadTexture(Bitmap bmp, int allocated_width,
int allocated_height) {
int internalFormat, format, type;
int unpackAlignment;
switch (bmp.getConfig()) {
case ARGB_4444:
case ARGB_8888:
internalFormat = format = GL_RGBA;
type = GL_UNSIGNED_BYTE;
unpackAlignment = 4;
break;
case RGB_565:
internalFormat = format = GL_RGB;
type = GL_UNSIGNED_SHORT_5_6_5;
unpackAlignment = 2;
break;
case ALPHA_8:
internalFormat = format = GL_ALPHA;
type = GL_UNSIGNED_BYTE;
unpackAlignment = 1;
break;
default:
return false;
}
/* create an empty texture, and load the Bitmap into it */
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat,
allocated_width, allocated_height,
0, format, type, null);
glPixelStorei(GL_UNPACK_ALIGNMENT, unpackAlignment);
GLUtils.texSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bmp, format, type);
return true;
}
/**
* Copy the red channel to a new Bitmap's alpha channel. The old
* one will be recycled.
*/
static Bitmap redToAlpha(Bitmap src, boolean recycle) {
Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
Bitmap.Config.ARGB_8888);
float[] matrix = new float[] {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
1, 0, 0, 0, 0
};
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(matrix)));
Canvas canvas = new Canvas(dest);
canvas.setDensity(Bitmap.DENSITY_NONE);
canvas.drawBitmap(src, 0, 0, paint);
if (recycle)
src.recycle();
return dest;
}
/**
* Convert the Bitmap to ALPHA_8. The old one will be recycled.
*/
static Bitmap toAlpha8(Bitmap src, boolean recycle) {
if (!src.hasAlpha()) {
src = redToAlpha(src, recycle);
recycle = true;
}
Bitmap dest = src.copy(Bitmap.Config.ALPHA_8, false);
if (recycle)
src.recycle();
return dest;
}
/**
* Loads an Android Bitmap as OpenGL texture.
*
* @param recycle recycle the #Bitmap parameter?
* @param alpha expect a GL_ALPHA texture?
* @param result an array of 5 integers: texture id, width, height,
* allocated width, allocated height (all output)
* @return true on success
*/
public static boolean bitmapToOpenGL(Bitmap bmp, boolean recycle,
boolean alpha,
int[] result) {
result[1] = bmp.getWidth();
result[2] = bmp.getHeight();
result[3] = validateTextureSize(result[1]);
result[4] = validateTextureSize(result[2]);
if (alpha && bmp.getConfig() != Bitmap.Config.ALPHA_8) {
bmp = toAlpha8(bmp, recycle);
recycle = true;
} else if (bmp.getConfig() == null) {
/* convert to a format compatible with OpenGL */
Bitmap.Config config = bmp.hasAlpha()
? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap tmp = bmp.copy(config, false);
if (recycle)
bmp.recycle();
if (tmp == null)
return false;
bmp = tmp;
recycle = true;
}
/* create and configure an OpenGL texture */
glGenTextures(1, result, 0);
glBindTexture(GL_TEXTURE_2D, result[0]);
glTexParameterf(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_NEAREST);
try {
if (!loadTexture(bmp, result[3], result[4])) {
glDeleteTextures(1, result, 0);
return false;
}
} catch (Exception e) {
glDeleteTextures(1, result, 0);
Log.e(TAG, "GLUtils error", e);
return false;
} finally {
if (recycle)
bmp.recycle();
}
/* done */
return true;
}
}
|
Neudesic.utilities.namespace('neu.metro.ui', function (exports, $) {
"use strict";
var initializeComponent = function (e) {
var $el = $(e),
componentName = $el.attr('data-component'),
componentClass = Neudesic.utilities.namespace(componentName),
instance,
args = [e, $el.data(),
new neu.metro.events.EventBusProxy($el)];
instance = Object.create(componentClass.prototype);
if ('init' in instance) {
instance.init.apply(instance, args);
}
componentClass.apply(instance, args);
return instance;
};
$(function () {
$('.component').each(function (i, e) {
initializeComponent(e);
});
});
exports.initializeComponent = initializeComponent;
}, window.jQuery);
|
using System.Data;
using System.Data.SqlClient;
using Moq;
using NBi.Core.ResultSet;
using NBi.NUnit.ResultSetComparison;
using NUnit.Framework;
using NBi.Core;
using NBi.Core.ResultSet.Resolver;
using NBi.Core.ResultSet.Equivalence;
namespace NBi.Testing.Unit.NUnit.ResultSetComparison
{
[TestFixture]
public class EqualToConstraintTest
{
[Test]
public void Matches_AnyServices_EachCalledOnce()
{
var rs = new ResultSet();
rs.Load("a;b;c");
var expectedServiceMock = new Mock<IResultSetService>();
expectedServiceMock.Setup(s => s.Execute())
.Returns(rs);
var expectedService = expectedServiceMock.Object;
var actualServiceMock = new Mock<IResultSetService>();
actualServiceMock.Setup(s => s.Execute())
.Returns(rs);
var actualService = actualServiceMock.Object;
var rscMock = new Mock<IEquivaler>();
rscMock.Setup(engine => engine.Compare(It.IsAny<ResultSet>(), It.IsAny<ResultSet>()))
.Returns(new ResultResultSet() { Difference = ResultSetDifferenceType.None });
var rsc = rscMock.Object;
var equalToConstraint = new EqualToConstraint(expectedService) { Engine = rsc };
//Method under test
equalToConstraint.Matches(actualService);
//Test conclusion
rscMock.Verify(engine => engine.Compare(It.IsAny<ResultSet>(), It.IsAny<ResultSet>()), Times.Once());
expectedServiceMock.Verify(s => s.Execute(), Times.Once);
actualServiceMock.Verify(s => s.Execute(), Times.Once);
}
[Test]
public void Matches_AnyServices_TheirResultsAreCompared()
{
var expectedRs = new ResultSet();
expectedRs.Load("a;b;c");
var actualRs = new ResultSet();
actualRs.Load("x;y;z");
var expectedServiceMock = new Mock<IResultSetService>();
expectedServiceMock.Setup(s => s.Execute())
.Returns(expectedRs);
var expectedService = expectedServiceMock.Object;
var actualServiceMock = new Mock<IResultSetService>();
actualServiceMock.Setup(s => s.Execute())
.Returns(actualRs);
var actualService = actualServiceMock.Object;
var rscMock = new Mock<IEquivaler>();
rscMock.Setup(engine => engine.Compare(It.IsAny<ResultSet>(), It.IsAny<ResultSet>()))
.Returns(new ResultResultSet() { Difference = ResultSetDifferenceType.Content });
var rsc = rscMock.Object;
var equalToConstraint = new EqualToConstraint(expectedService) { Engine = rsc };
//Method under test
equalToConstraint.Matches(actualService);
//Test conclusion
rscMock.Verify(engine => engine.Compare(actualRs, expectedRs), Times.Once());
}
[Test]
public void Matches_TwoIdenticalResultSets_ReturnTrue()
{
var rs = new ResultSet();
rs.Load("a;b;c");
var expectedServiceMock = new Mock<IResultSetService>();
expectedServiceMock.Setup(s => s.Execute())
.Returns(rs);
var expectedService = expectedServiceMock.Object;
var actualServiceMock = new Mock<IResultSetService>();
actualServiceMock.Setup(s => s.Execute())
.Returns(rs);
var actualService = actualServiceMock.Object;
var rscMock = new Mock<IEquivaler>();
rscMock.Setup(engine => engine.Compare(rs, rs))
.Returns(new ResultResultSet() { Difference = ResultSetDifferenceType.None });
var rsc = rscMock.Object;
var equalToConstraint = new EqualToConstraint(expectedService) { Engine = rsc };
//Method under test
var result = equalToConstraint.Matches(actualService);
//Test conclusion
Assert.That(result, Is.True);
}
[Test]
public void Matches_TwoDifferentResultSets_ReturnFalse()
{
var expectedRs = new ResultSet();
expectedRs.Load("a;b;c");
var actualRs = new ResultSet();
actualRs.Load("x;y;z");
var expectedServiceMock = new Mock<IResultSetService>();
expectedServiceMock.Setup(s => s.Execute())
.Returns(expectedRs);
var expectedService = expectedServiceMock.Object;
var actualServiceMock = new Mock<IResultSetService>();
actualServiceMock.Setup(s => s.Execute())
.Returns(actualRs);
var actualService = actualServiceMock.Object;
var rscMock = new Mock<IEquivaler>();
rscMock.Setup(engine => engine.Compare(actualRs, expectedRs))
.Returns(new ResultResultSet() { Difference = ResultSetDifferenceType.Content });
var rsc = rscMock.Object;
var equalToConstraint = new EqualToConstraint(expectedService) { Engine = rsc };
//Method under test
var result = equalToConstraint.Matches(actualService);
//Test conclusion
Assert.That(result, Is.False);
}
}
}
|
# coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Data generators for the Quora Question Pairs dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import zipfile
import six
from tensor2tensor.data_generators import generator_utils
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators import text_encoder
from tensor2tensor.data_generators import text_problems
from tensor2tensor.utils import registry
import tensorflow as tf
EOS = text_encoder.EOS
@registry.register_problem
class QuoraQuestionPairs(text_problems.TextConcat2ClassProblem):
"""Quora duplicate question pairs binary classification problems."""
# Link to data from GLUE: https://gluebenchmark.com/tasks
_QQP_URL = ("https://firebasestorage.googleapis.com/v0/b/"
"mtl-sentence-representations.appspot.com/o/"
"data%2FQQP.zip?alt=media&token=700c6acf-160d-"
"4d89-81d1-de4191d02cb5")
@property
def is_generate_per_split(self):
return True
@property
def dataset_splits(self):
return [{
"split": problem.DatasetSplit.TRAIN,
"shards": 100,
}, {
"split": problem.DatasetSplit.EVAL,
"shards": 1,
}]
@property
def approx_vocab_size(self):
return 2**15
@property
def num_classes(self):
return 2
def class_labels(self, data_dir):
del data_dir
return ["not_duplicate", "duplicate"]
def _maybe_download_corpora(self, tmp_dir):
qqp_filename = "QQP.zip"
qqp_finalpath = os.path.join(tmp_dir, "QQP")
if not tf.gfile.Exists(qqp_finalpath):
zip_filepath = generator_utils.maybe_download(
tmp_dir, qqp_filename, self._QQP_URL)
zip_ref = zipfile.ZipFile(zip_filepath, "r")
zip_ref.extractall(tmp_dir)
zip_ref.close()
return qqp_finalpath
def example_generator(self, filename):
skipped = 0
for idx, line in enumerate(tf.gfile.Open(filename, "rb")):
if idx == 0: continue # skip header
if six.PY2:
line = unicode(line.strip(), "utf-8")
else:
line = line.strip().decode("utf-8")
split_line = line.split("\t")
if len(split_line) < 6:
skipped += 1
tf.logging.info("Skipping %d" % skipped)
continue
s1, s2, l = split_line[3:]
# A neat data augmentation trick from Radford et al. (2018)
# https://blog.openai.com/language-unsupervised/
inputs = [[s1, s2], [s2, s1]]
for inp in inputs:
yield {
"inputs": inp,
"label": int(l)
}
def generate_samples(self, data_dir, tmp_dir, dataset_split):
qqp_dir = self._maybe_download_corpora(tmp_dir)
if dataset_split == problem.DatasetSplit.TRAIN:
filesplit = "train.tsv"
else:
filesplit = "dev.tsv"
filename = os.path.join(qqp_dir, filesplit)
for example in self.example_generator(filename):
yield example
@registry.register_problem
class QuoraQuestionPairsCharacters(QuoraQuestionPairs):
"""Quora duplicate question pairs classification problems, character level"""
@property
def vocab_type(self):
return text_problems.VocabType.CHARACTER
def global_task_id(self):
return problem.TaskID.EN_SIM
|
var https=require("https");
var fs=require("fs");
var server=https.createServer({
key:fs.readFileSync("../ssl/server.key"),
cert:fs.readFileSync("../ssl/server.crt")
}).listen(9503);
var websocket=require("ws").Server;
var ws=new websocket({server:server});
var rooms=[];
//---------聊天室 rooms[key]结构
// userList:[] 在该房间内的玩家列表,包括各自的信息
//---------message结构
// type: 事件类型,有"broadcast"(广播事件)
// "sync"(信息同步事件),"audio"(音频通讯事件)
// res: 传输的消息,包含用户名称,座位ID。
ws.on('connection',function(conn){
conn.on('message',function(message){
var msgJson=JSON.parse(message);
var roomID=msgJson.res.roomID;
if(!rooms[roomID]){
//create
rooms[roomID]={
userList:[], // 玩家列表,用于广播
}
}
if(msgJson.type=="sync"){
conn.userInfo={
usrName:msgJson.res.userName,
roomID:roomID
};
if(rooms[roomID].userList.length<18){
rooms[roomID].userList.push(conn);
}
else{
return conn.send(JSON.stringify({
type:"reject"
}))
}
}
if(msgJson.type=="broadcast")
broadcast(roomID,msgJson.res.message,"broadcast");
if(msgJson.type=="audio") {
broadcast(roomID, msgJson.res.audio, "audio");
}
});
conn.on('close',function(){
var userList=rooms[conn.userInfo.roomID].userList;
userList.splice(userList.indexOf(conn),1);
rooms[conn.userInfo.roomID].userList=userList;
})
function broadcast(roomID,msg,type){
var userList=rooms[roomID].userList;
for(var i=0;i<userList.length;i++){
if(userList[i]!=conn) {
userList[i].send(JSON.stringify({
type: type,
res: {
message: msg
}
}))
}
}
}
})
|
import composer
class Dog(composer.Composable):
def __init__(self,age):
self.age = age
self.race = "corgi"
def add5(self):
self.age += 5
def addX(self,x):
self.age += x
class Zombie(object):
def __init__(self, brains):
self.brains = brains
def grgl(self):
return self.brains
class Robot(object):
def __init__(self, voltage):
self.voltage = voltage
self.plating = "steel"
def beep(self):
return "beep"
def reduce_voltage(self,amount):
self.voltage -= amount
def shutdown(self):
self.voltage = 0
def mul(a,b):
return a*b
def square(x):
return x*x
def test_function_addition():
f = composer.cp_func(mul)
assert(f(2,3) == 6)
dog = Dog(10)
robot = Robot(230)
robot_dog = dog.extend(robot)
assert(robot_dog.age == 10)
assert(robot_dog.voltage == 230)
assert(robot_dog.beep() == "beep")
robot_dog.add5()
assert(robot_dog.age == 15)
robot_dog.addX(2)
assert(robot_dog.age == 17)
robot_dog.reduce_voltage(30)
assert(robot_dog.voltage == 200)
robot_dog.shutdown()
assert(robot_dog.voltage == 0)
zombie = Zombie(5)
zombie_robot_dog = robot_dog.extend(zombie)
assert(zombie_robot_dog.grgl() == 5)
zombie_robot_dog.add5()
assert(zombie_robot_dog.age == 22)
assert(zombie_robot_dog.plating == "steel")
assert(zombie_robot_dog.race == "corgi")
def test_add_method():
dog = Dog(10)
dog.add_method(mul)
#print mul
#print "Attached method: "+ str(dog.mul)
#print(dog.age)
assert(dog.mul(dog.age,2) == 20)
assert(dog.mul(5,5) == 25)
robot = Robot(230)
robot_dog = dog.extend(robot)
assert(robot_dog.mul(robot_dog.voltage,2) == 460)
robot_dog.add_method(square)
assert(robot_dog.square(robot_dog.age) == 100)
def test_lol():
assert(1==1)
|
#!/usr/bin/env python
"""
TODO: Change the module doc.
"""
from __future__ import division
__author__ = "shyuepingong"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "[email protected]"
__status__ = "Beta"
__date__ = "11/19/12"
import numpy as np
from scipy.spatial import ConvexHull as CHullSci
from pyhull.convex_hull import ConvexHull as CHullPyhull
def scipy_test(data):
return CHullSci(data)
def pyhull_test(data):
return CHullPyhull(data)
if __name__ == "__main__":
import timeit
global data
output = ["<table>", "<tr><th>Number of points</th>",
"<th>Dim</th><th>scipy</th>",
"<th>pyhull</th>"]
for npts in [100, 1000, 2000]:
for dim in [3, 4, 5, 6]:
row = []
row.append("{:5d}".format(npts))
row.append("{:3d}".format(dim))
data = np.random.randn(npts, dim)
t = timeit.timeit("scipy_test(data)",
setup="from __main__ import scipy_test, data",
number=1)
row.append("{:.5f}".format(t))
t = timeit.timeit("pyhull_test(data)",
setup="from __main__ import pyhull_test, data",
number=1)
row.append("{:.5f}".format(t))
print " ".join(row)
print "\n".join(output)
|
"""
Tar archive parser.
Author: Victor Stinner
"""
from hachoir_parser import Parser
from hachoir_core.field import (FieldSet,
Enum, UInt8, SubFile, String, NullBytes)
from hachoir_core.tools import humanFilesize, paddingSize, timestampUNIX
from hachoir_core.endian import BIG_ENDIAN
import re
class FileEntry(FieldSet):
type_name = {
# 48 is "0", 49 is "1", ...
0: u"Normal disk file (old format)",
48: u"Normal disk file",
49: u"Link to previously dumped file",
50: u"Symbolic link",
51: u"Character special file",
52: u"Block special file",
53: u"Directory",
54: u"FIFO special file",
55: u"Contiguous file"
}
def getOctal(self, name):
return self.octal2int(self[name].value)
def getDatetime(self):
"""
Create modification date as Unicode string, may raise ValueError.
"""
timestamp = self.getOctal("mtime")
return timestampUNIX(timestamp)
def createFields(self):
yield String(self, "name", 100, "Name", strip="\0", charset="ISO-8859-1")
yield String(self, "mode", 8, "Mode", strip=" \0", charset="ASCII")
yield String(self, "uid", 8, "User ID", strip=" \0", charset="ASCII")
yield String(self, "gid", 8, "Group ID", strip=" \0", charset="ASCII")
yield String(self, "size", 12, "Size", strip=" \0", charset="ASCII")
yield String(self, "mtime", 12, "Modification time", strip=" \0", charset="ASCII")
yield String(self, "check_sum", 8, "Check sum", strip=" \0", charset="ASCII")
yield Enum(UInt8(self, "type", "Type"), self.type_name)
yield String(self, "lname", 100, "Link name", strip=" \0", charset="ISO-8859-1")
yield String(self, "magic", 8, "Magic", strip=" \0", charset="ASCII")
yield String(self, "uname", 32, "User name", strip=" \0", charset="ISO-8859-1")
yield String(self, "gname", 32, "Group name", strip=" \0", charset="ISO-8859-1")
yield String(self, "devmajor", 8, "Dev major", strip=" \0", charset="ASCII")
yield String(self, "devminor", 8, "Dev minor", strip=" \0", charset="ASCII")
yield NullBytes(self, "padding", 167, "Padding (zero)")
filesize = self.getOctal("size")
if filesize:
yield SubFile(self, "content", filesize, filename=self["name"].value)
size = paddingSize(self.current_size//8, 512)
if size:
yield NullBytes(self, "padding_end", size, "Padding (512 align)")
def convertOctal(self, chunk):
return self.octal2int(chunk.value)
def isEmpty(self):
return self["name"].value == ""
def octal2int(self, text):
try:
return int(text, 8)
except ValueError:
return 0
def createDescription(self):
if self.isEmpty():
desc = "(terminator, empty header)"
else:
filename = self["name"].value
filesize = humanFilesize(self.getOctal("size"))
desc = "(%s: %s, %s)" % \
(filename, self["type"].display, filesize)
return "Tar File " + desc
class TarFile(Parser):
endian = BIG_ENDIAN
PARSER_TAGS = {
"id": "tar",
"category": "archive",
"file_ext": ("tar",),
"mime": (u"application/x-tar", u"application/x-gtar"),
"min_size": 512*8,
"magic": (("ustar \0", 257*8),),
"subfile": "skip",
"description": "TAR archive",
}
_sign = re.compile("ustar *\0|[ \0]*$")
def validate(self):
if not self._sign.match(self.stream.readBytes(257*8, 8)):
return "Invalid magic number"
if self[0].name == "terminator":
return "Don't contain any file"
try:
int(self["file[0]/uid"].value, 8)
int(self["file[0]/gid"].value, 8)
int(self["file[0]/size"].value, 8)
except ValueError:
return "Invalid file size"
return True
def createFields(self):
while not self.eof:
field = FileEntry(self, "file[]")
if field.isEmpty():
yield NullBytes(self, "terminator", 512)
break
yield field
if self.current_size < self._size:
yield self.seekBit(self._size, "end")
def createContentSize(self):
return self["terminator"].address + self["terminator"].size
|
<!DOCTYPE html>
<head>
<title>text-indent test</title>
<style type="text/css">
i { float: left; height: 0.3em; width: 100px; }
span { background: yellow }
</style>
</head>
<body>
<p><i></i><span>This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines. This is a long piece of text that will wrap to multiple lines.</span></p>
</body>
</html>
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Janus WebRTC Gateway: Text Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/webrtc-adapter/5.0.1/adapter.min.js" ></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js" ></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.1.0/bootbox.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.2/spin.min.js"></script>
<script type="text/javascript" src="janus.js" ></script>
<script type="text/javascript" src="textroomtest.js"></script>
<script>
$(function() {
$(".navbar-static-top").load("navbar.html", function() {
$(".navbar-static-top li.dropdown").addClass("active");
$(".navbar-static-top a[href='textroomtest.html']").parent().addClass("active");
});
$(".footer").load("footer.html");
});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.min.css" type="text/css"/>
<link rel="stylesheet" href="css/demo.css" type="text/css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.min.css" type="text/css"/>
</head>
<body>
<a href="https://github.com/meetecho/janus-gateway"><img style="position: absolute; top: 0; left: 0; border: 0; z-index: 1001;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_darkblue_121621.png" alt="Fork me on GitHub"></a>
<nav class="navbar navbar-default navbar-static-top">
</nav>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1>Plugin Demo: Text Room
<button class="btn btn-default" autocomplete="off" id="start">Start</button>
</h1>
</div>
<div class="container" id="details">
<div class="row">
<div class="col-md-12">
<h3>Demo details</h3>
<p>The Text Room demo is a simple example of how you can use this text
broadcasting plugin, which uses Data Channels, to implement something
similar to a chatroom. More specifically, the demo allows you to join
a previously created and configured text room together with other
participants, and send/receive public and private messages to
individual participants. To send messages on the chatroom, just type
your text and send. To send private messages to individual participants,
click the participant name in the list on the right and a custom dialog
will appear.</code>.</p>
<p>To try the demo, just insert a username to join the room. This will
add you to chatroom, and allow you to interact with the other participants.</p>
<p>Notice that this is just a very basic demo, and that is just one of
the several different ways you can use this plugin for. The plugin
actually allows you to join multiple rooms at the same time, and also
to forward incoming messages to the room to external components. This
makes it a useful tool whenever you have to interact with third party
applications and exchange text data.</p>
<p>Press the <code>Start</code> button above to launch the demo.</p>
</div>
</div>
</div>
<div class="container hide" id="roomjoin">
<div class="row">
<span class="label label-info" id="you"></span>
<div class="col-md-12" id="controls">
<div class="input-group margin-bottom-md hide" id="registernow">
<span class="input-group-addon">@</span>
<input class="form-control" type="text" placeholder="Choose a display name" autocomplete="off" id="username" onkeypress="return checkEnter(this, event);"></input>
<span class="input-group-btn">
<button class="btn btn-success" autocomplete="off" id="register">Join the room</button>
</span>
</div>
</div>
</div>
</div>
<div class="container hide" id="room">
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Participants <span class="label label-info hide" id="participant"></span></h3>
</div>
<div class="panel-body">
<ul id="list" class="list-group">
</ul>
</div>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Public Chatroom</span></h3>
</div>
<div class="panel-body relative" style="overflow-x: auto;" id="chatroom">
</div>
<div class="panel-footer">
<div class="input-group margin-bottom-sm">
<span class="input-group-addon"><i class="fa fa-cloud-upload fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Write a chatroom message" autocomplete="off" id="datasend" onkeypress="return checkEnter(this, event);" disabled></input>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="footer">
</div>
</div>
</body>
</html>
|
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
namespace SixtyNineDegrees.MiteDesk.WinForms
{
public static class Helper
{
public static string CurrentVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version.Major + "." +
Assembly.GetExecutingAssembly().GetName().Version.Minor;
}
}
public static string CurrentBuild
{
get { return Assembly.GetExecutingAssembly().GetName().Version.Build.ToString(); }
}
public static void OpenBrowser(string url)
{
try
{
Process.Start(url);
}
catch
{
}
}
public static void ValidateTextEnteredInComboBox(object sender, EventArgs e)
{
var comboBox = (ComboBox)sender;
string text = comboBox.Text;
if (string.IsNullOrEmpty(text) || text.Length == 0)
return;
foreach (ListItem item in comboBox.Items)
{
if (item.Text.ToLower().StartsWith(text.ToLower()))
return;
}
comboBox.Text = text.Substring(0, text.Length - 1);
comboBox.Select(comboBox.Text.Length, 0);
}
public static string GetFormattedTimeText(int minutes)
{
return (minutes / 60).ToString().PadLeft(2, '0') + ":" + (minutes % 60).ToString().PadLeft(2, '0');
}
public static void StartBackgroundWorker(BackgroundWorker worker, object argument)
{
if(worker.IsBusy)
{
worker.CancelAsync();
while (worker.IsBusy)
Application.DoEvents();
}
if (argument != null)
worker.RunWorkerAsync(argument);
else
worker.RunWorkerAsync();
}
public static void SetCulture(string culture)
{
var ci = new System.Globalization.CultureInfo(culture, false);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
}
}
|
//// [jsxNamespacePrefixIntrinsics.tsx]
declare namespace JSX {
interface IntrinsicElements {
"ns:element": {
"ns:attribute": string;
},
"ns:NamespacedUpcaseAlsoIntrinsic": any,
"NS:NamespacedUpcaseAlsoIntrinsic": any
}
}
const valid = <ns:element ns:attribute="yep" />;
const validUpcase1 = <ns:NamespacedUpcaseAlsoIntrinsic />;
const validUpcase2 = <NS:NamespacedUpcaseAlsoIntrinsic />;
const invalid1 = <element />;
const invalid2 = <ns:element attribute="nope" />;
const invalid3 = <ns:element ns:invalid="nope" />;
//// [jsxNamespacePrefixIntrinsics.jsx]
var valid = <ns:element ns:attribute="yep"/>;
var validUpcase1 = <ns:NamespacedUpcaseAlsoIntrinsic />;
var validUpcase2 = <NS:NamespacedUpcaseAlsoIntrinsic />;
var invalid1 = <element />;
var invalid2 = <ns:element attribute="nope"/>;
var invalid3 = <ns:element ns:invalid="nope"/>;
|
#!/usr/bin/env python3
import sys
import click
from csaopt.utils import internet_connectivity_available, get_configs
from csaopt import Runner
from csaopt import __appname__ as csaopt_name
from csaopt import __version__ as csaopt_version
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
@click.group()
@click.version_option(version=csaopt_version, prog_name=csaopt_name)
@click.pass_context
def cli(ctx):
try:
internal_conf = get_configs('csaopt/internal/csaopt-internal.conf')
ctx.obj['internal_conf'] = internal_conf
except Exception as e:
eprint('Could not load configs', e)
sys.exit(1)
@cli.command(name='run', help='Run the optimization based on the provided config and model.')
@click.option(
'--model',
type=click.Path(exists=True, resolve_path=True),
multiple=True,
help='Folder containing the model that should be used for optimization.')
@click.option(
'--conf',
type=click.Path(exists=True, resolve_path=True),
multiple=True,
help='Path to the CSAOpt config. If not provided, \'conf/csaopt.conf\' will be used')
@click.pass_context
def run_opt(ctx, model, conf):
runner = Runner(list(model), list(conf), ctx.obj)
runner.run()
runner.console_printer.print_magenta('Bye.\n')
@cli.command(name='check', help='Check and validate the provided configuration and model.')
@click.option(
'--model',
type=click.Path(exists=True, resolve_path=True),
help='Folder containing the model that should be used for optimization.')
@click.option(
'--conf',
default='conf/csaopt.conf',
type=click.Path(exists=True, resolve_path=True),
help='Path to the CSAOpt config. If not provided, \'conf/csaopt.conf\' will be used')
@click.option(
'--with-aws',
is_flag=True,
default=False,
help='If enabled, the check will also spin up EC2 instances to verify configuration and communication.')
def run_check(**kwargs):
print('Check called')
@cli.command(name='cleanup', help='Clean up generated files and terminate any running EC2 instances')
def cleanup():
pass
if __name__ == '__main__':
cli(obj={})
|
<nav class="navbar navbar-light navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'blog:home' %}">Home</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<!-- <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">Link</a></li> -->
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Menu <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="{% url 'blog:order_list' %}">Order</a></li>
<li>
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Inventory <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="{% url 'blog:computing_list' %}">Computing</a></li>
<li><a href="{% url 'blog:electronic_list_type_components' %}">Electronic</a></li>
<li><a href="{% url 'blog:optic_list_type_optic' %}">Optics</a></li>
<li><a href="{% url 'blog:chemical_list_type_chemical' %}">Chemical</a></li>
<li><a href="{% url 'blog:biological_list_type_biological' %}">Biological</a></li>
<li><a href="{% url 'blog:instrumentation_list_type' %}">Instrumentation</a></li>
<li><a href="{% url 'blog:consumable_list' %}">Consumable</a></li>
</ul>
</li>
<li><a href="{% url 'blog:run_list' %}">RUN</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
{% if user.is_staff %}
<li><a href="{% url 'blog:messages_list' %}" class="navbar-link">Messages</a></li>
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
{% if user.is_authenticated %}
<li><p class="navbar-text navbar-right">Hello {{ user.username }} </p></li>
<li><a href="{% url 'blog:signout' %}" class="navbar-link"> (Log out)</a></li>
{% endif %}
</ul>
</div>
</div>
</nav>
|
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import (
QToolButton, QSize, QPropertyAnimation, Qt, QMetaObject, pyqtProperty,
QWidget, QIcon, QPainter, QStyleOptionToolButton)
from calibre.gui2 import config
class ThrobbingButton(QToolButton):
@pyqtProperty(int)
def icon_size(self):
return self._icon_size
@icon_size.setter
def icon_size(self, value):
self._icon_size = value
def __init__(self, *args):
QToolButton.__init__(self, *args)
self._icon_size = -1
QToolButton.setIcon(self, QIcon(I('donate.png')))
self.setText('\xa0')
self.animation = QPropertyAnimation(self, b'icon_size', self)
self.animation.setDuration(60/72.*1000)
self.animation.setLoopCount(4)
self.animation.valueChanged.connect(self.value_changed)
self.setCursor(Qt.PointingHandCursor)
self.animation.finished.connect(self.animation_finished)
def animation_finished(self):
self.icon_size = self.iconSize().width()
def enterEvent(self, ev):
self.start_animation()
def leaveEvent(self, ev):
self.stop_animation()
def value_changed(self, val):
self.update()
def start_animation(self):
if config['disable_animations']:
return
if self.animation.state() != self.animation.Stopped or not self.isVisible():
return
size = self.iconSize().width()
smaller = int(0.7 * size)
self.animation.setStartValue(smaller)
self.animation.setEndValue(size)
QMetaObject.invokeMethod(self.animation, 'start', Qt.QueuedConnection)
def stop_animation(self):
self.animation.stop()
self.animation_finished()
def paintEvent(self, ev):
size = self._icon_size if self._icon_size > 10 else self.iconSize().width()
p = QPainter(self)
opt = QStyleOptionToolButton()
self.initStyleOption(opt)
s = self.style()
opt.iconSize = QSize(size, size)
s.drawComplexControl(s.CC_ToolButton, opt, p, self)
if __name__ == '__main__':
from PyQt5.Qt import QApplication, QHBoxLayout
app = QApplication([])
w = QWidget()
w.setLayout(QHBoxLayout())
b = ThrobbingButton()
b.setIcon(QIcon(I('donate.png')))
w.layout().addWidget(b)
w.show()
b.set_normal_icon_size(64, 64)
b.start_animation()
app.exec_()
|
$(document).ready(function(){
//Set opacity on each span to 0%
$(".rollover").css({'opacity':'0'});
$(".rollover-zoom").css({'opacity':'0'});
$(".rollover-list").css({'opacity':'0'});
$('ul a').hover(
function() {
$(this).find('.rollover').stop().fadeTo(500, 1);
$(this).find('.rollover-zoom').stop().fadeTo(500, 1);
$(this).find('.rollover-list').stop().fadeTo(500, 1);
},
function() {
$(this).find('.rollover').stop().fadeTo(500, 0);
$(this).find('.rollover-zoom').stop().fadeTo(500, 0);
$(this).find('.rollover-list').stop().fadeTo(500, 0);
}
)
});
|
/*
* Seven Kingdoms: Ancient Adversaries
*
* Copyright 1997,1998 Enlight Software Ltd.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
//Filename : MISC.H
//Description : Header file for MISC function object
#ifndef __MISC_H
#define __MISC_H
#include <stdint.h>
//-------- Define macro constant ---------//
#define LINE_FEED 0xA // Line feed ascii code
#define RETURN 0xD
//-----------------------------------------//
class Misc
{
public:
enum { STR_BUF_LEN = 120 };
char str_buf[STR_BUF_LEN+1];
char freeze_seed;
int32_t random_seed;
public:
Misc();
int str_cut(char*,const char*,int,int=-1);
int str_chr(const char*,char,int=1,int=-1);
int str_str(const char*,const char*,int=1,int=-1);
int str_cmp(const char*,const char*);
int str_cmpx(const char*,const char*);
int str_icmpx(const char*,const char*);
void str_shorten(char*,const char*,int);
int upper(int);
int lower(int);
int rtrim_len(char*,int=1,int=-1);
int ltrim_len(char*,int=1,int=-1);
void rtrim(char*,char*);
void ltrim(char*,char*);
void alltrim(char*,char*);
char* rtrim(char*);
char* ltrim(char*);
char* alltrim(char*);
char* nullify(char*,int);
void rtrim_fld(char*,char*,int);
int atoi(char*,int);
void empty(char*,int);
int is_empty(char*,int=0);
int valid_char(char);
void fix_str(char*,int,char=0);
int check_sum(char*,int=-1);
char* format(double,int=1);
char* format_percent(double);
char* format(int,int=1);
char* format(short a,int b=1) { return format((int)a, b); }
char* format(long a,int b=1) { return format((int)a, b); }
char* num_th(int);
char* num_to_str(int);
char* roman_number(int);
int get_key();
int key_pressed();
int is_touch(int,int,int,int,int,int,int,int);
int sqrt(long);
int diagonal_distance(int,int,int,int);
int points_distance(int,int,int,int);
float round(float,int,int=0);
float round_dec(float);
void delay(float wait);
unsigned long get_time();
void randomize();
void set_random_seed(long);
long get_random_seed();
int rand();
int random(int);
int is_file_exist(const char*);
int path_cat(char *dest, const char *src1, const char *src2, int max_len);
int mkpath(char *abs_path);
void change_file_ext(char*,const char*,const char*);
void extract_file_name(char*,const char*);
void put_text_scr(char*);
void del_array_rec(void* arrayBody, int arraySize, int recSize, int delRecno);
void cal_move_around_a_point(short num, short width, short height, int& xShift, int& yShift);
void cal_move_around_a_point_v2(short num, short width, short height, int& xShift, int& yShift);
void set_surround_bit(long int& flag, int bitNo);
void lock_seed();
void unlock_seed();
int is_seed_locked();
private:
void construct_move_around_table();
};
extern Misc misc, misc2; // two instance for separate random_seed
//---------- End of define class ---------------//
//--------- Begin of inline function Misc::is_touch ------------//
//
// Check if the given two area touch each other
//
// Return : 1 or 0
//
inline int Misc::is_touch(int x1, int y1, int x2, int y2, int a1, int b1, int a2, int b2 )
{
return (( b1 <= y1 && b2 >= y1 ) ||
( y1 <= b1 && y2 >= b1 )) &&
(( a1 <= x1 && a2 >= x1 ) ||
( x1 <= a1 && x2 >= a1 ));
}
//--------- End of inline function Misc::is_touch -----------//
#endif
|
package co.navdeep.popmovies.tmdb.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ProductionCountry {
@SerializedName("iso_3166_1")
@Expose
private String iso31661;
@SerializedName("name")
@Expose
private String name;
/**
*
* @return
* The iso31661
*/
public String getIso31661() {
return iso31661;
}
/**
*
* @param iso31661
* The iso_3166_1
*/
public void setIso31661(String iso31661) {
this.iso31661 = iso31661;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
}
|
"""
Tests for transformers.py
"""
from mock import MagicMock, patch
from nose.plugins.attrib import attr
from unittest import TestCase
from ..block_structure import BlockStructureModulestoreData
from ..exceptions import TransformerException
from ..transformers import BlockStructureTransformers
from .helpers import (
ChildrenMapTestMixin, MockTransformer, mock_registered_transformers
)
@attr('shard_2')
class TestBlockStructureTransformers(ChildrenMapTestMixin, TestCase):
"""
Test class for testing BlockStructureTransformers
"""
class UnregisteredTransformer(MockTransformer):
"""
Mock transformer that is not registered.
"""
pass
def setUp(self):
super(TestBlockStructureTransformers, self).setUp()
self.transformers = BlockStructureTransformers(usage_info=MagicMock())
self.registered_transformers = [MockTransformer]
def add_mock_transformer(self):
"""
Adds the registered transformers to the self.transformers collection.
"""
with mock_registered_transformers(self.registered_transformers):
self.transformers += self.registered_transformers
def test_add_registered(self):
self.add_mock_transformer()
self.assertIn(MockTransformer, self.transformers._transformers) # pylint: disable=protected-access
def test_add_unregistered(self):
with self.assertRaises(TransformerException):
self.transformers += [self.UnregisteredTransformer]
self.assertEquals(self.transformers._transformers, []) # pylint: disable=protected-access
def test_collect(self):
with mock_registered_transformers(self.registered_transformers):
with patch(
'openedx.core.lib.block_structure.tests.helpers.MockTransformer.collect'
) as mock_collect_call:
self.transformers.collect(block_structure=MagicMock())
self.assertTrue(mock_collect_call.called)
def test_transform(self):
self.add_mock_transformer()
with patch(
'openedx.core.lib.block_structure.tests.helpers.MockTransformer.transform'
) as mock_transform_call:
self.transformers.transform(block_structure=MagicMock())
self.assertTrue(mock_transform_call.called)
def test_is_collected_outdated(self):
block_structure = self.create_block_structure(
self.SIMPLE_CHILDREN_MAP,
BlockStructureModulestoreData
)
with mock_registered_transformers(self.registered_transformers):
self.assertTrue(self.transformers.is_collected_outdated(block_structure))
self.transformers.collect(block_structure)
self.assertFalse(self.transformers.is_collected_outdated(block_structure))
|
# Yahoo (News)
#
# @website https://news.yahoo.com
# @provide-api yes (https://developer.yahoo.com/boss/search/)
# $0.80/1000 queries
#
# @using-api no (because pricing)
# @results HTML (using search portal)
# @stable no (HTML can change)
# @parse url, title, content, publishedDate
import re
from datetime import datetime, timedelta
from lxml import html
from searx.engines.xpath import extract_text, extract_url
from searx.engines.yahoo import parse_url, _fetch_supported_languages, supported_languages_url
from dateutil import parser
from searx.url_utils import urlencode
# engine dependent config
categories = ['news']
paging = True
language_support = True
# search-url
search_url = 'https://news.search.yahoo.com/search?{query}&b={offset}&{lang}=uh3_news_web_gs_1&pz=10&xargs=0&vl=lang_{lang}' # noqa
# specific xpath variables
results_xpath = '//ol[contains(@class,"searchCenterMiddle")]//li'
url_xpath = './/h3/a/@href'
title_xpath = './/h3/a'
content_xpath = './/div[@class="compText"]'
publishedDate_xpath = './/span[contains(@class,"tri")]'
suggestion_xpath = '//div[contains(@class,"VerALSOTRY")]//a'
# do search-request
def request(query, params):
offset = (params['pageno'] - 1) * 10 + 1
language = params['language'].split('-')[0]
params['url'] = search_url.format(offset=offset,
query=urlencode({'p': query}),
lang=language)
# TODO required?
params['cookies']['sB'] = '"v=1&vm=p&fl=1&vl=lang_{lang}&sh=1&pn=10&rw=new'\
.format(lang=language)
return params
def sanitize_url(url):
if ".yahoo.com/" in url:
return re.sub(u"\\;\\_ylt\\=.+$", "", url)
else:
return url
# get response from search-request
def response(resp):
results = []
dom = html.fromstring(resp.text)
# parse results
for result in dom.xpath(results_xpath):
urls = result.xpath(url_xpath)
if len(urls) != 1:
continue
url = sanitize_url(parse_url(extract_url(urls, search_url)))
title = extract_text(result.xpath(title_xpath)[0])
content = extract_text(result.xpath(content_xpath)[0])
# parse publishedDate
publishedDate = extract_text(result.xpath(publishedDate_xpath)[0])
# still useful ?
if re.match("^[0-9]+ minute(s|) ago$", publishedDate):
publishedDate = datetime.now() - timedelta(minutes=int(re.match(r'\d+', publishedDate).group()))
elif re.match("^[0-9]+ days? ago$", publishedDate):
publishedDate = datetime.now() - timedelta(days=int(re.match(r'\d+', publishedDate).group()))
elif re.match("^[0-9]+ hour(s|), [0-9]+ minute(s|) ago$", publishedDate):
timeNumbers = re.findall(r'\d+', publishedDate)
publishedDate = datetime.now()\
- timedelta(hours=int(timeNumbers[0]))\
- timedelta(minutes=int(timeNumbers[1]))
else:
try:
publishedDate = parser.parse(publishedDate)
except:
publishedDate = datetime.now()
if publishedDate.year == 1900:
publishedDate = publishedDate.replace(year=datetime.now().year)
# append result
results.append({'url': url,
'title': title,
'content': content,
'publishedDate': publishedDate})
# return results
return results
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import re
import subprocess
import sys
from telemetry.core.backends import adb_commands
from telemetry.core.platform import device
from telemetry.core.platform.profiler import monsoon
from telemetry.core import util
class AndroidDevice(device.Device):
""" Class represents information for connecting to an android device.
Attributes:
device_id: the device's serial string created by adb to uniquely
identify an emulator/device instance. This string can be found by running
'adb devices' command
enable_performance_mode: when this is set to True, android platform will be
set to high performance mode after browser is started.
"""
def __init__(self, device_id, enable_performance_mode=True):
super(AndroidDevice, self).__init__(
name='Android device %s' % device_id, guid=device_id)
self._device_id = device_id
self._enable_performance_mode = enable_performance_mode
@classmethod
def GetAllConnectedDevices(cls):
device_serials = GetDeviceSerials()
return [cls(s) for s in device_serials]
@property
def device_id(self):
return self._device_id
@property
def enable_performance_mode(self):
return self._enable_performance_mode
def GetDeviceSerials():
device_serials = adb_commands.GetAttachedDevices()
# The monsoon provides power for the device, so for devices with no
# real battery, we need to turn them on after the monsoon enables voltage
# output to the device.
if not device_serials:
try:
m = monsoon.Monsoon(wait=False)
m.SetUsbPassthrough(1)
m.SetVoltage(3.8)
m.SetMaxCurrent(8)
logging.warn("""
Monsoon power monitor detected, but no Android devices.
The Monsoon's power output has been enabled. Please now ensure that:
1. The Monsoon's front and back USB are connected to the host.
2. The device is connected to the Monsoon's main and USB channels.
3. The device is turned on.
Waiting for device...
""")
util.WaitFor(adb_commands.GetAttachedDevices, 600)
device_serials = adb_commands.GetAttachedDevices()
except IOError:
return []
return device_serials
def GetDevice(finder_options):
"""Return a Platform instance for the device specified by |finder_options|."""
if not CanDiscoverDevices():
logging.info(
'No adb command found. Will not try searching for Android browsers.')
return None
if finder_options.device and finder_options.device in GetDeviceSerials():
return AndroidDevice(
finder_options.device,
enable_performance_mode=not finder_options.no_performance_mode)
devices = AndroidDevice.GetAllConnectedDevices()
if len(devices) == 0:
logging.info('No android devices found.')
return None
if len(devices) > 1:
logging.warn(
'Multiple devices attached. Please specify one of the following:\n' +
'\n'.join([' --device=%s' % d.device_id for d in devices]))
return None
return devices[0]
def CanDiscoverDevices():
"""Returns true if devices are discoverable via adb."""
if not adb_commands.IsAndroidSupported():
logging.info(
'Android build commands unavailable on this machine. '
'Have you installed Android build dependencies?')
return False
try:
with open(os.devnull, 'w') as devnull:
adb_process = subprocess.Popen(
['adb', 'devices'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=devnull)
stdout = adb_process.communicate()[0]
if re.search(re.escape('????????????\tno permissions'), stdout) != None:
logging.warn('adb devices gave a permissions error. '
'Consider running adb as root:')
logging.warn(' adb kill-server')
logging.warn(' sudo `which adb` devices\n\n')
return True
except OSError:
pass
chromium_adb_path = os.path.join(
util.GetChromiumSrcDir(), 'third_party', 'android_tools', 'sdk',
'platform-tools', 'adb')
if sys.platform.startswith('linux') and os.path.exists(chromium_adb_path):
os.environ['PATH'] = os.pathsep.join(
[os.path.dirname(chromium_adb_path), os.environ['PATH']])
return True
return False
def FindAllAvailableDevices(_):
"""Returns a list of available devices.
"""
if not CanDiscoverDevices():
return []
else:
return AndroidDevice.GetAllConnectedDevices()
|
module.exports = ['$scope', '$rootScope', '$location', '$window', 'db', home];
function home($scope, $rootScope, $location, $window, db) {
'use strict';
db.fetchAll(function (err, schema) {
if (err) {
console.error(err);
return;
}
$scope.matches = schema.matches;
$scope.$apply();
});
}
|
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015, 2016 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/>.
import os
import subprocess
from . import errors
from ._base import Base
class Git(Base):
def __init__(self, source, source_dir, source_tag=None, source_commit=None,
source_branch=None, source_depth=None):
super().__init__(source, source_dir, source_tag, source_commit,
source_branch, source_depth, 'git')
if source_tag and source_branch:
raise errors.IncompatibleOptionsError(
'can\'t specify both source-tag and source-branch for '
'a git source')
if source_tag and source_commit:
raise errors.IncompatibleOptionsError(
'can\'t specify both source-tag and source-commit for '
'a git source')
if source_branch and source_commit:
raise errors.IncompatibleOptionsError(
'can\'t specify both source-branch and source-commit for '
'a git source')
def pull(self):
if os.path.exists(os.path.join(self.source_dir, '.git')):
refspec = 'HEAD'
if self.source_branch:
refspec = 'refs/heads/' + self.source_branch
elif self.source_tag:
refspec = 'refs/tags/' + self.source_tag
elif self.source_commit:
refspec = self.source_commit
# Pull changes to this repository and any submodules.
subprocess.check_call([self.command, '-C', self.source_dir,
'pull', '--recurse-submodules=yes',
self.source, refspec])
# Merge any updates for the submodules (if any).
subprocess.check_call([self.command, '-C', self.source_dir,
'submodule', 'update'])
else:
command = [self.command, 'clone', '--recursive']
if self.source_tag or self.source_branch:
command.extend([
'--branch', self.source_tag or self.source_branch])
if self.source_depth:
command.extend(['--depth', str(self.source_depth)])
subprocess.check_call(command + [self.source, self.source_dir])
if self.source_commit:
subprocess.check_call([self.command, '-C', self.source_dir,
'checkout', self.source_commit])
|
/* eslint */
/* global element, by */
/**
* This class is represents a Fees Centers Distributions page in term of structure and
* behaviour so it is a Distribution page object
*/
const GU = require('../shared/GridUtils');
const FU = require('../shared/FormUtils');
const GridRow = require('../shared/GridRow');
const components = require('../shared/components');
const gridId = 'allocation-center-grid';
class DistributionPage {
constructor() {
this.gridId = 'allocation-center-grid';
this.rubricGrid = element(by.id(this.gridId));
this.actionLinkColumn = 9;
this.actionLinkUpdateColumn = 10;
}
async setDistributionPercentage(dataset) {
await components.fiscalPeriodSelect.set(dataset.fiscal_id, dataset.periodFrom_id, dataset.periodTo_id);
if (dataset.profitCenter) {
await element(by.id('is_profit')).click();
}
await FU.buttons.submit();
await GU.selectRow(gridId, 0);
await element(by.css('[data-action="open-menu"]')).click();
await element(by.css('[data-method="breakdown-percentages"]')).click();
// Prevent initialization of allocation keys greater than 100 percent
await components.percentageInput.set(40, 'principal_1');
await components.percentageInput.set(100, 'principal_2');
await components.percentageInput.set(13, 'principal_3');
await FU.buttons.submit();
await FU.exists(by.id('validation-error'), true);
// Prevent initialization of allocation keys less than 100 percent
await components.percentageInput.set(1, 'principal_1');
await components.percentageInput.set(2, 'principal_2');
await components.percentageInput.set(3, 'principal_3');
await FU.buttons.submit();
await FU.exists(by.id('validation-error'), true);
await components.percentageInput.set(50, 'principal_1');
await components.percentageInput.set(35, 'principal_2');
await components.percentageInput.set(15, 'principal_3');
await FU.buttons.submit();
await components.notification.hasSuccess();
}
async setDistributionAutomatic() {
await GU.selectRow(gridId, 0);
await element(by.css('[data-action="open-menu"]')).click();
await element(by.css('[data-method="automatic-breakdown"]')).click();
await components.notification.hasSuccess();
}
async setDistributionManual(dataset) {
await element(by.css('[data-method="setting"]')).click();
await components.fiscalPeriodSelect.set(dataset.fiscal_id, dataset.periodFrom_id, dataset.periodTo_id);
if (!dataset.profitCenter) {
await element(by.id('is_cost')).click();
}
await FU.buttons.submit();
// get the grid row
const row = new GridRow(dataset.trans_id);
await row.dropdown().click();
await row.method('allocation').click();
await components.currencyInput.set(1000, 'principal_1');
await components.currencyInput.set(145, 'principal_2');
await components.currencyInput.set(76, 'principal_3');
await FU.buttons.submit();
await FU.exists(by.id('validation-error'), true);
await components.percentageInput.set(1, 'principal_1');
await components.percentageInput.set(2, 'principal_2');
await components.percentageInput.set(3, 'principal_3');
await FU.buttons.submit();
await FU.exists(by.id('validation-error'), true);
await components.percentageInput.set(100.62, 'principal_1');
await components.percentageInput.set(78, 'principal_2');
await components.percentageInput.set(78, 'principal_3');
await FU.buttons.submit();
await components.notification.hasSuccess();
}
async setUpdatedDistribution(dataset) {
await components.fiscalPeriodSelect.set(dataset.fiscal_id, dataset.periodFrom_id, dataset.periodTo_id);
if (dataset.costCenter) {
await element(by.id('is_cost')).click();
}
await FU.buttons.submit();
const row = new GridRow(dataset.trans_id);
await row.dropdown().click();
await row.edit().click();
await components.currencyInput.set(1000, 'principal_1');
await components.currencyInput.set(100, 'principal_2');
await components.currencyInput.set(500, 'principal_3');
await FU.buttons.submit();
await FU.exists(by.id('validation-error'), true);
await components.percentageInput.set(1, 'principal_1');
await components.percentageInput.set(2, 'principal_2');
await components.percentageInput.set(3, 'principal_3');
await FU.buttons.submit();
await FU.exists(by.id('validation-error'), true);
await components.percentageInput.set(92, 'principal_1');
await components.percentageInput.set(88.6, 'principal_2');
await components.percentageInput.set(76.02, 'principal_3');
await FU.buttons.submit();
await components.notification.hasSuccess();
}
}
module.exports = DistributionPage;
|
from cygnet_adapter.adapter.api.cygnusApi import CygnusAPI
import unittest
from random import randint
class mockClusterState(object):
def __init__(self):
self.containers = dict()
def addContainer(self, containerId):
self.containers[containerId] = 1
def stopContainer(self, containerId):
self.containers[containerId] = 0
def updateContainer(self, containerId, field, value):
if field == 'State':
self.containers[containerId] = value
class mockClient(object):
def __init__(self):
self.cluster_state = mockClusterState()
class CygnusApiTest(unittest.TestCase):
def setUp(self):
CygnusAPI.client = mockClient()
self.api = CygnusAPI()
self.containers = []
self.dummy_req = dict()
self.dummy_req['ClientRequest'] = dict()
self.dummy_req['ClientRequest']['Request'] = None
self.dummy_req['ClientRequest']['Method'] = 'POST'
self.dummy_req['ServerResponse'] = 'dummy'
def tearDown(self):
del self.api
def mock_createContainer(self, *args):
randid = str(args[0])
self.containers.append(randid)
self.api.client.cluster_state.addContainer(randid)
def mock_stopContainer(self, *args):
self.api.client.cluster_state.stopContainer(str(args[0]))
def mock_startContainer(self, *args):
if type(args[0]) is dict:
self.api.client.cluster_state.updateContainer(int(args[0]['ClientRequest']['Request'].split('/')[3]), 'State', 1)
return
self.api.client.cluster_state.updateContainer(args[0],'State',1)
def test_getResponse(self):
reqs = [
'/version/containers/create',
'/version/containers/alterme/stop',
'/version/containers/alterme/start'
]
self.api.createContainer = self.mock_createContainer
self.api.stopContainer = self.mock_stopContainer
self.api.startContainer = self.mock_startContainer
conts = ['1','2','3','4']
## Create
for cont in conts:
self.api.createContainer(cont)
for cont in self.api.client.cluster_state.containers.values():
self.assertEquals(cont,1)
for cont in conts:
self.api.stopContainer(cont)
for cont in self.api.client.cluster_state.containers.values():
self.assertEquals(cont, 0)
for cont in conts:
self.api.startContainer(cont)
for cont in self.api.client.cluster_state.containers.values():
self.assertEquals(cont, 1)
for cont in conts:
self.dummy_req['ClientRequest']['Request'] = (reqs[randint(0,2)]).replace('alterme',cont)
self.api.getResponse(self.dummy_req,'foo')
def test_getEndpoint(self):
req = '/'
for i in range(0,randint(3,4)):
for i in range(0,randint(1,10)):
randnum = chr(randint(48,57))
randlow = chr(randint(97,122))
randup = chr(randint(65,90))
randarr = [randnum,randlow,randup]
req = req + randarr[randint(0,2)]
req = req + '/'
## erase the most right slash
req = req[:len(req)-1]
ep = self.api.getEndpoint(req)
req = req[1:]
req_dis = req.split("/")
if len(req_dis) == 4:
self.assertIsInstance(ep, tuple)
self.assertEquals(ep[0], req_dis[-1])
self.assertEquals(ep[1], req_dis[-2])
elif len(req_dis) == 3:
self.assertIsInstance(ep, tuple)
self.assertEquals(ep[0], req_dis[-1])
self.assertEquals(ep[1],'')
if __name__ == "__main__":
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.