text
stringlengths 27
775k
|
|---|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'booting' do
it 'can boot gisAssembly' do
expect(Robots::DorRepo::GisAssembly.is_a? Module).to be_truthy
end
it 'can boot gisDelivery' do
expect(Robots::DorRepo::GisDelivery.is_a? Module).to be_truthy
end
it 'can boot gisDiscovery' do
expect(Robots::DorRepo::GisDiscovery.is_a? Module).to be_truthy
end
end
|
import jwt
from django.conf import settings
from rest_framework import authentication, exceptions
from questioner.apps.user.models import User
class JWTAuthentication(authentication.BaseAuthentication):
"""
This class handles authentication of the user.
"""
def authenticate(self, request):
"""This method authenticates the Authorization header
GIVEN:
request (Request object): Django Request context
RETURN:
None: Failed Authentication
(user, token): Successful Authentication.
"""
auth_header = authentication.get_authorization_header(request).split()
if not auth_header:
return None
if len(auth_header) < 2:
msg = 'Invalid authorization header'
raise exceptions.AuthenticationFailed(msg)
prefix = auth_header[0].decode('utf-8')
token = auth_header[1].decode('utf-8')
if prefix != 'Bearer':
msg = 'Use a Bearer Token'
raise exceptions.AuthenticationFailed(msg)
return self.authenticate_token(request, token)
def authenticate_token(self, request, token):
"""This method authenticates the given token
GIVEN:
request (Request object): Django Request context
token (str): JSON Web Token
RETURN:
None: Failed Authentication
(user, token): Successful Authentication.
"""
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms='HS256', verify=True)
except jwt.InvalidTokenError:
msg = 'Invalid token. Token decode failed'
raise exceptions.AuthenticationFailed(msg)
except jwt.ExpiredSignatureError:
msg = 'Token expired, please re-authenticate.'
raise exceptions.AuthenticationFailed(msg)
email = payload['user_data']['email']
username = payload['user_data']['username']
try:
user = User.objects.get(email=email, username=username)
except User.DoesNotExist:
msg = 'No user matching this token'
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = "User has been deactivated"
raise exceptions.AuthenticationFailed(msg)
return (user, token)
|
# frozen_string_literal: true
require 'spec_helper'
describe 'Seller Dashboard', type: :feature do
include Warden::Test::Helpers
context 'when logged as seller user' do
let(:user) { create(:seller_user, seller: seller) }
before do
login_as user
end
context 'when the seller is in pending' do
let(:seller) { create(:pending_seller, action_url: 'https://example.com/onboarding') }
it 'shows the button to link the PayPal account' do
visit spree.admin_sellers_dashboard_path
expect(page).to have_link(I18n.t('spree.seller.link_paypal_account'))
expect(page).not_to have_link(I18n.t('spree.admin.tab.offers'))
end
end
context 'when the seller is accepted' do
let(:seller) { create(:seller) }
it 'shows the accepted message' do
visit spree.admin_sellers_dashboard_path
expect(page).to have_content('Accepted')
expect(page).to have_link(I18n.t('spree.admin.tab.offers'))
end
end
end
end
|
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- |
module VK.API.Routable where
import Control.Monad.IO.Class (MonadIO)
import Network.API.Builder
import Network.API.Builder.Queryable
class (Queryable q, Receivable a) => Routable q a | q -> a where
toRoute :: q -> Route
toAPI :: (MonadIO m, ErrorReceivable e) => q -> APIT s e m a
toAPI = runRoute . toRoute
|
# `{% hook %}` タグ
このタグは、テンプレート内でプラグインやモジュールに追加の HTML を返すか、利用可能なテンプレート変数を変更する機会を与えます。
```twig
{# Give plugins a chance to make changes here #}
{% hook 'my-custom-hook-name' %}
```
プラグインやモジュールが `{% hook %}` タグで作動できる詳細については、[テンプレートフック](../../extend/template-hooks.md)を参照してください。
|
fn part1(l: &str, len: usize) -> usize {
let mut r = aoc::Rope::new(len);
for pos in aoc::uints::<usize>(l) {
r.twist(pos);
}
r.product()
}
#[test]
fn part1_works() {
assert_eq!(part1("3,4,1,5", 5), 12);
}
fn part2(l: &str) -> String {
let r = aoc::Rope::new_twisted(256, l);
r.dense_hash()
}
fn main() {
let inp = aoc::read_input_line();
aoc::benchme(|bench: bool| {
let p1 = part1(&inp, 256);
let p2 = part2(&inp);
if !bench {
println!("Part 1: {}", p1);
println!("Part 2: {}", p2);
}
});
}
#[test]
fn part2_works() {
for tc in &[
("", "a2582a3a0e66e6e86e3812dcb672a272"),
("AoC 2017", "33efeb34ea91902bb2f59c9920caa6cd"),
("1,2,3", "3efbe78a8d82f29979031a4aa0b16a9d"),
("1,2,4", "63960835bcdc130f0b66d7ff4f6a5a8e"),
] {
assert_eq!(part2(tc.0), tc.1, "{}", tc.0);
}
}
|
# Playing with Firefox background scripts
1. about:debugging - load temporary addon
2. click "debug"
3. click "console"
4. disable most things apart from logging
5. have fun
# Playing with content scripts
1. about:debugging
2. dunno the rest
# Experimental WebExtension API addons
1. complicated, but Colin knows a bit.
# Compiling CoffeeScript
coffee -c script.coffee
|
package ezstack
import (
"github.com/function61/hautomo/pkg/ezstack/zcl/cluster"
"github.com/function61/hautomo/pkg/ezstack/zigbee"
)
/* TODO: has source NwkAddr confused with destination NwkAddr
// "Zigbee has support for binding which makes it possible that devices can directly control each
// other without the intervention of Zigbee2MQTT or any home automation software."
// https://www.zigbee2mqtt.io/information/binding.html
func (s *Stack) Bind(
sourceAddress zigbee.IEEEAddress,
sourceEndpoint zigbee.EndpointId,
clusterId cluster.ClusterId,
destinationIeeeAddress zigbee.IEEEAddress,
destinationEndpoint zigbee.EndpointId,
) (*znp.ZdoBindRsp, error) {
dev, found := s.db.GetDevice(sourceAddress)
if !found {
return nil, fmt.Errorf("device not found: %s", sourceAddress)
}
return s.coordinator.Bind(
dev.NetworkAddress,
sourceAddress,
sourceEndpoint,
clusterId,
destinationIeeeAddress,
destinationEndpoint)
}
*/
func (s *Stack) BindToCoordinator(
sourceAddress zigbee.IEEEAddress,
sourceEndpoint zigbee.EndpointId,
clusterId cluster.ClusterId,
coordinatorEndpoint zigbee.EndpointId,
) error {
resp, err := s.coordinator.Bind(
zigbee.CoordinatorNwkAddr,
sourceAddress,
sourceEndpoint,
clusterId,
s.coordinator.NetworkConf().IEEEAddress,
coordinatorEndpoint)
if err != nil {
return err
}
return resp.Status.Error()
}
/* TODO: has source NwkAddr confused with destination NwkAddr
// undoes the effect of Bind()
func (s *Stack) Unbind(
sourceAddress zigbee.IEEEAddress,
sourceEndpoint zigbee.EndpointId,
clusterId cluster.ClusterId,
destinationIeeeAddress zigbee.IEEEAddress,
destinationEndpoint zigbee.EndpointId,
) (*znp.ZdoUnbindRsp, error) {
dev, found := s.db.GetDevice(sourceAddress)
if !found {
return nil, fmt.Errorf("device not found: %s", sourceAddress)
}
return s.coordinator.Unbind(
dev.NetworkAddress,
sourceAddress,
sourceEndpoint,
clusterId,
destinationIeeeAddress,
destinationEndpoint)
}
*/
|
import { LatinWordTokenizer } from './latin-word-tokenizer';
describe('LatinWordTokenizer', () => {
it('empty string', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('')).toEqual([]);
});
it('whitespace-only string', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize(' ')).toEqual([]);
});
it('word with punctuation at the end', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('This is a test, also.')).toEqual(['This', 'is', 'a', 'test', ',', 'also', '.']);
});
it('word with punctuation at the beginning', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('Is this a test? (yes)')).toEqual(['Is', 'this', 'a', 'test', '?', '(', 'yes', ')']);
});
it('word with internal punctuation', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize("This isn't a test.")).toEqual(['This', "isn't", 'a', 'test', '.']);
expect(tokenizer.tokenize('He had $5,000.')).toEqual(['He', 'had', '$', '5,000', '.']);
});
it('string with symbol', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('He had $50.')).toEqual(['He', 'had', '$', '50', '.']);
});
it('string with abbreviations', () => {
const tokenizer = new LatinWordTokenizer(['mr', 'dr', 'ms']);
expect(tokenizer.tokenize('Mr. Smith went to Washington.')).toEqual([
'Mr.',
'Smith',
'went',
'to',
'Washington',
'.',
]);
});
it('string with quotes', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('"This is a test."')).toEqual(['"', 'This', 'is', 'a', 'test', '.', '"']);
});
it('string with apostrophe not treated as single quote', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize("“Moses' cat said ‘Meow’ to the dog.”")).toEqual([
'“',
"Moses'",
'cat',
'said',
'‘',
'Meow',
'’',
'to',
'the',
'dog',
'.',
'”',
]);
expect(tokenizer.tokenize("i ha''on 'ot ano'.")).toEqual(['i', "ha''on", "'ot", "ano'", '.']);
});
it('string with apostrophe treated as single quote', () => {
const tokenizer = new LatinWordTokenizer();
tokenizer.treatApostropheAsSingleQuote = true;
expect(tokenizer.tokenize("'Moses's cat said 'Meow' to the dog.'")).toEqual([
"'",
"Moses's",
'cat',
'said',
"'",
'Meow',
"'",
'to',
'the',
'dog',
'.',
"'",
]);
});
it('string with slash', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('This is a test/trial.')).toEqual(['This', 'is', 'a', 'test', '/', 'trial', '.']);
});
it('string with angle bracket', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('This is a <<test>>.')).toEqual(['This', 'is', 'a', '<<', 'test', '>>', '.']);
});
it('string with a non-ASCII character', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('This is—a test.')).toEqual(['This', 'is', '—', 'a', 'test', '.']);
});
it('string with email address', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('This is an email address, name@test.com, in a sentence.')).toEqual([
'This',
'is',
'an',
'email',
'address',
',',
'name@test.com',
',',
'in',
'a',
'sentence',
'.',
]);
});
it('string with email address at end of sentence', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('Here is an email address: name@test.com.')).toEqual([
'Here',
'is',
'an',
'email',
'address',
':',
'name@test.com',
'.',
]);
});
it('string with URL', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('This is an email address, http://www.test.com/page.html, in a sentence.')).toEqual([
'This',
'is',
'an',
'email',
'address',
',',
'http://www.test.com/page.html',
',',
'in',
'a',
'sentence',
'.',
]);
});
it('string with URL at end of sentence', () => {
const tokenizer = new LatinWordTokenizer();
expect(tokenizer.tokenize('Here is a url: http://www.test.com/page.html?param=1.')).toEqual([
'Here',
'is',
'a',
'url',
':',
'http://www.test.com/page.html?param=1',
'.',
]);
});
});
|
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
name VARCHAR(250),
description VARCHAR(500),
create_date TIMESTAMP
);
CREATE TABLE IF NOT EXISTS comments (
id serial PRIMARY KEY,
task_id INT NOT NULL REFERENCES tasks(id),
comment text
);
|
import { Listenable } from '../api';
export interface Listener<T> {
(prop: Listenable<T>, oldVal: T | undefined, newVal: T): void;
}
|
package inject.log4j.redis.rest.utils;
public interface TimeProvider {
long currentTimeMillis();
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace src.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class FibonacciController : ControllerBase
{
private readonly ILogger<FibonacciController> _logger;
public FibonacciController(ILogger<FibonacciController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<int> Get(int len)
{
var sequence = new List<int>();
int a = 0, b = 1, c = 0;
for (int i = 2; i < len; i++)
{
c= a + b;
sequence.Add(c);
a= b;
b= c;
}
return sequence;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MineCase.Protocol.Handshaking;
namespace MineCase.Client.Network.Handshaking
{
public interface IHandshakingPacketGenerator
{
Task Handshake(uint protocolVersion, string serverAddress, ushort serverPort, uint nextState);
}
internal class HandshakingHandler : IHandshakingPacketGenerator
{
private readonly IPacketSink _packetSink;
private readonly IPacketRouter _packetRouter;
public HandshakingHandler(IPacketSink packetSink, IPacketRouter packetRouter)
{
_packetSink = packetSink;
_packetRouter = packetRouter;
}
async Task IHandshakingPacketGenerator.Handshake(uint protocolVersion, string serverAddress, ushort serverPort, uint nextState)
{
if (nextState != 1 && nextState != 2) throw new ArgumentOutOfRangeException(nameof(nextState));
await _packetSink.SendPacket(new Handshake
{
ProtocolVersion = protocolVersion,
ServerAddress = serverAddress,
ServerPort = serverPort,
NextState = nextState
});
_packetRouter.State = nextState == 1 ? SessionState.Status : SessionState.Login;
}
}
}
|
module Day19 where
import Advent.Intcode
import Advent.Input
import qualified Data.List as L
import qualified Data.Set as S
isPulled program x y = o == 1
where
Halt [o] = run program [x,y]
closestSquare program x y =
case (isP (x,y), isP (x+99,y-99)) of
(False, _) -> go (x+1) y
(True, False) -> go x (y+1)
(True, True) -> (x, y-99)
where
isP (x,y) = isPulled program x y
go = closestSquare program
partOne :: State -> Int
partOne program =
length $
[ (x,y) | x <- [0..49], y <- [0..49], isPulled program x y ]
partTwo :: State -> Int
partTwo program = 10000 * x + y
where (x, y) = closestSquare program 0 100
main :: IO ()
main = do
Right program <- fmap (parse pProgram) $ readDay 19
putStrLn $ "Part One: " ++ (show $ partOne program)
putStrLn $ "Part Two: " ++ (show $ partTwo program)
|
import logging
import unittest
import collections
from yarabuilder.yararule import (
YaraRule,
YaraCondition,
YaraTags,
YaraImports,
YaraString,
YaraStrings,
YaraMeta,
YaraMetaEntry,
YaraComment,
YaraCommentEnabledClass,
)
class TestYaraComment(unittest.TestCase):
def setUp(self):
self.test_yara_comment = YaraComment()
def test_yara_comment_init(self):
self.assertFalse(self.test_yara_comment.above)
self.assertIsNone(self.test_yara_comment.inline)
self.assertFalse(self.test_yara_comment.below)
def test_get_yara_comment(self):
self.test_yara_comment.above = "above_comment"
self.test_yara_comment.inline = "inline_comment"
self.test_yara_comment.below = "below_comment"
pod_yara_comment = self.test_yara_comment.get_yara_comment()
self.assertEqual(pod_yara_comment["above"], "above_comment")
self.assertEqual(pod_yara_comment["inline"], "inline_comment")
self.assertEqual(pod_yara_comment["below"], "below_comment")
def test_set_yara_comment(self):
self.test_yara_comment.set_yara_comment(
{"above": "test_above", "inline": "test_inline", "below": "test_below"}
)
self.assertEqual(self.test_yara_comment.above, "test_above")
self.assertEqual(self.test_yara_comment.inline, "test_inline")
self.assertEqual(self.test_yara_comment.below, "test_below")
class TestYaraCommentEnabledClass(unittest.TestCase):
def setUp(self):
self.test_yara_comment_enabled_class = YaraCommentEnabledClass()
self.raw = ""
def test_yara_comment_enabled_class_init(self):
self.assertIsInstance(
self.test_yara_comment_enabled_class.yara_comment, YaraComment
)
def test_add_comment(self):
self.test_yara_comment_enabled_class.add_comment("test1")
self.assertEqual(
self.test_yara_comment_enabled_class.yara_comment.inline, "test1"
)
self.test_yara_comment_enabled_class.add_comment("test2", position="above")
self.assertEqual(
self.test_yara_comment_enabled_class.yara_comment.above, ["test2"]
)
self.test_yara_comment_enabled_class.add_comment("test3", position="below")
self.assertEqual(
self.test_yara_comment_enabled_class.yara_comment.below, ["test3"]
)
def test_add_multiple_comments(self):
self.test_yara_comment_enabled_class.add_comment("test1", position="above")
self.test_yara_comment_enabled_class.add_comment("test2", position="above")
self.assertEqual(
self.test_yara_comment_enabled_class.yara_comment.above, ["test1", "test2"]
)
def test_build_comment_above(self):
self.test_yara_comment_enabled_class.add_comment("test", position="above")
self.raw = self.test_yara_comment_enabled_class.build_comments(self.raw)
self.assertEqual(self.raw, "// test\n ")
def test_build_comment_inline(self):
self.test_yara_comment_enabled_class.add_comment("test", position="inline")
self.raw = self.test_yara_comment_enabled_class.build_comments(self.raw)
self.assertEqual(self.raw, " // test")
def test_build_comment_below(self):
self.test_yara_comment_enabled_class.add_comment("test", position="below")
self.raw = self.test_yara_comment_enabled_class.build_comments(self.raw)
self.assertEqual(self.raw, "\n // test")
def test_build_multiple_above_comments(self):
self.test_yara_comment_enabled_class.add_comment("test1", position="above")
self.test_yara_comment_enabled_class.add_comment("test2", position="above")
self.raw = self.test_yara_comment_enabled_class.build_comments(self.raw)
self.assertEqual(self.raw, "// test1\n // test2\n ")
def test_build_multiple_below_comments(self):
self.test_yara_comment_enabled_class.add_comment("test1", position="below")
self.test_yara_comment_enabled_class.add_comment("test2", position="below")
self.raw = self.test_yara_comment_enabled_class.build_comments(self.raw)
self.assertEqual(self.raw, "\n // test1\n // test2")
class TestYaraRule(unittest.TestCase):
def setUp(self):
self.test_rule_name = "test_rule"
self.test_condition = "filesize > 0"
self.yara_rule = YaraRule(self.test_rule_name)
self.raw_rule = ""
def test_yara_rule_init(self):
self.assertEqual(self.test_rule_name, self.yara_rule.rule_name)
self.assertEqual(" ", self.yara_rule.whitespace)
def test_yara_rule_init_custom_logger(self):
logger = logging.getLogger("test")
yara_rule = YaraRule(self.test_rule_name, logger=logger)
self.assertEqual(yara_rule.logger, logger)
def test_build_rule_no_condition(self):
self.assertRaises(KeyError, self.yara_rule.build_rule)
def test_build_rule_header(self):
self.yara_rule.condition.add_raw_condition(self.test_condition)
self.raw_rule = self.yara_rule.build_rule_header(self.raw_rule)
self.assertEqual(self.raw_rule, "rule %s {\n" % self.test_rule_name)
def test_build_rule_header_w_tags(self):
self.yara_rule.condition.add_raw_condition(self.test_condition)
self.yara_rule.tags.add_tag("test1")
self.yara_rule.tags.add_tag("test2")
self.raw_rule = self.yara_rule.build_rule_header(self.raw_rule)
self.assertEqual(
self.raw_rule, "rule %s : test1 test2 {\n" % self.test_rule_name
)
def test_build_rule_header_w_imports(self):
self.yara_rule.condition.add_raw_condition(self.test_condition)
self.yara_rule.imports.add_import("pe")
self.yara_rule.imports.add_import("math")
self.raw_rule = self.yara_rule.build_rule_header(self.raw_rule)
self.assertEqual(
self.raw_rule,
'import "pe"\nimport "math"\n\nrule %s {\n' % self.test_rule_name,
)
def test_build_rule_strings_section(self):
self.yara_rule.strings.add_anonymous_string("anon_test")
self.yara_rule.strings.add_string("test_name1", "test_value1")
self.yara_rule.strings.add_modifier("test_name1", "ascii")
self.yara_rule.strings.add_modifier("test_name1", "wide")
self.yara_rule.strings.add_string("test_name2", "test_value2")
self.yara_rule.strings.add_modifier("test_name2", "nocase")
self.raw_rule = self.yara_rule.build_rule_strings_section(self.raw_rule)
self.assertEqual(
self.raw_rule,
' strings:\n $ = "anon_test"\n '
'$test_name1 = "test_value1" ascii wide\n $test_name2 = "test_value2" nocase\n\n',
)
def test_build_rule_condition_section(self):
self.yara_rule.condition.raw_condition = "any of them"
self.raw_rule = self.yara_rule.build_rule_condition_section(self.raw_rule)
self.assertEqual(self.raw_rule, " condition:\n any of them\n}")
def test_build_rule_meta_section(self):
self.yara_rule.meta.add_meta("test_name1", "test_value1")
self.yara_rule.meta.add_meta("test_name2", 10, meta_type="int")
self.raw_rule = self.yara_rule.build_rule_meta_section(self.raw_rule)
self.assertEqual(
self.raw_rule,
" meta:\n "
'test_name1 = "test_value1"\n '
"test_name2 = 10\n\n",
)
def test_build_rule(self):
self.yara_rule.meta.add_meta("description", "Generated by yarabuilder")
self.yara_rule.strings.add_string("test_name", "test_value")
self.yara_rule.condition.add_raw_condition("any of them")
rule = self.yara_rule.build_rule()
self.assertEqual(
rule,
"rule test_rule {\n meta:\n "
'description = "Generated by yarabuilder"\n\n '
'strings:\n $test_name = "test_value"\n\n '
"condition:\n any of them\n}",
)
def test_build_rule_twice(self):
self.yara_rule.meta.add_meta("description", "Generated by yarabuilder")
self.yara_rule.strings.add_string("test_name", "test_value")
self.yara_rule.condition.add_raw_condition("any of them")
rule = self.yara_rule.build_rule()
rule = self.yara_rule.build_rule()
self.assertEqual(
rule,
"rule test_rule {\n meta:\n "
'description = "Generated by yarabuilder"\n\n '
'strings:\n $test_name = "test_value"\n\n '
"condition:\n any of them\n}",
)
def test_get_yara_rule_no_condition(self):
self.assertRaises(KeyError, self.yara_rule.get_yara_rule)
def test_get_yara_rule(self):
self.yara_rule.meta.add_meta("description", "Generated by yarabuilder")
self.yara_rule.strings.add_string("test_name", "test_value")
self.yara_rule.condition.add_raw_condition("any of them")
self.yara_rule.imports.add_import("pe")
self.yara_rule.tags.add_tag("test_tag")
yara_rule = self.yara_rule.get_yara_rule()
self.assertEqual(yara_rule["rule_name"], "test_rule")
self.assertEqual(
yara_rule["meta"]["description"][0]["value"], "Generated by yarabuilder"
)
self.assertEqual(yara_rule["strings"]["test_name"]["value"], "test_value")
self.assertEqual(yara_rule["condition"], "any of them")
self.assertEqual(yara_rule["imports"][0], "pe")
self.assertEqual(yara_rule["tags"][0], "test_tag")
def test_set_yara_rule(self):
self.yara_rule.set_yara_rule(
{
"condition": "any of them",
"imports": ["pe"],
"meta": collections.OrderedDict(
[
(
"description",
[
{
"meta_type": "text",
"name": "description",
"position": 0,
"value": "Generated by yarabuilder",
}
],
)
]
),
"rule_name": "my_rule",
"strings": collections.OrderedDict(
[
(
"@anon0",
{
"is_anonymous": True,
"name": "@anon0",
"str_type": "text",
"value": "Anonymous string",
},
),
(
"str",
{
"comment": {"inline": "example comment"},
"is_anonymous": False,
"modifiers": ["ascii", "wide"],
"name": "str",
"str_type": "text",
"value": "Named string",
},
),
(
"@anon1",
{
"is_anonymous": True,
"name": "@anon1",
"str_type": "hex",
"value": "DE AD BE EF",
},
),
(
"@anon2",
{
"is_anonymous": True,
"name": "@anon2",
"str_type": "regex",
"value": "regex[0-9]{2}",
},
),
]
),
"tags": ["yarabuilder"],
}
)
self.assertEqual(self.yara_rule.rule_name, "my_rule")
self.assertEqual(self.yara_rule.imports.imports, ["pe"])
self.assertEqual(self.yara_rule.tags.tags, ["yarabuilder"])
self.assertEqual(
self.yara_rule.meta.meta["description"][0].value, "Generated by yarabuilder"
)
self.assertEqual(self.yara_rule.strings.strings["str"].value, "Named string")
self.assertEqual(self.yara_rule.condition.raw_condition, "any of them")
class TestYaraCondition(unittest.TestCase):
def test_add_raw_condition(self):
condition = YaraCondition()
condition.add_raw_condition("filesize > 0")
self.assertEqual("filesize > 0", condition.raw_condition)
def test_get_yara_condition(self):
condition = YaraCondition()
condition.add_raw_condition("filesize > 0")
self.assertEqual(condition.get_yara_condition(), "filesize > 0")
class TestYaraTags(unittest.TestCase):
def setUp(self):
self.yara_tags = YaraTags()
def test_yara_tags_constructor(self):
self.assertEqual(self.yara_tags.tags, [])
def test_has_tags(self):
self.assertFalse(self.yara_tags.has_tags())
self.yara_tags.add_tag("test1")
self.assertTrue(self.yara_tags.has_tags())
def test_add_tag(self):
self.yara_tags.add_tag("test1")
self.yara_tags.add_tag("test2")
self.assertEqual(self.yara_tags.tags, ["test1", "test2"])
def test_build_tags(self):
self.yara_tags.add_tag("test1")
self.yara_tags.add_tag("test2")
self.yara_tags.build_tags()
self.assertEqual(self.yara_tags.raw_tags, "test1 test2")
def test_get_yara_tags(self):
self.yara_tags.add_tag("test1")
self.yara_tags.add_tag("test2")
self.assertEqual(self.yara_tags.get_yara_tags(), ["test1", "test2"])
def test_set_yara_tags(self):
self.yara_tags.set_yara_tags(["test1", "test2"])
self.assertEqual(self.yara_tags.tags, ["test1", "test2"])
class TestYaraImports(unittest.TestCase):
def setUp(self):
self.yara_imports = YaraImports()
def test_yara_imports_constructor(self):
self.assertEqual(self.yara_imports.imports, [])
def test_has_imports(self):
self.assertFalse(self.yara_imports.has_imports())
self.yara_imports.add_import("pe")
self.assertTrue(self.yara_imports.has_imports())
def test_add_import(self):
self.yara_imports.add_import("pe")
self.yara_imports.add_import("math")
self.assertEqual(self.yara_imports.imports, ["pe", "math"])
def test_build_imports(self):
self.yara_imports.add_import("pe")
self.yara_imports.add_import("math")
self.yara_imports.build_imports()
self.assertEqual(self.yara_imports.raw_imports, 'import "pe"\nimport "math"\n')
def test_build_imports_twice(self):
self.yara_imports.add_import("pe")
self.yara_imports.build_imports()
self.assertEqual(self.yara_imports.raw_imports, 'import "pe"\n')
self.yara_imports.add_import("math")
self.yara_imports.build_imports()
self.assertEqual(self.yara_imports.raw_imports, 'import "pe"\nimport "math"\n')
def test_no_duplicate_imports(self):
self.yara_imports.add_import("pe")
self.yara_imports.add_import("math")
self.yara_imports.add_import("pe")
self.assertEqual(self.yara_imports.imports, ["pe", "math"])
def test_get_yara_imports(self):
self.yara_imports.add_import("pe")
self.yara_imports.add_import("math")
self.assertEqual(self.yara_imports.get_yara_imports(), ["pe", "math"])
def test_set_yara_imports(self):
self.yara_imports.set_yara_imports(["pe", "math"])
self.assertEqual(self.yara_imports.imports, ["pe", "math"])
class TestYaraString(unittest.TestCase):
def test_yara_string_constructor(self):
yara_string = YaraString("test_name", "test_value")
self.assertEqual(yara_string.name, "test_name")
self.assertEqual(yara_string.value, "test_value")
self.assertEqual(yara_string.str_type, "text")
self.assertFalse(yara_string.is_anonymous)
def test_build_string_text(self):
yara_string = YaraString("test_name", "test_value")
yara_string.build_string()
self.assertEqual(yara_string.raw_string, '$test_name = "test_value"')
def test_build_string_hex(self):
yara_string = YaraString("test_name", "AA BB CC DD", str_type="hex")
yara_string.build_string()
self.assertEqual(yara_string.raw_string, "$test_name = {AA BB CC DD}")
def test_build_string_regex(self):
yara_string = YaraString("test_name", "test[0-9]{2}", str_type="regex")
yara_string.build_string()
self.assertEqual(yara_string.raw_string, "$test_name = /test[0-9]{2}/")
def test_build_string_regex_w_regex_flags(self):
yara_string = YaraString("test_name", "test[0-9]{2}", str_type="regex", regex_flags="i")
yara_string.build_string()
self.assertEqual(yara_string.raw_string, "$test_name = /test[0-9]{2}/i")
def test_build_string_w_condition(self):
yara_string = YaraString("test_name", "test_value")
yara_string.modifiers = ["ascii", "wide"]
yara_string.build_string()
self.assertEqual(yara_string.raw_string, '$test_name = "test_value" ascii wide')
def test_build_string_w_newline_after(self):
yara_string = YaraString("test_name", "test_value", newline_after = True)
yara_string.build_string()
self.assertEqual(yara_string.raw_string, '$test_name = "test_value"\n')
def test_get_yara_string(self):
yara_string = YaraString("test_name", "test_value")
yara_string.modifiers = ["ascii", "wide"]
yara_string.yara_comment = YaraComment()
yara_string.yara_comment.inline = "test_comment"
pod_yara_string = yara_string.get_yara_string()
self.assertEqual(pod_yara_string["name"], "test_name")
self.assertEqual(pod_yara_string["value"], "test_value")
self.assertEqual(pod_yara_string["modifiers"], ["ascii", "wide"])
self.assertEqual(pod_yara_string["comment"]["inline"], "test_comment")
def test_get_yara_string_with_regex_flags(self):
yara_string = YaraString("test_name", "test_regex", regex_flags="i")
pod_yara_string = yara_string.get_yara_string()
self.assertEqual(pod_yara_string["name"], "test_name")
self.assertEqual(pod_yara_string["value"], "test_regex")
self.assertEqual(pod_yara_string["regex_flags"], "i")
def test_set_yara_string(self):
yara_string = YaraString(None, None)
yara_string.set_yara_string(
{
"comment": {"inline": "example comment"},
"is_anonymous": False,
"modifiers": ["ascii", "wide"],
"name": "str",
"str_type": "text",
"value": "Named string",
}
)
self.assertEqual(yara_string.yara_comment.inline, "example comment")
self.assertEqual(yara_string.is_anonymous, False)
self.assertEqual(yara_string.modifiers, ["ascii", "wide"])
self.assertEqual(yara_string.name, "str")
self.assertEqual(yara_string.str_type, "text")
self.assertEqual(yara_string.value, "Named string")
def test_set_yara_regex_string_with_flags(self):
yara_string = YaraString(None, None)
yara_string.set_yara_string(
{
"is_anonymous": False,
"name": "str",
"str_type": "regex",
"value": "test regex",
"regex_flags": "i"
}
)
self.assertEqual(yara_string.is_anonymous, False)
self.assertEqual(yara_string.name, "str")
self.assertEqual(yara_string.str_type, "regex")
self.assertEqual(yara_string.value, "test regex")
self.assertEqual(yara_string.regex_flags, "i")
def test_set_yara_string_invalid_keys(self):
yara_string = YaraString(None, None)
self.assertRaises(
KeyError, yara_string.set_yara_string, {"invalid_key": "test"}
)
class TestYaraStrings(unittest.TestCase):
def setUp(self):
self.yara_strings = YaraStrings()
def test_add_string(self):
self.yara_strings.add_string("test_name", "test_value")
self.assertIn("test_name", self.yara_strings.strings)
self.assertEqual(self.yara_strings.strings["test_name"].value, "test_value")
self.assertEqual(self.yara_strings.number_of_strings, 1)
def test_add_string_invalid_str_type(self):
self.yara_strings.add_string("test_name", "test_value", str_type="invalid_type")
self.assertEqual(self.yara_strings.strings["test_name"].str_type, "text")
def test_add_anonymous_string_invalid_str_type(self):
name = self.yara_strings.add_anonymous_string(
"test_value", str_type="invalid_type"
)
self.assertEqual(self.yara_strings.strings[name].str_type, "text")
def test_invalid_str_type_handler_valid_str_type(self):
str_type = self.yara_strings._invalid_str_type_handler("hex")
self.assertEqual(str_type, "hex")
def test_invalid_str_type_handler_invalid_str_type(self):
str_type = self.yara_strings._invalid_str_type_handler("invalid_type")
self.assertEqual(str_type, "text")
def test_no_duplicate_string_names(self):
self.yara_strings.add_string("test_name", "test_value")
self.assertRaises(
ValueError, self.yara_strings.add_string, "test_name", "test_value"
)
def test_add_modifier(self):
self.yara_strings.add_string("test_name", "test_value")
self.yara_strings.add_modifier("test_name", "ascii")
self.yara_strings.add_modifier("test_name", "wide")
self.assertEqual(
self.yara_strings.strings["test_name"].modifiers, ["ascii", "wide"]
)
def test_no_duplicate_modifiers(self):
self.yara_strings.add_string("test_name", "test_value")
self.yara_strings.add_modifier("test_name", "ascii")
self.yara_strings.add_modifier("test_name", "wide")
self.yara_strings.add_modifier("test_name", "ascii")
self.assertEqual(
self.yara_strings.strings["test_name"].modifiers, ["ascii", "wide"]
)
def test_add_modifier_when_no_matching_string(self):
self.assertRaises(
KeyError, self.yara_strings.add_modifier, "test_name", "test_value"
)
def test_add_anonymous_string_returned_name(self):
name = self.yara_strings.add_anonymous_string("test_value")
self.assertEqual(name, "@anon0")
def test_add_anonymous_string(self):
name = self.yara_strings.add_anonymous_string("test_value")
self.assertIn(name, self.yara_strings.strings)
self.assertEqual(self.yara_strings.strings[name].value, "test_value")
self.assertEqual(self.yara_strings.number_of_strings, 1)
self.assertEqual(self.yara_strings.number_of_anonymous_strings, 1)
def test_error_when_adding_modifier_to_hex_string(self):
self.yara_strings.add_string("test_name", "AA BB CC DD", str_type="hex")
self.assertRaises(
TypeError, self.yara_strings.add_modifier, "test_name", "ascii"
)
def test_build_text_strings(self):
self.yara_strings.add_anonymous_string("anon_test")
self.yara_strings.add_string("test_name1", "test_value1")
self.yara_strings.add_modifier("test_name1", "ascii")
self.yara_strings.add_modifier("test_name1", "wide")
self.yara_strings.add_string("test_name2", "test_value2")
self.yara_strings.add_modifier("test_name2", "nocase")
self.yara_strings.build_strings()
self.assertEqual(
self.yara_strings.raw_strings,
[
'$ = "anon_test"',
'$test_name1 = "test_value1" ascii wide',
'$test_name2 = "test_value2" nocase',
],
)
def test_build_hex_strings(self):
self.yara_strings.add_anonymous_string("AA BB CC DD", str_type="hex")
self.yara_strings.add_string("test_name1", "EE FF 00 11", str_type="hex")
self.yara_strings.build_strings()
self.assertEqual(
self.yara_strings.raw_strings,
["$ = {AA BB CC DD}", "$test_name1 = {EE FF 00 11}"],
)
def test_build_regex_strings(self):
self.yara_strings.add_anonymous_string("anon_test[0-9]{2}", str_type="regex")
self.yara_strings.add_string("test_name1", "test_value\\d", str_type="regex")
self.yara_strings.add_modifier("test_name1", "ascii")
self.yara_strings.add_modifier("test_name1", "wide")
self.yara_strings.add_string("test_name2", "test_value\\D", str_type="regex")
self.yara_strings.add_modifier("test_name2", "nocase")
self.yara_strings.build_strings()
self.assertEqual(
self.yara_strings.raw_strings,
[
"$ = /anon_test[0-9]{2}/",
"$test_name1 = /test_value\\d/ ascii wide",
"$test_name2 = /test_value\\D/ nocase",
],
)
def test_build_regex_strings_w_regex_flag(self):
self.yara_strings.add_anonymous_string("anon_test[0-9]{2}", str_type="regex", regex_flags="i")
self.yara_strings.add_string("test_name1", "test_value\\d", str_type="regex", regex_flags="s")
self.yara_strings.add_modifier("test_name1", "ascii")
self.yara_strings.add_modifier("test_name1", "wide")
self.yara_strings.add_string("test_name2", "test_value\\D", str_type="regex", regex_flags="is")
self.yara_strings.add_modifier("test_name2", "nocase")
self.yara_strings.build_strings()
self.assertEqual(
self.yara_strings.raw_strings,
[
"$ = /anon_test[0-9]{2}/i",
"$test_name1 = /test_value\\d/s ascii wide",
"$test_name2 = /test_value\\D/is nocase",
],
)
def test_build_strings_with_newline_after(self):
self.yara_strings.add_string("test_name1", "test_value1", newline_after=True)
self.yara_strings.add_modifier("test_name1", "ascii")
self.yara_strings.add_modifier("test_name1", "wide")
self.yara_strings.add_string("test_name2", "test_value2")
self.yara_strings.add_modifier("test_name2", "nocase")
self.yara_strings.build_strings()
self.assertEqual(
self.yara_strings.raw_strings,
[
'$test_name1 = "test_value1" ascii wide\n',
'$test_name2 = "test_value2" nocase',
],
)
def test_get_yara_strings(self):
self.yara_strings.add_string("test_name1", "test_value1")
self.yara_strings.add_modifier("test_name1", "ascii")
self.yara_strings.add_modifier("test_name1", "wide")
self.yara_strings.add_string("test_name2", "test_value2")
yara_strings = self.yara_strings.get_yara_strings()
self.assertEqual(yara_strings["test_name1"]["value"], "test_value1")
self.assertEqual(yara_strings["test_name1"]["modifiers"], ["ascii", "wide"])
self.assertEqual(yara_strings["test_name2"]["value"], "test_value2")
def test_set_yara_strings(self):
self.yara_strings.set_yara_strings(
collections.OrderedDict(
[
(
"@anon0",
{
"is_anonymous": True,
"name": "@anon0",
"str_type": "text",
"value": "Anonymous string",
},
),
(
"str",
{
"comment": {"inline": "example comment"},
"is_anonymous": False,
"modifiers": ["ascii", "wide"],
"name": "str",
"str_type": "text",
"value": "Named string",
},
),
]
)
)
self.assertEqual(self.yara_strings.strings["@anon0"].value, "Anonymous string")
self.assertEqual(self.yara_strings.strings["str"].value, "Named string")
class TestYaraMeta(unittest.TestCase):
def setUp(self):
self.yara_meta = YaraMeta()
def test_add_new_meta(self):
self.yara_meta.add_meta("test_name", "test_value")
self.assertIn("test_name", self.yara_meta.meta)
self.assertEqual(self.yara_meta.meta["test_name"][0].value, "test_value")
self.assertEqual(self.yara_meta.meta["test_name"][0].meta_type, "text")
self.assertEqual(self.yara_meta.meta["test_name"][0].position, 0)
def test_add_duplicate_meta_name(self):
self.yara_meta.add_meta("test_name", "test_value1")
self.yara_meta.add_meta("test_name", "test_value2")
self.assertIn("test_name", self.yara_meta.meta)
self.assertEqual(self.yara_meta.meta["test_name"][0].value, "test_value1")
self.assertEqual(self.yara_meta.meta["test_name"][0].meta_type, "text")
self.assertEqual(self.yara_meta.meta["test_name"][0].position, 0)
self.assertEqual(self.yara_meta.meta["test_name"][1].value, "test_value2")
self.assertEqual(self.yara_meta.meta["test_name"][1].meta_type, "text")
self.assertEqual(self.yara_meta.meta["test_name"][1].position, 1)
def test_add_meta_text(self):
self.yara_meta.add_meta("test_name", "test_value", meta_type="text")
self.assertIsInstance(self.yara_meta.meta["test_name"][0].value, str)
def test_add_meta_int(self):
self.yara_meta.add_meta("test_name", 10, meta_type="int")
self.assertIsInstance(self.yara_meta.meta["test_name"][0].value, int)
def test_add_meta_bool(self):
self.yara_meta.add_meta("test_name", True, meta_type="bool")
self.assertIsInstance(self.yara_meta.meta["test_name"][0].value, bool)
def test_add_invalid_meta_type(self):
self.yara_meta.add_meta("test_name", "test_value", meta_type="invalid_type")
self.assertEqual(self.yara_meta.meta["test_name"][0].meta_type, "text")
def test_build_meta(self):
self.yara_meta.add_meta("test_name1", "test_value1")
self.yara_meta.add_meta("test_name2", 10, meta_type="int")
self.yara_meta.add_meta("test_name3", True, meta_type="bool")
self.yara_meta.add_meta("test_name4", False, meta_type="bool")
self.yara_meta.build_meta()
self.assertEqual(
self.yara_meta.raw_meta,
[
'test_name1 = "test_value1"',
"test_name2 = 10",
"test_name3 = true",
"test_name4 = false",
],
)
def test_get_yara_meta(self):
self.yara_meta.add_meta("test_name", "test_value1")
self.yara_meta.add_meta("test_name", "test_value2")
pod_yara_meta = self.yara_meta.get_yara_meta()
self.assertEqual(pod_yara_meta["test_name"][0]["value"], "test_value1")
self.assertEqual(pod_yara_meta["test_name"][1]["value"], "test_value2")
def test_set_yara_meta(self):
self.yara_meta.set_yara_meta(
collections.OrderedDict(
[
(
"test_name",
[
{
"meta_type": "text",
"name": "test_name",
"position": 0,
"value": "test_1",
},
{
"meta_type": "text",
"name": "test_name",
"position": 1,
"value": "test_2",
},
],
)
]
)
)
self.assertEqual(self.yara_meta.meta["test_name"][0].value, "test_1")
self.assertEqual(self.yara_meta.meta["test_name"][1].value, "test_2")
class TestYaraMetaEntry(unittest.TestCase):
def test_yara_meta_entry_constructor(self):
yara_meta_entry = YaraMetaEntry("test_name", "test_value", 0)
self.assertEqual(yara_meta_entry.name, "test_name")
self.assertEqual(yara_meta_entry.value, "test_value")
self.assertEqual(yara_meta_entry.position, 0)
def test_build_meta_entry_text(self):
yara_meta_entry = YaraMetaEntry("test_name", "test_value", 0)
yara_meta_entry.build_meta_entry()
self.assertEqual(yara_meta_entry.raw_meta_entry, 'test_name = "test_value"')
def test_build_meta_entry_int(self):
yara_meta_entry = YaraMetaEntry("test_name", 10, 0, meta_type="int")
yara_meta_entry.build_meta_entry()
self.assertEqual(yara_meta_entry.raw_meta_entry, "test_name = 10")
def test_build_meta_entry_bool(self):
yara_meta_entry = YaraMetaEntry("test_name", True, 0, meta_type="bool")
yara_meta_entry.build_meta_entry()
self.assertEqual(yara_meta_entry.raw_meta_entry, "test_name = true")
yara_meta_entry = YaraMetaEntry("test_name", False, 0, meta_type="bool")
yara_meta_entry.build_meta_entry()
self.assertEqual(yara_meta_entry.raw_meta_entry, "test_name = false")
def test_get_yara_meta_entry(self):
yara_meta_entry = YaraMetaEntry("test_name", "test_value", 0)
yara_meta_entry.yara_comment.inline = "test_inline_comment"
pod_yara_meta_entry = yara_meta_entry.get_yara_meta_entry()
self.assertEqual(pod_yara_meta_entry["name"], "test_name")
self.assertEqual(pod_yara_meta_entry["value"], "test_value")
self.assertEqual(pod_yara_meta_entry["position"], 0)
self.assertEqual(pod_yara_meta_entry["meta_type"], "text")
self.assertEqual(
pod_yara_meta_entry["comment"]["inline"], "test_inline_comment"
)
def test_set_yara_meta_entry(self):
yara_meta_entry = YaraMetaEntry(None, None, None)
yara_comment = {"inline": "test_inline_comment"}
yara_meta_entry.set_yara_meta_entry(
{
"name": "test_name",
"value": "test_value",
"position": 0,
"meta_type": "text",
"comment": yara_comment,
}
)
self.assertEqual(yara_meta_entry.name, "test_name")
self.assertEqual(yara_meta_entry.value, "test_value")
self.assertEqual(yara_meta_entry.position, 0)
self.assertEqual(yara_meta_entry.yara_comment.inline, "test_inline_comment")
def test_set_yara_meta_entry_invalid_keys(self):
yara_meta_entry = YaraMetaEntry(None, None, None)
self.assertRaises(
KeyError, yara_meta_entry.set_yara_meta_entry, {"invalid_key": "test"}
)
|
package io.kanro.idea.plugin.protobuf.lang.psi.primitive.structure
interface ProtobufMultiNameDefinition : ProtobufDefinition {
fun names(): Set<String>
}
|
require_relative "helper"
require "goofy/safe/csrf"
require "goofy/test"
def assert_no_raise
yield
success
end
class UnsafeRequest < RuntimeError; end
scope do
setup do
Goofy.reset!
Goofy.use(Rack::Session::Cookie, secret: "_this_must_be_secret")
Goofy.plugin(Goofy::Safe::CSRF)
end
test "safe http methods" do
Goofy.define do
raise UnsafeRequest if csrf.unsafe?
end
assert_no_raise do
get "/"
head "/"
end
end
test "invalid csrf param" do
Goofy.define do
if csrf.unsafe?
csrf.reset!
end
res.write(csrf.token)
end
get "/"
old_token = last_response.body
post "/", "csrf_token" => "nonsense"
new_token = last_response.body
assert(old_token != new_token)
end
test "valid csrf param" do
Goofy.define do
raise unless csrf.safe?
on get do
res.write(csrf.token)
end
on post do
res.write("safe")
end
end
get "/"
csrf_token = last_response.body
assert(!csrf_token.empty?)
assert_no_raise do
post "/", "csrf_token" => csrf_token
end
end
test "http header" do
csrf_token = SecureRandom.hex(32)
Goofy.define do
session[:csrf_token] = csrf_token
raise if csrf.unsafe?
end
assert_no_raise do
post "/", {}, { "HTTP_X_CSRF_TOKEN" => csrf_token }
end
end
test "sub app raises too" do
class App < Goofy
define do
on post do
res.write("unsafe")
end
end
end
Goofy.define do
raise UnsafeRequest unless csrf.safe?
on "app" do
run(App)
end
end
assert_raise(UnsafeRequest) do
post "/app"
end
end
test "only sub app" do
class App < Goofy
define do
raise UnsafeRequest unless csrf.safe?
on post do
res.write("unsafe")
end
end
end
Goofy.define do
on "app" do
run(App)
end
on default do
res.write("safe")
end
end
assert_no_raise do
post "/"
end
assert_raise(UnsafeRequest) do
post "/app"
end
end
end
|
MRuby::Gem::Specification.new('mruby-mwaf') do |spec|
spec.author = "Julien Boulnois"
spec.version = "0.1.0"
spec.license = "MIT"
spec.add_dependency "mruby-erb", :github => 'fukaoi/mruby-erb'
spec.add_dependency "mruby-sqlite", :github => 'asfluido/mruby-sqlite'
end
|
module Langusta
class DetectorFactory
include Inspector
attr_reader :word_lang_prob_map, :lang_list
def initialize
@word_lang_prob_map = {}
@lang_list = []
end
# Adds a new language profile to this factory.
# @param [LangProfile] language profile to be added.
# @param [Fixnum] index at which the language profile is to be added.
# @param [Fixnum] counts how many language profiles are to be added to this factory in total.
def add_profile(profile)
raise DuplicateProfilesError.new(profile.name) if @lang_list.include?(profile.name)
@lang_list << profile.name
last_lang_index = @lang_list.size - 1
profile.freq.keys.each do |word|
@word_lang_prob_map[word] ||= []
prob = 1.0 * profile.freq[word] / profile.n_words[word.length - 1]
@word_lang_prob_map[word][last_lang_index] = prob
end
end
# Creates a new detector object, based on a preconfigured set of language profiles.
# @return [Detector]
def create(alpha=nil)
if alpha
detector = create_detector()
detector.alpha = alpha
detector
else
create_detector()
end
end
def inspect
"#<#{self.class.name}:0x#{object_ptr} (#{@lang_list.size} profile(s))"
end
private
def create_detector
raise NoProfilesLoadedError if @lang_list.empty?
detector = Detector.new(self)
end
end
end
|
// Copyright (c) 2021 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
use crate::{
command_buffer::synced::SyncCommandBufferBuilder,
pipeline::{ComputePipeline, GraphicsPipeline},
};
use std::{error, fmt};
pub(in super::super) fn check_pipeline_compute(
builder: &SyncCommandBufferBuilder,
) -> Result<&ComputePipeline, CheckPipelineError> {
let pipeline = match builder.bound_pipeline_compute() {
Some(x) => x,
None => return Err(CheckPipelineError::PipelineNotBound),
};
Ok(pipeline)
}
pub(in super::super) fn check_pipeline_graphics(
builder: &SyncCommandBufferBuilder,
) -> Result<&GraphicsPipeline, CheckPipelineError> {
let pipeline = match builder.bound_pipeline_graphics() {
Some(x) => x,
None => return Err(CheckPipelineError::PipelineNotBound),
};
Ok(pipeline)
}
/// Error that can happen when checking whether the pipeline is valid.
#[derive(Debug, Copy, Clone)]
pub enum CheckPipelineError {
/// No pipeline was bound to the bind point used by the operation.
PipelineNotBound,
}
impl error::Error for CheckPipelineError {}
impl fmt::Display for CheckPipelineError {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CheckPipelineError::PipelineNotBound => write!(
fmt,
"no pipeline was bound to the bind point used by the operation",
),
}
}
}
|
package com.heapdump.analysis;
import java.util.ArrayList;
import java.util.List;
public class OutOFMemoryHeapDump {
public static void main(String[] args) {
List<ObjectForLeak> leak = new ArrayList<>();
while(true) {
leak.add(new ObjectForLeak());
}
}
}
|
;;; Copyright (c) 2011-2012, James M. Lawrence. All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials provided
;;; with the distribution.
;;;
;;; * Neither the name of the project 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.
(in-package #:lparallel.kernel)
(defslots wrapped-error ()
((value :type condition :reader wrapped-error-value))
(:documentation
"This is a container for transferring an error that occurs inside
`call-with-task-handler' to the calling thread."))
(defun wrap-error (condition)
"Wrap an error. A non-error condition may also be wrapped, though it
will still be signaled with `error'."
(make-wrapped-error-instance
:value (ctypecase condition
(symbol (make-condition condition))
(condition condition))))
(defun unwrap-result (result)
"In `receive-result', this is called on the stored task result. The
user receives the return value of this function."
(declare #.*full-optimize*)
(typecase result
(wrapped-error
;; A `wrapped-error' signals an error upon being unwrapped.
(error (wrapped-error-value result)))
(otherwise
;; Most objects unwrap to themselves.
result)))
(deftype handler-binding-condition-type ()
`(or symbol (cons symbol)))
(defmacro task-handler-bind (clauses &body body)
"Like `handler-bind' but handles conditions signaled inside tasks
that were created in `body'."
(let ((forms (loop for clause in clauses
for (type handler . more) = clause
do (unless (and (typep type 'handler-binding-condition-type)
handler
(not more))
(error "Ill-formed binding in `task-handler-bind': ~a"
clause))
collect `(cons ',type ,handler))))
`(let ((*client-handlers* (list* ,@forms *client-handlers*)))
,@body)))
(defun invoke-transfer-error (error)
"Equivalent to (invoke-restart 'transfer-error error).
This is a convenience function for use in `task-handler-bind'."
(invoke-restart 'transfer-error error))
(defun condition-handler (condition)
"Mimic the CL handling mechanism, calling handlers until one assumes
control (or not)."
(loop for ((condition-type . handler) . rest) on *client-handlers*
do (when (typep condition condition-type)
(let ((*client-handlers* rest))
(handler-bind ((condition #'condition-handler))
(funcall handler condition)))))
(when (and (typep condition 'error)
(not *debug-tasks-p*))
(invoke-transfer-error condition)))
(defun call-with-tracked-error (condition body-fn)
(unwind-protect/ext
:prepare (when *worker*
(with-lock-held (*erroring-workers-lock*)
(push *worker* *erroring-workers*)))
:main (let ((*debugger-error* condition))
(funcall body-fn))
:cleanup (when *worker*
(with-lock-held (*erroring-workers-lock*)
(setf *erroring-workers*
(delete *worker* *erroring-workers*))))))
(defmacro with-tracked-error (condition &body body)
`(call-with-tracked-error ,condition (lambda () ,@body)))
(defun make-debugger-hook ()
"Record `*debugger-error*' for the `transfer-error' restart."
(if *debugger-hook*
(let ((previous-hook *debugger-hook*))
(lambda (condition self)
(with-tracked-error condition
(funcall previous-hook condition self))))
(lambda (condition self)
(declare (ignore self))
(with-tracked-error condition
(invoke-debugger condition)))))
(defun transfer-error-report (stream)
(format stream "Transfer this error to a dependent thread, if one exists."))
(defconstant +current-task+ 'current-task)
(defun transfer-error-restart (&optional (err *debugger-error*))
(when err
(throw +current-task+ (wrap-error err))))
#-lparallel.without-task-handling
(progn
(defmacro with-task-context (&body body)
`(catch +current-task+
,@body))
(defun %call-with-task-handler (fn)
(declare #.*full-optimize*)
(declare (type function fn))
(let ((*handler-active-p* t)
(*debugger-hook* (make-debugger-hook)))
(handler-bind ((condition #'condition-handler))
(restart-bind ((transfer-error #'transfer-error-restart
:report-function #'transfer-error-report))
(funcall fn)))))
(defun call-with-task-handler (fn)
(declare #.*full-optimize*)
(declare (type function fn))
(with-task-context
(if *handler-active-p*
(funcall fn)
(%call-with-task-handler fn)))))
#+lparallel.without-task-handling
(progn
(defmacro with-task-context (&body body) `(progn ,@body))
(alias-function %call-with-task-handler funcall)
(alias-function call-with-task-handler funcall))
(define-condition task-killed-error (error) ()
(:report
"The task was killed.")
(:documentation
"Error signaled when attempting to obtain the result of a killed task."))
(define-condition no-kernel-error (error) ()
(:report
"Welcome to lparallel. To get started, you need to create some worker
threads. Choose the MAKE-KERNEL restart to create them now.
Worker threads are asleep when not in use. They are typically created
once per Lisp session.
Adding the following line to your startup code will prevent this
message from appearing in the future (N is the number of workers):
(setf lparallel:*kernel* (lparallel:make-kernel N))
")
(:documentation
"Error signaled when `*kernel*' is nil."))
(define-condition kernel-creation-error (error) ()
(:report
"Failed to create a kernel.")
(:documentation
"Error signaled when `make-kernel' fails."))
|
# ADN.EntityFrameworkCore
# Content
- [EntityFrameworkCoreUtils](#T:ADN.EntityFrameworkCore.EntityFrameworkCoreUtils)
- [InsertOrUpdate`<T>(context, model)](#EntityFrameworkCoreUtils.InsertOrUpdate`<T>(context,model))
<a name='T:ADN.EntityFrameworkCore.EntityFrameworkCoreUtils'></a>
## EntityFrameworkCoreUtils
A static class of methods for EntityFramework Core.
<a name='EntityFrameworkCoreUtils.InsertOrUpdate`<T>(context,model)'></a>
### InsertOrUpdate`<T>(context, model)
Insert or update an element in a database.
#### Parameters
| Name | Description |
| ---- | ----------- |
| context | *Microsoft.EntityFrameworkCore.DbContext*<br>A DbContext instance. |
#### Parameters
| model | *``0*<br>Element to insert or update in the database. |
|
using System;
using System.Collections.Generic;
namespace NetConf.StaticLocalFunctions
{
public class StaticLocalFunction
{
public static void Demo()
{
foreach (var i in IterateFromTo(1,10))
Console.WriteLine(i);
}
private static IEnumerable<int> IterateFromTo(int start, int end)
{
if (start >= end)
throw new ArgumentOutOfRangeException(null,"The beginning must be less than the end.");
return IterateFromToLocally(start, end);
static IEnumerable<int> IterateFromToLocally(int localStart, int localEnd)
{
for (var i = localStart; i <= localEnd; i++)
yield return i;
}
}
}
}
|
#!/usr/bin/env bash
updatedb
XDEBUG_PATH=$(locate xdebug.so)
sed -i "s%EXTENSION_LOCATION%${XDEBUG_PATH}%g" /usr/local/etc/php/conf.d/xdebug.ini
|
package com.example.pavneet_singh.room_demo_kotin_mvvm_dagger.di.activities
import dagger.Module
/**
* Created by Pavneet_Singh on 2020-01-31.
*/
/**
* Add dependencies for AddNoteActivity, if required
*/
@Module
abstract class AddNoteActivityModule
|
#!/bin/bash
# SPDX-FileCopyrightText: 2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
COMPONENTS=$(echo "$1" | sed "s/,/ /g")
sudo apt-get install -y "$COMPONENTS"
sudo apt-get clean
|
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl.jobexecutor;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.cmd.AbstractSetProcessDefinitionStateCmd;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.jobexecutor.TimerChangeProcessDefinitionSuspensionStateJobHandler.ProcessDefinitionSuspensionStateConfiguration;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.impl.repository.UpdateProcessDefinitionSuspensionStateBuilderImpl;
import org.camunda.bpm.engine.impl.util.JsonUtil;
import com.google.gson.JsonObject;
/**
* @author Joram Barrez
* @author roman.smirnov
*/
public abstract class TimerChangeProcessDefinitionSuspensionStateJobHandler implements JobHandler<ProcessDefinitionSuspensionStateConfiguration> {
protected static final String JOB_HANDLER_CFG_BY = "by";
protected static final String JOB_HANDLER_CFG_PROCESS_DEFINITION_ID = "processDefinitionId";
protected static final String JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY = "processDefinitionKey";
protected static final String JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID = "processDefinitionTenantId";
protected static final String JOB_HANDLER_CFG_INCLUDE_PROCESS_INSTANCES = "includeProcessInstances";
public void execute(ProcessDefinitionSuspensionStateConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) {
AbstractSetProcessDefinitionStateCmd cmd = getCommand(configuration);
cmd.disableLogUserOperation();
cmd.execute(commandContext);
}
protected abstract AbstractSetProcessDefinitionStateCmd getCommand(ProcessDefinitionSuspensionStateConfiguration configuration);
@Override
public ProcessDefinitionSuspensionStateConfiguration newConfiguration(String canonicalString) {
JsonObject jsonObject = JsonUtil.asObject(canonicalString);
return ProcessDefinitionSuspensionStateConfiguration.fromJson(jsonObject);
}
public static class ProcessDefinitionSuspensionStateConfiguration implements JobHandlerConfiguration {
protected String processDefinitionKey;
protected String processDefinitionId;
protected boolean includeProcessInstances;
protected String tenantId;
protected boolean isTenantIdSet;
protected String by;
@Override
public String toCanonicalString() {
JsonObject json = JsonUtil.createObject();
JsonUtil.addField(json, JOB_HANDLER_CFG_BY, by);
JsonUtil.addField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY, processDefinitionKey);
JsonUtil.addField(json, JOB_HANDLER_CFG_INCLUDE_PROCESS_INSTANCES, includeProcessInstances);
JsonUtil.addField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_ID, processDefinitionId);
if (isTenantIdSet) {
if (tenantId != null) {
JsonUtil.addField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID, tenantId);
} else {
JsonUtil.addNullField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID);
}
}
return json.toString();
}
public UpdateProcessDefinitionSuspensionStateBuilderImpl createBuilder() {
UpdateProcessDefinitionSuspensionStateBuilderImpl builder = new UpdateProcessDefinitionSuspensionStateBuilderImpl();
if (by.equals(JOB_HANDLER_CFG_PROCESS_DEFINITION_ID)) {
builder.byProcessDefinitionId(processDefinitionId);
} else if (by.equals(JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY)) {
builder.byProcessDefinitionKey(processDefinitionKey);
if (isTenantIdSet) {
if (tenantId != null) {
builder.processDefinitionTenantId(tenantId);
} else {
builder.processDefinitionWithoutTenantId();
}
}
} else {
throw new ProcessEngineException("Unexpected job handler configuration for property '" + JOB_HANDLER_CFG_BY + "': " + by);
}
builder.includeProcessInstances(includeProcessInstances);
return builder;
}
public static ProcessDefinitionSuspensionStateConfiguration fromJson(JsonObject jsonObject) {
ProcessDefinitionSuspensionStateConfiguration config = new ProcessDefinitionSuspensionStateConfiguration();
config.by = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_BY);
if (jsonObject.has(JOB_HANDLER_CFG_PROCESS_DEFINITION_ID)) {
config.processDefinitionId = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_ID);
}
if (jsonObject.has(JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY)) {
config.processDefinitionKey = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY);
}
if (jsonObject.has(JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID)) {
config.isTenantIdSet = true;
if (!JsonUtil.isNull(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID)) {
config.tenantId = JsonUtil.getString(jsonObject, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID);
}
}
if (jsonObject.has(JOB_HANDLER_CFG_INCLUDE_PROCESS_INSTANCES)) {
config.includeProcessInstances = JsonUtil.getBoolean(jsonObject, JOB_HANDLER_CFG_INCLUDE_PROCESS_INSTANCES);
}
return config;
}
public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionId(String processDefinitionId, boolean includeProcessInstances) {
ProcessDefinitionSuspensionStateConfiguration configuration = new ProcessDefinitionSuspensionStateConfiguration();
configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_ID;
configuration.processDefinitionId = processDefinitionId;
configuration.includeProcessInstances = includeProcessInstances;
return configuration;
}
public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionKey(String processDefinitionKey, boolean includeProcessInstances) {
ProcessDefinitionSuspensionStateConfiguration configuration = new ProcessDefinitionSuspensionStateConfiguration();
configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY;
configuration.processDefinitionKey = processDefinitionKey;
configuration.includeProcessInstances = includeProcessInstances;
return configuration;
}
public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionKeyAndTenantId(String processDefinitionKey, String tenantId, boolean includeProcessInstances) {
ProcessDefinitionSuspensionStateConfiguration configuration = byProcessDefinitionKey(processDefinitionKey, includeProcessInstances);
configuration.isTenantIdSet = true;
configuration.tenantId = tenantId;
return configuration;
}
}
public void onDelete(ProcessDefinitionSuspensionStateConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
}
|
/*
* Copyright 2013 Valery Lobachev
*
* 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 biz.lobachev.annette.principal_group.api
import akka.Done
import biz.lobachev.annette.core.model.auth.AnnettePrincipal
import biz.lobachev.annette.core.model.indexing.FindResult
import biz.lobachev.annette.principal_group.api.group._
import biz.lobachev.annette.core.model.category._
import io.scalaland.chimney.dsl._
import scala.concurrent.{ExecutionContext, Future}
class PrincipalGroupServiceImpl(api: PrincipalGroupServiceApi, implicit val ec: ExecutionContext)
extends PrincipalGroupService {
override def createPrincipalGroup(payload: CreatePrincipalGroupPayload): Future[Done] =
api.createPrincipalGroup.invoke(payload)
override def updatePrincipalGroupName(payload: UpdatePrincipalGroupNamePayload): Future[Done] =
api.updatePrincipalGroupName.invoke(payload)
override def updatePrincipalGroupDescription(payload: UpdatePrincipalGroupDescriptionPayload): Future[Done] =
api.updatePrincipalGroupDescription.invoke(payload)
override def updatePrincipalGroupCategory(payload: UpdatePrincipalGroupCategoryPayload): Future[Done] =
api.updatePrincipalGroupCategory.invoke(payload)
override def deletePrincipalGroup(payload: DeletePrincipalGroupPayload): Future[Done] =
api.deletePrincipalGroup.invoke(payload)
override def assignPrincipal(payload: AssignPrincipalPayload): Future[Done] =
api.assignPrincipal.invoke(payload)
override def unassignPrincipal(payload: UnassignPrincipalPayload): Future[Done] =
api.unassignPrincipal.invoke(payload)
override def getPrincipalGroupById(id: PrincipalGroupId, fromReadSide: Boolean): Future[PrincipalGroup] =
api.getPrincipalGroupById(id, fromReadSide).invoke()
override def getPrincipalGroupsById(
ids: Set[PrincipalGroupId],
fromReadSide: Boolean
): Future[Seq[PrincipalGroup]] =
api.getPrincipalGroupsById(fromReadSide).invoke(ids)
override def findPrincipalGroups(query: PrincipalGroupFindQuery): Future[FindResult] =
api.findPrincipalGroups.invoke(query)
override def getAssignments(id: PrincipalGroupId): Future[Set[AnnettePrincipal]] =
api.getAssignments(id).invoke()
// org category methods
def createCategory(payload: CreateCategoryPayload): Future[Done] =
api.createCategory.invoke(payload)
def updateCategory(payload: UpdateCategoryPayload): Future[Done] =
api.updateCategory.invoke(payload)
def createOrUpdateCategory(payload: CreateCategoryPayload): Future[Done] =
createCategory(payload).recoverWith {
case CategoryAlreadyExist(_) =>
val updatePayload = payload
.into[UpdateCategoryPayload]
.withFieldComputed(_.updatedBy, _.createdBy)
.transform
updateCategory(updatePayload)
case th => Future.failed(th)
}
def deleteCategory(payload: DeleteCategoryPayload): Future[Done] =
api.deleteCategory.invoke(payload)
def getCategoryById(id: CategoryId, fromReadSide: Boolean): Future[Category] =
api.getCategoryById(id, fromReadSide).invoke()
def getCategoriesById(ids: Set[CategoryId], fromReadSide: Boolean): Future[Seq[Category]] =
api.getCategoriesById(fromReadSide).invoke(ids)
def findCategories(query: CategoryFindQuery): Future[FindResult] =
api.findCategories.invoke(query)
}
|
<?php
namespace Tagcade\Repository\Core;
use Doctrine\Common\Persistence\ObjectRepository;
use Tagcade\Model\Core\DisplayWhiteListInterface;
use Tagcade\Model\Core\LibraryAdTagInterface;
use Tagcade\Model\Core\LibraryExpressionInterface;
interface WhiteListExpressionRepositoryInterface extends ObjectRepository
{
public function checkLibraryExpressionExist(LibraryExpressionInterface $libraryExpression, $whiteListId);
public function checkLibraryAdTagExist(LibraryAdTagInterface $libraryAdTag, $whiteListId);
public function getByWhiteList(DisplayWhiteListInterface $whiteList);
}
|
<?php
/*
-------------------------------------------------------------------------
GDPR Records of Processing Activities plugin for GLPI
Copyright (C) 2020 by Yild.
https://github.com/yild/gdprropa
-------------------------------------------------------------------------
LICENSE
This file is part of GDPR Records of Processing Activities.
GDPR Records of Processing Activities 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.
GDPR Records of Processing Activities 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 GDPR Records of Processing Activities.
If not, see <http://www.gnu.org/licenses/>.
Based on DPO Register plugin, by Karhel Tmarr.
--------------------------------------------------------------------------
@package gdprropa
@author Yild
@copyright Copyright (c) 2020 by Yild
@license GPLv3+
http://www.gnu.org/licenses/gpl.txt
@link https://github.com/yild/gdprropa
@since 2020
--------------------------------------------------------------------------
*/
include("../../../inc/includes.php");
Plugin::load('gdprropa', true);
Session::checkCentralAccess();
if (isset($_GET['createpdf'])) {
$print_options = PluginGdprropaCreatePDF::preparePrintOptionsFromForm($_GET);
if (isset($_GET['action'])) {
if ($_GET['action'] == 'prepare') {
if (isset($_GET['report_type'])) {
$type = $_GET['report_type'];
} else {
$type = PluginGdprropaCreatePDF::REPORT_ALL;
}
Html::header(PluginGdprropaRecord::getTypeName(0), '', "management", "plugingdprropamenu");
PluginGdprropaCreatePDF::showPrepareForm($type);
} else if ($_GET['action'] == 'print') {
$pdfoutput = new PluginGdprropaCreatePDF();
$pdfoutput->generateReport($_GET, $print_options);
$pdfoutput->showPDF();
}
}
}
|
package render
import (
"image"
"image/draw"
"time"
"github.com/oakmound/oak/v4/event"
"github.com/oakmound/oak/v4/render/mod"
"github.com/oakmound/oak/v4/timing"
)
// A Sequence is a series of modifiables drawn as an animation. It is more
// primitive than animation, but less efficient.
type Sequence struct {
LayeredPoint
pauseBool
InterruptBool
rs []Modifiable
lastChange time.Time
sheetPos int
frameTime int64
event.CallerID
}
// NewSequence returns a new sequence from the input modifiables, playing at
// the given fps rate.
func NewSequence(fps float64, mods ...Modifiable) *Sequence {
return &Sequence{
LayeredPoint: NewLayeredPoint(0, 0, 0),
pauseBool: pauseBool{
playing: true,
},
InterruptBool: InterruptBool{
Interruptable: true,
},
sheetPos: 0,
frameTime: timing.FPSToNano(fps),
rs: mods,
lastChange: time.Now(),
}
}
// SetFPS sets the number of frames that should advance per second to be
// the input fps
func (sq *Sequence) SetFPS(fps float64) {
sq.frameTime = timing.FPSToNano(fps)
}
// GetDims of a Sequence returns the dims of the current Renderable for the sequence
func (sq *Sequence) GetDims() (int, int) {
return sq.rs[sq.sheetPos].GetDims()
}
// Copy copies each modifiable inside this sequence in order to produce a new
// copied sequence
func (sq *Sequence) Copy() Modifiable {
newSq := new(Sequence)
*newSq = *sq
newRs := make([]Modifiable, len(sq.rs))
for i, r := range sq.rs {
newRs[i] = r.Copy()
}
newSq.rs = newRs
newSq.LayeredPoint = sq.LayeredPoint.Copy()
return newSq
}
var AnimationEnd = event.RegisterEvent[struct{}]()
// SetTriggerID sets the ID that AnimationEnd will be triggered on when this
// sequence loops over from its last frame to its first
func (sq *Sequence) SetTriggerID(id event.CallerID) {
sq.CallerID = id
}
func (sq *Sequence) update() {
if sq.playing && time.Since(sq.lastChange).Nanoseconds() > sq.frameTime {
sq.lastChange = time.Now()
sq.sheetPos = (sq.sheetPos + 1) % len(sq.rs)
if sq.sheetPos == (len(sq.rs)-1) && sq.CallerID != 0 {
// TODO: not default bus
event.TriggerForCallerOn(event.DefaultBus, sq.CallerID, AnimationEnd, struct{}{})
}
}
}
// Get returns the Modifiable stored at this sequence's ith index. If the sequence
// does not have an ith index this returns nil
func (sq *Sequence) Get(i int) Modifiable {
if i < 0 || i >= len(sq.rs) {
return nil
}
return sq.rs[i]
}
// Draw draws this sequence at +xOff, +yOff
func (sq *Sequence) Draw(buff draw.Image, xOff, yOff float64) {
sq.update()
sq.rs[sq.sheetPos].Draw(buff, sq.X()+xOff, sq.Y()+yOff)
}
// GetRGBA returns the RGBA of the currently showing frame of this sequence
func (sq *Sequence) GetRGBA() *image.RGBA {
return sq.rs[sq.sheetPos].GetRGBA()
}
// Modify alters each renderable in this sequence by the given
// modifications
func (sq *Sequence) Modify(ms ...mod.Mod) Modifiable {
for _, r := range sq.rs {
r.Modify(ms...)
}
return sq
}
// Filter filters each element in the sequence by the inputs
func (sq *Sequence) Filter(fs ...mod.Filter) {
for _, r := range sq.rs {
r.Filter(fs...)
}
}
// IsStatic returns false for sequences
func (sq *Sequence) IsStatic() bool {
return false
}
// TweenSequence returns a sequence that is the tweening between the input images
// at the given frame rate over the given frame count.
func TweenSequence(a, b image.Image, frames int, fps float64) *Sequence {
images := Tween(a, b, frames)
ms := make([]Modifiable, len(images))
for i, v := range images {
ms[i] = NewSprite(0, 0, v)
}
return NewSequence(fps, ms...)
}
|
#!/bin/bash
# Install DST version 26
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code
mkdir -p asalto26.5
cd asalto26.5
tar xvfz ../asalto26.5.tar.gz
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code
mkdir -p asalto27
cd asalto27
tar xvfz ../asalto27.tar.gz
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code
mkdir -p juan
cd juan
tar xvfz ../juan.tar.gz
# Patch Juan's Makefiles into a working state
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code/juan
cp Makefile Makefile.original
patch Makefile < Makefile.juan.patch
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code/asalto26.5
cp Makefile Makefile.original
patch Makefile < Makefile.asalto26.5.patch
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code/asalto27
cp Makefile Makefile.original
patch Makefile < Makefile.asalto27.patch
# Build Juan's code: libjuan
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code/juan
make -j 4
# Build Juan's code: asalto27
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code/asalto27
make -j 4
# Build Juan's code: asalto26.5
cd /plato-wp36-v2/docker_containers/worker_dst_v26/private_code/asalto26.5
make -j 4
|
<?php
session_start();
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'Library.utility.php');
// Include files
Library::using(Library::CORLY_SERVICE_FACTORY, ['FactoryService.class.php']);
/**
* PluginManagementController short summary.
*
* PluginManagementController description.
*
* @version 1.0
* @author Filip
*/
class PluginManagementController
{
// Method constants
const UNINSTALLED = "UNINSTALLED";
const INSTALLP = "INSTALLP";
const INSTALLC = "INSTALLC";
const COMPONENTS = "COMPONENTS";
/**
* Install plugin
* @param mixed $plugin
* @return mixed
*/
public function Install($plugin) {
return FactoryService::PluginManagementService()->Install($plugin);
}
/**
* Get list of all plugins
* @return list of plugins
*/
public function Uninstalled() {
return FactoryService::PluginManagementService()->GetNotInstalledPlugins();
}
/**
* Get list of all components
*/
public function Components() {
return FactoryService::ComponentService()->GetComponents();
}
/**
* Install component
*/
public function InstallComponent($component) {
return FactoryService::ComponentService()->Install($component);
}
}
// Extract json data
$rawData = file_get_contents('php://input');
$data = json_decode($rawData);
// Check GET requests
if (isset($_GET["method"])) {
// Init result
$result = new stdClass();
$PluginManagementController = new PluginManagementController();
switch ($_GET["method"]) {
case PluginManagementController::UNINSTALLED:
$result = $PluginManagementController->Uninstalled();
break;
case PluginManagementController::INSTALLP:
$result = $PluginManagementController->Install($data);
break;
case PluginManagementController::COMPONENTS:
$result = $PluginManagementController->Components();
break;
case PluginManagementController::INSTALLC:
$result = $PluginManagementController->InstallComponent($data);
break;
default:
$result = false;
break;
}
// Return answer to client
exit(json_encode($result));
}
|
import { ArgumentMetadata, BadRequestException, Injectable } from "@nestjs/common";
import { plainToInstance } from "class-transformer";
import { GetUsersDto } from "../dto/get-users.dto";
import { AdminGetUsersValidation } from "./admin-get-users.validation";
@Injectable()
export class AdminDeleteUsersValidation extends AdminGetUsersValidation {
async transform(value: any, metadata: ArgumentMetadata) {
if (!Array.isArray(value)) {
throw new BadRequestException(`validate delete users failed, value is not an array`);
}
for (const item of value) {
if (typeof item !== "string") {
throw new BadRequestException(`validate delete users failed, element ${item} is not a string`);
}
}
return value;
}
}
|
/*
* MIT License
*
* Copyright (c) 2017 KSat e.V. and AerospaceResearch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.ksatstuttgart.usoc.gui.panel;
import com.ksatstuttgart.usoc.controller.MainController;
import com.ksatstuttgart.usoc.gui.controller.ChartController;
import com.ksatstuttgart.usoc.gui.setup.configuration.USOCPaneProperties;
import com.ksatstuttgart.usoc.gui.setup.configuration.entity.Chart;
import com.ksatstuttgart.usoc.gui.worldwind.GNSSPanel;
import javafx.geometry.Insets;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import java.util.Optional;
/**
* Tab Panel
* Contains GNSS View and Chart Grid
*/
public class USOCPanel extends TabPane {
/**
* Properties class
*/
private USOCPaneProperties properties;
/**
* Chart Tab
*/
private Tab chartTab = new Tab();
/**
* Chart Grid
*/
private GridPane chartGrid = new GridPane();
/**
* GNSS Tab
*/
private Tab gnssTab = new Tab();
/**
* Keeps track of the current row index
* in the chart grid
*/
private int row = 0;
/**
* Keeps track of the current column index
* in the chart grid
*/
private int column = 0;
/**
* Creates an instance of the Tab Panel
*/
public USOCPanel() {
properties = MainController.getInstance()
.getLayout().getUsocPaneProperties();
prepareComponents();
}
/**
* Sets up components and prepares layouts
*/
private void prepareComponents() {
setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
minWidth(320);
// Charts Tab
ScrollPane chartScroll = new ScrollPane();
chartScroll.setFitToWidth(true);
chartScroll.setFitToHeight(true);
// Adds each chart to the chart grid
for (Chart chart : properties.getCharts()) {
addChart(chart);
}
prepareContextMenu();
// Add chart to main tabs
chartScroll.setContent(chartGrid);
chartTab.setText("Charts");
chartTab.setContent(chartScroll);
getTabs().add(chartTab);
if (properties.isGnssEnabled()) {
StackPane gnssStack = new StackPane();
GNSSPanel.addGNSSPaneltoStackPane(gnssStack);
gnssTab.setText("GNSS 3D View");
gnssTab.setContent(gnssStack);
getTabs().add(gnssTab);
}
}
/**
* Prepares ChartGrid Context Menu
*/
private void prepareContextMenu() {
ContextMenu chartGridContextMenu = new ContextMenu();
chartGridContextMenu.setImpl_showRelativeToWindow(true);
MenuItem addChartMenuItem = new MenuItem("Add Chart");
addChartMenuItem.setOnAction(onAction -> {
chartGridContextMenu.hide();
Dialog<Chart> addChartDialog = createAddEditChartDialog(false);
Optional<Chart> result = addChartDialog.showAndWait();
result.ifPresent(newChart -> {
addChart(newChart);
properties.getCharts().add(newChart);
});
});
chartGridContextMenu.setImpl_showRelativeToWindow(true);
chartGrid.setOnContextMenuRequested(onRequest -> {
onRequest.consume();
chartGridContextMenu.show(chartGrid,
onRequest.getScreenX(), onRequest.getScreenY());
});
chartGridContextMenu.getItems().addAll(addChartMenuItem);
}
/**
* Creates the add/edit chart dialog
*
* @param isEditDialog flag used to tell if the dialog is used to edit or add a chart
* @return the created dialog
*/
private Dialog<Chart> createAddEditChartDialog(boolean isEditDialog) {
Dialog<Chart> dialog = new Dialog<>();
dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField title = new TextField();
title.setPromptText("Title");
TextField xLabel = new TextField();
xLabel.setPromptText("x Label");
TextField yLabel = new TextField();
yLabel.setPromptText("y Label");
grid.add(new Label("Title:"), 0, 0);
grid.add(title, 1, 0);
grid.add(new Label("x Label:"), 0, 1);
grid.add(xLabel, 1, 1);
grid.add(new Label("y Label:"), 0, 2);
grid.add(yLabel, 1, 2);
dialog.getDialogPane().setContent(grid);
dialog.setResultConverter(dialogButton -> {
if (dialogButton == ButtonType.OK) {
return new Chart(title.getText(),
xLabel.getText(), yLabel.getText());
}
return null;
});
if (isEditDialog) {
dialog.setTitle("Edit Chart");
dialog.setHeaderText("Edit a current chart");
} else {
dialog.setTitle("Add Chart");
dialog.setHeaderText("Add a new Chart to the grid");
}
return dialog;
}
/**
* Creates a new Line Chart, and adds it to the correct
* position inside the chartGrid
*
* @param chart given chart configuration instance
*/
private void addChart(Chart chart) {
final int maxColumns = properties.getChartColumns();
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
ChartController chartController = new ChartController();
xAxis.setLabel(chart.getxLabel());
yAxis.setLabel(chart.getyLabel());
LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
lineChart.setTitle(chart.getTitle());
// Create context menu for each chart
ContextMenu chartContextMenu = new ContextMenu();
MenuItem editChartMenuItem = new MenuItem("Edit");
editChartMenuItem.setOnAction(onAction -> {
chartContextMenu.hide();
Dialog<Chart> editChartDialog = createAddEditChartDialog(true);
Optional<Chart> res = editChartDialog.showAndWait();
res.ifPresent(newChart -> {
chart.setTitle(newChart.getTitle());
chart.setxLabel(newChart.getxLabel());
chart.setyLabel(newChart.getyLabel());
lineChart.setTitle(chart.getTitle());
lineChart.getXAxis().setLabel(chart.getxLabel());
lineChart.getYAxis().setLabel(chart.getyLabel());
});
});
MenuItem deleteChartMenuItem = new MenuItem("Delete");
deleteChartMenuItem.setOnAction(onAction -> {
chartContextMenu.hide();
chartGrid.getChildren().remove(lineChart);
properties.getCharts().remove(chart);
});
// Auto-Hides Menu when clicked outside of it
chartContextMenu.setImpl_showRelativeToWindow(true);
chartContextMenu.getItems().addAll(editChartMenuItem,
new SeparatorMenuItem(), deleteChartMenuItem);
lineChart.setOnContextMenuRequested(onAction -> {
onAction.consume();
chartContextMenu.show(lineChart,
onAction.getScreenX(), onAction.getScreenY());
});
chartController.addChart(lineChart);
chartGrid.add(lineChart, column, row);
column++;
if (column > (maxColumns - 1)) {
row++;
column = 0;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.rhhs.frc.commands;
import edu.rhhs.frc.subsystems.PneumaticSubsystem;
import edu.rhhs.frc.subsystems.Winch;
/**
*
* @author kenny
*/
public class WinchRewind extends ExtraTwoTimeoutCommandBase {
private static final double REWIND_TIME = 2.0;
private static final double UNWIND_TIME = 0.1;
private boolean m_doneRewinding = false;
public WinchRewind() {
requires(getWinch());
}
// Called just before this Command runs the first time
protected void initialize() {
m_doneRewinding = false;
// System.out.println("Start rewind");
getWinch().setBrakePosition(PneumaticSubsystem.RETRACT);
getWinch().setShiftPosition(PneumaticSubsystem.EXTEND);
getWinch().setWinchSpeed(Winch.WINCH_REWIND_SPEED);
startExtraTimeout1(REWIND_TIME);
resetTimer2();
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (m_doneRewinding == false && isExtraTimedOut1()) {
// System.out.println("Done with rewinding");
getWinch().stopWinch();
startExtraTimeout2(UNWIND_TIME);
m_doneRewinding = true;
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isExtraTimedOut2();
}
// Called once after isFinished returns true
protected void end() {
// System.out.println("Rewind Reset Zero");
getWinch().stopWinch();
getWinch().resetZeroPosition();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
|
package com.parseus.codecinfo.fragments
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ShareCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.parseus.codecinfo.MainActivity
import com.parseus.codecinfo.R
import com.parseus.codecinfo.settings.SettingsActivity
import com.parseus.codecinfo.adapters.CodecInfoAdapter
import com.parseus.codecinfo.codecinfo.getDetailedCodecInfo
import kotlinx.android.synthetic.main.codec_details_fragment_layout.*
class CodecDetailsDialogFragment : DialogFragment() {
private var dismissDialog = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.codec_details_fragment_layout, container, false)
val toolbar: Toolbar
try {
toolbar = ViewCompat.requireViewById(view, R.id.dialogToolbar)
} catch (e: Exception) {
dismissDialog = true
return null
}
toolbar.title = requireContext().getString(R.string.codec_details)
(requireActivity() as MainActivity).setSupportActionBar(toolbar)
(requireActivity() as MainActivity).supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeButtonEnabled(true)
setHomeAsUpIndicator(android.R.drawable.ic_menu_close_clear_cancel)
}
setHasOptionsMenu(true)
return view
}
override fun onResume() {
super.onResume()
if (dismissDialog) {
requireActivity().supportFragmentManager.popBackStack()
dismiss()
return
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val codecId = arguments!!.getString("codecId")
val codecName = arguments!!.getString("codecName")
val codecInfoMap = getDetailedCodecInfo(requireContext(), codecId!!, codecName!!)
val codecAdapter = CodecInfoAdapter(codecInfoMap)
(full_codec_info_name as TextView).text = codecName
full_codec_info_content.apply {
layoutManager = LinearLayoutManager(context)
adapter = codecAdapter
ViewCompat.setNestedScrollingEnabled(this, false)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(R.menu.fragment_bar_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
@SuppressLint("InflateParams")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> dismiss()
R.id.fragment_menu_item_share -> {
val codecId = arguments!!.getString("codecId")
val codecName = arguments!!.getString("codecName")
val header = "${requireContext().getString(R.string.codec_details)}: $codecName\n\n"
val codecStringBuilder = StringBuilder(header)
val codecInfoMap = getDetailedCodecInfo(requireContext(), codecId!!, codecName!!)
for (key in codecInfoMap.keys) {
codecStringBuilder.append("$key\n${codecInfoMap[key]}\n\n")
}
ShareCompat.IntentBuilder.from(activity).setType("text/plain")
.setText(codecStringBuilder.toString()).startChooser()
}
R.id.menu_item_settings -> startActivity(Intent(requireActivity(), SettingsActivity::class.java))
}
return true
}
}
|
package thesis.data.repositories;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import thesis.data.entities.Question;
import thesis.data.entities.QuestionTermFrequency;
import thesis.data.entities.Term;
import thesis.data.repositoryinterfaces.IQuestionTermFrequencyRepository;
import thesis.util.Constants;
public class QuestionTermFrequencyRepository extends GenericRepository<QuestionTermFrequency>
implements IQuestionTermFrequencyRepository {
private static Logger logger = LogManager.getLogger(QuestionTermFrequencyRepository.class);
public QuestionTermFrequencyRepository() {
super(Constants.Entities.QuestionTermFrequency);
}
public List<QuestionTermFrequency> createQuestionTermFrequencies(HashMap<String, Term> termMap, Question question,
HashMap<String, Integer> questionTermFreqMap) {
List<QuestionTermFrequency> questionTermFrequencies = questionTermFreqMap.keySet()
.stream()
.map(term -> {
if (termMap.get(term) == null) {
logger.warn("************" + term);
}
QuestionTermFrequency questionTermFrequency = new QuestionTermFrequency();
questionTermFrequency.setQuestion(question);
questionTermFrequency.setTerm(termMap.get(term));
questionTermFrequency.setFrequency(questionTermFreqMap.get(term));
return questionTermFrequency;
})
.collect(Collectors.toList());
create(questionTermFrequencies);
return questionTermFrequencies;
}
}
|
package org.bitlap.zim.domain
import org.bitlap.zim.configuration.SystemConstant
/**
* 结果集
*
* @param code 状态,0表示成功,其他表示失败
* @param msg 额外信息
* @since 2021年12月25日
* @author 梦境迷离
*/
class ResultSet[T](
val data: T,
val code: Int = SystemConstant.SUCCESS,
val msg: String = SystemConstant.SUCCESS_MESSAGE
)
object ResultSet {
def apply[T](
data: T = null,
code: Int = SystemConstant.SUCCESS,
msg: String = SystemConstant.SUCCESS_MESSAGE
): ResultSet[T] = new ResultSet(data, code, msg)
}
class ResultSets[T](
val data: List[T] = Nil,
val code: Int = SystemConstant.SUCCESS,
val msg: String = SystemConstant.SUCCESS_MESSAGE
)
object ResultSets {
def apply[T](
data: List[T] = Nil,
code: Int = SystemConstant.SUCCESS,
msg: String = SystemConstant.SUCCESS_MESSAGE
): ResultSets[T] = new ResultSets(data, code, msg)
}
case class ResultPageSet[T](override val data: T, pages: Int) extends ResultSet(data)
|
namespace DarwinClient.SchemaV16
{
public partial class Pport
{
public Message Message { get; set; }
}
}
|
MODULE m_vvacxc
! ********************************************************************
! calculates 2-dim star function coefficients of exchange-correlation*
! potential in the vacuum regions and adds them to the corresponding*
! coeffs of the coulomb potential c.l.fu, r.podloucky *
! ********************************************************************
CONTAINS
SUBROUTINE vvacxc(ifftd2,stars,vacuum,xcpot,input,noco,den,vxc,exc)
! ********************************************************************
! instead of vvacxcor.f: the different exchange-correlation
! potentials defined through the key icorr are called through
! the driver subroutine vxcall.f, subroutines vectorized
! in case of TOTAL = .TRUE. calculates the ex.-corr. energy
! density through the driver subroutine excall.f
! ** r.pentcheva 08.05.96
! ********************************************************************
USE m_types
USE m_constants
USE m_fft2d
IMPLICIT NONE
CLASS(t_xcpot),INTENT(IN) :: xcpot
TYPE(t_input),INTENT(IN) :: input
TYPE(t_vacuum),INTENT(IN) :: vacuum
TYPE(t_noco),INTENT(IN) :: noco
TYPE(t_stars),INTENT(IN) :: stars
TYPE(t_potden),INTENT(IN) :: den
TYPE(t_potden),INTENT(INOUT) :: vxc,exc
! ..
! .. Scalar Arguments ..
INTEGER, INTENT (IN) :: ifftd2
! ..
! ..
! .. Local Scalars ..
INTEGER :: k,js,nt,irec2,nmzdiff,ivac,ip,i
REAL :: rhti
REAL :: chdens,magmom
! ..
! .. Local Arrays ..
COMPLEX :: fgxy(stars%ng2-1)
REAL :: af2(0:ifftd2-1,input%jspins),bf2(0:ifftd2-1),fgz
REAL,ALLOCATABLE :: mx(:),my(:)
! warping region
REAL :: v_xc(0:ifftd2-1,input%jspins),e_xc(0:ifftd2-1)
REAL :: v_x (0:ifftd2-1,input%jspins)
! beyond warping region
REAL :: vxcz(vacuum%nmzd,input%jspins)
REAL :: vxz (vacuum%nmzd,input%jspins)
IF (noco%l_noco) THEN
ALLOCATE (mx(0:ifftd2-1),my(0:ifftd2-1))
END IF
nt = ifftd2
rhti = 0.
!
! the charge density in vacuum is expanded in 2-dim stars on a mesh
! in z-direction . The G||.ne.zero-components expand from 1 to nmzxy
! the G||.eq.zero-components expand from 1 to nmz
! first we calculate vxc in the warping region
!
DO ivac = 1,vacuum%nvac
DO ip = 1,vacuum%nmzxy
!
! transform charge density to real space: 2-dim FFT
!
DO js = 1,input%jspins
CALL fft2d(stars, af2(0,js),bf2, den%vacz(ip,ivac,js),rhti,&
den%vacxy(ip,1,ivac,js), vacuum%nmzxyd,+1)
END DO
IF (noco%l_noco) THEN
CALL fft2d(stars, mx,my, den%vacz(ip,ivac,3),den%vacz(ip,ivac,4),&
den%vacxy(ip,1,ivac,3), vacuum%nmzxyd,1)
DO i=0,9*stars%mx1*stars%mx2-1
chdens= (af2(i,1)+af2(i,2))/2.
magmom= mx(i)**2 + my(i)**2 + ((af2(i,1)-af2(i,2))/2.)**2
magmom= SQRT(magmom)
af2(i,1)= chdens + magmom
af2(i,2)= chdens - magmom
END DO
END IF
!
! calculate the exchange-correlation potential in real space
!
CALL xcpot%get_vxc(input%jspins,af2,v_xc,v_x)
DO js = 1,input%jspins
!
! ----> 2-d back fft to g space
!
bf2=0.0
CALL fft2d(stars, v_xc(0,js),bf2, fgz,rhti,fgxy, 1,-1)
!
! ----> and add vxc to coulomb potential
! the G||.eq.zero component is added to vz
!
vxc%vacz(ip,ivac,js) = fgz + vxc%vacz(ip,ivac,js)
!
! the G||.ne.zero components are added to vxc%vacxy
!
DO irec2 = 1,stars%ng2-1
vxc%vacxy(ip,irec2,ivac,js) = vxc%vacxy(ip,irec2,ivac,js) + fgxy(irec2)
ENDDO
ENDDO
!
!i calculate the exchange-correlation energy density in real space
!
IF (ALLOCATED(exc%vacz)) THEN
call xcpot%get_exc(input%jspins,af2,e_xc, mt_call=.False.)
!
! ----> 2-d back fft to g space
!
bf2=0.0
CALL fft2d(stars, e_xc,bf2, exc%vacz(ip,ivac,1),rhti,exc%vacxy(ip,1,ivac,1), vacuum%nmzxyd,-1)
ENDIF
ENDDO
!
! calculate vxc for z now beyond warping region
!
nmzdiff = vacuum%nmz - vacuum%nmzxy
DO k=1,nmzdiff
DO js=1,input%jspins
af2(k-1,js) = den%vacz(vacuum%nmzxy+k,ivac,js)
ENDDO
IF (noco%l_noco) THEN
mx(0)= den%vacz(vacuum%nmzxy+k,ivac,3)
my(0)= den%vacz(vacuum%nmzxy+k,ivac,4)
chdens= (af2(k-1,1)+af2(k-1,2))/2.
magmom= mx(0)**2 + my(0)**2 + ((af2(k-1,1)-af2(k-1,2))/2.)**2
magmom= SQRT(magmom)
af2(k-1,1)= chdens + magmom
af2(k-1,2)= chdens - magmom
END IF
ENDDO
CALL xcpot%get_vxc(input%jspins,af2(0:nmzdiff-1,:),vxz,vxcz)
!+gu
DO js=1,input%jspins
DO k=vacuum%nmzxy+1,vacuum%nmz
vxc%vacz(k,ivac,js) = vxc%vacz(k,ivac,js) + vxcz(k-vacuum%nmzxy,js)
ENDDO
ENDDO
!
WRITE (oUnit,FMT=8020) ivac, (vxc%vacz(vacuum%nmz,ivac,js),js=1,input%jspins)
8020 FORMAT (/,5x,'vacuum zero for vacuum',i3,' = ',2f10.5)
!
! calculate the ex.-corr. energy density now beyond warping region
!
IF (ALLOCATED(exc%vacz)) THEN
CALL xcpot%get_exc(input%jspins,af2(0:nmzdiff-1,:),exc%vacz(vacuum%nmzxy+1:,ivac,1), mt_call=.False.)
END IF
ENDDO
IF (noco%l_noco) THEN
DEALLOCATE (mx,my)
END IF
END SUBROUTINE vvacxc
END MODULE m_vvacxc
|
import React from 'react';
import PropTypes from 'prop-types';
import { request } from '../../../globalLib';
import {
Dialog,
Button,
Form,
Grid,
Input,
Pagination,
Table,
ConfigProvider,
} from '@alifd/next';
const FormItem = Form.Item;
const { Row, Col } = Grid;
const { Column } = Table;
@ConfigProvider.config
class ServiceDialog extends React.Component {
static displayName = 'ServiceDialog';
static propTypes = {
getInstance: PropTypes.func,
};
constructor(props) {
super(props);
this.state = {
loading: false,
total: 0,
pageSize: 10,
currentPage: 1,
dataSource: [],
dialogVisible: false,
search: {
serviceName: '',
},
};
this.show = this.show.bind(this);
}
componentDidMount() {
this.queryServiceList();
}
queryServiceList() {
const { currentPage, pageSize, search } = this.state;
const parameter = [
`pageNo=${currentPage}`,
`pageSize=${pageSize}`,
`serviceNameParam=${search.serviceName}`,
];
request({
url: `v1/ns/catalog/services?${parameter.join('&')}`,
beforeSend: () => this.openLoading(),
success: ({ count = 0, serviceList = [] } = {}) => {
this.setState({
dataSource: serviceList,
total: count,
});
},
error: () =>
this.setState({
dataSource: [],
total: 0,
currentPage: 0,
}),
complete: () => this.closeLoading(),
});
}
openLoading() {
this.setState({ loading: true });
}
closeLoading() {
this.setState({ loading: false });
}
show() {
this.setState({ dialogVisible: true });
}
hide() {
this.setState({ dialogVisible: false });
}
onConfirm(item) {
this.props.getInstance && this.props.getInstance(item);
this.hide();
}
render() {
const { search, loading, dialogVisible, currentPage, total, pageSize, dataSource } = this.state;
return (
<Dialog
className="service-dialog"
title="选择服务"
style={{ width: 600 }}
footerActions={['cancel']}
visible={dialogVisible}
onCancel={() => this.hide()}
onClose={() => this.hide()}
>
<Row
className="demo-row"
style={{
marginBottom: 10,
padding: 0,
}}
>
<Col span="24">
<Form inline field={this.field}>
<FormItem label="服务名称">
<Input
placeholder="请输入服务名称"
style={{ width: 200 }}
value=""
onChange={serviceName => this.setState({ search: { ...search, serviceName } })}
onPressEnter={() =>
this.setState({ currentPage: 1 }, () => this.queryServiceList())
}
/>
</FormItem>
<FormItem label="">
<Button
type="primary"
onClick={() => this.setState({ currentPage: 1 }, () => this.queryServiceList())}
style={{ marginRight: 10 }}
>
查询
</Button>
</FormItem>
</Form>
</Col>
</Row>
<Row style={{ padding: 0 }}>
<Col span="24" style={{ padding: 0 }}>
<Table
dataSource={dataSource}
loading={loading}
locale={{ empty: '没有数据' }}
>
<Column title="服务名" dataIndex="name" />
<Column title="分组名称" width={150} dataIndex="groupName" />
<Column title="实例数" width={70} dataIndex="ipCount" />
<Column title="健康实例数" width={100} dataIndex="healthyInstanceCount" />
<Column
title="操作"
align="center"
width={80}
cell={(value, index, record) => (
<div>
<Button type="primary" onClick={() => this.onConfirm(record)}>选择</Button>
</div>
)}
/>
</Table>
</Col>
</Row>
{total > pageSize && (
<div
style={{
marginTop: 10,
textAlign: 'right',
}}
>
<Pagination
current={currentPage}
total={total}
pageSize={pageSize}
onChange={currentPage =>
this.setState({ currentPage }, () => this.queryServiceList())
}
/>
</div>
)}
</Dialog>
);
}
}
export default ServiceDialog;
|
package utils.connection
import common.CommonParams
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.hbase.client._
import org.apache.hadoop.hbase.{HBaseConfiguration, HColumnDescriptor, HTableDescriptor, TableName}
/**
* @author YKL on 2018/3/27.
* @version 1.0
* 说明:
*/
object HBaseUtil {
def getHBaseConf(): Configuration = {
val hbaseConf = HBaseConfiguration.create()
hbaseConf.set("hbase.zookeeper.quorum", CommonParams.HBASEHOST)
hbaseConf.set("hbase.zookeeper.property.clientPort", CommonParams.HBASEPORT)
hbaseConf.set("hbase.defaults.for.version.skip", "true")
hbaseConf
}
def getHBaseConnection(): Connection = {
val hbaseConf = HBaseConfiguration.create()
hbaseConf.set("hbase.zookeeper.quorum", CommonParams.HBASEHOST)
hbaseConf.set("hbase.zookeeper.property.clientPort", CommonParams.HBASEPORT)
hbaseConf.set("hbase.defaults.for.version.skip", "true")
val hbaseConn = ConnectionFactory.createConnection(hbaseConf) //获取HBase连接,分区创建一个连接,分区不跨节点,不需要序列化
return hbaseConn
}
def getHBaseTable(tableName: String): Table = {
val userTable = TableName.valueOf(tableName)
val admin = getHBaseConnection().getAdmin
if (admin.tableExists(userTable)) {
val table = getHBaseConnection().getTable(userTable)
return table
} else {
val tableDesc = new HTableDescriptor(userTable)
tableDesc.addFamily(new HColumnDescriptor(CommonParams.FINALCOLUMNFAMILY.getBytes))
admin.createTable(tableDesc)
val table = getHBaseConnection().getTable(userTable)
return table
}
}
}
|
identities = (2..99).flat_map { |x| ((x > 9 ? 123 : 1234)..(10000 / x)).map { |y| { x: x, y: y, p: x * y } } }
pandigital_identities = identities.select { |i| [i[:x], i[:y], i[:p]].join.split('').sort.join == '123456789' }
unique_pandigital_identities = pandigital_identities.uniq { |i| i[:p] }
puts unique_pandigital_identities.map { |i| i[:p] }.inject(:+)
|
(in-package :cl-user)
(defpackage :mof-browser
(:nicknames :mofb)
(:use :cl :closer-mop :pod-utils :cl-who :hunchentoot :mofi)
(:shadowing-import-from :closer-mop #:standard-class #:ensure-generic-function
#:defgeneric #:standard-generic-function #:defclass #:defmethod)
(:export #:*application-url-key-fn*
#:decode-angle
#:decode-for-url
#:decode-for-url-meth
#:encode-angle
#:encode-for-url
#:*list-title-fn*
#:*mof-browser-class-view-menu-structure*
#:mof-class-view-dsp
#:mof-model-list-dsp
#:mof-obj-view-dsp
#:mof-pprint
#:pretty-html
#:request-uri
#:remove-model-dsp
#:show-slot
#:url-class-browser
#:url-object-browser
#:url-ocl-operator
#:url-mof-model
#:url-property-button
#:url-remove-model))
|
// Long-term
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_macros)]
#![allow(unused_braces)]
#![allow(non_upper_case_globals)]
// Short-term allows
/* */
#![allow(unused_imports)]
#![allow(unused_mut)]
/* */
extern crate alloc;
#[cfg(not(debug_assertions))]
macro_rules! panic {
( $( $arg:tt )+ ) => {{
#[cfg(target_arch = "wasm32")]
core::arch::wasm32::unreachable();
#[cfg(not(target_arch = "wasm32"))]
unsafe {
core::ptr::write_volatile(core::ptr::null_mut(), 0);
core::hint::unreachable_unchecked()
}
}};
}
#[cfg(not(debug_assertions))]
macro_rules! unreachable {
( $( $arg:tt )* ) => {{
panic!()
}};
}
#[macro_use]
mod basic;
mod alloc_api;
mod global_bulk;
#[macro_use]
mod pod;
mod bump;
mod fswatch;
mod hashref;
pub use alloc_api::*;
pub use basic::*;
pub use bump::*;
pub use global_bulk::*;
pub use hashref::*;
pub use pod::*;
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class LoginUserController extends Controller
{
public function index()
{
return view('login.index');
}
public function put()
{
Session::put('login', 'Selamat anda berhasil login');
return redirect()->route('home');
}
public function home()
{
return view('login.home');
}
public function logoutuser()
{
Session::forget('login');
return redirect()->route('login.user');
}
}
|
<<<<<<< HEAD
# cs3240-labdmo
=======
# cs3240-labdem
>>>>>>> refs/remotes/origin/master
|
qemu-system-i386 -serial mon:stdio -hdb fs.img xv6.img -smp 1 -m 512
|
/*******************************************************************************
* Copyright 2008-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2011-10-01
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.SQS.Model
{
/// <summary>
/// Retrieves one or more messages from the specified queue, including the message body and message ID of each message.
/// Messages returned by this action stay in the queue until you delete them. However, once a message is returned to a
/// ReceiveMessage request, it is not returned on subsequent ReceiveMessage requests for the duration of the
/// VisibilityTimeout. If you do not specify a VisibilityTimeout in the request, the overall visibility timeout for the
/// queue is used for the returned messages.
/// </summary>
[XmlRootAttribute(Namespace = "http://queue.amazonaws.com/doc/2011-10-01/", IsNullable = false)]
public class ReceiveMessageRequest
{
private string queueUrlField;
private Decimal? maxNumberOfMessagesField;
private Decimal? visibilityTimeoutField;
private List<string> attributeNameField;
/// <summary>
/// Gets and sets the QueueUrl property.
/// The URL associated with the Amazon SQS queue.
/// </summary>
[XmlElementAttribute(ElementName = "QueueUrl")]
public string QueueUrl
{
get { return this.queueUrlField; }
set { this.queueUrlField = value; }
}
/// <summary>
/// Sets the QueueUrl property
/// </summary>
/// <param name="queueUrl">The URL associated with the Amazon SQS queue.</param>
/// <returns>this instance</returns>
public ReceiveMessageRequest WithQueueUrl(string queueUrl)
{
this.queueUrlField = queueUrl;
return this;
}
/// <summary>
/// Checks if QueueUrl property is set
/// </summary>
/// <returns>true if QueueUrl property is set</returns>
public bool IsSetQueueUrl()
{
return this.queueUrlField != null;
}
/// <summary>
/// Gets and sets the MaxNumberOfMessages property.
/// Maximum number of messages to return. SQS never returns more messages than this value but might return fewer.
/// Not necessarily all the messages in the queue are returned (for more information, see the preceding note about
/// machine sampling). Values can be from 1 to 10. Default is 1.
/// </summary>
[XmlElementAttribute(ElementName = "MaxNumberOfMessages")]
public Decimal MaxNumberOfMessages
{
get { return this.maxNumberOfMessagesField.GetValueOrDefault(); }
set { this.maxNumberOfMessagesField = value; }
}
/// <summary>
/// Sets the MaxNumberOfMessages property
/// </summary>
/// <param name="maxNumberOfMessages">Maximum number of messages to return. SQS never returns more messages than this value but might return fewer.
/// Not necessarily all the messages in the queue are returned (for more information, see the preceding note about
/// machine sampling). Values can be from 1 to 10. Default is 1.</param>
/// <returns>this instance</returns>
public ReceiveMessageRequest WithMaxNumberOfMessages(Decimal maxNumberOfMessages)
{
this.maxNumberOfMessagesField = maxNumberOfMessages;
return this;
}
/// <summary>
/// Checks if MaxNumberOfMessages property is set
/// </summary>
/// <returns>true if MaxNumberOfMessages property is set</returns>
public bool IsSetMaxNumberOfMessages()
{
return this.maxNumberOfMessagesField.HasValue;
}
/// <summary>
/// Gets and sets the VisibilityTimeout property.
/// The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved
/// by a ReceiveMessage request.
/// </summary>
[XmlElementAttribute(ElementName = "VisibilityTimeout")]
public Decimal VisibilityTimeout
{
get { return this.visibilityTimeoutField.GetValueOrDefault(); }
set { this.visibilityTimeoutField = value; }
}
/// <summary>
/// Sets the VisibilityTimeout property
/// </summary>
/// <param name="visibilityTimeout">The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved
/// by a ReceiveMessage request.</param>
/// <returns>this instance</returns>
public ReceiveMessageRequest WithVisibilityTimeout(Decimal visibilityTimeout)
{
this.visibilityTimeoutField = visibilityTimeout;
return this;
}
/// <summary>
/// Checks if VisibilityTimeout property is set
/// </summary>
/// <returns>true if VisibilityTimeout property is set</returns>
public bool IsSetVisibilityTimeout()
{
return this.visibilityTimeoutField.HasValue;
}
/// <summary>
/// Gets and sets the AttributeName property.
/// The attribute you want to get. Valid values: All | SenderId | SentTimestamp | ApproximateReceiveCount |
/// ApproximateFirstReceiveTimestamp
/// </summary>
[XmlElementAttribute(ElementName = "AttributeName")]
public List<string> AttributeName
{
get
{
if (this.attributeNameField == null)
{
this.attributeNameField = new List<string>();
}
return this.attributeNameField;
}
set { this.attributeNameField = value; }
}
/// <summary>
/// Sets the AttributeName property
/// </summary>
/// <param name="list">The attribute you want to get. Valid values: All | SenderId | SentTimestamp | ApproximateReceiveCount |
/// ApproximateFirstReceiveTimestamp</param>
/// <returns>this instance</returns>
public ReceiveMessageRequest WithAttributeName(params string[] list)
{
foreach (string item in list)
{
AttributeName.Add(item);
}
return this;
}
/// <summary>
/// Checks if AttributeName property is set
/// </summary>
/// <returns>true if AttributeName property is set</returns>
public bool IsSetAttributeName()
{
return (AttributeName.Count > 0);
}
}
}
|
The "Python-Deprecated" project has moved since November 2017 to https://github.com/tantale/deprecated
|
program primo;
var n,i,cont:longint;
begin
read(n);
cont:=0;
i:=2;
while i<=n-1 do
begin
if(n mod i = 0) then
cont:=cont+1;
i:=i+1;
end;
if cont = 0 then
writeln('SIM')
else
writeln('NAO');
end.
|
<?php
declare(strict_types=1);
namespace App\Method;
/**
* @author Dean Blackborough <dean@g3d-development.com>
* @copyright Dean Blackborough 2018-2021
* @license https://github.com/costs-to-expect/api/blob/master/LICENSE
*/
class GetRequest extends Method
{
protected bool $pagination;
protected array $pagination_parameters;
protected array $parameters;
protected array $dynamic_parameters;
protected array $parameters_after_localisation;
protected bool $filterable;
protected array $filterable_parameters;
protected bool $searchable;
protected array $searchable_parameters;
protected bool $sortable;
protected array $sortable_parameters;
public function __construct()
{
parent::__construct();
$this->pagination = false;
$this->pagination_parameters = [];
$this->parameters = [];
$this->dynamic_parameters = [];
$this->parameters_after_localisation = [];
$this->filterable = false;
$this->filterable_parameters = [];
$this->searchable = false;
$this->searchable_parameters = [];
$this->sortable = false;
$this->sortable_parameters = [];
}
public function setFilterableParameters(
array $parameters
): GetRequest
{
if (count($parameters) > 0) {
$this->filterable = true;
$this->filterable_parameters = $parameters;
}
return $this;
}
public function setPaginationStatus(
bool $status = false,
bool $override = false
): GetRequest
{
if ($status === true) {
$this->pagination = true;
if ($override === false) {
$this->pagination_parameters = $this->api_config->paginationParameters();
} else {
$this->pagination_parameters = $this->api_config->paginationParametersAllowingEntireCollection();
}
}
return $this;
}
public function setParameters(
array $parameters
): GetRequest
{
if (count($parameters) > 0) {
$this->parameters = $parameters;
}
return $this;
}
public function setDynamicParameters(
array $parameters = []
): GetRequest
{
$this->dynamic_parameters = $parameters;
return $this;
}
public function setSearchableParameters(
array $parameters
): GetRequest
{
if (count($parameters) > 0) {
$this->searchable = true;
$this->searchable_parameters = $parameters;
}
return $this;
}
public function setSortableParameters(
array $parameters
): GetRequest
{
if (count($parameters) > 0) {
$this->sortable = true;
$this->sortable_parameters = $parameters;
}
return $this;
}
protected function mergeAndLocalise(): void
{
foreach (
array_merge_recursive(
$this->pagination_parameters,
($this->sortable === true ? $this->api_config->sortParameter() : []),
($this->searchable === true ? $this->api_config->searchParameter() : []),
($this->filterable === true ? $this->api_config->filterParameter() : []),
$this->parameters,
$this->dynamic_parameters
)
as $parameter => $parameter_data
) {
if (
array_key_exists('title', $parameter_data) === true &&
array_key_exists('description', $parameter_data) === true
) {
$parameter_data['title'] = trans($parameter_data['title']);
$parameter_data['description'] = trans($parameter_data['description']);
$this->parameters_after_localisation[$parameter] = $parameter_data;
}
}
}
public function option(): array
{
$this->mergeAndLocalise();
return [
'description' => $this->description,
'authentication' => [
'required' => $this->authentication,
'authenticated' => $this->authenticated
],
'sortable' => $this->sortable_parameters,
'searchable' => $this->searchable_parameters,
'filterable' => $this->filterable_parameters,
'parameters' => $this->parameters_after_localisation
];
}
}
|
package runtime
// Object represents minimal object that could be operated in runtime with only Kind being mandatory characteristic
type Object interface {
GetKind() Kind
}
// Storable represents runtime object that could be stored in database and having two additional mandatory characteristics:
// Name and Namespace that together with Kind forms Key (namespace + kind + name) that represents coordinates of the
// object in database
type Storable interface {
Object
GetName() string
GetNamespace() string
}
// Versioned extends Storable with mandatory Generation characteristic to represent versioned objects that are having
// multiple generations stored in database
type Versioned interface {
Storable
GetGeneration() Generation
SetGeneration(gen Generation)
}
// Deletable extends Versioned with deleted marker to represent versioned objects that could be marked as deleted,
// but then created again even with the same content. Best example of such objects is policy objects (and the only for now).
// todo remove deletable as it should be handled just outside of the storage, move it to lang.Base
type Deletable interface {
Versioned
IsDeleted() bool
SetDeleted(bool)
}
|
#ifndef _ISSHE_SOCKS_PROTOCOL_H_
#define _ISSHE_SOCKS_PROTOCOL_H_
// 标准
#include <stdint.h>
// 第三方
#include <event2/event.h>
#include <event2/listener.h>
#define ISSHE_SOCKS_FLAG_TO_USER 1
#define ISSHE_SOCKS_FLAG_FROM_USER 2
#define ISSHE_SOCKS_FLAG_CONFIG 4
#define ISSHE_SOCKS_OPT_MAX_LEN 1024
/*
+----------+---------+---------+
| 消息验证码 | 协议选项 | 加密数据 |
+----------+---------+---------+
* 消息验证码:128位/16字节,根据程序ID、时间等生成;防篡改,程序认证。
* 协议选项:类似DHCP选项的形式。通过某个加密算法加密。
* 加密数据:对用户数据进行加密
*/
enum isshe_socks_opt_type
{
ISSHE_SOCKS_OPT_MAC = 0, // Message Authentication Code
ISSHE_SOCKS_OPT_VERSION,
ISSHE_SOCKS_OPT_PROTOCOL, // TCP/UDP
ISSHE_SOCKS_OPT_DOMAIN,
ISSHE_SOCKS_OPT_IPV4,
ISSHE_SOCKS_OPT_IPV6,
ISSHE_SOCKS_OPT_PORT,
ISSHE_SOCKS_OPT_CRYPTO, // 指定数据部分加密算法,没有指定就按配置文件的来
ISSHE_SOCKS_OPT_CRYPTO_KEY,
ISSHE_SOCKS_OPT_CRYPTO_IVEC,
ISSHE_SOCKS_OPT_USER, // 用户名,可以用于流量统计等
ISSHE_SOCKS_OPT_USER_DATA_LEN,
ISSHE_SOCKS_OPT_END = 255,
};
enum isshe_socks_connection_status
{
ISSHE_SCS_CLOSED = 0,
ISSHE_SCS_ESTABLISHED = 1,
};
struct isshe_socks_opt
{
uint8_t type;
uint8_t len;
uint8_t data[0];
};
// TODO 再考虑一下
/*
* isshe_socks_header: 请求/应答,对称协议使用
* isshe_socks_request: 请求,非对称协议使用
* isshe_socks_reply: 应答,非对称协议使用
*/
struct isshe_socks_header
{
uint8_t mac[16];
struct isshe_socks_opt opts[0];
//uint8_t version;
//uint8_t addr_type;
//uint8_t addr_len; // bytes
//uint8_t addr;
};
struct isshe_socks_request
{
// 请求
// uint8_t mac[16];
};
struct isshe_socks_reply
{
// 应答
// uint8_t mac[16];
// isshe_socks_opt opts[0];
};
struct isshe_socks_opts
{
uint8_t addr_type; // 初始化为0, ISSHE_SOCKS_ADDR_TYPE_DOMAIN
uint32_t ipv4; // 初始化为0
uint16_t port; // 初始化为0
uint8_t dname_len; // 初始化为0
uint8_t ipv6_len; // 初始化为0
uint8_t *dname; // domain name
uint8_t *ipv6; // 初始化为NULL
uint32_t user_data_len; // 用户数据长度
};
struct isshe_socks_connection
{
uint8_t status;
int fd;
struct bufferevent *bev;
struct addrinfo *target_ai;
struct isshe_socks_opts *opts;
};
/*
struct isshe_socks_connection
{
uint8_t status;
int fd_from_user;
int fd_to_user;
struct addrinfo *target_ai;
struct isshe_socks_opts *opts;
struct bufferevent *bev_from_user; // 出去的流量(用户角度)
struct bufferevent *bev_to_user; // 进来的流量(用户角度)
};
*/
void isshe_socks_opt_init(uint8_t *buf);
void isshe_socks_opt_add(uint8_t *buf,
uint8_t type, uint8_t len, const void *data);
int isshe_socks_opt_len(uint8_t *buf);
void isshe_socks_opt_parse(uint8_t *buf, int buflen,
struct isshe_socks_opts *opts);
struct isshe_socks_connection *isshe_socks_connection_new();
void isshe_socks_connection_free(
struct isshe_socks_connection *isc);
struct bufferevent *isshe_socks_connect_to_next(
struct event_base *evbase,
struct sockaddr *ai_addr,
socklen_t ai_addrlen,
uint16_t port);
#endif
|
#!/bin/sh
set -e
cd /var/app
if [ -n "$KUZZLE_PLUGINS" ]; then
enable_plugins="--enable-plugins $KUZZLE_PLUGINS"
fi
exec ./bin/start-kuzzle-server "$@" $enable_plugins
|
export default [
{
code: 100,
key: 'CONTINUE',
message: 'Continue',
category: 'INFORMATIONAL'
},
{
code: 101,
key: 'SWITCHING_PROTOCOLS',
message: 'Switching Protocols',
category: 'INFORMATIONAL'
},
{
code: 102,
key: 'PROCESSING',
message: 'Processing',
category: 'INFORMATIONAL'
},
{
code: 200,
key: 'OK',
message: 'OK',
category: 'SUCCESS'
},
{
code: 201,
key: 'CREATED',
message: 'Created',
category: 'SUCCESS'
},
{
code: 202,
key: 'ACCEPTED',
message: 'Accepted',
category: 'SUCCESS'
},
{
code: 203,
key: 'NON_AUTHORITATIVE_INFORMATION',
message: 'Non-authoritative Information',
category: 'SUCCESS'
},
{
code: 204,
key: 'NO_CONTENT',
message: 'No Content',
category: 'SUCCESS'
},
{
code: 205,
key: 'RESET_CONTENT',
message: 'Reset Content',
category: 'SUCCESS'
},
{
code: 205,
key: 'RESET_CONTENT',
message: 'Reset Content',
category: 'SUCCESS'
},
{
code: 206,
key: 'PARTIAL_CONTENT',
message: 'Partial Content',
category: 'SUCCESS'
},
{
code: 207,
key: 'MULTI_STATUS',
message: 'Multi-Status',
category: 'SUCCESS'
},
{
code: 208,
key: 'ALREADY_REPORTED',
message: 'Already Reported',
category: 'SUCCESS'
},
{
code: 216,
key: 'IM_USED',
message: 'IM Used',
category: 'SUCCESS'
},
{
code: 300,
key: 'MULTIPLE_CHOICES',
message: 'Multiple Choices',
category: 'REDIRECTION'
},
{
code: 301,
key: 'MOVED_PERMANENTLY',
message: 'Moved Permanently',
category: 'REDIRECTION'
},
{
code: 302,
key: 'FOUND',
message: 'Found',
category: 'REDIRECTION'
},
{
code: 303,
key: 'SEE_OTHER',
message: 'See Other',
category: 'REDIRECTION'
},
{
code: 304,
key: 'NOT_MODIFIED',
message: 'Not Modified',
category: 'REDIRECTION'
},
{
code: 305,
key: 'USE_PROXY',
message: 'Use Proxy',
category: 'REDIRECTION'
},
{
code: 307,
key: 'TEMPORARY_REDIRECT',
message: 'Temporary Redirect',
category: 'REDIRECTION'
},
{
code: 308,
key: 'PERMANENT_REDIRECT',
message: 'Permanent Redirect',
category: 'REDIRECTION'
},
{
code: 400,
key: 'BAD_REQUEST',
message: 'Bad Request',
category: 'CLIENT_ERROR'
},
{
code: 401,
key: 'UNAUTHORIZED',
message: 'Unauthorized',
category: 'CLIENT_ERROR'
},
{
code: 402,
key: 'PAYMENT_REQUIRED',
message: 'Payment Required',
category: 'CLIENT_ERROR'
},
{
code: 403,
key: 'FORBIDDEN',
message: 'Forbidden',
category: 'CLIENT_ERROR'
},
{
code: 404,
key: 'NOT_FOUND',
message: 'Not Found',
category: 'CLIENT_ERROR'
},
{
code: 405,
key: 'METHOD_NOT_ALLOWED',
message: 'Method Not Allowed',
category: 'CLIENT_ERROR'
},
{
code: 406,
key: 'NOT_ACCEPTABLE',
message: 'Not Acceptable',
category: 'CLIENT_ERROR'
},
{
code: 407,
key: 'PROXY_AUTHENTICATION_REQUIRED',
message: 'Proxy Authentication Required',
category: 'CLIENT_ERROR'
},
{
code: 408,
key: 'REQUEST_TIMEOUT',
message: 'Request Timeout',
category: 'CLIENT_ERROR'
},
{
code: 409,
key: 'CONFLICT',
message: 'Conflict',
category: 'CLIENT_ERROR'
},
{
code: 410,
key: 'GONE',
message: 'Gone',
category: 'CLIENT_ERROR'
},
{
code: 411,
key: 'LENGTH_REQUIRED',
message: 'Length Required',
category: 'CLIENT_ERROR'
},
{
code: 412,
key: 'PRECONDITION_FAILED',
message: 'Precondition Failed',
category: 'CLIENT_ERROR'
},
{
code: 413,
key: 'PAYLOAD_TOO_LARGE',
message: 'Payload Too Large',
category: 'CLIENT_ERROR'
},
{
code: 414,
key: 'REQUEST_URI_TOO_LONG',
message: 'Request-URI Too Long',
category: 'CLIENT_ERROR'
},
{
code: 415,
key: 'UNSUPORTED_MEDIA_TYPE',
message: 'Unsupported Media Type',
category: 'CLIENT_ERROR'
},
{
code: 416,
key: 'REQUESTED_RANGE_NOT_SATISFIABLE',
message: 'Requested Range Not Satisfiable',
category: 'CLIENT_ERROR'
},
{
code: 417,
key: 'EXPECTATION_FAILED',
message: 'Expectation Failed',
category: 'CLIENT_ERROR'
},
{
code: 418,
key: 'IM_A_TEAPOT',
message: "I'm a teapot",
category: 'CLIENT_ERROR'
},
{
code: 421,
key: 'MISDIRECTED_REQUEST',
message: 'Misdirected Request',
category: 'CLIENT_ERROR'
},
{
code: 422,
key: 'UNPROCESSABLE_ENTITY',
message: 'Unprocessable Entity',
category: 'CLIENT_ERROR'
},
{
code: 423,
key: 'LOCKED',
message: 'Locked',
category: 'CLIENT_ERROR'
},
{
code: 424,
key: 'FAILED_DEPENDENCY',
message: 'Failed Dependency',
category: 'CLIENT_ERROR'
},
{
code: 426,
key: 'UPGRADE_REQUIRED',
message: 'Upgrade Required',
category: 'CLIENT_ERROR'
},
{
code: 428,
key: 'PRECONDITION_REQUIRED',
message: 'Precondition Required',
category: 'CLIENT_ERROR'
},
{
code: 429,
key: 'TOO_MANY_REQUESTS',
message: 'Too Many Requests',
category: 'CLIENT_ERROR'
},
{
code: 431,
key: 'REQUEST_HEADER_FIELDS_TOO_LARGE',
message: 'Request Header Fields Too Large',
category: 'CLIENT_ERROR'
},
{
code: 444,
key: 'CONNECTION_CLOSED_WITHOUT_RESPONSE',
message: 'Connection Closed Without Response',
category: 'CLIENT_ERROR'
},
{
code: 451,
key: 'UNAVAILABLE_FOR_LEGAL_REASONS',
message: 'Unavailable For Legal Reasons',
category: 'CLIENT_ERROR'
},
{
code: 499,
key: 'CLIENT_CLOSED_REQUEST',
message: 'Client Closed Request',
category: 'CLIENT_ERROR'
},
{
code: 500,
key: 'INTERNAL_SERVER_ERROR',
message: 'Internal Server Error',
category: 'SERVER_ERROR'
},
{
code: 501,
key: 'NOT_IMPLEMENTED',
message: 'Not Implemented',
category: 'SERVER_ERROR'
},
{
code: 502,
key: 'BAD_GATEWAY',
message: 'Bad Gateway',
category: 'SERVER_ERROR'
},
{
code: 503,
key: 'SERVICE_UNAVAILABLE',
message: 'Service Unavailable',
category: 'SERVER_ERROR'
},
{
code: 504,
key: 'GATEWAY_TIMEOUT',
message: 'Gateway Timeout',
category: 'SERVER_ERROR'
},
{
code: 505,
key: 'HTTP_VERSION_NOT_SUPPORTED',
message: 'HTTP Version Not Supported',
category: 'SERVER_ERROR'
},
{
code: 506,
key: 'VARIANT_ALSO_NEGOTIATES',
message: 'Variant Also Negotiates',
category: 'SERVER_ERROR'
},
{
code: 507,
key: 'INSUFFICIENT_STORAGE',
message: 'Insufficient Storage',
category: 'SERVER_ERROR'
},
{
code: 508,
key: 'LOOP_DETECTED',
message: 'Loop Detected',
category: 'SERVER_ERROR'
},
{
code: 510,
key: 'NOT_EXTENDED',
message: 'Not Extended',
category: 'SERVER_ERROR'
},
{
code: 511,
key: 'NETWORK_AUTHENTICATION_REQUIRED',
message: 'Network Authentication Required',
category: 'SERVER_ERROR'
},
{
code: 599,
key: 'NETWORK_CONNECT_TIMEOUT_ERROR',
message: 'Network Connect Timeout Error',
category: 'SERVER_ERROR'
}
];
|
package pod
import (
"reflect"
"testing"
saasv1alpha1 "github.com/3scale/saas-operator/api/v1alpha1"
secretsmanagerv1alpha1 "github.com/3scale/saas-operator/pkg/apis/secrets-manager/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/pointer"
)
func TestGenerateSecretDefinitionFn(t *testing.T) {
type args struct {
name string
namespace string
labels map[string]string
opts interface{}
}
tests := []struct {
name string
args args
want *secretsmanagerv1alpha1.SecretDefinition
}{
{
name: "Generates a new SecretDefinition from an Options struct",
args: args{
name: "my-secret",
namespace: "test",
labels: map[string]string{},
opts: struct {
Option1 EnvVarValue `env:"OPTION1"`
Option2 EnvVarValue `env:"OPTION2" secret:"my-secret"`
Option3 EnvVarValue `env:"OPTION3" secret:"my-secret"`
Option4 EnvVarValue `env:"OPTION4" secret:"other-secret"`
Option5 EnvVarValue `env:"OPTION5" secret:"not-set"`
}{
Option1: &ClearTextValue{Value: "value1"},
Option2: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key2", Path: "path2"}}},
Option3: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key3", Path: "path3"}}},
Option4: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key3", Path: "path3"}}},
},
},
want: &secretsmanagerv1alpha1.SecretDefinition{
TypeMeta: metav1.TypeMeta{
Kind: "SecretDefinition",
APIVersion: secretsmanagerv1alpha1.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "my-secret",
Namespace: "test",
Labels: map[string]string{},
},
Spec: secretsmanagerv1alpha1.SecretDefinitionSpec{
Name: "my-secret",
Type: "opaque",
KeysMap: map[string]secretsmanagerv1alpha1.DataSource{
"OPTION2": {Key: "key2", Path: "path2"},
"OPTION3": {Key: "key3", Path: "path3"}},
},
},
},
{
name: "Generates other SecretDefinition from the same Options struct (see previous test)",
args: args{
name: "other-secret",
namespace: "test",
labels: map[string]string{},
opts: struct {
Option1 EnvVarValue `env:"OPTION1"`
Option2 EnvVarValue `env:"OPTION2" secret:"my-secret"`
Option3 EnvVarValue `env:"OPTION3" secret:"my-secret"`
Option4 EnvVarValue `env:"OPTION4" secret:"other-secret"`
}{
Option1: &ClearTextValue{Value: "value1"},
Option2: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key2", Path: "path2"}}},
Option3: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key3", Path: "path3"}}},
Option4: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key4", Path: "path4"}}},
},
},
want: &secretsmanagerv1alpha1.SecretDefinition{
TypeMeta: metav1.TypeMeta{
Kind: "SecretDefinition",
APIVersion: secretsmanagerv1alpha1.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "other-secret",
Namespace: "test",
Labels: map[string]string{},
},
Spec: secretsmanagerv1alpha1.SecretDefinitionSpec{
Name: "other-secret",
Type: "opaque",
KeysMap: map[string]secretsmanagerv1alpha1.DataSource{
"OPTION4": {Key: "key4", Path: "path4"},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fn := GenerateSecretDefinitionFn(tt.args.name, tt.args.namespace, tt.args.labels, tt.args.opts)
if got := fn(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("GenerateSecretDefinitionFn() = %v, want %v", got, tt.want)
}
})
}
}
func Test_keysMap(t *testing.T) {
type args struct {
name string
opts interface{}
}
tests := []struct {
name string
args args
want map[string]secretsmanagerv1alpha1.DataSource
wantPanic bool
}{
{
name: "Generates a DataSources map",
args: args{
name: "my-secret",
opts: struct {
Option1 EnvVarValue `env:"OPTION1"`
Option2 EnvVarValue `env:"OPTION2" secret:"my-secret"`
Option3 EnvVarValue `env:"OPTION3" secret:"my-secret"`
Option4 EnvVarValue `env:"OPTION4" secret:"other-secret"`
}{
Option1: &ClearTextValue{Value: "value1"},
Option2: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key2", Path: "path2"}}},
Option3: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key3", Path: "path3"}}},
Option4: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key4", Path: "path4"}}},
},
},
want: map[string]secretsmanagerv1alpha1.DataSource{
"OPTION2": {Key: "key2", Path: "path2"},
"OPTION3": {Key: "key3", Path: "path3"},
},
wantPanic: false,
},
{
name: "Generates a DataSources map, with secret overrides",
args: args{
name: "my-secret",
opts: struct {
Option1 EnvVarValue `env:"OPTION1"`
Option2 EnvVarValue `env:"OPTION2" secret:"my-secret"`
Option3 EnvVarValue `env:"OPTION3" secret:"my-secret"`
Option4 EnvVarValue `env:"OPTION4" secret:"other-secret"`
}{
Option1: &ClearTextValue{Value: "value1"},
Option2: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key2", Path: "path2"}}},
Option3: &SecretValue{Value: saasv1alpha1.SecretReference{
Override: pointer.StringPtr("override")}},
Option4: &SecretValue{Value: saasv1alpha1.SecretReference{
FromVault: &saasv1alpha1.VaultSecretReference{Key: "key4", Path: "path4"}}},
},
},
want: map[string]secretsmanagerv1alpha1.DataSource{
"OPTION2": {Key: "key2", Path: "path2"},
// "OPTION3": {Key: "key3", Path: "path3"},
},
wantPanic: false,
},
{
name: "Panics if value is not a SecretValue",
args: args{
name: "my-secret",
opts: struct {
Option1 EnvVarValue `env:"OPTION1" secret:"my-secret"`
}{
Option1: &ClearTextValue{Value: "xxxx"},
},
},
want: map[string]secretsmanagerv1alpha1.DataSource{},
wantPanic: true,
},
{
name: "Panics if 'env' tag is missing",
args: args{
name: "my-secret",
opts: struct {
Option1 EnvVarValue `secret:"my-secret"`
}{
Option1: &SecretValue{Value: saasv1alpha1.SecretReference{}},
},
},
want: map[string]secretsmanagerv1alpha1.DataSource{},
wantPanic: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer func() {
r := recover()
if r == nil && tt.wantPanic {
t.Errorf("code did not panic")
}
if r != nil && !tt.wantPanic {
t.Errorf("code caused a panic")
}
}()
if got := keysMap(tt.args.name, tt.args.opts); !reflect.DeepEqual(got, tt.want) {
t.Errorf("keysMap() = %v, want %v", got, tt.want)
}
})
}
}
|
<?php
namespace App\Http\Requests\Recursos_Humanos;
use Illuminate\Foundation\Http\FormRequest;
class PermisoEmpleadoRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'persona_id'=>'required|integer',
'asistencia_id'=>'required|integer',
'razon_permiso_id'=>'required|integer',
'fecha_inicio'=>'required|date',
'fecha_fin'=>'required|date',
];
}
public function messages(){
return [
'persona_id.required'=>'Es necesario seleccionar un empleado',
'persona_id.integer'=>'Tipo de dato invalido al seleccionar empleado',
'asistencia_id.required'=>'Es necesario seleccionar una asistencia',
'asistencia_id.integer'=>'Tipo de dato invalido al seleccionar asistencia',
'razon_permiso_id.required'=>'Es necesario seleccionar una justificación',
'razon_permiso_id.integer'=>'Tipo de dato invalido al seleccionar una justificación',
'fecha_inicio.required'=>'Es necesario seleccionar una fecha de inicio',
'fecha_inicio.date'=>'Formato de fecha de inicio no valido',
'fecha_fin.required'=>'Es necesario seleccionar una fecha de fin',
'fecha_fin.date'=>'Formato de fecha de fin no valido',
];
}
}
|
<?php
function Phuby($object, $lookup_class = true) {
if ($lookup_class && is_string($object) && class_exists($object))
return Phuby\Module::const_get($object);
if (Phuby\Enumerable::numeric($object))
return Phuby\Ary::__new($object);
if (is_array($object))
return Phuby\Hash::__new($object);
switch(gettype($object)) {
case 'float': return Phuby\Float::__new($object);
case 'integer': return Phuby\Integer::__new($object);
case 'object': return Phuby\Proxy::__new($object);
case 'string': return Phuby\String::__new($object);
default: return $object;
}
}
|
const emitter = require('emitter-io')
const client = emitter.connect({ host: '127.0.0.1', port: 8083, secure: false })
client.on('message', message => {
console.log({
channel: message.channel,
body: String(JSON.parse(message.binary))
})
})
client.subscribe({
key: process.env.EMITTER_CHANNEL_KEY,
channel: process.env.EMITTER_CHANNEL
})
|
-module(ws_handler).
-export([init/2,
websocket_init/1,
websocket_handle/2,
websocket_info/2
]).
init(Req, _) ->
Room = cowboy_req:binding(room, Req),
{cowboy_websocket, Req, #{room => Room}}.
websocket_init(State) ->
Room = maps:get(room, State),
syn:join(Room, self()),
%% client needs to know if it's the initiator
Members = syn:get_members(Room),
case length(Members) of
1 ->
{reply, reply_text(created), State};
_ ->
syn:publish(Room, reply_text(joined)),
{ok, State}
end.
websocket_handle(Frame = {text, Text}, State) ->
lager:debug("Received text frame ~p", [Frame]),
%% send to all other pids in group
Room = maps:get(room, State),
Members = syn:get_members(Room),
Self = self(),
Send = fun(Pid) when Pid /= Self -> Pid ! {text, Text};
(_Pid) -> ok
end,
lists:foreach(Send, Members),
{ok, State};
websocket_handle(Frame, State) ->
lager:warn("Received non text frame ~p", [Frame]),
{ok, State}.
websocket_info({text, Text}, State) ->
lager:debug("Sending to client ~p", [Text]),
{reply, {text, Text}, State};
websocket_info(Info, State) ->
lager:warn("Received unexpected info ~p", [Info]),
{ok, State}.
%%% internal
reply_text(Event) ->
{text, jsx:encode(#{event => Event})}.
|
namespace BluetoothXPlatformChat.Common.Model
{
public class Message
{
public bool IsToShowDevices { get; set; }
public Message(bool isToShowDevices)
{
this.IsToShowDevices = isToShowDevices;
}
}
}
|
#what is the 10001st prime number?
#set-up
primes = []
p = 2
#Setting up the loop
while not len(primes) == 10001:
num_prime = True
#Eleminate any even candidate primes
if p > 3 and p % 2 == 0:
p += 1
continue
#Check if the candidate is divisible by any odd numbers
for x in range(3, p-1, 2):
if p % x == 0:
num_prime = False
break
#print("Checked :", p)
#Processing the result of the check above
if num_prime == False:
p += 1
continue
if num_prime == True:
primes.append(p)
#print("%d is prime" %p)
p += 1
#print("Number of primes found: ",len(primes))
#Reporting the last known prime
primes.sort()
#print(primes)
print("last prime found was %d" %primes[-1])
print("the number of primes found was %d" %len(primes))
# first full run clocked in at: 10:17.64 (min:sec)
# second run: 9:29.96
# third run: 6:14.07
# fourth run: 2:36.36
# fifth run: 2:33.37
# sixth run: 00:29.76 ***current state***
|
import { map2Maybe, mapMaybe, Maybe } from "./Maybe"
export type Tuple<A, B> = [A, B]
export function tuple<A,B>(a: A, b: B): [A,B] { return [a,b] }
export function mapFirst<A,B,C>(tup: [A,B], f: (a: A) => C): [C,B] { return applyTuple([f, x => x], tup) }
export function mapSecond<A,B,C>(tup: [A,B], f: (b: B) => C): [A,C] { return applyTuple([x => x, f], tup) }
export function extractFromTuple<A,B,C>(tup: [A,B], f:(a:A,b:B) => C): C { return f(tup[0], tup[1])}
export function zipTuplesWith<A,B,C,D,E,F>(tup1: [A,B], tup2: [C,D], f: (a:A,c:C) => E, g: (b:B,d:D) => F): [E,F] {
return [f(tup1[0], tup2[0]), g(tup1[1],tup2[1])] }
export function zipTuples<A,B,C,D>(tup1: [A,B], tup2: [C,D]): [[A,C], [B,D]] {
return zipTuplesWith(tup1, tup2, tuple, tuple)}
export function applyTuple<A,B,C,D>(funcs: [(a:A) => C, (b:B) => D], tup: [A,B]): [C,D] {
return zipTuplesWith(funcs, tup, (f,a) => f(a), (f,b) => f(b))}
export function pullFirstMaybe<A,B>(tup: [Maybe<A>, B]): Maybe<[A,B]> {
return extractFromTuple(tup, (ma,b) => mapMaybe(ma, a => tuple(a,b))) }
export function pullSecondMaybe<A,B>(tup: [A, Maybe<B>]): Maybe<[A,B]> {
return extractFromTuple(tup, (a,mb) => mapMaybe(mb, b => tuple(a,b)))}
export function extractTupleMaybes<A,B,C>(tup: [Maybe<A>, Maybe<B>], f:(a:A, b:B) => C): Maybe<C> {
return extractFromTuple(tup, (ma,mb) => map2Maybe(ma, mb, f)) }
export function sequenceMaybeTuple<A,B>(tup: [Maybe<A>, Maybe<B>]): Maybe<[A,B]> {
return extractTupleMaybes(tup, tuple) }
|
<#
.SYNOPSIS
Automated unit test for DSC_SqlDatabaseUser DSC resource.
#>
Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1')
if (-not (Test-BuildCategory -Type 'Unit'))
{
return
}
$script:dscModuleName = 'SqlServerDsc'
$script:dscResourceName = 'DSC_SqlDatabaseUser'
function Invoke-TestSetup
{
try
{
Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
}
catch [System.IO.FileNotFoundException]
{
throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
}
$script:testEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:dscModuleName `
-DSCResourceName $script:dscResourceName `
-ResourceType 'Mof' `
-TestType 'Unit'
Add-Type -Path (Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Stubs') -ChildPath 'SMO.cs')
}
function Invoke-TestCleanup
{
Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}
Invoke-TestSetup
try
{
InModuleScope $script:dscResourceName {
$mockName = 'DatabaseUser1'
$mockServerName = 'localhost'
$mockInstanceName = 'MSSQLSERVER'
$mockDatabaseName = 'TestDB'
$mockDatabaseIsUpdateable = $true
$mockLoginName = 'CONTOSO\Login1'
$mockAsymmetricKeyName = 'AsymmetricKey1'
$mockCertificateName = 'Certificate1'
$mockLoginType = 'WindowsUser'
$mockUserType = 'Login'
$mockAuthenticationType = 'Windows'
# Default parameters that are used for the It-blocks.
$mockDefaultParameters = @{
Name = $mockName
InstanceName = $mockInstanceName
ServerName = $mockServerName
DatabaseName = $mockDatabaseName
Verbose = $true
}
Describe 'DSC_SqlDatabaseUser\Get-TargetResource' -Tag 'Get' {
Context 'When the system is in the desired state' {
BeforeAll {
# Scriptblock for mocked object for mocks of Connect-SQL.
$mockSqlServerObject = {
New-Object -TypeName Object |
Add-Member -MemberType ScriptProperty -Name 'Databases' -Value {
return @(
@{
$mockDatabaseName = New-Object -TypeName Object |
Add-Member -MemberType NoteProperty -Name 'Name' -Value $mockDatabaseName -PassThru |
Add-Member -MemberType NoteProperty -Name 'IsUpdateable' -Value $mockDatabaseIsUpdateable -PassThru |
Add-Member -MemberType ScriptProperty -Name 'Users' -Value {
return @(
@{
$mockName = New-Object -TypeName Object |
Add-Member -MemberType NoteProperty -Name 'Name' -Value $mockName -PassThru |
Add-Member -MemberType NoteProperty -Name 'AsymmetricKey' -Value $mockAsymmetricKeyName -PassThru |
Add-Member -MemberType NoteProperty -Name 'Certificate' -Value $mockCertificateName -PassThru |
Add-Member -MemberType NoteProperty -Name 'AuthenticationType' -Value $mockAuthenticationType -PassThru |
Add-Member -MemberType NoteProperty -Name 'LoginType' -Value $mockLoginType -PassThru |
Add-Member -MemberType NoteProperty -Name 'Login' -Value $mockLoginName -PassThru -Force
}
)
} -PassThru -Force
}
)
} -PassThru -Force
}
Mock -CommandName Connect-SQL -MockWith $mockSqlServerObject
}
AfterEach {
Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope It
}
Context 'When the configuration is absent' {
BeforeAll {
$mockMissingName = 'MissingUser1'
$getTargetResourceParameters = $mockDefaultParameters.Clone()
$getTargetResourceParameters['Name'] = $mockMissingName
}
It 'Should return the state as absent' {
$getTargetResourceResult = Get-TargetResource @getTargetResourceParameters
$getTargetResourceResult.Ensure | Should -Be 'Absent'
}
It 'Should return the same values as passed as parameters' {
$result = Get-TargetResource @getTargetResourceParameters
$result.ServerName | Should -Be $getTargetResourceParameters.ServerName
$result.InstanceName | Should -Be $getTargetResourceParameters.InstanceName
$result.DatabaseName | Should -Be $getTargetResourceParameters.DatabaseName
$result.Name | Should -Be $mockMissingName
}
It 'Should return $null for the rest of the properties' {
$getTargetResourceResult = Get-TargetResource @getTargetResourceParameters
$getTargetResourceResult.LoginName | Should -BeNullOrEmpty
$getTargetResourceResult.AsymmetricKeyName | Should -BeNullOrEmpty
$getTargetResourceResult.CertificateName | Should -BeNullOrEmpty
$getTargetResourceResult.AuthenticationType | Should -BeNullOrEmpty
$getTargetResourceResult.LoginType | Should -BeNullOrEmpty
$getTargetResourceResult.UserType | Should -BeNullOrEmpty
}
It 'Should return $true for the property DatabaseIsUpdateable' {
$getTargetResourceResult = Get-TargetResource @getTargetResourceParameters
$getTargetResourceResult.DatabaseIsUpdateable | Should -Be $true
}
}
Context 'When the configuration is present' {
BeforeAll {
$getTargetResourceParameters = $mockDefaultParameters.Clone()
}
It 'Should return the state as present' {
$getTargetResourceResult = Get-TargetResource @getTargetResourceParameters
$getTargetResourceResult.Ensure | Should -Be 'Present'
}
It 'Should return the same values as passed as parameters' {
$result = Get-TargetResource @getTargetResourceParameters
$result.ServerName | Should -Be $getTargetResourceParameters.ServerName
$result.InstanceName | Should -Be $getTargetResourceParameters.InstanceName
$result.DatabaseName | Should -Be $getTargetResourceParameters.DatabaseName
$result.Name | Should -Be $getTargetResourceParameters.Name
}
It 'Should return the correct values for the rest of the properties' {
$getTargetResourceResult = Get-TargetResource @getTargetResourceParameters
$getTargetResourceResult.LoginName | Should -Be $mockLoginName
$getTargetResourceResult.AsymmetricKeyName | Should -Be $mockAsymmetricKeyName
$getTargetResourceResult.CertificateName | Should -Be $mockCertificateName
$getTargetResourceResult.AuthenticationType | Should -Be $mockAuthenticationType
$getTargetResourceResult.LoginType | Should -Be 'WindowsUser'
$getTargetResourceResult.UserType | Should -Be $mockUserType
}
It 'Should return $true for the property DatabaseIsUpdateable' {
$getTargetResourceResult = Get-TargetResource @getTargetResourceParameters
$getTargetResourceResult.DatabaseIsUpdateable | Should -Be $true
}
}
}
Context 'When the system is not in the desired state' {
Context 'When the database name does not exist' {
BeforeAll {
Mock -CommandName Connect-SQL -MockWith $mockSqlServerObject
$mockMissingName = 'MissingUser1'
$mockMissingDatabaseName = 'MissingDatabase1'
$getTargetResourceParameters = $mockDefaultParameters.Clone()
$getTargetResourceParameters['DatabaseName'] = $mockMissingDatabaseName
$getTargetResourceParameters['Name'] = $mockMissingName
}
It 'Should throw the correct error' {
{
Get-TargetResource @getTargetResourceParameters
} | Should -Throw ($script:localizedData.DatabaseNotFound -f $mockMissingDatabaseName)
Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope It
}
}
}
Assert-VerifiableMock
}
Describe 'DSC_SqlDatabaseUser\Test-TargetResource' -Tag 'Test' {
Context 'When the system is in the desired state' {
Context 'When the configuration is absent' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Absent'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
DatabaseIsUpdateable = $mockDatabaseIsUpdateable
LoginName = $null
AsymmetricKeyName = $null
CertificateName = $null
UserType = $null
AuthenticationType = $null
LoginType = $null
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['Ensure'] = 'Absent'
}
It 'Should return the state as $true' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $true
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
Context 'When the configuration is present' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
DatabaseIsUpdateable = $mockDatabaseIsUpdateable
LoginName = $mockLoginName
AsymmetricKeyName = $null
CertificateName = $null
UserType = $mockUserType
AuthenticationType = $mockAuthenticationType
LoginType = $mockLoginType
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['UserType'] = $mockUserType
$testTargetResourceParameters['LoginName'] = $mockLoginName
}
It 'Should return the state as $true' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $true
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
}
Context 'When the system is not in the desired state' {
Context 'When the configuration should be absent' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['Ensure'] = 'Absent'
}
It 'Should return the state as $false' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $false
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
Context 'When the configuration should be present' {
Context 'When the property LoginName is not in desired state' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
LoginName = 'OtherLogin1'
AsymmetricKeyName = $null
CertificateName = $null
UserType = 'Login'
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['LoginName'] = $mockLoginName
$testTargetResourceParameters['UserType'] = 'Login'
}
It 'Should return the state as $false' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $false
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
Context 'When the property AsymmetricKeyName is not in desired state' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
LoginName = $null
AsymmetricKeyName = 'OtherAsymmetricKey1'
CertificateName = $null
UserType = 'AsymmetricKey'
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['AsymmetricKeyName'] = $mockAsymmetricKeyName
$testTargetResourceParameters['UserType'] = 'AsymmetricKey'
}
It 'Should return the state as $false' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $false
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
Context 'When the property CertificateName is not in desired state' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
LoginName = $null
AsymmetricKeyName = $null
CertificateName = 'OtherCertificate1'
UserType = 'Certificate'
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['CertificateName'] = $mockCertificateName
$testTargetResourceParameters['UserType'] = 'Certificate'
}
It 'Should return the state as $false' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $false
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
Context 'When the property UserType is not in desired state' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
LoginName = $null
AsymmetricKeyName = $null
CertificateName = 'OtherCertificate1'
UserType = 'Certificate'
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['LoginName'] = $mockLoginName
$testTargetResourceParameters['UserType'] = 'Login'
}
It 'Should return the state as $false' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $false
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
}
}
Context 'When the database is not updatable' {
Context 'When the configuration is absent' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Absent'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
DatabaseIsUpdateable = $false
LoginName = $null
AsymmetricKeyName = $null
CertificateName = $null
UserType = $null
AuthenticationType = $null
LoginType = $null
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['Ensure'] = 'Absent'
}
It 'Should return the state as $true' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $true
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
Context 'When the configuration is present' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
DatabaseIsUpdateable = $false
LoginName = $mockLoginName
AsymmetricKeyName = $null
CertificateName = $null
UserType = $mockUserType
AuthenticationType = $mockAuthenticationType
LoginType = $mockLoginType
}
}
$testTargetResourceParameters = $mockDefaultParameters.Clone()
$testTargetResourceParameters['UserType'] = $mockUserType
$testTargetResourceParameters['LoginName'] = $mockLoginName
}
It 'Should return the state as $true' {
$testTargetResourceResult = Test-TargetResource @testTargetResourceParameters
$testTargetResourceResult | Should -Be $true
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
}
}
}
Assert-VerifiableMock
}
Describe 'DSC_SqlDatabaseUser\Set-TargetResource' -Tag 'Set' {
BeforeAll {
Mock -CommandName Invoke-Query
Mock -CommandName Assert-SqlLogin
Mock -CommandName Assert-DatabaseAsymmetricKey
Mock -CommandName Assert-DatabaseCertificate
}
Context 'When the system is in the desired state' {
Context 'When the configuration is absent' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Absent'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $null
AsymmetricKeyName = $null
CertificateName = $null
UserType = $null
AuthenticationType = $null
LoginType = $null
}
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['Ensure'] = 'Absent'
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -Exactly -Times 0 -Scope It
}
}
Context 'When the configuration is present' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $mockLoginName
AsymmetricKeyName = $null
CertificateName = $null
UserType = $mockUserType
AuthenticationType = $mockAuthenticationType
LoginType = $mockLoginType
}
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['UserType'] = $mockUserType
$setTargetResourceParameters['LoginName'] = $mockLoginName
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -Exactly -Times 0 -Scope It
}
}
}
Context 'When the system is not in the desired state' {
Context 'When the configuration should be absent' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $mockLoginName
AsymmetricKeyName = $null
CertificateName = $null
UserType = $mockUserType
AuthenticationType = $mockAuthenticationType
LoginType = $mockLoginType
}
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['Ensure'] = 'Absent'
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('DROP USER [{0}];' -f $mockName)
} -Exactly -Times 1 -Scope It
}
Context 'When trying to drop a database user but Invoke-Query fails' {
BeforeAll {
Mock -CommandName Invoke-Query -MockWith {
throw
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['Ensure'] = 'Absent'
}
It 'Should throw the correct error' {
{
Set-TargetResource @setTargetResourceParameters
} | Should -Throw ($script:localizedData.FailedDropDatabaseUser -f $mockName, $MockDatabaseName)
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -Exactly -Times 1 -Scope It
}
}
}
Context 'When the configuration should be present' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Absent'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $null
AsymmetricKeyName = $null
CertificateName = $null
UserType = $null
AuthenticationType = $null
LoginType = $null
}
}
}
Context 'When creating a database user with a login' {
Context 'When calling an using the default ServerName' {
BeforeAll {
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['LoginName'] = $mockLoginName
$setTargetResourceParameters['UserType'] = 'Login'
<#
Make sure to use the default value for ServerName.
Regression test for issue #1647.
#>
$setTargetResourceParameters.Remove('ServerName')
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] FOR LOGIN [{1}];' -f $mockName, $mockLoginName)
} -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Assert-SqlLogin -ParameterFilter {
$ServerName -eq (Get-ComputerName)
} -Exactly -Times 1 -Scope It
}
}
Context 'When calling with an explicit ServerName' {
BeforeAll {
$expectedServerName = 'host.company.local'
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['LoginName'] = $mockLoginName
$setTargetResourceParameters['UserType'] = 'Login'
<#
Set an explicit value for ServerName.
Regression test for issue #1647.
#>
$setTargetResourceParameters['ServerName'] = $expectedServerName
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] FOR LOGIN [{1}];' -f $mockName, $mockLoginName)
} -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Assert-SqlLogin -ParameterFilter {
$ServerName -eq $expectedServerName
} -Exactly -Times 1 -Scope It
}
}
}
Context 'When creating a database user without a login' {
BeforeAll {
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['UserType'] = 'NoLogin'
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] WITHOUT LOGIN;' -f $mockName)
} -Exactly -Times 1 -Scope It
}
}
Context 'When creating a database user mapped to a certificate' {
BeforeAll {
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['CertificateName'] = $mockCertificateName
$setTargetResourceParameters['UserType'] = 'Certificate'
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] FOR CERTIFICATE [{1}];' -f $mockName, $mockCertificateName)
} -Exactly -Times 1 -Scope It
}
}
Context 'When creating a database user mapped to an asymmetric key' {
BeforeAll {
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['AsymmetricKeyName'] = $mockAsymmetricKeyName
$setTargetResourceParameters['UserType'] = 'AsymmetricKey'
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] FOR ASYMMETRIC KEY [{1}];' -f $mockName, $mockAsymmetricKeyName)
} -Exactly -Times 1 -Scope It
}
}
Context 'When trying to create a database user but Invoke-Query fails' {
BeforeAll {
Mock -CommandName Invoke-Query -MockWith {
throw
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['UserType'] = 'NoLogin'
}
It 'Should throw the correct error' {
{
Set-TargetResource @setTargetResourceParameters
} | Should -Throw ($script:localizedData.FailedCreateDatabaseUser -f $mockName, $MockDatabaseName, 'NoLogin')
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -Exactly -Times 1 -Scope It
}
}
}
Context 'When properties are not in desired state' {
Context 'When the database user has the wrong login name' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $mockLoginName
AsymmetricKeyName = $null
CertificateName = $null
UserType = $mockUserType
AuthenticationType = $mockAuthenticationType
LoginType = 'WindowsUser'
}
}
}
Context 'When calling an using the default ServerName' {
BeforeAll {
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['LoginName'] = 'OtherLogin1'
$setTargetResourceParameters['UserType'] = 'Login'
<#
Make sure to use the default value for ServerName.
Regression test for issue #1647.
#>
$setTargetResourceParameters.Remove('ServerName')
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('ALTER USER [{0}] WITH NAME = [{1}], LOGIN = [{2}];' -f $mockName, $mockName, 'OtherLogin1')
} -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Assert-SqlLogin -ParameterFilter {
$ServerName -eq (Get-ComputerName)
} -Exactly -Times 1 -Scope It
}
}
Context 'When calling with an explicit ServerName' {
BeforeAll {
$expectedServerName = 'host.company.local'
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['LoginName'] = 'OtherLogin1'
$setTargetResourceParameters['UserType'] = 'Login'
<#
Set an explicit value for ServerName.
Regression test for issue #1647.
#>
$setTargetResourceParameters['ServerName'] = $expectedServerName
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('ALTER USER [{0}] WITH NAME = [{1}], LOGIN = [{2}];' -f $mockName, $mockName, 'OtherLogin1')
} -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Assert-SqlLogin -ParameterFilter {
$ServerName -eq $expectedServerName
} -Exactly -Times 1 -Scope It
}
}
Context 'When trying to alter the login name but Invoke-Query fails' {
BeforeAll {
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['LoginName'] = 'OtherLogin1'
$setTargetResourceParameters['UserType'] = 'Login'
Mock -CommandName Invoke-Query -MockWith {
throw
}
}
It 'Should throw the correct error' {
{
Set-TargetResource @setTargetResourceParameters
} | Should -Throw ($script:localizedData.FailedUpdateDatabaseUser -f $mockName, $MockDatabaseName, 'Login')
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -Exactly -Times 1 -Scope It
}
}
}
Context 'When the database user has the wrong asymmetric key name' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $mockLoginName
AsymmetricKeyName = $mockAsymmetricKeyName
CertificateName = $null
UserType = 'AsymmetricKey'
AuthenticationType = $mockAuthenticationType
LoginType = 'AsymmetricKey'
}
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['AsymmetricKeyName'] = 'OtherAsymmetricKey1'
$setTargetResourceParameters['UserType'] = 'AsymmetricKey'
$setTargetResourceParameters['Force'] = $true
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('DROP USER [{0}];' -f $mockName)
} -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] FOR ASYMMETRIC KEY [{1}];' -f $mockName, 'OtherAsymmetricKey1')
} -Exactly -Times 1 -Scope It
}
}
Context 'When the database user has the wrong certificate name' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $mockLoginName
AsymmetricKeyName = $mockAsymmetricKeyName
CertificateName = $null
UserType = 'Certificate'
AuthenticationType = $mockAuthenticationType
LoginType = 'Certificate'
}
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['CertificateName'] = 'OtherCertificate1'
$setTargetResourceParameters['UserType'] = 'Certificate'
$setTargetResourceParameters['Force'] = $true
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('DROP USER [{0}];' -f $mockName)
} -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] FOR CERTIFICATE [{1}];' -f $mockName, 'OtherCertificate1')
} -Exactly -Times 1 -Scope It
}
}
Context 'When the database user has the wrong certificate name' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $mockLoginName
AsymmetricKeyName = $mockAsymmetricKeyName
CertificateName = $null
UserType = 'Certificate'
AuthenticationType = $mockAuthenticationType
LoginType = 'Certificate'
}
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['LoginName'] = 'OtherLogin1'
$setTargetResourceParameters['UserType'] = 'Login'
$setTargetResourceParameters['Force'] = $true
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('DROP USER [{0}];' -f $mockName)
} -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -ParameterFilter {
$Query -eq ('CREATE USER [{0}] FOR LOGIN [{1}];' -f $mockName, 'OtherLogin1')
} -Exactly -Times 1 -Scope It
}
}
Context 'When the configuration has not opt-in to re-create a database user' {
BeforeAll {
Mock -CommandName Get-TargetResource -MockWith {
return @{
Ensure = 'Present'
Name = $mockName
ServerName = $mockServerName
InstanceName = $mockInstanceName
DatabaseName = $mockDatabaseName
LoginName = $mockLoginName
AsymmetricKeyName = $mockAsymmetricKeyName
CertificateName = $null
UserType = 'Certificate'
AuthenticationType = $mockAuthenticationType
LoginType = 'Certificate'
}
}
$setTargetResourceParameters = $mockDefaultParameters.Clone()
$setTargetResourceParameters['LoginName'] = 'OtherLogin1'
$setTargetResourceParameters['UserType'] = 'Login'
}
It 'Should not throw and should call the correct mocks' {
{ Set-TargetResource @setTargetResourceParameters } | Should -Throw $script:localizedData.ForceNotEnabled
Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It
Assert-MockCalled -CommandName Invoke-Query -Exactly -Times 0 -Scope It
}
}
}
}
Assert-VerifiableMock
}
Describe 'Assert-Parameters' -Tag 'Helper' {
BeforeAll {
$mockUserType = 'NoLogin'
}
Context 'When parameter LoginName is provided, but with the wrong user type' {
It 'Should throw the correct error' {
{
Assert-Parameters -LoginName 'AnyValue' -UserType $mockUserType
} | Should -Throw ($script:localizedData.LoginNameProvidedWithWrongUserType -f $mockUserType)
}
}
Context 'When parameter CertificateName is provided, but with the wrong user type' {
It 'Should throw the correct error' {
{
Assert-Parameters -CertificateName 'AnyValue' -UserType $mockUserType
} | Should -Throw ($script:localizedData.CertificateNameProvidedWithWrongUserType -f $mockUserType)
}
}
Context 'When parameter AsymmetricKeyName is provided, but with the wrong user type' {
It 'Should throw the correct error' {
{
Assert-Parameters -AsymmetricKeyName 'AnyValue' -UserType $mockUserType
} | Should -Throw ($script:localizedData.AsymmetricKeyNameProvidedWithWrongUserType -f $mockUserType)
}
}
Context 'When parameter LoginName is not provided when providing the user type ''Login''' {
It 'Should throw the correct error' {
{
Assert-Parameters -UserType 'Login'
} | Should -Throw ($script:localizedData.LoginUserTypeWithoutLoginName -f 'Login')
}
}
Context 'When parameter AsymmetricKeyName is not provide when providing the user type ''AsymmetricKey''' {
It 'Should throw the correct error' {
{
Assert-Parameters -UserType 'AsymmetricKey'
} | Should -Throw ($script:localizedData.AsymmetricKeyUserTypeWithoutAsymmetricKeyName -f 'AsymmetricKey')
}
}
Context 'When parameter CertificateName is not provide when providing the user type ''Certificate''' {
It 'Should throw the correct error' {
{
Assert-Parameters -UserType 'Certificate'
} | Should -Throw ($script:localizedData.CertificateUserTypeWithoutCertificateName -f 'Certificate')
}
}
}
Describe 'ConvertTo-UserType' -Tag 'Helper' {
Context 'When converting to a user type' {
BeforeAll {
$testCases = @(
@{
AuthenticationType = 'Windows'
LoginType = 'WindowsUser'
ExpectedResult = 'Login'
}
@{
AuthenticationType = 'Windows'
LoginType = 'WindowsGroup'
ExpectedResult = 'Login'
}
@{
AuthenticationType = 'Instance'
LoginType = 'SqlLogin'
ExpectedResult = 'Login'
}
@{
AuthenticationType = 'None'
LoginType = 'SqlLogin'
ExpectedResult = 'NoLogin'
}
@{
AuthenticationType = 'None'
LoginType = 'AsymmetricKey'
ExpectedResult = 'AsymmetricKey'
}
@{
AuthenticationType = 'None'
LoginType = 'Certificate'
ExpectedResult = 'Certificate'
}
)
}
It 'Should return the correct value when converting authentication type <AuthenticationType> and login type <LoginType>' -TestCases $testCases {
param
(
[Parameter()]
[System.String]
$AuthenticationType,
[Parameter()]
[System.String]
$LoginType,
[Parameter()]
[System.String]
$ExpectedResult
)
$convertToUserTypeResult = ConvertTo-UserType -AuthenticationType $AuthenticationType -LoginType $LoginType
$convertToUserTypeResult | Should -Be $ExpectedResult
}
Context 'When calling with an unsupported authentication type' {
BeforeAll {
$mockUnsupportedValue = 'UnsupportedValue'
$mockLoginType = 'SqlLogin'
}
It 'Should throw the correct error' {
{
ConvertTo-UserType -AuthenticationType $mockUnsupportedValue -LoginType $mockLoginType
} | Should -Throw ($script:localizedData.UnknownAuthenticationType -f $mockUnsupportedValue, $mockLoginType)
}
}
}
}
Describe 'Assert-SqlLogin' -Tag 'Helper' {
BeforeAll {
$mockSqlServerObject = {
New-Object -TypeName Object |
Add-Member -MemberType ScriptProperty -Name 'Logins' -Value {
return @(
@{
$mockLoginName = New-Object -TypeName Object |
Add-Member -MemberType NoteProperty -Name 'Name' -Value $mockLoginName -PassThru -Force
}
)
} -PassThru -Force
}
Mock -CommandName Connect-SQL -MockWith $mockSqlServerObject
}
Context 'When the SQL login exist' {
BeforeAll {
$assertSqlLoginParameters = @{
InstanceName = $mockInstanceName
ServerName = $mockServerName
LoginName = $mockLoginName
Verbose = $true
}
}
It 'Should not throw any error' {
{ Assert-SqlLogin @assertSqlLoginParameters } | Should -Not -Throw
}
}
Context 'When the SQL login does not exist' {
BeforeAll {
$assertSqlLoginParameters = @{
InstanceName = $mockInstanceName
ServerName = $mockServerName
LoginName = 'AnyValue'
Verbose = $true
}
}
It 'Should throw the correct error' {
{
Assert-SqlLogin @assertSqlLoginParameters
} | Should -Throw ($script:localizedData.SqlLoginNotFound -f 'AnyValue')
}
}
}
Describe 'Assert-DatabaseCertificate' -Tag 'Helper' {
BeforeAll {
$mockSqlServerObject = {
New-Object -TypeName Object |
Add-Member -MemberType ScriptProperty -Name 'Databases' -Value {
return @(
@{
$mockDatabaseName = New-Object -TypeName Object |
Add-Member -MemberType NoteProperty -Name 'Name' -Value $mockDatabaseName -PassThru |
Add-Member -MemberType NoteProperty -Name 'IsUpdateable' -Value $mockDatabaseIsUpdateable -PassThru |
Add-Member -MemberType ScriptProperty -Name 'Certificates' -Value {
return @(
@{
$mockCertificateName = New-Object -TypeName Object |
Add-Member -MemberType NoteProperty -Name 'Name' -Value $mockCertificateName -PassThru -Force
}
)
} -PassThru -Force
}
)
} -PassThru -Force
}
Mock -CommandName Connect-SQL -MockWith $mockSqlServerObject
}
Context 'When the certificate exist in the database' {
BeforeAll {
$assertDatabaseCertificateParameters = $mockDefaultParameters.Clone()
$assertDatabaseCertificateParameters['CertificateName'] = $mockCertificateName
}
It 'Should not throw any error' {
{ Assert-DatabaseCertificate @assertDatabaseCertificateParameters } | Should -Not -Throw
}
}
Context 'When the certificate does not exist in the database' {
BeforeAll {
$assertDatabaseCertificateParameters = $mockDefaultParameters.Clone()
$assertDatabaseCertificateParameters['CertificateName'] = 'AnyValue'
}
It 'Should throw the correct error' {
{
Assert-DatabaseCertificate @assertDatabaseCertificateParameters
} | Should -Throw ($script:localizedData.CertificateNotFound -f 'AnyValue', $mockDatabaseName)
}
}
}
Describe 'Assert-DatabaseAsymmetricKey' -Tag 'Helper' {
BeforeAll {
$mockSqlServerObject = {
New-Object -TypeName Object |
Add-Member -MemberType ScriptProperty -Name 'Databases' -Value {
return @(
@{
$mockDatabaseName = New-Object -TypeName Object |
Add-Member -MemberType NoteProperty -Name 'Name' -Value $mockDatabaseName -PassThru |
Add-Member -MemberType NoteProperty -Name 'IsUpdateable' -Value $mockDatabaseIsUpdateable -PassThru |
Add-Member -MemberType ScriptProperty -Name 'AsymmetricKeys' -Value {
return @(
@{
$mockAsymmetricKeyName = New-Object -TypeName Object |
Add-Member -MemberType NoteProperty -Name 'Name' -Value $mockAsymmetricKeyName -PassThru -Force
}
)
} -PassThru -Force
}
)
} -PassThru -Force
}
Mock -CommandName Connect-SQL -MockWith $mockSqlServerObject
}
Context 'When the asymmetric key exist in the database' {
BeforeAll {
$assertDatabaseAsymmetricKeyParameters = $mockDefaultParameters.Clone()
$assertDatabaseAsymmetricKeyParameters['AsymmetricKeyName'] = $mockAsymmetricKeyName
}
It 'Should not throw any error' {
{ Assert-DatabaseAsymmetricKey @assertDatabaseAsymmetricKeyParameters } | Should -Not -Throw
}
}
Context 'When the asymmetric key does not exist in the database' {
BeforeAll {
$assertDatabaseAsymmetricKeyParameters = $mockDefaultParameters.Clone()
$assertDatabaseAsymmetricKeyParameters['AsymmetricKeyName'] = 'AnyValue'
}
It 'Should throw the correct error' {
{
Assert-DatabaseAsymmetricKey @assertDatabaseAsymmetricKeyParameters
} | Should -Throw ($script:localizedData.AsymmetryKeyNotFound -f 'AnyValue', $mockDatabaseName)
}
}
}
}
}
finally
{
Invoke-TestCleanup
}
|
namespace Spotopedia.Web.Controllers
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Spotopedia.Data.Models;
using Spotopedia.Services.Data;
using Spotopedia.Web.ViewModels.SpotVotes;
[ApiController]
[Route("api/[controller]")]
public class PostVotesController : ControllerBase
{
private readonly IPostVotesService postVotesService;
private readonly UserManager<ApplicationUser> userManager;
public PostVotesController(IPostVotesService postVotesService, UserManager<ApplicationUser> userManager)
{
this.postVotesService = postVotesService;
this.userManager = userManager;
}
[Authorize]
[HttpPost]
public async Task<ActionResult<VoteResponseModel>> Post(VoteInputModel input)
{
var userId = this.userManager.GetUserId(this.User);
await this.postVotesService.VoteAsync(input.PostId, userId, input.IsLiked);
var likesCount = this.postVotesService.GetLikes(input.PostId);
var dislikesCount = this.postVotesService.GetDislikes(input.PostId);
var responseModel = new VoteResponseModel
{
LikesCount = likesCount,
DislikesCount = dislikesCount,
};
return responseModel;
}
}
}
|
package com.hasbihal.extension
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.google.android.material.snackbar.Snackbar
fun View.showKeyboard(){
val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
fun View.hideKeyboard(){
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun View.showSnackbar(snackbarText: String, timeLength: Int) {
Snackbar.make(this, snackbarText, timeLength).show()
}
fun View.show(): View {
if (visibility != View.VISIBLE) {
visibility = View.VISIBLE
}
return this
}
fun View.hide(): View{
if(visibility != View.INVISIBLE){
visibility = View.INVISIBLE
}
return this
}
inline fun View.showIf(condition: () -> Boolean): View {
if (visibility != View.VISIBLE && condition()) {
visibility = View.VISIBLE
}
return this
}
fun View.setPaddingLeft(value: Int) = setPadding(value, paddingTop, paddingRight, paddingBottom)
fun View.setPaddingRight(value: Int) = setPadding(paddingLeft, paddingTop, value, paddingBottom)
fun View.setPaddingTop(value: Int) = setPaddingRelative(paddingStart, value, paddingEnd, paddingBottom)
fun View.setPaddingBottom(value: Int) = setPaddingRelative(paddingStart, paddingTop, paddingEnd, value)
fun View.setPaddingStart(value: Int) = setPaddingRelative(value, paddingTop, paddingEnd, paddingBottom)
fun View.setPaddingEnd(value: Int) = setPaddingRelative(paddingStart, paddingTop, value, paddingBottom)
|
class AccountsController < ApplicationController
skip_before_filter :find_account
skip_before_filter :verify_authenticity_token
before_filter :clear_flash
skip_before_filter :login_required, :only => [:new, :create]
before_filter :ensure_no_accounts, :only => [:new, :create]
layout 'login', :only => [:new, :create]
# Root account creation
# ---------------------
# Both the #new and #create actions are reserved for creating the root account
# during installation.
def new
@account = Account.new
@user = User.new
render :template => "accounts/first_account_form"
end
def create
@account = Account.new(params[:account])
@user = User.new(params[:user])
ActiveRecord::Base.transaction do
@account.save!
@user.save!
end
@user.has_role "admin"
@account.accepts_role "manager", @user # Gives admin control over account
@account.accepts_role "staff", @user # Makes user a staff member of the account
flash[:notice] = "Welcome to Hot Ink!"
redirect_to articles_url(@user.account)
rescue ActiveRecord::RecordInvalid => invalid
# TODO: below is a hack to fix broken transaction above (why isn't the transaction working?!)
unless @account.new_record?
@account.destroy
@account = Account.new(params[:account])
end
render :action=>"accounts/first_account_form", :layout=>'login'
return
end
# Simple redirect to dashboard
def index
redirect_to dashboard_url
end
def show
@account = Account.find(params[:id])
redirect_to dashboard_url
end
# Loads the account management tabs
def edit
@account = Account.find(params[:id])
permit "manager of :account or admin" do
if permit? "admin"
@accounts = Account.find(:all, :order => "name asc")
end
respond_to do |format|
format.html
end
end
end
# PUT /accounts/1
def update
@account = Account.find(params[:id])
permit "manager of :account or admin" do
if @account.update_attributes(params[:account])
flash[:notice] = "Account updated"
end
end
end
private
def ensure_no_accounts
unless Account.all.empty?
render :text => "Page not found", :status => :not_found
false
end
end
end
|
# Lint as: python3
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Semantic segmentation configuration definition."""
import os
from typing import List, Union, Optional
import dataclasses
from official.core import exp_factory
from official.modeling import hyperparams
from official.modeling import optimization
from official.modeling.hyperparams import config_definitions as cfg
from official.vision.beta.configs import backbones
from official.vision.beta.configs import common
from official.vision.beta.configs import decoders
@dataclasses.dataclass
class DataConfig(cfg.DataConfig):
"""Input config for training."""
input_path: str = ''
global_batch_size: int = 0
is_training: bool = True
dtype: str = 'float32'
shuffle_buffer_size: int = 1000
cycle_length: int = 10
resize_eval_groundtruth: bool = True
groundtruth_padded_size: List[int] = dataclasses.field(default_factory=list)
aug_scale_min: float = 1.0
aug_scale_max: float = 1.0
drop_remainder: bool = True
@dataclasses.dataclass
class SegmentationHead(hyperparams.Config):
level: int = 3
num_convs: int = 2
num_filters: int = 256
upsample_factor: int = 1
@dataclasses.dataclass
class SemanticSegmentationModel(hyperparams.Config):
"""Semantic segmentation model config."""
num_classes: int = 0
input_size: List[int] = dataclasses.field(default_factory=list)
min_level: int = 3
max_level: int = 6
head: SegmentationHead = SegmentationHead()
backbone: backbones.Backbone = backbones.Backbone(
type='resnet', resnet=backbones.ResNet())
decoder: decoders.Decoder = decoders.Decoder(type='identity')
norm_activation: common.NormActivation = common.NormActivation()
@dataclasses.dataclass
class Losses(hyperparams.Config):
label_smoothing: float = 0.1
ignore_label: int = 255
class_weights: List[float] = dataclasses.field(default_factory=list)
l2_weight_decay: float = 0.0
use_groundtruth_dimension: bool = True
@dataclasses.dataclass
class SemanticSegmentationTask(cfg.TaskConfig):
"""The model config."""
model: SemanticSegmentationModel = SemanticSegmentationModel()
train_data: DataConfig = DataConfig(is_training=True)
validation_data: DataConfig = DataConfig(is_training=False)
losses: Losses = Losses()
gradient_clip_norm: float = 0.0
init_checkpoint: Optional[str] = None
init_checkpoint_modules: Union[
str, List[str]] = 'all' # all, backbone, and/or decoder
@exp_factory.register_config_factory('semantic_segmentation')
def semantic_segmentation() -> cfg.ExperimentConfig:
"""Semantic segmentation general."""
return cfg.ExperimentConfig(
task=SemanticSegmentationModel(),
trainer=cfg.TrainerConfig(),
restrictions=[
'task.train_data.is_training != None',
'task.validation_data.is_training != None'
])
# PASCAL VOC 2012 Dataset
PASCAL_TRAIN_EXAMPLES = 10582
PASCAL_VAL_EXAMPLES = 1449
PASCAL_INPUT_PATH_BASE = 'pascal_voc_seg'
@exp_factory.register_config_factory('seg_deeplabv3_pascal')
def seg_deeplabv3_pascal() -> cfg.ExperimentConfig:
"""Image segmentation on imagenet with resnet deeplabv3."""
train_batch_size = 16
eval_batch_size = 8
steps_per_epoch = PASCAL_TRAIN_EXAMPLES // train_batch_size
config = cfg.ExperimentConfig(
task=SemanticSegmentationTask(
model=SemanticSegmentationModel(
num_classes=21,
# TODO(arashwan): test changing size to 513 to match deeplab.
input_size=[512, 512, 3],
backbone=backbones.Backbone(
type='dilated_resnet', dilated_resnet=backbones.DilatedResNet(
model_id=50, output_stride=8)),
decoder=decoders.Decoder(
type='aspp', aspp=decoders.ASPP(
level=3, dilation_rates=[12, 24, 36])),
head=SegmentationHead(level=3, num_convs=0),
norm_activation=common.NormActivation(
activation='swish',
norm_momentum=0.9997,
norm_epsilon=1e-3,
use_sync_bn=True)),
losses=Losses(l2_weight_decay=1e-4),
train_data=DataConfig(
input_path=os.path.join(PASCAL_INPUT_PATH_BASE, 'train_aug*'),
is_training=True,
global_batch_size=train_batch_size,
aug_scale_min=0.5,
aug_scale_max=2.0),
validation_data=DataConfig(
input_path=os.path.join(PASCAL_INPUT_PATH_BASE, 'val*'),
is_training=False,
global_batch_size=eval_batch_size,
resize_eval_groundtruth=False,
groundtruth_padded_size=[512, 512],
drop_remainder=False),
# resnet50
init_checkpoint='gs://cloud-tpu-checkpoints/vision-2.0/deeplab/deeplab_resnet50_imagenet/ckpt-62400',
init_checkpoint_modules='backbone'),
trainer=cfg.TrainerConfig(
steps_per_loop=steps_per_epoch,
summary_interval=steps_per_epoch,
checkpoint_interval=steps_per_epoch,
train_steps=45 * steps_per_epoch,
validation_steps=PASCAL_VAL_EXAMPLES // eval_batch_size,
validation_interval=steps_per_epoch,
optimizer_config=optimization.OptimizationConfig({
'optimizer': {
'type': 'sgd',
'sgd': {
'momentum': 0.9
}
},
'learning_rate': {
'type': 'polynomial',
'polynomial': {
'initial_learning_rate': 0.007,
'decay_steps': 45 * steps_per_epoch,
'end_learning_rate': 0.0,
'power': 0.9
}
},
'warmup': {
'type': 'linear',
'linear': {
'warmup_steps': 5 * steps_per_epoch,
'warmup_learning_rate': 0
}
}
})),
restrictions=[
'task.train_data.is_training != None',
'task.validation_data.is_training != None'
])
return config
|
# ============================================================================
# TypeFX - Typewriter effect text printer
# PowerShell script function
# Copyright (C) 2020 by Ralf Kilian
# Distributed under the MIT License (https://opensource.org/licenses/MIT)
#
# GitHub: https://github.com/urbanware-org/typefx
# GitLab: https://gitlab.com/urbanware-org/typefx
# ============================================================================
$TypeFxVersion = "1.1.1"
Function Type-Dynamic([Int32]$DelayMin, [Int32]$DelayMax, [String]$String) {
For ($i = 0; $i -lt $String.Length; $i++) {
Write-Host $String[$i] -NoNewLine
$Delay = Get-Random -Minimum $DelayMin -Maximum $DelayMax
Start-Sleep -Milliseconds $Delay
}
Write-Host
}
Function Type-Static([Int32]$Delay, [String]$String) {
For ($i = 0; $i -lt $String.Length; $i++) {
Write-Host $String[$i] -NoNewLine
Start-Sleep -Milliseconds $Delay
}
Write-Host
}
|
#!/bin/bash
npm audit | grep -i "^# run" | cut -d " " -f "3-8"
|
import React from 'react'
import { Graph, Node, Color } from '@antv/x6'
import { ReactShape } from '@antv/x6-react-shape'
// 使用教程:https://x6.antv.vision/zh/docs/tutorial/advanced/react#%E6%B8%B2%E6%9F%93-react-%E8%8A%82%E7%82%B9
class MyComponent extends React.Component<{
node?: ReactShape
text: string
}> {
shouldComponentUpdate() {
const node = this.props.node
if (node) {
if (node.hasChanged('data')) {
return true
}
}
return false
}
render() {
return (
<div
style={{
width: '100%',
height: '100%',
textAlign: 'center',
lineHeight: '50px',
border: '2px solid #9254de',
borderRadius: 4,
background: '#efdbff',
}}
>
{this.props.text}
</div>
)
}
}
const graph = new Graph({
container: document.getElementById('container'),
grid: true,
})
const source = graph.addNode({
x: 120,
y: 50,
width: 120,
height: 50,
shape: 'react-shape',
component: <MyComponent text="Hello" />,
})
const target = graph.addNode({
x: 320,
y: 260,
width: 120,
height: 50,
shape: 'react-shape',
component(node: Node) {
const color = node.prop<string>('color')
return (
<div
style={{
color: '#fff',
width: '100%',
height: '100%',
textAlign: 'center',
lineHeight: '50px',
borderRadius: 4,
background: color,
}}
>
{color}
</div>
)
},
})
graph.addEdge({
source,
target,
})
const update = () => {
target.prop('color', Color.randomHex())
setTimeout(update, 1000)
}
update()
|
import 'bytes_encoder.dart';
import 'int_encoder.dart';
import 'list_encoder.dart';
import 'map_encoder.dart';
import 'option_encoder.dart';
import 'pair_encoder.dart';
import 'string_encoder.dart';
import 'timestamp_encoder.dart';
import 'unit_encoder.dart';
/// A class that converts Dart type object to Micheline
///
/// [type] is a Map defining the type of the data we want to convert
/// [params] the data we want to convert
class MichelineEncoder {
final Map<String, dynamic> type;
final dynamic params;
MichelineEncoder({required this.type, required this.params});
// might be Map<String,dynamic> in the general case but also List in the case of prim == 'list'
dynamic encode() {
final prim = type['prim'];
MichelineEncoder encoder;
switch (prim) {
case 'pair':
encoder = PairEncoder(params: _params, type: type);
break;
case 'timestamp':
encoder = TimestampEncoder(_params);
break;
case 'string':
// TODO: implement validators of these types
case 'address':
case 'contract':
case 'key':
case 'signature':
encoder = StringEncoder(_params);
break;
case 'bytes':
encoder = BytesEncoder(_params);
break;
case 'nat':
case 'int':
encoder = IntEncoder(_params);
break;
case 'option':
encoder = OptionEncoder(params: _params, type: type);
break;
case 'list':
encoder = ListEncoder(params: _params, type: type);
break;
case 'map':
case 'big_map':
encoder = MapEncoder(params: _params, type: type);
break;
case 'unit':
encoder = UnitEncoder();
break;
default:
throw UnimplementedError('Unknown type : $prim');
}
return encoder.encode();
}
bool get _isAnonymous {
return !(type.containsKey('annots') && type['annots'] != null);
}
dynamic get _params {
return _isAnonymous ? params : (params as Map<String, dynamic>)[_annot];
}
String? get _annot {
if (_isAnonymous) return null;
return (type['annots'].first as String).substring(1);
}
}
|
namespace Bearded.Graphics.Pipelines.Context
{
sealed class BlendModeChange<TState> : ContextChange<TState, BlendMode>
{
public BlendModeChange(BlendMode newValue) : base(newValue)
{
}
protected override BlendMode GetCurrent() => GLState.BlendMode;
protected override void Set(BlendMode value) => GLState.SetBlendMode(value);
}
}
|
#!/bin/sh
VERSION=elasticsearch-2.3.3
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
if [ ! -f $DIR/$VERSION/bin/elasticsearch ]; then
wget https://download.elasticsearch.org/elasticsearch/elasticsearch/$VERSION.tar.gz -O $DIR/$VERSION.tar.gz
tar -xf $DIR/$VERSION.tar.gz -C $DIR
cd $VERSION
sudo bin/plugin install cloud-aws
fi
ES_HEAP_SIZE=4g $DIR/$VERSION/bin/elasticsearch
|
module DocgenSpec where
import Pact.Docgen
import Test.Hspec
spec :: Spec
spec = runIO funDocs
|
package com.test.shoppingapp
import com.test.networkmodule.DataProvider
import com.test.shoppingapp.di.DaggerShoppingComponent
import com.test.shoppingapp.di.applyAutoInjector
import dagger.Lazy
import dagger.android.DaggerApplication
import javax.inject.Inject
class ShoppingApplication : DaggerApplication() {
@Inject
lateinit var dataProviderLazy: Lazy<DataProvider>
override fun onCreate() {
super.onCreate()
initializeDI()
}
private fun initializeDI() {
applyAutoInjector()
val networkSDK = DataProvider
dataProviderLazy.get()?.initialize()
}
override fun applicationInjector() = DaggerShoppingComponent.builder()
.application(this)
.build()
}
|
package com.fabiantarrach.breakinout.util.engine
import com.fabiantarrach.breakinout.util.GdxArray
class SystemDatabase {
private val systems = GdxArray<LogicSystem>()
fun addSystem(system: LogicSystem) {
systems.add(system)
}
fun each(action: (LogicSystem) -> Unit) =
systems.forEach(action)
operator fun iterator() = systems.iterator()
}
|
require 'typesafe_enum'
module OpenActive
module Enums
module Schema
# A list of possible statuses for the legal force of a legislation.
class LegalForceStatus < TypesafeEnum::Base
new :NotInForce, "https://schema.org/NotInForce"
new :PartiallyInForce, "https://schema.org/PartiallyInForce"
new :InForce, "https://schema.org/InForce"
end
end
end
end
|
# fb-image-downloader
Downloads a batch of images from Facebook given a list of their FB Urls
## Instructions
### 1. Clone and setup project
```bash
git clone https://github.com/dkundel/fb-image-downloader.git
cd fb-image-downloader
yarn # or npm install
```
### 2. Create a file (e.g. `download.txt`) with all the Facebook Image Urls on single lines. Example:
```text
https://www.facebook.com/TeamTwilio/photos/a.469738127758.246095.39535177758/10154477881737759/?type=3&theater
https://www.facebook.com/TeamTwilio/photos/a.469738127758.246095.39535177758/10154230523777759/?type=3&theater
```
### 3. Get an Access Token for the FB Graph API.
You can get one here: https://developers.facebook.com/tools/explorer/
### 4. Run the Script:
```bash
FB_TOKEN=youraccesstoken node index.js out download.txt
```
### 5. Check out the `out` folder for the pictures :)
# Contributors
- Dominik Kundel <dominik.kundel@gmail.com>
# License
MIT
|
package main;
import java.io.IOException;
import java.time.LocalTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.SilentJavaScriptErrorListener;
import model.Match;
import model.Search;
import util.Pool;
import util.html.SilentIncorrectnessListener;
import util.html.SynchronousAjaxController;
public class JNvidiaSnatcher
{
private static final Logger LOGGER = LoggerFactory.getLogger(JNvidiaSnatcher.class);
private JNvidiaSnatcher()
{
}
private static WebClient createWebClient(final Environment pEnvironment)
{
final WebClient webClient = new WebClient();
webClient.setAjaxController(SynchronousAjaxController.instance());
webClient.setJavaScriptErrorListener(new SilentJavaScriptErrorListener());
webClient.setIncorrectnessListener(SilentIncorrectnessListener.instance());
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setDownloadImages(false);
webClient.getOptions().setPrintContentOnFailingStatusCode(false);
webClient.getOptions().setPopupBlockerEnabled(true);
webClient.getOptions().setWebSocketEnabled(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setAppletEnabled(false);
webClient.getOptions().setHistoryPageCacheLimit(0);
webClient.getOptions().setHistorySizeLimit(-1);
pEnvironment.proxyConfig().ifPresent(webClient.getOptions()::setProxyConfig);
return webClient;
}
private static Future<Match> loadAsync(final WebClient pWebClient, final Search pSearch,
final ExecutorService pExecutor)
{
return pExecutor.submit(() ->
{
try
{
final HtmlPage page = pWebClient.getPage(pSearch.url());
Match match = pSearch.isInStock(page).orElse(null);
if (pSearch.javascript())
{
for (int i = 0; i < 5 && match == null; i++)
{
pWebClient.waitForBackgroundJavaScript(200);
match = pSearch.isInStock(page).orElse(null);
}
}
return match;
}
catch (FailingHttpStatusCodeException e)
{
return Match.invalidHttpStatus(pSearch, e.getMessage());
}
});
}
private static void load(final Search pSearch, final Environment pEnvironment, final Pool<WebClient> pPool,
final ExecutorService pAsyncPool)
{
final LocalTime now = LocalTime.now();
if (now.isBefore(pEnvironment.timeFrom()) || now.isAfter(pEnvironment.timeTo()))
{
return;
}
Match result = null;
try (final var pooledWebClient = pPool.get())
{
final WebClient webClient = pooledWebClient.element();
webClient.getOptions().setJavaScriptEnabled(pSearch.javascript());
try
{
result = loadAsync(webClient, pSearch, pAsyncPool).get(pEnvironment.waitTimeout(), TimeUnit.SECONDS);
}
catch (final Exception e)
{
LOGGER.error("ERROR while scraping page: ", e);
}
if (result == null)
{
pooledWebClient.destroyed();
reset(webClient);
}
}
catch (final Exception e)
{
// should not happen
LOGGER.error("ERROR while waiting for pooled WebClient: ", e);
}
try
{
notifyMatch(result == null ? Match.unknown(pSearch) : result, pSearch, pEnvironment);
}
catch (final Exception e)
{
// should not happen
LOGGER.error("ERROR while sending notifications: ", e);
}
}
private static void reset(final WebClient pWebClient)
{
if (pWebClient != null)
{
// if nothing found, clear cache and cookies before next try:
pWebClient.getCache().clear();
pWebClient.getCookieManager().clearCookies();
pWebClient.close();
}
}
private static void notifyMatch(final Match pMessage, final Search pSearch, final Environment pEnvironment)
{
LOGGER.info(pMessage.consoleMessage());
final var last = pSearch.lastMatch(pMessage);
boolean notified = true;
if (pMessage.inStock() || (pEnvironment.notifyOnStatusChanged() && notifyOnChange(pMessage, last)))
{
for (final var notify : pEnvironment.notifiers())
{
try
{
notify.notify(pSearch, pMessage.notificationMessage());
}
catch (final IOException e)
{
notified = false;
LOGGER.error("Failed to notify about match:", e);
}
}
}
if (pMessage.inStock() && notified)
{
// if the "in stock" notification has been sent successfully send this search to sleep for a while:
try
{
Thread.sleep(60000);
}
catch (InterruptedException pE)
{
// sleep interrupted
}
}
}
private static boolean notifyOnChange(final Match pNow, final Match pPrevious)
{
if (pNow == null || pPrevious == null || pPrevious.unknown() || pNow.unknown())
{
return false;
}
return pPrevious.inStock() != pNow.inStock() || !Objects.equals(pNow.message(), pPrevious.message());
}
public static void main(final String[] args)
{
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
final var environment = Environment.fromSystemEnv();
final var schedulePool = Executors.newScheduledThreadPool(environment.searches().size());
final var asyncPool = Executors.newCachedThreadPool();
final var webClientPool = new Pool<>(environment.parallelism(), () -> createWebClient(environment));
for (final var search : environment.searches())
{
schedulePool.scheduleWithFixedDelay(() -> load(search, environment, webClientPool, asyncPool), 0,
environment.interval(), TimeUnit.SECONDS);
}
try
{
schedulePool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
LOGGER.error("Process interrupted!");
}
}
}
|
package br.com.everis.sovamu.feature.updateuser.ui
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import br.com.everis.sovamu.R.*
import br.com.everis.sovamu.feature.updateuser.model.UpdateUser
import br.com.everis.sovamu.feature.updateuser.usecase.UpdateUserUseCase
import br.com.everis.sovamu.ui.BaseViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
sealed class UpdateUserViewAction {
open class Success(val data: UpdateUser) : UpdateUserViewAction()
open class Loading(val loading: Boolean) : UpdateUserViewAction()
open class Error(val message: String) : UpdateUserViewAction()
}
class UpdateUserViewModel(
val useCase: UpdateUserUseCase,
mainDispatcher: CoroutineDispatcher,
ioDispatcher: CoroutineDispatcher
) : BaseViewModel(mainDispatcher, ioDispatcher) {
private val _updateUser by lazy { MutableLiveData<UpdateUser>() }
val updateUser: LiveData<UpdateUser>
get() = _updateUser
val zipCode by lazy { MutableLiveData<String>("") }
val setFocus by lazy { MutableLiveData<String>("") }
val name by lazy { MutableLiveData<String>("") }
val surname by lazy { MutableLiveData<String>("") }
val email by lazy { MutableLiveData<String>("") }
val password by lazy { MutableLiveData<String>("") }
val passwordNew by lazy { MutableLiveData<String>("") }
val confirmation by lazy { MutableLiveData<String>("") }
private val _messageAlert by lazy { MutableLiveData<String>("") }
val messageAlert: LiveData<String>
get() = _messageAlert
private val _actionView by lazy { MutableLiveData<UpdateUserViewAction>() }
val actionView: LiveData<UpdateUserViewAction>
get() = _actionView
fun putUpdateUser(updateUser: UpdateUser, context: Context) {
if (validadeUpdateUser(updateUser, context)) {
_actionView.value = UpdateUserViewAction.Loading(true)
mUiScope.launch { execute() }
}
}
private suspend fun execute() {
fun showError(message: String) {
mIoScope.launch {
_actionView.postValue(UpdateUserViewAction.Loading(false))
}
_actionView.postValue(UpdateUserViewAction.Error(message))
_messageAlert.postValue("")
}
fun showSuccess(data: UpdateUser) {
_actionView.postValue(UpdateUserViewAction.Loading(false))
_actionView.postValue(UpdateUserViewAction.Success(data))
}
mIoScope.async {
return@async useCase.execute()
}.await().fold(::showError, ::showSuccess)
}
private fun validadeUpdateUser(updateUser: UpdateUser, context: Context): Boolean {
updateUser.apply {
if (name.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (surname.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (email.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (password.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (cep.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (logradouro.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (complemento.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (bairro.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
} else if (localidade.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
}
if (uf.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
}
}
return true
}
private val _zipCodeAction by lazy { MutableLiveData<UpdateUserViewAction>() }
val zipCodeAction: LiveData<UpdateUserViewAction>
get() = _zipCodeAction
fun getBuscarCep(context: Context) {
if (validateCepInput(zipCode.value.toString(),context)) {
_zipCodeAction.value = UpdateUserViewAction.Loading(true)
mUiScope.launch { executeEndereco(zipCode.value.toString()) }
}
}
private suspend fun executeEndereco(cep: String) {
fun showCepError(message: String) {
mIoScope.launch {
_zipCodeAction.postValue(UpdateUserViewAction.Loading(false))
}
_zipCodeAction.postValue(UpdateUserViewAction.Error(message))
_messageAlert.postValue(message)
}
fun showCepSuccess(data: UpdateUser) {
_zipCodeAction.postValue(UpdateUserViewAction.Loading(false))
_zipCodeAction.postValue(UpdateUserViewAction.Success(data))
_updateUser.postValue(data)
}
mIoScope.async {
return@async useCase.executeEnderecoUser(cep)
}.await().fold(::showCepError, ::showCepSuccess)
}
private fun validateCepInput(cep: String, context: Context): Boolean {
if (cep.isEmpty()) {
_messageAlert.value = context.getString(string.preencher_campos)
return false
}
return true
}
}
|
<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Importer\Sources\Csv;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Importer\Sources\Csv\InvalidPathException;
use function sprintf;
class InvalidPathExceptionTest extends TestCase
{
/** @test */
public function pathNotProvidedCreatesExceptionAsExpected(): void
{
$e = InvalidPathException::pathNotProvided();
self::assertEquals('The path of the file is required.', $e->getMessage());
}
/**
* @test
* @dataProvider providePaths
*/
public function pathIsNotFileCreatesExceptionAsExpected(string $path): void
{
$e = InvalidPathException::pathIsNotFile($path);
self::assertEquals(sprintf('The file "%s" does not seem to exist. Try another one.', $path), $e->getMessage());
}
public function providePaths(): iterable
{
yield ['/foo'];
yield ['/bar'];
yield ['/bar/baz'];
}
}
|
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import run from './run';
import runServer from './runServer';
import webpackConfig from './webpack.config';
import clean from './clean';
import copy from './copy';
import webpackMiddleware from 'webpack-middleware'
import webpackdevMiddleware from 'webpack-dev-middleware'
const DEBUG = !process.argv.includes('--release');
var bundleStart;
/**
* Launches a development web server with "live reload" functionality -
* synchronizing URLs, interactions and code changes across multiple devices.
*/
async function start() {
await run(clean);
await run(copy.bind(undefined, { watch: true }));
await new Promise(resolve => {
// Patch the client-side bundle configurations
// to enable Hot Module Replacement (HMR) and React Transform
webpackConfig.filter(x => x.target !== 'node').forEach(config => {
/* eslint-disable no-param-reassign */
config.entry = ['react-hot-loader/patch'].concat(config.entry);
config.entry = ['webpack/hot/only-dev-server'].concat(config.entry);
config.entry = ['webpack-dev-server/client?http://localhost:7070'].concat(config.entry);
config.output.filename = config.output.filename.replace('[chunkhash]', '[hash]');
config.output.chunkFilename = config.output.chunkFilename.replace('[chunkhash]', '[hash]');
config.plugins.push(new webpack.HotModuleReplacementPlugin());
config.plugins.push(new webpack.NoErrorsPlugin());
/* eslint-enable no-param-reassign */
});
const bundler = webpack(webpackConfig);
let webpackDevMiddlewareInstance = webpackMiddleware(bundler,{
publicPath:webpackConfig[0].output.publicPath
});
let hotMiddlewares;
hotMiddlewares = bundler.compilers
.filter(compiler => compiler.options.target !== 'node')
.map(c => {
let middl=new WebpackDevServer(c, {
publicPath:webpackConfig[0].output.publicPath,
// contentBase: paths.client(),
contentBase: "http://localhost:8000",
hot: true,
quiet: true,
noInfo: true,
lazy: false,
stats: webpackConfig[0].stats
})
middl.listen("8000","localhost");
return middl.middleware}
);
let handleServerBundleComplete = () => {
runServer((err, host) => {
if (!err) {
const bs = require('browser-sync').create();
bs.init({
proxy: {
target: 'localhost:3000', // <- where Node.js app is running
middleware: [webpackDevMiddlewareInstance,...hotMiddlewares]
},
files: ['build/public/*.*'],
},cb
);
handleServerBundleComplete = runServer;
}
});
};
bundler.plugin('done', () => handleServerBundleComplete());
});
}
export default start;
|
<?php
namespace Yaroslavche\UnCefact\CommonCode\SpaceAndTime;
use Yaroslavche\UnCefact\CommonCode\AbstractCommonCode;
class AngleMinute extends AbstractCommonCode
{
const GROUP_NUMBER = 1;
const SECTOR = 'Space and Time';
const GROUP_ID = 6;
const QUANTITY = 'angle (plane)';
const LEVEL = '1';
const STATUS = null;
const COMMON_CODE = 'D61';
const NAME = 'minute [unit of angle]';
const CONVERSION_FACTOR = '2,908 882 x 10⁻⁴ rad';
const SYMBOL = '\'';
const DESCRIPTION = null;
}
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright © 2011 Marcos Talau
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Marcos Talau (talau@users.sourceforge.net)
*
*/
#include "ns3/test.h"
#include "ns3/red-queue.h"
#include "ns3/uinteger.h"
#include "ns3/string.h"
#include "ns3/double.h"
#include "ns3/log.h"
#include "ns3/simulator.h"
using namespace ns3;
class RedQueueTestCase : public TestCase
{
public:
RedQueueTestCase ();
virtual void DoRun (void);
private:
void Enqueue (Ptr<RedQueue> queue, uint32_t size, uint32_t nPkt);
void RunRedTest (StringValue mode);
};
RedQueueTestCase::RedQueueTestCase ()
: TestCase ("Sanity check on the red queue implementation")
{
}
void
RedQueueTestCase::RunRedTest (StringValue mode)
{
uint32_t pktSize = 0;
// 1 for packets; pktSize for bytes
uint32_t modeSize = 1;
double minTh = 2;
double maxTh = 5;
uint32_t qSize = 8;
Ptr<RedQueue> queue = CreateObject<RedQueue> ();
// test 1: simple enqueue/dequeue with no drops
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true,
"Verify that we can actually set the attribute Mode");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinTh", DoubleValue (minTh)), true,
"Verify that we can actually set the attribute MinTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxTh", DoubleValue (maxTh)), true,
"Verify that we can actually set the attribute MaxTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true,
"Verify that we can actually set the attribute QueueLimit");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QW", DoubleValue (0.002)), true,
"Verify that we can actually set the attribute QW");
if (queue->GetMode () == RedQueue::QUEUE_MODE_BYTES)
{
pktSize = 1000;
modeSize = pktSize;
queue->SetTh (minTh * pktSize, maxTh * pktSize);
queue->SetQueueLimit (qSize * pktSize);
}
Ptr<Packet> p1, p2, p3, p4, p5, p6, p7, p8;
p1 = Create<Packet> (pktSize);
p2 = Create<Packet> (pktSize);
p3 = Create<Packet> (pktSize);
p4 = Create<Packet> (pktSize);
p5 = Create<Packet> (pktSize);
p6 = Create<Packet> (pktSize);
p7 = Create<Packet> (pktSize);
p8 = Create<Packet> (pktSize);
NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 0 * modeSize, "There should be no packets in there");
queue->Enqueue (p1);
NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 1 * modeSize, "There should be one packet in there");
queue->Enqueue (p2);
NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 2 * modeSize, "There should be two packets in there");
queue->Enqueue (p3);
queue->Enqueue (p4);
queue->Enqueue (p5);
queue->Enqueue (p6);
queue->Enqueue (p7);
queue->Enqueue (p8);
NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 8 * modeSize, "There should be eight packets in there");
Ptr<Packet> p;
p = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((p != 0), true, "I want to remove the first packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 7 * modeSize, "There should be seven packets in there");
NS_TEST_EXPECT_MSG_EQ (p->GetUid (), p1->GetUid (), "was this the first packet ?");
p = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((p != 0), true, "I want to remove the second packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 6 * modeSize, "There should be six packet in there");
NS_TEST_EXPECT_MSG_EQ (p->GetUid (), p2->GetUid (), "Was this the second packet ?");
p = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((p != 0), true, "I want to remove the third packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 5 * modeSize, "There should be five packets in there");
NS_TEST_EXPECT_MSG_EQ (p->GetUid (), p3->GetUid (), "Was this the third packet ?");
p = queue->Dequeue ();
p = queue->Dequeue ();
p = queue->Dequeue ();
p = queue->Dequeue ();
p = queue->Dequeue ();
p = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((p == 0), true, "There are really no packets in there");
// test 2: more data, but with no drops
queue = CreateObject<RedQueue> ();
minTh = 70 * modeSize;
maxTh = 150 * modeSize;
qSize = 300 * modeSize;
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true,
"Verify that we can actually set the attribute Mode");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinTh", DoubleValue (minTh)), true,
"Verify that we can actually set the attribute MinTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxTh", DoubleValue (maxTh)), true,
"Verify that we can actually set the attribute MaxTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true,
"Verify that we can actually set the attribute QueueLimit");
Enqueue (queue, pktSize, 300);
RedQueue::Stats st = StaticCast<RedQueue> (queue)->GetStats ();
NS_TEST_EXPECT_MSG_EQ (st.unforcedDrop, 0, "There should zero dropped packets due probability mark");
NS_TEST_EXPECT_MSG_EQ (st.forcedDrop, 0, "There should zero dropped packets due hardmark mark");
NS_TEST_EXPECT_MSG_EQ (st.qLimDrop, 0, "There should zero dropped packets due queue full");
// save number of drops from tests
struct d {
uint32_t test3;
uint32_t test4;
uint32_t test5;
uint32_t test6;
uint32_t test7;
} drop;
// test 3: more data, now drops due QW change
queue = CreateObject<RedQueue> ();
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true,
"Verify that we can actually set the attribute Mode");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinTh", DoubleValue (minTh)), true,
"Verify that we can actually set the attribute MinTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxTh", DoubleValue (maxTh)), true,
"Verify that we can actually set the attribute MaxTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true,
"Verify that we can actually set the attribute QueueLimit");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QW", DoubleValue (0.020)), true,
"Verify that we can actually set the attribute QW");
Enqueue (queue, pktSize, 300);
st = StaticCast<RedQueue> (queue)->GetStats ();
drop.test3 = st.unforcedDrop + st.forcedDrop + st.qLimDrop;
NS_TEST_EXPECT_MSG_NE (drop.test3, 0, "There should be some dropped packets");
// test 4: reduced maxTh, this causes more drops
maxTh = 100 * modeSize;
queue = CreateObject<RedQueue> ();
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true,
"Verify that we can actually set the attribute Mode");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinTh", DoubleValue (minTh)), true,
"Verify that we can actually set the attribute MinTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxTh", DoubleValue (maxTh)), true,
"Verify that we can actually set the attribute MaxTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true,
"Verify that we can actually set the attribute QueueLimit");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QW", DoubleValue (0.020)), true,
"Verify that we can actually set the attribute QW");
Enqueue (queue, pktSize, 300);
st = StaticCast<RedQueue> (queue)->GetStats ();
drop.test4 = st.unforcedDrop + st.forcedDrop + st.qLimDrop;
NS_TEST_EXPECT_MSG_GT (drop.test4, drop.test3, "Test 4 should have more drops than test 3");
// test 5: change drop probability to a high value (LInterm)
maxTh = 150 * modeSize;
queue = CreateObject<RedQueue> ();
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true,
"Verify that we can actually set the attribute Mode");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinTh", DoubleValue (minTh)), true,
"Verify that we can actually set the attribute MinTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxTh", DoubleValue (maxTh)), true,
"Verify that we can actually set the attribute MaxTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true,
"Verify that we can actually set the attribute QueueLimit");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QW", DoubleValue (0.020)), true,
"Verify that we can actually set the attribute QW");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("LInterm", DoubleValue (5)), true,
"Verify that we can actually set the attribute LInterm");
Enqueue (queue, pktSize, 300);
st = StaticCast<RedQueue> (queue)->GetStats ();
drop.test5 = st.unforcedDrop + st.forcedDrop + st.qLimDrop;
NS_TEST_EXPECT_MSG_GT (drop.test5, drop.test3, "Test 5 should have more drops than test 3");
// test 6: disable Gentle param
queue = CreateObject<RedQueue> ();
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true,
"Verify that we can actually set the attribute Mode");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinTh", DoubleValue (minTh)), true,
"Verify that we can actually set the attribute MinTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxTh", DoubleValue (maxTh)), true,
"Verify that we can actually set the attribute MaxTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true,
"Verify that we can actually set the attribute QueueLimit");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QW", DoubleValue (0.020)), true,
"Verify that we can actually set the attribute QW");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Gentle", BooleanValue (false)), true,
"Verify that we can actually set the attribute Gentle");
Enqueue (queue, pktSize, 300);
st = StaticCast<RedQueue> (queue)->GetStats ();
drop.test6 = st.unforcedDrop + st.forcedDrop + st.qLimDrop;
NS_TEST_EXPECT_MSG_GT (drop.test6, drop.test3, "Test 6 should have more drops than test 3");
// test 7: disable Wait param
queue = CreateObject<RedQueue> ();
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true,
"Verify that we can actually set the attribute Mode");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinTh", DoubleValue (minTh)), true,
"Verify that we can actually set the attribute MinTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxTh", DoubleValue (maxTh)), true,
"Verify that we can actually set the attribute MaxTh");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true,
"Verify that we can actually set the attribute QueueLimit");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QW", DoubleValue (0.020)), true,
"Verify that we can actually set the attribute QW");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Wait", BooleanValue (false)), true,
"Verify that we can actually set the attribute Wait");
Enqueue (queue, pktSize, 300);
st = StaticCast<RedQueue> (queue)->GetStats ();
drop.test7 = st.unforcedDrop + st.forcedDrop + st.qLimDrop;
NS_TEST_EXPECT_MSG_GT (drop.test7, drop.test3, "Test 7 should have more drops than test 3");
}
void
RedQueueTestCase::Enqueue (Ptr<RedQueue> queue, uint32_t size, uint32_t nPkt)
{
for (uint32_t i = 0; i < nPkt; i++)
{
queue->Enqueue (Create<Packet> (size));
}
}
void
RedQueueTestCase::DoRun (void)
{
RunRedTest (StringValue ("QUEUE_MODE_PACKETS"));
RunRedTest (StringValue ("QUEUE_MODE_BYTES"));
Simulator::Destroy ();
}
static class RedQueueTestSuite : public TestSuite
{
public:
RedQueueTestSuite ()
: TestSuite ("red-queue", UNIT)
{
AddTestCase (new RedQueueTestCase (), TestCase::QUICK);
}
} g_redQueueTestSuite;
|
package io.nacular.doodle
import io.nacular.doodle.scheduler.Scheduler
import io.nacular.doodle.scheduler.Task
import io.nacular.measured.units.Measure
import io.nacular.measured.units.Time
import io.nacular.measured.units.Time.Companion.milliseconds
import io.nacular.measured.units.times
class ManualScheduler: Scheduler {
private class SimpleTask(override var completed: Boolean = false) : Task {
override fun cancel() {
completed = true
}
}
private val tasks = mutableListOf<Pair<SimpleTask, (Measure<Time>) -> Unit>>()
fun runJobs() = tasks.forEach {
it.first.completed = true
it.second(0 * milliseconds)
}
override fun after(time: Measure<Time>, job: (Measure<Time>) -> Unit): Task {
val task = SimpleTask()
tasks += task to job
return task
}
override fun every(time: Measure<Time>, job: (Measure<Time>) -> Unit): Task {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override suspend fun delay(time: Measure<Time>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override suspend fun delayUntil(predicate: (Measure<Time>) -> Boolean) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun shutdown() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
|
<?php
namespace GeneralServicer\Service\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use GeneralServicer\Service\DateCalculationService;
/**
*
* @author swoopfx
*
*/
class DateCalculationServiceFactory implements FactoryInterface
{
/**
*/
public function __construct()
{
// TODO - Insert your code here
}
/**
* (non-PHPdoc)
*
* @see \Zend\ServiceManager\FactoryInterface::createService()
*
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$xserv = new DateCalculationService();
$generalService = $serviceLocator->get('GeneralServicer\Service\GeneralService');
$em = $generalService->getEntityManager();
$centralBroker = $generalService->getCentralBroker();
$brokerSub = $generalService->getSubscription();
$endDate = NULL;
if($brokerSub != NULL){
$endDate = $brokerSub->getEndDate();
}
$xserv->setEntityManager($em)->setSubsEndDate($endDate);
return $xserv;
}
}
|
-- create a database
-- create hbtn_0c_0 database if not exists
CREATE DATABASE IF NOT EXISTS hbtn_0c_0;
|
package com.example.a301pro;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.test.espresso.contrib.DrawerActions;
import androidx.test.rule.ActivityTestRule;
import com.example.a301pro.View.ViewUserProfile;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.robotium.solo.Solo;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.clearText;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static org.junit.Assert.assertTrue;
/**
* Intent testing for viewing/editing profile
*/
public class ProfileTest {
private Solo solo;
final FirebaseFirestore db = FirebaseFirestore.getInstance();
/**
* Set up test rule
*/
@Rule
public ActivityTestRule<Register> rule =
new ActivityTestRule<Register>(Register.class, true, true);
/**
* Intent testing for adding/editing function
*/
@Before
public void setUp() throws Exception {
solo = new Solo(getInstrumentation(), rule.getActivity());
}
/**
* Closes the activity after each test
* @throws Exception fail message
*/
@After
public void tearDown() throws Exception {
getUID();
solo.finishOpenedActivities();
}
/**
* get the user id
*/
public void getUID() {
String testUsername = "username";
CollectionReference collectionReference = db.collection("userDict");
DocumentReference docRef = collectionReference.document(testUsername);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
final String UID = (String) document.getData().get("UID");
deleteUser(UID);
}
}
}
});
}
/**
* delete the user for the purpose of next test
* @param UID user id
*/
public void deleteUser(String UID){
String testFirstName = "firstName";
String testLastName = "lastName";
String testUsername = "username";
final String testEmail = "firstname@uablerta.ca";
String testPhone = "1234567890";
db.collection("userDict").document(testUsername)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
db.collection("Users").document(UID)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
/**
* test for editing a user profile
* @throws Exception fail message
*/
@Test
public void testEditProfile() throws Exception {
solo.assertCurrentActivity("Wrong Activity", Register.class);
String testFirstName = "firstName";
String testLastName = "lastName";
String testUsername = "username";
final String testEmail = "firstname@uablerta.ca";
String testPhone = "1234567890";
final String testPassword = "88888888";
solo.enterText((EditText) solo.getView(R.id.first_name), testFirstName);
solo.enterText((EditText) solo.getView(R.id.last_name), testLastName);
solo.enterText((EditText) solo.getView(R.id.phone_num), testPhone);
solo.enterText((EditText) solo.getView(R.id.Email), testEmail);
solo.enterText((EditText) solo.getView(R.id.text_username), testUsername);
solo.enterText((EditText) solo.getView(R.id.text_password), testPassword);
solo.enterText((EditText) solo.getView(R.id.text_password_check), testPassword);
solo.clickOnButton("DONE REGISTER");
solo.waitForActivity(Login.class);
solo.assertCurrentActivity("Wrong activity", Login.class);
solo.sleep(1000);
solo.enterText((EditText) solo.getView(R.id.text_username), testUsername);
solo.enterText((EditText) solo.getView(R.id.text_password), testPassword);
solo.clickOnButton("Login");
solo.waitForActivity("MainActivity", 10000);
solo.assertCurrentActivity("Wrong activity", MainActivity.class);
solo.sleep(1000);
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withContentDescription("Navigation header")).perform(click());
solo.waitForActivity("ViewUserProfile", 10000);
solo.assertCurrentActivity("Wrong activity", ViewUserProfile.class);
onView(withText("Edit Profile"))
.perform(click());
onView(withId(R.id.user_first_name_display)).perform(clearText());
onView(withId(R.id.user_last_name_display)).perform(clearText());
onView(withId(R.id.phone_num_display)).perform(clearText());
onView(withId(R.id.user_email_display)).perform(clearText());
solo.enterText((EditText) solo.getView(R.id.user_first_name_display), "Edit firstname");
solo.enterText((EditText) solo.getView(R.id.user_last_name_display), "Edit lastname");
solo.enterText((EditText) solo.getView(R.id.phone_num_display), "1987654321");
solo.enterText((EditText) solo.getView(R.id.user_email_display), "edit@ualberta.ca");
assertTrue(solo.waitForText("Edit firstname"));
assertTrue(solo.waitForText("Edit lastname"));
assertTrue(solo.waitForText("1987654321"));
assertTrue(solo.waitForText("edit@ualberta.ca"));
onView(withText("Confirm"))
.perform(click());
solo.waitForActivity("MainActivity", 10000);
solo.assertCurrentActivity("Wrong activity", MainActivity.class);
solo.sleep(1000);
onView(withText("Logout"))
.perform(click());
solo.waitForActivity(Login.class);
solo.assertCurrentActivity("Wrong activity", Login.class);
solo.sleep(1000);
// relogin to delete user
solo.enterText((EditText) solo.getView(R.id.text_username), testUsername);
solo.enterText((EditText) solo.getView(R.id.text_password), testPassword);
solo.clickOnButton("Login");
solo.clickOnButton("Login");
solo.waitForActivity("MainActivity", 10000);
solo.assertCurrentActivity("Wrong activity", MainActivity.class);
solo.sleep(1000);
final FirebaseUser currUser;
currUser = FirebaseAuth.getInstance().getCurrentUser();
currUser.delete();
FirebaseAuth authenticatedUser = FirebaseAuth.getInstance();
authenticatedUser.signOut();
}
}
|
#
# @lc app=leetcode id=223 lang=python3
#
# [223] Rectangle Area
#
# @lc code=start
class Solution:
def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
overlap = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0)
total = (A - C) * (B - D) + (E - G) * (F - H)
return total - overlap
# @lc code=end
# Accepted
# 3082/3082 cases passed(56 ms)
# Your runtime beats 81.4 % of python3 submissions
# Your memory usage beats 100 % of python3 submissions(12.8 MB)
|
/**
* last :: m a -> Maybe a
*/
declare function last(a: object, b: object): object;
declare function last(a: object): (b: object) => object;
export default last;
|
module BasicObjectSpecs
class SingletonMethod
def self.singleton_method_added name
ScratchPad.record [:singleton_method_added, name]
end
def self.singleton_method_to_alias
end
end
end
|
// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include <processApi.h>
uint64_t createProcessAsm(uint64_t function,_ARGUMENTS,int foreground);
uint64_t niceAsm(uint64_t pid, uint64_t deltaNice);
uint64_t killAsm(uint64_t signal, uint64_t pid);
uint64_t renounceAsm(void);
void exitAsm();
void waitAsm();
uint64_t getPidAsm();
int createProcessUserland(uint64_t function,_ARGUMENTS,int foreground){
return createProcessAsm(function,argc,argv,foreground);
}
uint64_t nice(int pid, int deltaNice) {
return niceAsm(pid, deltaNice);
}
uint64_t kill(int signal, int pid) {
return killAsm(signal, pid);
}
uint64_t renounceUserland(void) {
return renounceAsm();
}
void exitUserland(){
exitAsm();
}
void waitSon(){
waitAsm();
}
uint64_t getPid(){
return getPidAsm();
}
|
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
// @ts-ignore
global.loader = {
enqueue: jest.fn(),
};
window.scrollTo = () => {};
/**
* This resolves the `parentStyleSheet` undefined warning due to `JSS`.
* @see https://stackoverflow.com/a/66903658/2791678
*/
window.CSSStyleSheet.prototype.insertRule = (rule) => {
const styleElement = document.createElement('style');
const textNode = document.createTextNode(rule);
styleElement.appendChild(textNode);
document.head.appendChild(styleElement);
return 0;
};
require('jest-fetch-mock').enableMocks();
|
import type { RayPointerSource, RayPointerDriver } from '@rafern/canvas-ui';
import type { Group, XRInputSource, WebXRManager } from 'three';
import { PointerHint } from '@rafern/canvas-ui';
export interface XRControllerSourceState {
source: XRInputSource | null;
pointer: number;
}
export declare class XRControllerRayPointerSource implements RayPointerSource {
private _controllers;
private driver;
constructor(webXRManager: WebXRManager);
get controllers(): IterableIterator<[Group, XRControllerSourceState]>;
private trackController;
private registerController;
private unregisterController;
setRayPointerDriver(driver: RayPointerDriver): void;
clearRayPointerDriver(): void;
onPointerHintChanged(pointer: number, hint: PointerHint): void;
}
|
package msgbs
type Message interface{}
type MessageBus interface {
Publish(Event, Message) error
Subscribe(Event)
Unsubscribe(Event)
Receive() interface{}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.