text
stringlengths 27
775k
|
---|
package com.smartgwt.mobile.showcase.client.widgets.layouts;
import com.smartgwt.mobile.client.types.Alignment;
import com.smartgwt.mobile.client.types.VerticalAlignment;
import com.smartgwt.mobile.client.widgets.Header1;
import com.smartgwt.mobile.client.widgets.Header2;
import com.smartgwt.mobile.client.widgets.Panel;
import com.smartgwt.mobile.client.widgets.ScrollablePanel;
import com.smartgwt.mobile.client.widgets.Segment;
import com.smartgwt.mobile.client.widgets.events.ClickEvent;
import com.smartgwt.mobile.client.widgets.events.ClickHandler;
import com.smartgwt.mobile.client.widgets.layout.HLayout;
import com.smartgwt.mobile.client.widgets.layout.Layout;
import com.smartgwt.mobile.client.widgets.layout.SegmentedControl;
import com.smartgwt.mobile.client.widgets.layout.VLayout;
import com.smartgwt.mobile.client.widgets.toolbar.ToolStrip;
import com.smartgwt.mobile.client.widgets.toolbar.ToolStripButton;
import com.smartgwt.mobile.showcase.client.resources.AppResources;
public class VerticalLayouts extends ScrollablePanel {
public VerticalLayouts(String title) {
super(title);
this.setWidth("100%");
final VLayout vlayout = new VLayout();
ToolStrip toolbar1 = new ToolStrip();
toolbar1.setWidth("100%");
toolbar1.setAlign(Alignment.CENTER);
ToolStripButton toolbarButton12 = new ToolStripButton("Reverse");
toolbarButton12.setTintColor("#ffc000");
toolbarButton12.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
vlayout.setReverseOrder(!vlayout.getReverseOrder());
}
});
toolbar1.addButton(toolbarButton12);
addMember(toolbar1);
HLayout hlayout = new HLayout();
hlayout.setAlign(Alignment.CENTER);
SegmentedControl segmentedControl1 = new SegmentedControl();
Segment segment11 = new Segment("1");
segment11.setIcon(AppResources.INSTANCE.chart(), true);
Segment segment12 = new Segment("2");
segment12.setIcon(AppResources.INSTANCE.settings(), true);
segmentedControl1.setSegments(segment11, segment12);
hlayout.addMember(segmentedControl1);
vlayout.addMember(hlayout);
vlayout.addMember(new Header1("child 1"));
vlayout.addMember(new Header2("child 2"));
addMember(vlayout);
final Layout layout2 = new HLayout();
ToolStrip toolbar2 = new ToolStrip();
toolbar2.setTintColor("#339944");
SegmentedControl control = new SegmentedControl();
control.setInheritTint(true);
Segment segment22 = new Segment("Top");
segment22.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
layout2.setAlign(VerticalAlignment.TOP);
}
});
Segment segment23 = new Segment("Center");
segment23.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
layout2.setAlign(VerticalAlignment.CENTER);
}
});
Segment segment24 = new Segment("Bottom");
segment24.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
layout2.setAlign(VerticalAlignment.BOTTOM);
}
});
control.setSegments(segment22, segment23, segment24);
control.selectSegment(0);
toolbar2.addSpacer();
toolbar2.addSegmentedControl(control);
toolbar2.addSpacer();
addMember(toolbar2);
layout2.setWidth("100%");
layout2.setHeight("140px");
layout2.setAlign(Alignment.CENTER);
layout2.getElement().getStyle().setProperty("marginLeft", "auto");
layout2.getElement().getStyle().setProperty("marginRight", "auto");
layout2.setAlign(VerticalAlignment.TOP);
Panel info1 = new Panel();
info1.setStyleName("sc-rounded-panel");
info1.setContents("<p>line 1</p>");
info1.setMargin(10);
Panel info2 = new Panel();
info2.setStyleName("sc-rounded-panel");
info2.setContents("<p>line 1<br/>line 2</p>");
info2.setMargin(10);
Panel info3 = new Panel();
info3.setStyleName("sc-rounded-panel");
info3.setContents("<p>line 1<br/>line 2<br/>line 3</p>");
info3.setMargin(10);
layout2.addMember(info1);
layout2.addMember(info2);
layout2.addMember(info3);
addMember(layout2);
}
}
|
import { Component, OnInit, QueryList, ViewChildren } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatSelectionList, MatSelectionListChange } from '@angular/material/list';
import { IForm } from '@core/models/form';
import { Equipment } from '@modules/inventory/equipments/models/equipment';
import { EquipmentService } from '@modules/inventory/equipments/services/equipment.service';
import { ObservableStatus } from '@shared/models/observable-with-status';
import { Observable } from 'rxjs';
import { delay } from 'rxjs/operators';
@Component({
selector: 'app-select-equipments',
templateUrl: './select-equipments.component.html',
styleUrls: [ './select-equipments.component.scss' ]
})
export class SelectEquipmentsComponent implements OnInit, IForm {
public ObsStatus: typeof ObservableStatus = ObservableStatus;
equipments$: Observable<Equipment[]>;
selectedEquipments: Equipment[] = [];
selectEquipmentsForm: FormGroup;
@ViewChildren('equipmentsListSelection') equipmentsListSelection: QueryList<MatSelectionList>;
get controls(): { [key: string]: AbstractControl } {
return this.selectEquipmentsForm.controls;
}
constructor(private equipmentService: EquipmentService, private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.initForm();
this.loadData();
}
private loadData(): void {
this.equipments$ = this.equipmentService.getEquipments();
this.equipments$.pipe(delay(250)).subscribe((equipments) => {
this.selectEquipments();
});
}
initForm(): void {
this.selectEquipmentsForm = this.formBuilder.group({
equipmentCode: [ '' ],
showSelectedEquipments: [ false ],
equipmentCodes: [ '', [ Validators.required ] ]
});
this.controls['equipmentCode'].valueChanges.pipe(delay(100)).subscribe((value) => {
this.selectEquipments();
});
this.controls['showSelectedEquipments'].valueChanges.subscribe((value) => {
if (value) {
this.controls['equipmentCode'].disable();
} else {
this.controls['equipmentCode'].enable();
}
});
}
selectEquipments(): void {
if (
this.selectedEquipments.length === 0 ||
this.equipmentsListSelection.first === undefined ||
this.equipmentsListSelection.first.options === undefined
) {
return;
}
const selectedOptions = this.equipmentsListSelection.first.options.filter((option) => {
return this.selectedEquipments.some((e) => e.code === option.value.code);
});
this.equipmentsListSelection.first.selectedOptions.select(...selectedOptions);
}
onSelectEquipment(event: MatSelectionListChange): void {
const option = event.option;
const value = option.value;
if (option.selected) {
this.selectedEquipments.push(value);
} else {
const index = this.selectedEquipments.indexOf(value);
if (index !== -1) {
this.selectedEquipments.splice(index, 1);
}
}
}
get valid(): boolean {
return this.selectEquipmentsForm.valid;
}
get invalid(): boolean {
return !this.valid;
}
get value(): any {
if (this.selectedEquipments.length === 0) {
return null;
}
return this.controls['equipmentCodes'].value.map((p: Equipment) => p.code);
}
setValue(value: Equipment[]): void {
this.selectedEquipments = value;
this.selectEquipments();
}
}
|
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
title: "GDG POS Demo",
home: GDGPosDemo(),
),
);
}
class GDGPosDemo extends StatefulWidget {
@override
_GDGPosDemoState createState() => _GDGPosDemoState();
}
class _GDGPosDemoState extends State<GDGPosDemo> {
int count = 0;
void _incrementCounter() {
setState(() => count++);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Gdg Demo'),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Text("+"),
),
body: Container(
child: Center(
child: Text("Coolest counter count $count"),
),
),
);
}
}
|
INSERT INTO table_test VALUES ('a2');
INSERT INTO table_test VALUES ('a4');
COMMIT; |
import timeit
import os
# time 1
# start pub/sub server and operator
startvis = timeit.default_timer()
print("draw the graph")
print (startvis) |
// A custom struct:
struct Droppable {
name: &'static str,
}
// A custom implementation of the Drop trait for the struct:
impl Drop for Droppable {
// Rust calls automatically `drop()` for each field of a struct. A custom
// implementation of the Drop trait needs only to dealocacte resources
// introduced by the struct. Hence this `drop()` implementation does not
// actually deallocate anything:
fn drop(&mut self) {
println!("> Dropping {}", self.name);
}
}
fn custom_drop_example() {
let _droppable = Droppable { name: "test value" };
// Won't compile as Rust does not allow explicit calls to drop:
// _droppable.drop();
} // `Droppable::drop()` is called automatically here.
fn file_drop_example() {
// Open a directory:
let dir_path = std::env::current_dir().unwrap();
// Get files present in the directory:
let dir_filepaths = std::fs::read_dir(dir_path).unwrap();
// Open each file:
for filepath in dir_filepaths {
let _file = std::fs::File::open(filepath.unwrap().path()).unwrap();
// There is no `close()` in Rust.
} // Dropping `_file` closes the opened file.
}
fn main() {
custom_drop_example();
file_drop_example();
}
|
package gcloud.scala.pubsub
import java.util.concurrent.TimeUnit
import com.google.api.gax.core.CredentialsProvider
import com.google.cloud.pubsub.v1.{
AckReplyConsumer,
MessageReceiver,
Subscriber => GCloudSubscriber
}
import com.google.pubsub.v1
object Subscriber {
private[pubsub] final val MaxInboundMessageSize = 20 * 1024 * 1024 // 20MB API maximum message size.
type MessageReceiverType = (v1.PubsubMessage, AckReplyConsumer) => Unit
def apply(
subscriptionName: v1.ProjectSubscriptionName
)(receiver: MessageReceiverType): GCloudSubscriber =
Builder(subscriptionName, MessageReceiverWrapper(receiver))
def apply(
subscriptionName: v1.ProjectSubscriptionName,
pubSubUrl: PubSubUrl = PubSubUrl.DefaultPubSubUrl,
credentialsProvider: CredentialsProvider =
com.google.cloud.pubsub.v1.SubscriptionAdminSettings.defaultCredentialsProviderBuilder.build,
maxInboundMessageSize: Int = MaxInboundMessageSize
)(receiver: MessageReceiverType): GCloudSubscriber =
Builder(subscriptionName, MessageReceiverWrapper(receiver))
.setChannelProviderWithUrl(pubSubUrl, maxInboundMessageSize)
.setCredentialsProvider(credentialsProvider)
object Builder {
def apply(subscriptionName: v1.ProjectSubscriptionName,
receiver: MessageReceiver): GCloudSubscriber.Builder =
GCloudSubscriber.newBuilder(subscriptionName, receiver)
private[pubsub] object Logic {
def setChannelProviderWithUrl(
builder: GCloudSubscriber.Builder,
pubSubUrl: PubSubUrl,
maxInboundMessageSize: Int = MaxInboundMessageSize
): GCloudSubscriber.Builder =
builder.setChannelProvider(
pubSubUrl
.channelProviderBuilder()
.maxInboundMessageSize(maxInboundMessageSize)
.keepAliveTime(5, TimeUnit.SECONDS)
.build()
)
}
}
private object MessageReceiverWrapper {
def apply(receiver: MessageReceiverType): MessageReceiverWrapper =
new MessageReceiverWrapper(receiver)
}
private class MessageReceiverWrapper(receiver: MessageReceiverType) extends MessageReceiver {
override def receiveMessage(message: v1.PubsubMessage, consumer: AckReplyConsumer): Unit =
receiver(message, consumer)
}
}
|
#!/bin/bash
flake8 cloudeyeclient | tee flake8.log
exit ${PIPESTATUS[0]}
|
import 'dart:math';
import 'package:data/injection.dart';
import 'package:domain/entity/item.dart';
import 'package:domain/entity/story_type.dart';
import 'package:domain/logger.dart';
import 'package:domain/usecase/get_item_use_case.dart';
import 'package:domain/usecase/get_stories_use_case.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class StoryViewModel extends ChangeNotifier {
static const pageSize = 10;
final GetItemUseCase _getItemUseCase;
final GetStoriesUseCase _getStoriesUseCase;
StoryViewModel(this._getItemUseCase, this._getStoriesUseCase);
List<int> _stories = [];
List<int> get stories => _stories;
Map<int, Item> _items = {};
Map<int, Item> get items => _items;
bool _isLoading = true;
bool get isLoading => _isLoading;
int _visibleStorySize = pageSize;
int get visibleStorySize => min(_visibleStorySize, _stories.length);
Future<void> fetchItems(StoryType storyType) async {
_isLoading = true;
_visibleStorySize = pageSize;
notifyListeners();
final result = await _getStoriesUseCase.execute(storyType);
if (result.isValue) {
final data = result.asValue.value;
_stories = data.toList();
_isLoading = false;
notifyListeners();
} else if (result.isError) {
final error = result.asError.error;
logger.e(error);
_stories = [];
_isLoading = false;
notifyListeners();
}
}
Future<void> fetchItem(int id) async {
final result = await _getItemUseCase.execute(id);
if (result.isValue) {
final data = result.asValue.value;
_items = Map.from(_items);
_items[id] = data;
notifyListeners();
} else if (result.isError) {
final error = result.asError.error;
logger.e(error);
}
}
void loadMoreStories() {
final nextVisibleStorySize = _visibleStorySize + pageSize;
_visibleStorySize = min(nextVisibleStorySize, _stories.length);
notifyListeners();
}
}
final storyViewModelProvider =
ChangeNotifierProvider.autoDispose<StoryViewModel>((ref) => getIt());
|
using AdventOfCode.Core;
using NUnit.Framework;
namespace AdventOfCode2017
{
public class Day17Tests : TestBase
{
const int DAY = 17;
[Test]
public void TestPartOne()
{
Assert.That(Day17.PartOne(343), Is.EqualTo(1914));
}
[Test]
public void TestPartOneExample()
{
Assert.That(Day17.PartOne(3), Is.EqualTo(638));
}
[Test]
public void TestPartTwo()
{
Assert.That(Day17.PartTwo(343), Is.EqualTo(41797835));
}
}
}
|
using Levels.domain.repositories;
using Purchases.domain.repositories;
using Purchases.presentation.ui;
using Zenject;
namespace Purchases.adapters
{
public class LevelNumberProviderAdapter : PassLevelRewardPurchaseItem.ILevelNumberProvider
{
[Inject] private IPassLevelRewardPurchasesRepository passLevelRewardPurchasesRepository;
[Inject] private ILevelsRepository levelsRepository;
public int GetLevelNumber(long purchaseId)
{
var targetLevelId = passLevelRewardPurchasesRepository.GetLevelId(purchaseId);
return levelsRepository.GetLevel(targetLevelId).Number;
}
}
} |
/*
* Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "config.h"
#if CROWN_BUILD_UNIT_TESTS
#include "core/command_line.h"
#include "core/containers/array.h"
#include "core/containers/hash_map.h"
#include "core/containers/hash_set.h"
#include "core/containers/vector.h"
#include "core/filesystem/path.h"
#include "core/guid.h"
#include "core/json/json.h"
#include "core/json/sjson.h"
#include "core/math/aabb.h"
#include "core/math/color4.h"
#include "core/math/math.h"
#include "core/math/matrix3x3.h"
#include "core/math/matrix4x4.h"
#include "core/math/quaternion.h"
#include "core/math/sphere.h"
#include "core/math/vector2.h"
#include "core/math/vector3.h"
#include "core/math/vector4.h"
#include "core/memory/memory.h"
#include "core/memory/temp_allocator.h"
#include "core/murmur.h"
#include "core/strings/dynamic_string.h"
#include "core/strings/string.h"
#include "core/strings/string_id.h"
#include "core/thread/thread.h"
#include "core/time.h"
#include <stdlib.h> // EXIT_SUCCESS, EXIT_FAILURE
#define ENSURE(condition) \
do \
{ \
if (!(condition)) \
{ \
printf("Assertion failed: '%s' in %s:%d\n\n" \
, #condition \
, __FILE__ \
, __LINE__ \
); \
exit(EXIT_FAILURE); \
} \
} \
while (0)
namespace crown
{
static void test_memory()
{
memory_globals::init();
Allocator& a = default_allocator();
void* p = a.allocate(32);
ENSURE(a.allocated_size(p) >= 32);
a.deallocate(p);
memory_globals::shutdown();
}
static void test_array()
{
memory_globals::init();
Allocator& a = default_allocator();
{
Array<int> v(a);
ENSURE(array::size(v) == 0);
array::push_back(v, 1);
ENSURE(array::size(v) == 1);
ENSURE(v[0] == 1);
}
memory_globals::shutdown();
}
static void test_vector()
{
memory_globals::init();
Allocator& a = default_allocator();
{
Vector<int> v(a);
ENSURE(vector::size(v) == 0);
vector::push_back(v, 1);
ENSURE(vector::size(v) == 1);
ENSURE(v[0] == 1);
}
memory_globals::shutdown();
}
static void test_hash_map()
{
memory_globals::init();
Allocator& a = default_allocator();
{
HashMap<s32, s32> m(a);
ENSURE(hash_map::size(m) == 0);
ENSURE(hash_map::get(m, 0, 42) == 42);
ENSURE(!hash_map::has(m, 10));
for (s32 i = 0; i < 100; ++i)
hash_map::set(m, i, i*i);
for (s32 i = 0; i < 100; ++i)
ENSURE(hash_map::get(m, i, 0) == i*i);
hash_map::remove(m, 20);
ENSURE(!hash_map::has(m, 20));
hash_map::remove(m, 2000);
ENSURE(!hash_map::has(m, 2000));
hash_map::remove(m, 50);
ENSURE(!hash_map::has(m, 50));
hash_map::clear(m);
for (s32 i = 0; i < 100; ++i)
ENSURE(!hash_map::has(m, i));
}
{
HashMap<s32, s32> m(a);
hash_map_internal::grow(m);
ENSURE(hash_map::capacity(m) == 16);
hash_map::set(m, 0, 7);
hash_map::set(m, 1, 1);
for (s32 i = 2; i < 150; ++i)
{
hash_map::set(m, i, 2);
ENSURE(hash_map::has(m, 0));
ENSURE(hash_map::has(m, 1));
ENSURE(hash_map::has(m, i));
hash_map::remove(m, i);
}
}
memory_globals::shutdown();
}
static void test_hash_set()
{
memory_globals::init();
Allocator& a = default_allocator();
{
HashSet<s32> m(a);
ENSURE(hash_set::size(m) == 0);
ENSURE(!hash_set::has(m, 10));
for (s32 i = 0; i < 100; ++i)
hash_set::insert(m, i*i);
for (s32 i = 0; i < 100; ++i)
ENSURE(hash_set::has(m, i*i));
hash_set::remove(m, 5*5);
ENSURE(!hash_set::has(m, 5*5));
hash_set::remove(m, 80*80);
ENSURE(!hash_set::has(m, 80*80));
hash_set::remove(m, 40*40);
ENSURE(!hash_set::has(m, 40*40));
hash_set::clear(m);
for (s32 i = 0; i < 100; ++i)
ENSURE(!hash_set::has(m, i*i));
}
memory_globals::shutdown();
}
static void test_vector2()
{
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = vector2(2.7f, -1.9f);
const Vector2 c = a - b;
ENSURE(fequal(c.x, -1.5f, 0.0001f));
ENSURE(fequal(c.y, 6.1f, 0.0001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = vector2(2.7f, -1.9f);
const Vector2 c = a + b;
ENSURE(fequal(c.x, 3.9f, 0.0001f));
ENSURE(fequal(c.y, 2.3f, 0.0001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = a * 2.0f;
ENSURE(fequal(b.x, 2.4f, 0.0001f));
ENSURE(fequal(b.y, 8.4f, 0.0001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = vector2(2.7f, -1.9f);
const f32 c = dot(a, b);
ENSURE(fequal(c, -4.74f, 0.0001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const f32 c = length_squared(a);
ENSURE(fequal(c, 19.08f, 0.0001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const f32 c = length(a);
ENSURE(fequal(c, 4.36806f, 0.0001f));
}
{
Vector2 a = vector2(1.2f, 4.2f);
normalize(a);
ENSURE(fequal(length(a), 1.0f, 0.00001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = vector2(2.7f, -1.9f);
const float c = distance_squared(a, b);
ENSURE(fequal(c, 39.46f, 0.00001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = vector2(2.7f, -1.9f);
const float c = distance(a, b);
ENSURE(fequal(c, 6.28171f, 0.00001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = vector2(2.7f, -1.9f);
const Vector2 c = max(a, b);
ENSURE(fequal(c.x, 2.7f, 0.00001f));
ENSURE(fequal(c.y, 4.2f, 0.00001f));
}
{
const Vector2 a = vector2(1.2f, 4.2f);
const Vector2 b = vector2(2.7f, -1.9f);
const Vector2 c = min(a, b);
ENSURE(fequal(c.x, 1.2f, 0.00001f));
ENSURE(fequal(c.y, -1.9f, 0.00001f));
}
}
static void test_vector3()
{
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const Vector3 c = a - b;
ENSURE(fequal(c.x, -1.5f, 0.0001f));
ENSURE(fequal(c.y, 6.1f, 0.0001f));
ENSURE(fequal(c.z, 1.8f, 0.0001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const Vector3 c = a + b;
ENSURE(fequal(c.x, 3.9f, 0.0001f));
ENSURE(fequal(c.y, 2.3f, 0.0001f));
ENSURE(fequal(c.z, -6.4f, 0.0001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = a * 2.0f;
ENSURE(fequal(b.x, 2.4f, 0.0001f));
ENSURE(fequal(b.y, 8.4f, 0.0001f));
ENSURE(fequal(b.z, -4.6f, 0.0001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const f32 c = dot(a, b);
ENSURE(fequal(c, 4.69f, 0.0001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const Vector3 c = cross(a, b);
ENSURE(fequal(c.x, -21.59f, 0.0001f));
ENSURE(fequal(c.y, -1.29f, 0.0001f));
ENSURE(fequal(c.z, -13.62f, 0.0001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const f32 c = length_squared(a);
ENSURE(fequal(c, 24.37f, 0.0001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const f32 c = length(a);
ENSURE(fequal(c, 4.93659f, 0.0001f));
}
{
Vector3 a = vector3(1.2f, 4.2f, -2.3f);
normalize(a);
ENSURE(fequal(length(a), 1.0f, 0.00001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const float c = distance_squared(a, b);
ENSURE(fequal(c, 42.70f, 0.00001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const float c = distance(a, b);
ENSURE(fequal(c, 6.53452f, 0.00001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const Vector3 c = max(a, b);
ENSURE(fequal(c.x, 2.7f, 0.00001f));
ENSURE(fequal(c.y, 4.2f, 0.00001f));
ENSURE(fequal(c.z, -2.3f, 0.00001f));
}
{
const Vector3 a = vector3(1.2f, 4.2f, -2.3f);
const Vector3 b = vector3(2.7f, -1.9f, -4.1f);
const Vector3 c = min(a, b);
ENSURE(fequal(c.x, 1.2f, 0.00001f));
ENSURE(fequal(c.y, -1.9f, 0.00001f));
ENSURE(fequal(c.z, -4.1f, 0.00001f));
}
}
static void test_vector4()
{
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const Vector4 b = vector4(2.7f, -1.9f, -4.1f, 1.0f);
const Vector4 c = a - b;
ENSURE(fequal(c.x, -1.5f, 0.0001f));
ENSURE(fequal(c.y, 6.1f, 0.0001f));
ENSURE(fequal(c.z, 1.8f, 0.0001f));
ENSURE(fequal(c.w, 4.5f, 0.0001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const Vector4 b = vector4(2.7f, -1.9f, -4.1f, 1.0f);
const Vector4 c = a + b;
ENSURE(fequal(c.x, 3.9f, 0.0001f));
ENSURE(fequal(c.y, 2.3f, 0.0001f));
ENSURE(fequal(c.z, -6.4f, 0.0001f));
ENSURE(fequal(c.w, 6.5f, 0.0001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 1.5f);
const Vector4 b = a * 2.0f;
ENSURE(fequal(b.x, 2.4f, 0.0001f));
ENSURE(fequal(b.y, 8.4f, 0.0001f));
ENSURE(fequal(b.z, -4.6f, 0.0001f));
ENSURE(fequal(b.w, 3.0f, 0.0001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const Vector4 b = vector4(2.7f, -1.9f, -4.1f, 1.0f);
const f32 c = dot(a, b);
ENSURE(fequal(c, 10.19f, 0.0001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const f32 c = length_squared(a);
ENSURE(fequal(c, 54.62f, 0.0001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const f32 c = length(a);
ENSURE(fequal(c, 7.39053f, 0.0001f));
}
{
Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
normalize(a);
ENSURE(fequal(length(a), 1.0f, 0.00001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const Vector4 b = vector4(2.7f, -1.9f, -4.1f, 1.0f);
const float c = distance_squared(a, b);
ENSURE(fequal(c, 62.95f, 0.00001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const Vector4 b = vector4(2.7f, -1.9f, -4.1f, 1.0f);
const float c = distance(a, b);
ENSURE(fequal(c, 7.93410f, 0.00001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const Vector4 b = vector4(2.7f, -1.9f, -4.1f, 1.0f);
const Vector4 c = max(a, b);
ENSURE(fequal(c.x, 2.7f, 0.00001f));
ENSURE(fequal(c.y, 4.2f, 0.00001f));
ENSURE(fequal(c.z, -2.3f, 0.00001f));
ENSURE(fequal(c.w, 5.5f, 0.00001f));
}
{
const Vector4 a = vector4(1.2f, 4.2f, -2.3f, 5.5f);
const Vector4 b = vector4(2.7f, -1.9f, -4.1f, 1.0f);
const Vector4 c = min(a, b);
ENSURE(fequal(c.x, 1.2f, 0.00001f));
ENSURE(fequal(c.y, -1.9f, 0.00001f));
ENSURE(fequal(c.z, -4.1f, 0.00001f));
ENSURE(fequal(c.w, 1.0f, 0.00001f));
}
}
static void test_quaternion()
{
{
const Quaternion a = quaternion(0.0f, 0.0f, 0.0f, 1.0f);
ENSURE(fequal(a.x, 0.0f, 0.00001f));
ENSURE(fequal(a.y, 0.0f, 0.00001f));
ENSURE(fequal(a.z, 0.0f, 0.00001f));
ENSURE(fequal(a.w, 1.0f, 0.00001f));
}
}
static void test_color4()
{
{
const Color4 a = color4(1.3f, 2.6f, 0.2f, 0.6f);
ENSURE(fequal(a.x, 1.3f, 0.00001f));
ENSURE(fequal(a.y, 2.6f, 0.00001f));
ENSURE(fequal(a.z, 0.2f, 0.00001f));
ENSURE(fequal(a.w, 0.6f, 0.00001f));
}
{
const Color4 a = from_rgba(63, 231, 12, 98);
ENSURE(fequal(a.x, 0.24705f, 0.00001f));
ENSURE(fequal(a.y, 0.90588f, 0.00001f));
ENSURE(fequal(a.z, 0.04705f, 0.00001f));
ENSURE(fequal(a.w, 0.38431f, 0.00001f));
}
{
const Color4 a = from_rgb(63, 231, 12);
ENSURE(fequal(a.x, 0.24705f, 0.00001f));
ENSURE(fequal(a.y, 0.90588f, 0.00001f));
ENSURE(fequal(a.z, 0.04705f, 0.00001f));
ENSURE(fequal(a.w, 1.0f , 0.00001f));
}
{
const Color4 a = from_rgba(0x3fe70c62);
ENSURE(fequal(a.x, 0.24705f, 0.00001f));
ENSURE(fequal(a.y, 0.90588f, 0.00001f));
ENSURE(fequal(a.z, 0.04705f, 0.00001f));
ENSURE(fequal(a.w, 0.38431f, 0.00001f));
}
{
const Color4 a = from_rgba(63, 231, 12, 98);
const u32 rgba = to_rgba(a);
ENSURE(rgba == 0x3fe70c62);
const u32 rgb = to_rgb(a);
ENSURE(rgb == 0x3fe70cff);
const u32 bgr = to_bgr(a);
ENSURE(bgr == 0xff0ce73f);
const u32 abgr = to_abgr(a);
ENSURE(abgr == 0x620ce73f);
}
}
static void test_matrix3x3()
{
{
const Matrix3x3 a = matrix3x3(1.2f, -2.3f, 5.1f
, 2.2f, -5.1f, 1.1f
, 3.2f, 3.3f, -3.8f
);
const Matrix3x3 b = matrix3x3(3.2f, 4.8f, 6.0f
, -1.6f, -7.1f, -2.4f
, -3.1f, -2.2f, 8.9f
);
const Matrix3x3 c = a + b;
ENSURE(fequal(c.x.x, 4.4f, 0.00001f));
ENSURE(fequal(c.x.y, 2.5f, 0.00001f));
ENSURE(fequal(c.x.z, 11.1f, 0.00001f));
ENSURE(fequal(c.y.x, 0.6f, 0.00001f));
ENSURE(fequal(c.y.y, -12.2f, 0.00001f));
ENSURE(fequal(c.y.z, -1.3f, 0.00001f));
ENSURE(fequal(c.z.x, 0.1f, 0.00001f));
ENSURE(fequal(c.z.y, 1.1f, 0.00001f));
ENSURE(fequal(c.z.z, 5.1f, 0.00001f));
}
{
const Matrix3x3 a = matrix3x3(1.2f, -2.3f, 5.1f
, 2.2f, -5.1f, 1.1f
, 3.2f, 3.3f, -3.8f
);
const Matrix3x3 b = matrix3x3(3.2f, 4.8f, 6.0f
, -1.6f, -7.1f, -2.4f
, -3.1f, -2.2f, 8.9f
);
const Matrix3x3 c = a - b;
ENSURE(fequal(c.x.x, -2.0f, 0.00001f));
ENSURE(fequal(c.x.y, -7.1f, 0.00001f));
ENSURE(fequal(c.x.z, -0.9f, 0.00001f));
ENSURE(fequal(c.y.x, 3.8f, 0.00001f));
ENSURE(fequal(c.y.y, 2.0f, 0.00001f));
ENSURE(fequal(c.y.z, 3.5f, 0.00001f));
ENSURE(fequal(c.z.x, 6.3f, 0.00001f));
ENSURE(fequal(c.z.y, 5.5f, 0.00001f));
ENSURE(fequal(c.z.z, -12.7f, 0.00001f));
}
{
const Matrix3x3 a = matrix3x3(1.2f, -2.3f, 5.1f
, 2.2f, -5.1f, 1.1f
, 3.2f, 3.3f, -3.8f
);
const Matrix3x3 b = matrix3x3(3.2f, 4.8f, 6.0f
, -1.6f, -7.1f, -2.4f
, -3.1f, -2.2f, 8.9f
);
const Matrix3x3 c = a * b;
ENSURE(fequal(c.x.x, -8.29f, 0.00001f));
ENSURE(fequal(c.x.y, 10.87f, 0.00001f));
ENSURE(fequal(c.x.z, 58.11f, 0.00001f));
ENSURE(fequal(c.y.x, 11.79f, 0.00001f));
ENSURE(fequal(c.y.y, 44.35f, 0.00001f));
ENSURE(fequal(c.y.z, 35.23f, 0.00001f));
ENSURE(fequal(c.z.x, 16.74f, 0.00001f));
ENSURE(fequal(c.z.y, 0.29f, 0.00001f));
ENSURE(fequal(c.z.z, -22.54f, 0.00001f));
}
{
const Matrix3x3 a = matrix3x3(1.2f, -2.3f, 5.1f
, 2.2f, -5.1f, 1.1f
, 3.2f, 3.3f, -3.8f
);
const Matrix3x3 b = get_inverted(a);
ENSURE(fequal(b.x.x, 0.140833f, 0.00001f));
ENSURE(fequal(b.x.y, 0.072339f, 0.00001f));
ENSURE(fequal(b.x.z, 0.209954f, 0.00001f));
ENSURE(fequal(b.y.x, 0.106228f, 0.00001f));
ENSURE(fequal(b.y.y, -0.186705f, 0.00001f));
ENSURE(fequal(b.y.z, 0.088524f, 0.00001f));
ENSURE(fequal(b.z.x, 0.210848f, 0.00001f));
ENSURE(fequal(b.z.y, -0.101221f, 0.00001f));
ENSURE(fequal(b.z.z, -0.009478f, 0.00001f));
}
{
const Matrix3x3 a = matrix3x3(1.2f, -2.3f, 5.1f
, 2.2f, -5.1f, 1.1f
, 3.2f, 3.3f, -3.8f
);
const Matrix3x3 b = get_transposed(a);
ENSURE(fequal(b.x.x, 1.2f, 0.00001f));
ENSURE(fequal(b.x.y, 2.2f, 0.00001f));
ENSURE(fequal(b.x.z, 3.2f, 0.00001f));
ENSURE(fequal(b.y.x, -2.3f, 0.00001f));
ENSURE(fequal(b.y.y, -5.1f, 0.00001f));
ENSURE(fequal(b.y.z, 3.3f, 0.00001f));
ENSURE(fequal(b.z.x, 5.1f, 0.00001f));
ENSURE(fequal(b.z.y, 1.1f, 0.00001f));
ENSURE(fequal(b.z.z, -3.8f, 0.00001f));
}
}
static void test_matrix4x4()
{
{
const Matrix4x4 a = matrix4x4(1.2f, -2.3f, 5.1f, -1.2f
, 2.2f, -5.1f, 1.1f, -7.4f
, 3.2f, 3.3f, -3.8f, -9.2f
, -6.8f, -2.9f, 1.0f, 4.9f
);
const Matrix4x4 b = matrix4x4(3.2f, 4.8f, 6.0f, 5.3f
, -1.6f, -7.1f, -2.4f, -6.2f
, -3.1f, -2.2f, 8.9f, 8.3f
, 3.8f, 9.1f, -3.1f, -7.1f
);
const Matrix4x4 c = a + b;
ENSURE(fequal(c.x.x, 4.4f, 0.00001f));
ENSURE(fequal(c.x.y, 2.5f, 0.00001f));
ENSURE(fequal(c.x.z, 11.1f, 0.00001f));
ENSURE(fequal(c.x.w, 4.1f, 0.00001f));
ENSURE(fequal(c.y.x, 0.6f, 0.00001f));
ENSURE(fequal(c.y.y, -12.2f, 0.00001f));
ENSURE(fequal(c.y.z, -1.3f, 0.00001f));
ENSURE(fequal(c.y.w, -13.6f, 0.00001f));
ENSURE(fequal(c.z.x, 0.1f, 0.00001f));
ENSURE(fequal(c.z.y, 1.1f, 0.00001f));
ENSURE(fequal(c.z.z, 5.1f, 0.00001f));
ENSURE(fequal(c.z.w, -0.9f, 0.00001f));
ENSURE(fequal(c.t.x, -3.0f, 0.00001f));
ENSURE(fequal(c.t.y, 6.2f, 0.00001f));
ENSURE(fequal(c.t.z, -2.1f, 0.00001f));
ENSURE(fequal(c.t.w, -2.2f, 0.00001f));
}
{
const Matrix4x4 a = matrix4x4(1.2f, -2.3f, 5.1f, -1.2f
, 2.2f, -5.1f, 1.1f, -7.4f
, 3.2f, 3.3f, -3.8f, -9.2f
, -6.8f, -2.9f, 1.0f, 4.9f
);
const Matrix4x4 b = matrix4x4(3.2f, 4.8f, 6.0f, 5.3f
, -1.6f, -7.1f, -2.4f, -6.2f
, -3.1f, -2.2f, 8.9f, 8.3f
, 3.8f, 9.1f, -3.1f, -7.1f
);
const Matrix4x4 c = a - b;
ENSURE(fequal(c.x.x, -2.0f, 0.00001f));
ENSURE(fequal(c.x.y, -7.1f, 0.00001f));
ENSURE(fequal(c.x.z, -0.9f, 0.00001f));
ENSURE(fequal(c.x.w, -6.5f, 0.00001f));
ENSURE(fequal(c.y.x, 3.8f, 0.00001f));
ENSURE(fequal(c.y.y, 2.0f, 0.00001f));
ENSURE(fequal(c.y.z, 3.5f, 0.00001f));
ENSURE(fequal(c.y.w, -1.2f, 0.00001f));
ENSURE(fequal(c.z.x, 6.3f, 0.00001f));
ENSURE(fequal(c.z.y, 5.5f, 0.00001f));
ENSURE(fequal(c.z.z, -12.7f, 0.00001f));
ENSURE(fequal(c.z.w, -17.5f, 0.00001f));
ENSURE(fequal(c.t.x, -10.6f, 0.00001f));
ENSURE(fequal(c.t.y, -12.0f, 0.00001f));
ENSURE(fequal(c.t.z, 4.1f, 0.00001f));
ENSURE(fequal(c.t.w, 12.0f, 0.00001f));
}
{
const Matrix4x4 a = matrix4x4(1.2f, -2.3f, 5.1f, -1.2f
, 2.2f, -5.1f, 1.1f, -7.4f
, 3.2f, 3.3f, -3.8f, -9.2f
, -6.8f, -2.9f, 1.0f, 4.9f
);
const Matrix4x4 b = matrix4x4(3.2f, 4.8f, 6.0f, 5.3f
, -1.6f, -7.1f, -2.4f, -6.2f
, -3.1f, -2.2f, 8.9f, 8.3f
, 3.8f, 9.1f, -3.1f, -7.1f
);
const Matrix4x4 c = a * b;
ENSURE(fequal(c.x.x, -12.85f, 0.00001f));
ENSURE(fequal(c.x.y, -0.05f, 0.00001f));
ENSURE(fequal(c.x.z, 61.83f, 0.00001f));
ENSURE(fequal(c.x.w, 71.47f, 0.00001f));
ENSURE(fequal(c.y.x, -16.33f, 0.00001f));
ENSURE(fequal(c.y.y, -22.99f, 0.00001f));
ENSURE(fequal(c.y.z, 58.17f, 0.00001f));
ENSURE(fequal(c.y.w, 104.95f, 0.00001f));
ENSURE(fequal(c.z.x, -18.22f, 0.00001f));
ENSURE(fequal(c.z.y, -83.43f, 0.00001f));
ENSURE(fequal(c.z.z, 5.98f, 0.00001f));
ENSURE(fequal(c.z.w, 30.28f, 0.00001f));
ENSURE(fequal(c.t.x, -1.60f, 0.00001f));
ENSURE(fequal(c.t.y, 30.34f, 0.00001f));
ENSURE(fequal(c.t.z, -40.13f, 0.00001f));
ENSURE(fequal(c.t.w, -44.55f, 0.00001f));
}
{
const Matrix4x4 a = matrix4x4(1.2f, -2.3f, 5.1f, -1.2f
, 2.2f, -5.1f, 1.1f, -7.4f
, 3.2f, 3.3f, -3.8f, -9.2f
, -6.8f, -2.9f, 1.0f, 4.9f
);
const Matrix4x4 b = get_inverted(a);
ENSURE(fequal(b.x.x, -0.08464f, 0.00001f));
ENSURE(fequal(b.x.y, 0.06129f, 0.00001f));
ENSURE(fequal(b.x.z, -0.15210f, 0.00001f));
ENSURE(fequal(b.x.w, -0.21374f, 0.00001f));
ENSURE(fequal(b.y.x, 0.14384f, 0.00001f));
ENSURE(fequal(b.y.y, -0.18486f, 0.00001f));
ENSURE(fequal(b.y.z, 0.14892f, 0.00001f));
ENSURE(fequal(b.y.w, 0.03565f, 0.00001f));
ENSURE(fequal(b.z.x, 0.26073f, 0.00001f));
ENSURE(fequal(b.z.y, -0.09877f, 0.00001f));
ENSURE(fequal(b.z.z, 0.07063f, 0.00001f));
ENSURE(fequal(b.z.w, 0.04729f, 0.00001f));
ENSURE(fequal(b.t.x, -0.08553f, 0.00001f));
ENSURE(fequal(b.t.y, -0.00419f, 0.00001f));
ENSURE(fequal(b.t.z, -0.13735f, 0.00001f));
ENSURE(fequal(b.t.w, -0.08108f, 0.00001f));
}
{
const Matrix4x4 a = matrix4x4(1.2f, -2.3f, 5.1f, -1.2f
, 2.2f, -5.1f, 1.1f, -7.4f
, 3.2f, 3.3f, -3.8f, -9.2f
, -6.8f, -2.9f, 1.0f, 4.9f
);
const Matrix4x4 b = get_transposed(a);
ENSURE(fequal(b.x.x, 1.2f, 0.00001f));
ENSURE(fequal(b.x.y, 2.2f, 0.00001f));
ENSURE(fequal(b.x.z, 3.2f, 0.00001f));
ENSURE(fequal(b.x.w, -6.8f, 0.00001f));
ENSURE(fequal(b.y.x, -2.3f, 0.00001f));
ENSURE(fequal(b.y.y, -5.1f, 0.00001f));
ENSURE(fequal(b.y.z, 3.3f, 0.00001f));
ENSURE(fequal(b.y.w, -2.9f, 0.00001f));
ENSURE(fequal(b.z.x, 5.1f, 0.00001f));
ENSURE(fequal(b.z.y, 1.1f, 0.00001f));
ENSURE(fequal(b.z.z, -3.8f, 0.00001f));
ENSURE(fequal(b.z.w, 1.0f, 0.00001f));
ENSURE(fequal(b.t.x, -1.2f, 0.00001f));
ENSURE(fequal(b.t.y, -7.4f, 0.00001f));
ENSURE(fequal(b.t.z, -9.2f, 0.00001f));
ENSURE(fequal(b.t.w, 4.9f, 0.00001f));
}
}
static void test_aabb()
{
{
AABB a;
aabb::reset(a);
ENSURE(a.min == VECTOR3_ZERO);
ENSURE(a.max == VECTOR3_ZERO);
}
{
AABB a;
a.min = vector3(-2.3f, 1.2f, -4.5f);
a.max = vector3( 3.7f, 5.3f, -2.9f);
const Vector3 c = aabb::center(a);
ENSURE(fequal(c.x, 0.70f, 0.00001f));
ENSURE(fequal(c.y, 3.25f, 0.00001f));
ENSURE(fequal(c.z, -3.70f, 0.00001f));
}
{
AABB a;
a.min = vector3(-2.3f, 1.2f, -4.5f);
a.max = vector3( 3.7f, 5.3f, -2.9f);
const float c = aabb::volume(a);
ENSURE(fequal(c, 39.36f, 0.00001f));
}
{
const Vector3 points[] =
{
{ -1.2f, 3.4f, 5.5f },
{ 8.2f, -2.4f, -1.5f },
{ -5.9f, 9.2f, 6.0f }
};
AABB a;
aabb::from_points(a, countof(points), points);
ENSURE(fequal(a.min.x, -5.9f, 0.00001f));
ENSURE(fequal(a.min.y, -2.4f, 0.00001f));
ENSURE(fequal(a.min.z, -1.5f, 0.00001f));
ENSURE(fequal(a.max.x, 8.2f, 0.00001f));
ENSURE(fequal(a.max.y, 9.2f, 0.00001f));
ENSURE(fequal(a.max.z, 6.0f, 0.00001f));
}
{
const Vector3 points[] =
{
{ -1.2f, 3.4f, 5.5f },
{ 8.2f, -2.4f, -1.5f },
{ -5.9f, 9.2f, 6.0f },
{ -2.8f, -3.5f, 1.9f },
{ -8.3f, -3.1f, 1.9f },
{ 4.0f, -3.9f, -1.4f },
{ -0.4f, -1.8f, -2.2f },
{ -8.6f, -4.8f, 2.8f },
{ 4.1f, 4.7f, -0.4f }
};
AABB boxes[3];
aabb::from_points(boxes[0], countof(points)/3, &points[0]);
aabb::from_points(boxes[1], countof(points)/3, &points[3]);
aabb::from_points(boxes[2], countof(points)/3, &points[6]);
AABB d;
aabb::from_boxes(d, countof(boxes), boxes);
ENSURE(fequal(d.min.x, -8.6f, 0.00001f));
ENSURE(fequal(d.min.y, -4.8f, 0.00001f));
ENSURE(fequal(d.min.z, -2.2f, 0.00001f));
ENSURE(fequal(d.max.x, 8.2f, 0.00001f));
ENSURE(fequal(d.max.y, 9.2f, 0.00001f));
ENSURE(fequal(d.max.z, 6.0f, 0.00001f));
}
{
AABB a;
a.min = vector3(-2.3f, 1.2f, -4.5f);
a.max = vector3( 3.7f, 5.3f, -2.9f);
ENSURE( aabb::contains_point(a, vector3(1.2f, 3.0f, -4.4f)));
ENSURE(!aabb::contains_point(a, vector3(3.8f, 3.0f, -4.4f)));
ENSURE(!aabb::contains_point(a, vector3(1.2f, -1.0f, -4.4f)));
ENSURE(!aabb::contains_point(a, vector3(1.2f, 3.0f, -4.6f)));
}
}
static void test_sphere()
{
{
Sphere a;
sphere::reset(a);
ENSURE(a.c == VECTOR3_ZERO);
ENSURE(fequal(a.r, 0.0f, 0.00001f));
}
{
Sphere a;
a.c = VECTOR3_ZERO;
a.r = 1.61f;
const float b = sphere::volume(a);
ENSURE(fequal(b, 17.48099f, 0.00001f));
}
{
Sphere a;
sphere::reset(a);
const Vector3 points[] =
{
{ -1.2f, 3.4f, 5.5f },
{ 8.2f, -2.4f, -1.5f },
{ -5.9f, 9.2f, 6.0f }
};
sphere::add_points(a, countof(points), points);
ENSURE(fequal(a.c.x, 0.0f, 0.00001f));
ENSURE(fequal(a.c.y, 0.0f, 0.00001f));
ENSURE(fequal(a.c.z, 0.0f, 0.00001f));
ENSURE(fequal(a.r, 12.46795f, 0.00001f));
}
{
Sphere spheres[3];
sphere::reset(spheres[0]);
sphere::reset(spheres[1]);
sphere::reset(spheres[2]);
const Vector3 points[] =
{
{ 6.6f, 3.5f, -5.7f },
{ -5.3f, -9.1f, -7.9f },
{ -1.5f, 4.4f, -5.8f },
{ 7.2f, -2.4f, -9.5f },
{ 4.0f, -8.1f, 6.6f },
{ -8.2f, 2.2f, 4.6f },
{ 2.9f, -4.8f, -6.8f },
{ -7.6f, -7.0f, 0.8f },
{ 8.2f, 2.8f, -4.8f }
};
sphere::add_points(spheres[0], countof(points)/3, &points[0]);
sphere::add_points(spheres[1], countof(points)/3, &points[3]);
sphere::add_points(spheres[2], countof(points)/3, &points[6]);
Sphere d;
sphere::reset(d);
sphere::add_spheres(d, countof(spheres), spheres);
ENSURE(fequal(d.r, 13.16472f, 0.00001f));
}
{
Sphere a;
a.c = vector3(-2.3f, 1.2f, -4.5f);
a.r = 1.0f;
ENSURE( sphere::contains_point(a, vector3(-2.9f, 1.6f, -4.0f)));
ENSURE(!sphere::contains_point(a, vector3(-3.9f, 1.6f, -4.0f)));
ENSURE(!sphere::contains_point(a, vector3(-2.9f, 2.6f, -4.0f)));
ENSURE(!sphere::contains_point(a, vector3(-2.9f, 1.6f, -6.0f)));
}
}
static void test_murmur()
{
const u32 m = murmur32("murmur32", 8, 0);
ENSURE(m == 0x7c2365dbu);
const u64 n = murmur64("murmur64", 8, 0);
ENSURE(n == 0x90631502d1a3432bu);
}
static void test_string_id()
{
memory_globals::init();
{
StringId32 a("murmur32");
ENSURE(a._id == 0x7c2365dbu);
StringId32 b("murmur32", 8);
ENSURE(a._id == 0x7c2365dbu);
TempAllocator64 ta;
DynamicString str(ta);
a.to_string(str);
ENSURE(strcmp(str.c_str(), "7c2365db") == 0);
}
{
StringId64 a("murmur64");
ENSURE(a._id == 0x90631502d1a3432bu);
StringId64 b("murmur64", 8);
ENSURE(a._id == 0x90631502d1a3432bu);
TempAllocator64 ta;
DynamicString str(ta);
a.to_string(str);
ENSURE(strcmp(str.c_str(), "90631502d1a3432b") == 0);
}
memory_globals::shutdown();
}
static void test_dynamic_string()
{
memory_globals::init();
{
TempAllocator1024 ta;
DynamicString str(ta);
ENSURE(str.empty());
str.set("murmur32", 8);
ENSURE(str.length() == 8);
const StringId32 id = str.to_string_id();
ENSURE(id._id == 0x7c2365dbu);
}
{
TempAllocator1024 ta;
DynamicString str(ta);
str += "Test ";
str += "string.";
ENSURE(strcmp(str.c_str(), "Test string.") == 0);
}
{
TempAllocator1024 ta;
DynamicString str(ta);
str.set(" \tSushi\t ", 13);
str.ltrim();
ENSURE(strcmp(str.c_str(), "Sushi\t ") == 0);
}
{
TempAllocator1024 ta;
DynamicString str(ta);
str.set(" \tSushi\t ", 13);
str.rtrim();
ENSURE(strcmp(str.c_str(), " \tSushi") == 0);
}
{
TempAllocator1024 ta;
DynamicString str(ta);
str.set(" \tSushi\t ", 13);
str.trim();
ENSURE(strcmp(str.c_str(), "Sushi") == 0);
}
{
TempAllocator1024 ta;
DynamicString str(ta);
str.set("Hello everyone!", 15);
ENSURE(str.has_prefix("Hello"));
ENSURE(!str.has_prefix("hello"));
ENSURE(str.has_suffix("one!"));
ENSURE(!str.has_suffix("one"));
ENSURE(!str.has_prefix("Hello everyone!!!"));
ENSURE(!str.has_suffix("Hello everyone!!!"));
}
memory_globals::shutdown();
}
static void test_guid()
{
memory_globals::init();
{
Guid guid = guid::new_guid();
TempAllocator1024 ta;
DynamicString str(ta);
guid::to_string(guid, str);
Guid parsed = guid::parse(str.c_str());
ENSURE(guid == parsed);
}
{
Guid guid;
ENSURE(guid::try_parse(guid, "961f8005-6a7e-4371-9272-8454dd786884"));
ENSURE(!guid::try_parse(guid, "961f80056a7e-4371-9272-8454dd786884"));
}
memory_globals::shutdown();
}
static void test_json()
{
memory_globals::init();
{
JsonValueType::Enum t = json::type("null");
ENSURE(t == JsonValueType::NIL);
}
{
JsonValueType::Enum t = json::type("true");
ENSURE(t == JsonValueType::BOOL);
}
{
JsonValueType::Enum t = json::type("false");
ENSURE(t == JsonValueType::BOOL);
}
{
JsonValueType::Enum t = json::type("3.14");
ENSURE(t == JsonValueType::NUMBER);
}
{
JsonValueType::Enum t = json::type("\"foo\"");
ENSURE(t == JsonValueType::STRING);
}
{
JsonValueType::Enum t = json::type("[]");
ENSURE(t == JsonValueType::ARRAY);
}
{
JsonValueType::Enum t = json::type("{}");
ENSURE(t == JsonValueType::OBJECT);
}
{
const s32 a = json::parse_int("3.14");
ENSURE(a == 3);
}
{
const f32 a = json::parse_float("3.14");
ENSURE(fequal(a, 3.14f));
}
{
const bool a = json::parse_bool("true");
ENSURE(a == true);
}
{
const bool a = json::parse_bool("false");
ENSURE(a == false);
}
{
TempAllocator1024 ta;
DynamicString str(ta);
json::parse_string("\"This is JSON\"", str);
ENSURE(strcmp(str.c_str(), "This is JSON") == 0);
}
memory_globals::shutdown();
}
static void test_sjson()
{
memory_globals::init();
{
JsonValueType::Enum t = sjson::type("null");
ENSURE(t == JsonValueType::NIL);
}
{
JsonValueType::Enum t = sjson::type("true");
ENSURE(t == JsonValueType::BOOL);
}
{
JsonValueType::Enum t = sjson::type("false");
ENSURE(t == JsonValueType::BOOL);
}
{
JsonValueType::Enum t = sjson::type("3.14");
ENSURE(t == JsonValueType::NUMBER);
}
{
JsonValueType::Enum t = sjson::type("\"foo\"");
ENSURE(t == JsonValueType::STRING);
}
{
JsonValueType::Enum t = sjson::type("[]");
ENSURE(t == JsonValueType::ARRAY);
}
{
JsonValueType::Enum t = sjson::type("{}");
ENSURE(t == JsonValueType::OBJECT);
}
{
const s32 a = sjson::parse_int("3.14");
ENSURE(a == 3);
}
{
const f32 a = sjson::parse_float("3.14");
ENSURE(fequal(a, 3.14f));
}
{
const bool a = sjson::parse_bool("true");
ENSURE(a == true);
}
{
const bool a = sjson::parse_bool("false");
ENSURE(a == false);
}
{
TempAllocator1024 ta;
DynamicString str(ta);
sjson::parse_string("\"This is JSON\"", str);
ENSURE(strcmp(str.c_str(), "This is JSON") == 0);
}
{
const Vector2 a = sjson::parse_vector2("[ 1.2 -2.5 ]");
ENSURE(fequal(a.x, 1.2f));
ENSURE(fequal(a.y, -2.5f));
}
{
const Vector3 a = sjson::parse_vector3("[ 3.1 0.5 -5.7]");
ENSURE(fequal(a.x, 3.1f));
ENSURE(fequal(a.y, 0.5f));
ENSURE(fequal(a.z, -5.7f));
}
{
const Vector4 a = sjson::parse_vector4("[ 6.7 -1.3 2.9 -0.4 ]");
ENSURE(fequal(a.x, 6.7f));
ENSURE(fequal(a.y, -1.3f));
ENSURE(fequal(a.z, 2.9f));
ENSURE(fequal(a.w, -0.4f));
}
{
const Quaternion a = sjson::parse_quaternion("[ -1.5 -3.4 9.1 -3.5 ]");
ENSURE(fequal(a.x, -1.5f));
ENSURE(fequal(a.y, -3.4f));
ENSURE(fequal(a.z, 9.1f));
ENSURE(fequal(a.w, -3.5f));
}
{
const Matrix4x4 a = sjson::parse_matrix4x4(
"["
"-3.2 5.3 -0.7 4.1 "
" 5.6 7.0 -3.2 -1.2 "
"-6.3 9.0 3.9 1.1 "
" 0.4 -7.3 8.9 -0.1 "
"]"
);
ENSURE(fequal(a.x.x, -3.2f));
ENSURE(fequal(a.x.y, 5.3f));
ENSURE(fequal(a.x.z, -0.7f));
ENSURE(fequal(a.x.w, 4.1f));
ENSURE(fequal(a.y.x, 5.6f));
ENSURE(fequal(a.y.y, 7.0f));
ENSURE(fequal(a.y.z, -3.2f));
ENSURE(fequal(a.y.w, -1.2f));
ENSURE(fequal(a.z.x, -6.3f));
ENSURE(fequal(a.z.y, 9.0f));
ENSURE(fequal(a.z.z, 3.9f));
ENSURE(fequal(a.z.w, 1.1f));
ENSURE(fequal(a.t.x, 0.4f));
ENSURE(fequal(a.t.y, -7.3f));
ENSURE(fequal(a.t.z, 8.9f));
ENSURE(fequal(a.t.w, -0.1f));
}
{
const StringId32 a = sjson::parse_string_id("\"murmur32\"");
ENSURE(a._id == 0x7c2365dbu);
}
{
const ResourceId a = sjson::parse_resource_id("\"murmur64\"");
ENSURE(a._id == 0x90631502d1a3432bu);
}
{
const Guid guid = guid::parse("0f6c3b1c-9cba-4282-9096-2a77ca047b1b");
const Guid parsed = sjson::parse_guid("\"0f6c3b1c-9cba-4282-9096-2a77ca047b1b\"");
ENSURE(guid == parsed);
}
{
TempAllocator128 ta;
DynamicString str(ta);
sjson::parse_verbatim("\"\"\"verbatim\"\"\"", str);
ENSURE(strcmp(str.c_str(), "verbatim") == 0);
}
memory_globals::shutdown();
}
static void test_path()
{
#if CROWN_PLATFORM_POSIX
{
const bool a = path::is_absolute("/home/foo");
ENSURE(a == true);
const bool b = path::is_absolute("home/foo");
ENSURE(b == false);
}
{
const bool a = path::is_relative("/home/foo");
ENSURE(a == false);
const bool b = path::is_relative("home/foo");
ENSURE(b == true);
}
{
const bool a = path::is_root("/");
ENSURE(a == true);
const bool b = path::is_root("/home");
ENSURE(b == false);
}
{
TempAllocator128 ta;
DynamicString path(ta);
path::join(path, "/home", "foo");
ENSURE(path == "/home/foo");
path::join(path, "/home", "bar");
ENSURE(path == "/home/bar");
}
{
ENSURE(path::has_trailing_separator("/home/foo/"));
ENSURE(!path::has_trailing_separator("/home/foo"));
}
{
TempAllocator128 ta;
DynamicString clean(ta);
path::reduce(clean, "/home//foo/");
ENSURE(clean == "/home/foo");
}
{
TempAllocator128 ta;
DynamicString clean(ta);
path::reduce(clean, "\\home\\\\foo\\");
ENSURE(clean == "/home/foo");
}
#else
{
const bool a = path::is_absolute("C:\\Users\\foo");
ENSURE(a == true);
const bool b = path::is_absolute("Users\\foo");
ENSURE(b == false);
}
{
const bool a = path::is_relative("D:\\Users\\foo");
ENSURE(a == false);
const bool b = path::is_relative("Users\\foo");
ENSURE(b == true);
}
{
const bool a = path::is_root("E:\\");
ENSURE(a == true);
const bool b = path::is_root("E:\\Users");
ENSURE(b == false);
}
{
TempAllocator128 ta;
DynamicString path(ta);
path::join(path, "C:\\Users", "foo");
ENSURE(path == "C:\\Users\\foo");
path::join(path, "C:\\Users", "bar");
ENSURE(path == "C:\\Users\\bar");
}
{
ENSURE(path::has_trailing_separator("C:\\Users\\foo\\"));
ENSURE(!path::has_trailing_separator("C:\\Users\\foo"));
}
{
TempAllocator128 ta;
DynamicString clean(ta);
path::reduce(clean, "C:\\Users\\\\foo\\");
ENSURE(clean == "C:\\Users\\foo");
}
{
TempAllocator128 ta;
DynamicString clean(ta);
path::reduce(clean, "C:/Users//foo/");
ENSURE(clean == "C:\\Users\\foo");
}
#endif // CROWN_PLATFORM_POSIX
{
const char* p = path::basename("");
ENSURE(strcmp(p, "") == 0);
const char* q = path::basename("/");
ENSURE(strcmp(q, "") == 0);
const char* r = path::basename("boot.config");
ENSURE(strcmp(r, "boot.config") == 0);
const char* s = path::basename("foo/boot.config");
ENSURE(strcmp(s, "boot.config") == 0);
const char* t = path::basename("/foo/boot.config");
ENSURE(strcmp(t, "boot.config") == 0);
}
{
const char* p = path::extension("");
ENSURE(p == NULL);
const char* q = path::extension("boot");
ENSURE(q == NULL);
const char* r = path::extension("boot.bar.config");
ENSURE(strcmp(r, "config") == 0);
}
}
static void test_command_line()
{
const char* argv[] =
{
"args",
"-s",
"--switch",
"--argument",
"orange"
};
CommandLine cl(countof(argv), argv);
ENSURE(cl.has_option("switch", 's'));
const char* orange = cl.get_parameter(0, "argument");
ENSURE(orange != NULL && strcmp(orange, "orange") == 0);
}
static void test_thread()
{
Thread thread;
ENSURE(!thread.is_running());
thread.start([](void*) { return 0; }, NULL);
thread.stop();
ENSURE(thread.exit_code() == 0);
thread.start([](void*) { return -1; }, NULL);
thread.stop();
ENSURE(thread.exit_code() == -1);
}
int main_unit_tests()
{
test_memory();
test_array();
test_vector();
test_hash_map();
test_hash_set();
test_vector2();
test_vector3();
test_vector4();
test_quaternion();
test_color4();
test_matrix3x3();
test_matrix4x4();
test_aabb();
test_sphere();
test_murmur();
test_string_id();
test_dynamic_string();
test_guid();
test_json();
test_sjson();
test_path();
test_command_line();
test_thread();
return EXIT_SUCCESS;
}
} // namespace crown
#endif // CROWN_BUILD_UNIT_TESTS
|
require 'brew_sparkling/logger'
require 'brew_sparkling/gateway/xcode'
require 'digest/sha1'
module BrewSparkling
class User
class <<self
def default
@user ||= new
end
end
def account
@account ||= find_or_first(accounts) { |account|
account.username == env(:username)
}.tap { |account|
logger.info "Account: #{account.username} (#{env_name(:username)}"
}
end
def certificate
@certificate ||= find_or_first(certificates) { |certificate|
certificate.commonName == env(:certificate)
}.tap { |certificate|
logger.info "Certificate: #{certificate.commonName} (#{env_name(:certificates)})"
}
end
def device
@device ||= find_or_first(devices) { |device|
device.name == env(:device)
}.tap { |device|
if device
logger.info "Device: #{device.name} (#{env_name(:device)})"
else
error 'cannot find iOS device. Please connect your device.'
end
}
end
def gateway
@gateway ||= Gateway::Xcode.default.tap do |gateway|
if gateway
logger.info "Xcode gateway: #{gateway.url}"
else
error 'cannot discover Xcode. Please invoke Xcode.'
end
end
end
def prefix
Digest::SHA1.hexdigest account.username
end
private
def error(message)
logger.error message
exit 1
end
def accounts
@accounts ||= gateway.accounts
end
def certificates
@certificates ||= gateway.certificates
end
def devices
@devices ||= gateway.devices
end
def env_name(name)
"BREW_SPARKLING_#{name.to_s.upcase}"
end
def env(name)
ENV[env_name(name)]
end
def find_or_first(xs, &f)
first = proc { xs.first }
xs.find(first, &f)
end
def logger
@logger ||= Logger.default
end
end
end
|
---
title: S002《I tell you》Windows系统各版本纯净镜像
---
## 直达链接: [https://msdn.itellyou.cn/](https://msdn.itellyou.cn/)

I tell you 提供从Windows98 之后时间段的所有镜像,如果你需要重装系统,或者安装虚拟机,可以从这里下载到纯净的ISO Windows镜像, 镜像提供了p2p下载链接,下载速度非常快,而且提供了sha1码以供校验,避免镜像被窜改,p2p下载软件推荐免费的utorrent |
class Regex {
// https://stackoverflow.com/a/32686261/9449426
Regex._();
static RegExp regExp = RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$');
static set regexp(RegExp value) {
regExp = value;
}
static RegExp get regexp => regExp;
}
|
package cz.prague.cvut.fit.steuejan.amtelapp.fragments.abstracts
import androidx.fragment.app.activityViewModels
import cz.prague.cvut.fit.steuejan.amtelapp.view_models.activities.MatchViewPagerActivityVM
abstract class AbstractMatchActivityFragment : AbstractBaseFragment()
{
protected val matchViewModel by activityViewModels<MatchViewPagerActivityVM>()
} |
# vkphpbot
Бот для ВКонтакте написанный на PHP, использует Callback API. Пример: https://vk.com/iusephpbtw
#### ОСТОРОЖНО! ГОВНОКОД !!!!
# Настройка
Создайте файл config.php и впишите туда:
``` php
<?php
$confirmation_token = "токен для подтверждения сервера";
$token="токен группы";
$dbhost="localhost или что нибудь еще";
$dbuser="пользователь бд";
$dbpassword="пароль пользователя бд";
$dbname="имя бд";
$admins=array("overpie", "собственно админы для доступа к консоли");
?>
```
Затем, запустите скрипт prepare\_db.php для инициализации MySQL
Также, нужно установить библиотеки PHP:
```
php-pdo-mysql
php-gd
php-json
php-curl
```
|
# gg18-etude
# GG18
R. Gennaro and S. Goldfeder. Fast Multiparty Threshold ECDSA with Fast Trustless Setup. In ACM CCS 2018.
4.1 Key generation protocol
Phase 1. Each Player Pi selects ui. Pi send g^ui to Pj(i!=j) by using commitment schema.
Phase 2. All Players perform Join-Feldman VSS together.
Phase 3. ZK-prove.
At the end of the KeyGen,
* Each player `Pi` secretly hold:
- Localy generated secret value `ui`
- `Pj`'s Feldman share value `sij`, and those summary `si = Σ j(sij)`
- Joint Feldman Shamir's secret share value `xi = si`
* All player knows:
- `g^ui`
- Joint Feldman Shamir's public key `y = g^x = g^Σ ui = Π g^ui`
* No any player knows:
- Joint Feldman Shamir's secret key `x = Σ ui`
4.2 Signature Generation
Phase 0. Convert (t,n) share xi to (t',t') share of wi
Phase 1. Each player `Pi` selects `ki`,`γ i`
Define `k = Σ ki, γ =Σ γ i`
Each player broadcast g^γ i by using commitment scheme.
Phase 2.
2-a. Every pair of Pi and Pj performs MtA against `ki` and `γ j` then get `α i` and `β j`.
Note that `ki * γ j = α ij + β ij`.
Each player `Pi` compute `δ i = ki * γ i + Σ j!=i(α ij + β ji).
Note that `k*γ = Σ δ i`
2-b. MtA agains `ki` and `wi` then get `μ ij` and `ν ij`
As is 2-a, Pi compute `σ i = ki*wi + Σ j!=i(μ ij + ν ji)`, note `k*x = Σ σ i`
Phase 3. Each player `Pi` broadcasts `δ i` and all players are compute δ = Σ δ i = k*γ
Phase 4. Each player `Pi` opens `g^γ i` and compute `R = (Π g^γ i)^(1/δ ) = g^(1/k)` and `r = H(R)`
Phase 5. Each player `Pi` compute `si = m*ki + r*σ i`
Note that `Σ si = mΣ ki + rΣ σ = mk + rkx = k(m+xr) = s`
Verify:
1. Each Player broadcast `g^wi` and calc `y = Π g^wi = g^(Σ wi) = g^x`
2. Test `g^(m/s) + y * (r/s) = R`
Note that `g^(m/s) + y ^ (r/s) = g^(m/s) + g^(x * (r/s)) = g^((m+rx)/s) = g^(1/k) = R`
# software design of this etude
To the protocol be simple, I start followint conditions:
a. Skip DKG. Each Player generate ui and treat the sum is secret.
b. threshold `t = n-1`, so `wi == ui`.
|
// -----------------------------------------------------------------------
// <copyright file="Extensions.cs" company="Asynkron AB">
// Copyright (C) 2015-2021 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using Google.Protobuf;
using Proto.Remote;
namespace Proto.Cluster
{
public record GrainRequestMessage(int MethodIndex, IMessage? RequestMessage) : IRootSerializable
{
//serialize into the on-the-wire format
public IRootSerialized Serialize(ActorSystem system)
{
if (RequestMessage is null) return new GrainRequest {MethodIndex = MethodIndex};
var ser = system.Serialization();
var (data, typeName, serializerId) = ser.Serialize(RequestMessage);
#if DEBUG
if (serializerId != Serialization.SERIALIZER_ID_PROTOBUF)
throw new Exception($"Grains must use ProtoBuf types: {RequestMessage.GetType().FullName}");
#endif
return new GrainRequest
{
MethodIndex = MethodIndex,
MessageData = data,
MessageTypeName = typeName,
};
}
}
} |
const ST = ScientificTypes
ST.scitype(::PersistenceDiagram, ::ST.DefaultConvention; kwargs...) = PersistenceDiagram
|
# LINQ - Ordering Operators
The `orderby` clause of a LINQ query sorts the output sequence. You can control the properties used for sorting, and specify ascending or descending order.
## orderby sorts elements
This sample uses `orderby` to sort a list of words alphabetically.
``` cs --region orderby-syntax --source-file ../src/Orderings.cs --project ../src/Try101LinqSamples.csproj
```
## Orderby using a property
This sample uses orderby to sort a list of words by length.
``` cs --region orderby-property --source-file ../src/Orderings.cs --project ../src/Try101LinqSamples.csproj
```
## Ordering user defined types
This sample uses orderby to sort a list of products by name.
``` cs --region orderby-user-types --source-file ../src/Orderings.cs --project ../src/Try101LinqSamples.csproj
```
**Next: [Orderby descending »](./orderings-2.md) Previous: [Partitions with conditions «](./partitions-2.md)**
**[Home](../README.md)**
|
<?php
namespace App\Http\Controllers;
use App\Workshop;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class PanelWorkshopsController extends Controller
{
public function index()
{
return view('panel.talleres.index', [
'talleres' => workshop::paginate()
]);
}
public function create()
{
return view('panel.talleres.create');
}
public function store()
{
$fields = request()->validate([
'nombre' => 'required',
'dirigido_a' => 'required',
'descripcion' => 'required',
'img' => 'required',
'img_single' => 'required'
], [
'img.required' => 'Debes seleccionar un archivo de imagen.',
'img_single.required' => 'Debes seleccionar un archivo de imagen.'
]);
$file_thumb = request()->file('img');
$file_single = request()->file('img_single');
$fecha = date('ymdhis');
$nombre_1 = $file_thumb->getClientOriginalName();
$nombre_2 = $file_single->getClientOriginalName();
$nombre_thumb = $fecha.'-'.$nombre_1;
$nombre_single = $fecha.'-'.$nombre_2;
Storage::disk('local')->put('public/talleres/'.$nombre_thumb, File::get($file_thumb));
Storage::disk('local')->put('public/talleres/'.$nombre_single, File::get($file_single));
Workshop::create([
'nombre' => request('nombre'),
'descripcion' => request('descripcion'),
'dirigido_a' => request('dirigido_a'),
'tipo' => request('tipo'),
'img' => $nombre_thumb,
'img_single' => $nombre_single
]);
return redirect()
->route('panel.workshops.index')
->with('success', 'Creado correctamente');
}
public function show(Workshop $id)
{
return view('panel.talleres.show', [
'taller' => $id
]);
}
public function edit(Workshop $id)
{
return view('panel.talleres.edit', [
'taller' => $id
]);
}
public function update(Workshop $id)
{
$fields = request()->validate([
'nombre' => 'required',
'descripcion' => 'required',
'dirigido_a' => 'required',
'tipo' => 'required'
]);
$id->update([
'nombre' => request('nombre'),
'descripcion' => request('descripcion'),
'dirigido_a' => request('dirigido_a'),
'tipo' => request('tipo')
]);
return redirect()
->route('panel.workshops.index')
->with('success', 'Actualizado correctamente');
}
public function destroy(Workshop $id)
{
Storage::delete('public/talleres/' . $id->img);
Storage::delete('public/talleres/' . $id->img_single);
$id->delete();
return redirect()
->route('panel.workshops.index')
->with('success', 'Eliminado correctamente');
}
}
|
import Base from './base';
import Content from './content';
import Wrapper from './wrapper';
export {
Base,
Content,
Wrapper,
} |
package de.javaclub.playground.hexagonal.domain
data class DeletionStatistic(
val successful: List<DeletionProof>,
val failure: List<DeletionProof>,
val repaired: List<DeletionProof>) |
# frozen_string_literal: true
##
# This module is the overall representation of our InspecDelta implementation
module InspecDelta
##
# This is the version constant for the inspec_delta gem
VERSION = '0.1.1'
end
|
@{
Layout = "~/Views/Shared/_ContentPage.cshtml";
Response.StatusCode = 404;
}
@section leftnav{
<li class="active"><a href="javascript:void(0)">Not found Error</a></li>
}
<h1>
Page not found (404)
</h1>
<p>
The page may have been moved or is no longer available.
</p>
<p>
<a href="/">WorldWide Telescope Home page</a>
</p> |
"""
---
Structure for OFDM
# --- Syntax
- nFFT : FFT size [Int]
- nCP : Cyclic prefix size [Int]
- allocatedSubcarriers : Vector of allocated subbcarriers [Array{Int}]
# ---
# v 1.0 - Robin Gerzaguet.
"""
struct StrucOFDM <: Waveform
nFFT::Int;
nCP::Int;
allocatedSubcarriers::Array{Int};
end
"""
---
Create OFDM structure
# --- Syntax
ofdm = initOFDM(nFFT,nCP,allocatedSubcarriers)
# --- Input parameters
- nFFT : FFT size [Int]
- nCP : Cyclic prefix size [Int]
- allocatedSubcarrier : Vector of allocated subbcarriers [Array{Int}]
# --- Output parameters
- ofdm : OFDM structure [StrucOFDM]
# ---
# v 1.0 - Robin Gerzaguet.
"""
function initOFDM(nFFT,nCP,allocatedSubcarriers)
# ---Checking FFT size
if maximum(allocatedSubcarriers) > nFFT || length(allocatedSubcarriers) > nFFT
error("Subcarrier allocation is impossible");
end
# --- Create the OFDM structure
return StrucOFDM(nFFT,nCP,allocatedSubcarriers)
end
"""
---
Create OFDM signal in time domain based on input T/F matrix and OFDM parameters
qamMat is a complex symbol matrix (for instance QPSK) of size length(allocatedSubcarriers) x nbSymb
The output signal in time domain is of size (nFFT+nCP)xnbSymb.
# --- Syntax
sigId = ofdmSigGen(qamMat,nFFT,nCP,allocatedSubcarriers)
# --- Input parameters
- qamMat : Complex T/F matrix to map [Array{Float64},length(allocatedSubcarriers),nbSymb]
- nFFT : FFT size [Int]
- nCP : Cylic prefix size [Int]
- allocatedSubcarrier : Vector of allocated subbcarriers [Array{Int}]
# --- Output parameters
- sigId : Signal in time domain [Array{Complex{Float64}},(nFFT+nCP)xnbSymb]
# ---
# v 1.0 - Robin Gerzaguet.
"""
function ofdmSigGen(qamMat,nFFT,nCP,allocatedSubcarriers)
nbSymb = size(qamMat,2);
sigId = zeros(Complex{Float64},(nFFT+nCP)*nbSymb);
ofdmSigGen!(sigId,qamMat,nFFT,nCP,allocatedSubcarriers);
return sigId;
end
"""
---
Populate a OFDM signal in time domain based on input T/F matrix and OFDM parameters
qamMat is a complex symbol matrix (for instance QPSK) of size length(allocatedSubcarriers) x nbSymb
The output signal in time domain is of size (nFFT+nCP)xnbSymb.
# --- Syntax
ofdmSigGen!(sigId,qamMat,nFFT,nCP,allocatedSubcarriers)
# --- Input parameters
- sigId : Signal in time domain [Array{Complex{Float64}},(nFFT+nCP)xnbSymb]
- qamMat : Complex T/F matrix to map [Array{Float64},length(allocatedSubcarriers),nbSymb]
- nFFT : FFT size [Int]
- nCP : Cylic prefix size [Int]
- allocatedSubcarrier : Vector of allocated subbcarriers [Array{Int}]
# --- Output parameters
- []
# ---
# v 1.0 - Robin Gerzaguet.
"""
function ofdmSigGen!(sigId,qamMat,nFFT,nCP,allocatedSubcarriers)
# Set 4 core for FFT computation
#FFTW.set_num_threads(4)
# --- Getting parameters
nbSymb = size(qamMat,2); # --- Applied on x symbols
symbSize = nFFT + nCP; # --- Symbol size
nSize = symbSize*nbSymb; # --- Total burst length
# --- Mapping to nFFT elements
qamCurr = zeros(Complex{Float64},nFFT,nbSymb);
qamCurr[allocatedSubcarriers,:] .= qamMat;
# --- Switch to time domain
ifft!(qamCurr,1);
# --- Inserting Cyclic prefix
#sigId .= reshape([qamCurr[end+1-nCP:end,:] ; qamCurr], symbSize*nbSymb,1);
for iN = 1 : 1 : nbSymb
# --- Classic cyclic
sigId[ (iN-1)*symbSize + nCP .+ (1:nFFT)] .= qamCurr[:,iN];
# --- CP insertion
sigId[ (iN-1)*symbSize .+ (1:nCP)] .= qamCurr[end-nCP+1:end,iN];
end
end
# --- MD is waveform structure is given
"""
---
Create OFDM signal in time domain based on input T/F matrix and OFDM structure
qamMat is a complex symbol matrix (for instance QPSK) of size length(allocatedSubcarriers) x nbSymb
The output signal in time domain is of size (nFFT+nCP)xnbSymb.
# --- Syntax
sigId = ofdmSigGen(qamMat,nFFT,nCP,allocatedSubcarriers)
# --- Input parameters
- qamMat : Complex T/F matrix to map [Array{Float64},length(allocatedSubcarriers),nbSymb]
- ofdm : OFDM structure [StrucOFDM]
# --- Output parameters
- sigId : Signal in time domain [Array{Complex{Float64}},(nFFT+nCP)xnbSymb]
# ---
# v 1.0 - Robin Gerzaguet.
"""
function ofdmSigGen(qamMat,ofdm::StrucOFDM)
return ofdmSigGen(qamMat,ofdm.nFFT,ofdm.nCP,ofdm.allocatedSubcarriers);
end
# --- MD is waveform structure is given
"""
---
Populate a OFDM signal in time domain based on input T/F matrix and OFDM structure
qamMat is a complex symbol matrix (for instance QPSK) of size length(allocatedSubcarriers) x nbSymb
The output signal in time domain is of size (nFFT+nCP)xnbSymb.
# --- Syntax
ofdmSigGen!(sigId,qamMat,nFFT,nCP,allocatedSubcarriers)
# --- Input parameters
- sigId : Signal in time domain [Array{Complex{Float64}},(nFFT+nCP)xnbSymb]
- qamMat : Complex T/F matrix to map [Array{Float64},length(allocatedSubcarriers),nbSymb]
- ofdm : OFDM structure [StrucOFDM]
# --- Output parameters
- []
# ---
# v 1.0 - Robin Gerzaguet.
"""
function ofdmSigGen!(sigId,qamMat,ofdm::StrucOFDM)
return ofdmSigGen!(sigId,qamMat,ofdm.nFFT,ofdm.nCP,ofdm.allocatedSubcarriers);
end
|
@page
@model Senparc.Areas.Admin.Pages.IndexModel
@{
ViewData["Title"] = "管理员后台首页";
Layout = "_Layout_Vue";
}
@section style{
<style>
.xncf-stat-item {
position: relative;
display: block;
margin-bottom: 12px;
border: 1px solid #E4E4E4;
overflow: hidden;
padding-bottom: 5px;
border-radius: 5px;
background-clip: padding-box;
background: #FFF;
transition: all 300ms ease-in-out;
padding-left: 10px;
}
.xncf-stat-item .icon {
font-size: 60px;
color: #BAB8B8;
position: absolute;
right: 20px;
top: -5px;
}
.xncf-stat-item .count {
font-size: 38px;
font-weight: bold;
line-height: 1.65857;
}
.xncf-stat-item .tit {
color: #BAB8B8;
font-size: 24px;
}
.xncf-stat-item p {
margin-bottom: 5px;
}
.chart-title {
font-size: 20px;
}
.chart-li {
padding-top: 20px;
}
.chart-li li {
line-height: 2;
}
.chart-li .fa {
margin-right: 5px;
}
.box-card {
margin-top:20px
}
#xncf-modules-area{margin-bottom:50px;}
#xncf-modules-area .xncf-item{
}
#xncf-modules-area .xncf-item .version{ float:right;}
#xncf-modules-area .xncf-item .icon{ float:left;}
</style>
}
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
<!-- 统计数据 -->
<div>
<el-container>
<el-header class="module-header">
<span class="start-title"><span class="module-header-v">NeuCharFramework 管理员后台</span></span>
</el-header>
<el-main></el-main>
</el-container>
<el-row :gutter="20">
<el-col :span="6">
<a href="~/Admin/XncfModule/Index">
<div class="grid-content xncf-stat-item">
<span class="count">{{xncfStat.installedXncfCount || 0}}</span>
<div class="icon">
<i class="fa fa-caret-square-o-right"></i>
</div>
<p class="tit">已安装模块</p>
</div>
</a>
</el-col>
<el-col :span="6">
<a href="~/Admin/XncfModule/Index">
<div class="grid-content bg-purple xncf-stat-item">
<span class="count">{{xncfStat.updateVersionXncfCount || 0}}</span>
<div class="icon">
<i class="fa fa-comments-o"></i>
</div>
<p class="tit">待更新模块</p>
</div>
</a>
</el-col>
<el-col :span="6">
<a href="~/Admin/XncfModule/Index">
<div class="grid-content bg-purple xncf-stat-item">
<span class="count">{{xncfStat.newXncfCount || 0}}</span>
<div class="icon">
<i class="fa fa-sort-amount-desc"></i>
</div>
<p class="tit">发现新模块</p>
</div>
</a>
</el-col>
<el-col :span="6">
<a href="~/Admin/XncfModule/Index">
<div class="grid-content bg-purple xncf-stat-item">
<span class="count">{{xncfStat.missingXncfCount || 0}}</span>
<div class="icon">
<i class="fa fa-check-square-o"></i>
</div>
<p class="tit">模块异常</p>
</div>
</a>
</el-col>
</el-row>
<el-row :gutter="10">
<el-col :xs="20" :sm="20" :md="20" :lg="12" :xl="12">
<el-card class="box-card">
<div id="firstChart" style="height:350px;width: 100%">
</div>
</el-card>
</el-col>
<el-col :xs="20" :sm="20" :md="20" :lg="12" :xl="12">
<el-card class="box-card">
<div id="secondChart" style="height:350px;width: 100%">
</div>
</el-card>
</el-col>
</el-row>
</div>
<!-- 功能模块 -->
<div>
<el-row>
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>功能模块</span>
</div>
<div id="xncf-modules-area">
<el-row :gutter="20">
<el-col :span="6" class="xncf-item" v-for="item in xncfOpeningList" v-key="item.Id">
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>{{item.menuName}}</span> <small class="version">v{{item.version}}</small>
</div>
<a class="component-item" v-bind:href="'/Admin/XncfModule/Start/?uid='+item.uid">
<span class=""><i v-bind:class="[item.icon,'icon']"></i></span>
@*<a v-bind:href="'/Admin/XncfModule/Start/?uid='+item.uid">{{item.menuName}}</a>*@
</a>
</el-card>
</el-col>
</el-row>
</div>
</el-card>
</el-row>
</div>
@section scripts{
<script src="~/lib/echarts/dist/echarts.js"></script>
<script src="~/js/Admin/Pages/Index/Index.js"></script>
} |
using System;
using System.Linq;
using Microsoft.Azure.Cosmos;
using CosmosToolbox.Core.Attributes;
using CosmosToolbox.Core.Data;
using CosmosToolbox.Core.Extensions;
namespace CosmosToolbox.App.Extensions
{
public static class EntityExtensions
{
public static ContainerProperties GetContainerProperties(this Type type)
{
var attribute = type
.GetCustomAttributes(typeof(CosmosEntityAttribute), true)
.OfType<CosmosEntityAttribute>()
.Single();
var properties = new ContainerProperties(
attribute.ContainerId,
attribute.PartitionKeyPath);
return properties;
}
public static PartitionKey GetPartitionKey(this IEntity entity)
{
var value = entity.GetPartitionKeyValue();
var partitionKey = value != null ? new PartitionKey(value) : PartitionKey.Null;
return partitionKey;
}
public static string GetTableName(this Type type)
{
var attribute = type
.GetCustomAttributes(typeof(TableEntityAttribute), true)
.OfType<TableEntityAttribute>()
.Single();
return attribute.TableName;
}
}
} |
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
backgroundColor: Colors.white,
body: initBody()
);
}
Widget initBody() {
List<Color> colors = [
Colors.red,
Colors.green,
Colors.indigo,
Colors.pinkAccent,
Colors.blue,
];
return new Container(
padding: const EdgeInsets.all(0.0),
decoration: new BoxDecoration(
color: Colors.black,
),
child: new ListView(
padding: const EdgeInsets.all(5.0),
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new _UserAvatar(userAvatar: 'assets/image/Avatar.png',),
new _LoginGroupForm(),
new _LoginGithub(),
new _RegisterAccount(),
new _AssistantCopyRight(copyrightSize: 9,),
],
),
],
),
);
}
}
class _UserAvatar extends StatelessWidget {
final String userAvatar;
_UserAvatar({@required this.userAvatar,});
@override
Widget build(BuildContext context) {
return (new Padding(
padding: const EdgeInsets.only(top: 60.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Container(
child: new CircleAvatar(
backgroundImage: AssetImage(userAvatar),
backgroundColor: Colors.transparent,
radius: 40.0,
),
),
new SizedBox(
height: 10,
),
new Text(
"Sign in to GitHub",
style: new TextStyle(
fontFamily: "ADELE",
fontSize: 22.0,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
],
),
));
}
}
class _InputFieldArea extends StatelessWidget {
final String hint;
final bool obscure;
final IconData icon;
_InputFieldArea({this.hint, this.obscure, this.icon});
@override
Widget build(BuildContext context) {
return (new Container(
decoration: new BoxDecoration(
border: new Border(
bottom: new BorderSide(
width: 0.5,
color: Colors.white24,
),
),
),
child: new TextFormField(
obscureText: obscure,
style: const TextStyle(
fontFamily: 'ADELE',
fontWeight: FontWeight.w500,
color: Colors.white,
),
decoration: new InputDecoration(
icon: new Icon(
icon,
color: Colors.white,
),
border: InputBorder.none,
hintText: hint,
hintStyle: const TextStyle(color: Colors.white, fontSize: 14.0),
contentPadding: const EdgeInsets.only(
top: 40.0, right: 30.0, bottom: 30.0, left: 3.0),
),
),
));
}
}
class _LoginGroupForm extends StatelessWidget {
@override
Widget build(BuildContext context) {
return (new Container(
margin: new EdgeInsets.symmetric(horizontal: 20.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new Form(
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new _InputFieldArea(
hint: "Username or email address",
obscure: false,
icon: Icons.person_outline,
),
new _InputFieldArea(
hint: "Password",
obscure: true,
icon: Icons.lock_outline,
),
],
),
),
],
),
));
}
}
class _LoginGithub extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 20),
alignment: FractionalOffset.center,
child: SizedBox(
width: 320.0,
height: 60.0,
child: new RaisedButton(
//color: const Color.fromRGBO(247, 64, 106, 1.0),
color: Color.fromRGBO(81, 81, 81, 1.0),
child: new Text(
'Sign in',
style: new TextStyle(
color: Colors.white,
fontFamily: 'ADELE',
fontSize: 22.0,
fontWeight: FontWeight.w800,
letterSpacing: 0.9,
),
),
onPressed: (){
print("login is click.");
},
shape: StadiumBorder(),
elevation: 24,
splashColor: Colors.black,
),
),
);
}
}
class _RegisterAccount extends StatelessWidget {
@override
Widget build(BuildContext context) {
return (new Container(
child: new FlatButton(
padding: const EdgeInsets.only(top: 90),
onPressed: null,
child: new Column(
children: <Widget>[
new Text(
"Don't have an account?\nRegistered in Github",
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
softWrap: true,
style: new TextStyle(
fontWeight: FontWeight.w400,
fontFamily: 'ADELE',
letterSpacing: 0.5,
color: Colors.white,
fontSize: 13.0
),
),
],
)
),
));
}
}
class _AssistantCopyRight extends StatelessWidget{
final double copyrightSize;
_AssistantCopyRight({@required this.copyrightSize});
@override
Widget build(BuildContext context) {
// TODO: implement build
return (new Container(
alignment: Alignment.bottomCenter,
child: new FlatButton(
padding: const EdgeInsets.only(top: 35),
onPressed: null,
child: new Text(
"Power by UESTC-2017.1101.Mardan & \nCopyright © 2017 - 2021 Mardan. All Rights Reserved.",
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
softWrap: true,
style: new TextStyle(
fontWeight: FontWeight.w600,
letterSpacing: 0.3,
color: Colors.white,
fontSize: 9.0),
),
),
));
}
} |
using Content.Client.GameObjects.Components.Research;
using Content.Shared.Research;
using Robust.Client.Graphics;
using Robust.Client.Graphics.Drawing;
using Robust.Client.Interfaces.Graphics;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Client.Utility;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Maths;
using Robust.Shared.ViewVariables;
namespace Content.Client.Research
{
public class LatheQueueMenu : SS14Window
{
protected override Vector2? CustomSize => (300, 450);
public LatheBoundUserInterface Owner { get; set; }
[ViewVariables]
private ItemList QueueList;
private Label NameLabel;
private Label Description;
private TextureRect Icon;
protected override void Initialize()
{
base.Initialize();
HideOnClose = true;
Title = "Lathe Queue";
Visible = false;
var margin = new MarginContainer()
{
MarginTop = 5f,
MarginLeft = 5f,
MarginRight = -5f,
MarginBottom = -5f,
};
margin.SetAnchorAndMarginPreset(LayoutPreset.Wide);
var vbox = new VBoxContainer();
vbox.SetAnchorAndMarginPreset(LayoutPreset.Wide);
var descMargin = new MarginContainer()
{
MarginTop = 5f,
MarginLeft = 5f,
MarginRight = -5f,
MarginBottom = -5f,
SizeFlagsHorizontal = SizeFlags.FillExpand,
SizeFlagsStretchRatio = 2,
};
var hbox = new HBoxContainer()
{
SizeFlagsHorizontal = SizeFlags.FillExpand,
};
Icon = new TextureRect()
{
SizeFlagsHorizontal = SizeFlags.FillExpand,
SizeFlagsStretchRatio = 2,
};
var vboxInfo = new VBoxContainer()
{
SizeFlagsVertical = SizeFlags.FillExpand,
SizeFlagsStretchRatio = 3,
};
NameLabel = new Label()
{
RectClipContent = true,
SizeFlagsHorizontal = SizeFlags.Fill,
};
Description = new Label()
{
RectClipContent = true,
SizeFlagsVertical = SizeFlags.FillExpand,
SizeFlagsHorizontal = SizeFlags.Fill,
};
QueueList = new ItemList()
{
SizeFlagsHorizontal = SizeFlags.Fill,
SizeFlagsVertical = SizeFlags.FillExpand,
SizeFlagsStretchRatio = 3,
SelectMode = ItemList.ItemListSelectMode.None
};
vboxInfo.AddChild(NameLabel);
vboxInfo.AddChild(Description);
hbox.AddChild(Icon);
hbox.AddChild(vboxInfo);
descMargin.AddChild(hbox);
vbox.AddChild(descMargin);
vbox.AddChild(QueueList);
margin.AddChild(vbox);
Contents.AddChild(margin);
ClearInfo();
}
public void SetInfo(LatheRecipePrototype recipe)
{
Icon.Texture = recipe.Icon.Frame0();
if (recipe.Name != null)
NameLabel.Text = recipe.Name;
if (recipe.Description != null)
Description.Text = recipe.Description;
}
public void ClearInfo()
{
Icon.Texture = Texture.Transparent;
NameLabel.Text = "-------";
Description.Text = "Not producing anything.";
}
public void PopulateList()
{
QueueList.Clear();
var idx = 1;
foreach (var recipe in Owner.QueuedRecipes)
{
QueueList.AddItem($"{idx}. {recipe.Name}", recipe.Icon.Frame0(), false);
idx++;
}
}
}
}
|
require 'test_helper'
class AssignmentTest < ActiveSupport::TestCase
setup do
@user = Factory(:user, :username => 'bob', :password => 'secret')
@course = Factory(:course)
@repository = Factory(:repository, :user => @user)
end
teardown :clean_local_fs!
test "should create assignment with attached course and repository" do
assignment = Factory(:assignment, :course => @course, :repository => @repository)
assert_equal(@course, assignment.course)
assert_equal(@repository, assignment.repository)
assert_equal(assignment, @repository.storeable)
end
end
|
use regex::Regex;
use std::str::FromStr;
#[derive(Debug)]
pub enum DirectoryItemType {
Link,
File,
Directory,
}
#[derive(Debug)]
pub struct DirectoryItem {
name: String,
item_type: DirectoryItemType,
}
impl FromStr for DirectoryItem {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Process the first character for the file type
let item_type = match &s[0..1] {
"d" => DirectoryItemType::Directory,
"-" => DirectoryItemType::File,
"l" => DirectoryItemType::Link,
_ => return Err("Unknown type".to_string()),
};
lazy_static! {
static ref RE: Regex = Regex::new(
r"[A-z]{3}[ ]{1,}[0-9]{1,2}[ ]{1,}([0-9]{4}|[0-9]{2}:[0-9]{2})[ ]{1,}(.{1,})",
).unwrap();
}
let name_captures = match RE.captures(&s) {
Some(v) => v,
None => return Err("No name found".to_string()),
};
if name_captures.len() < 3 {
return Err("No name found".to_string());
}
Ok(DirectoryItem {
name: name_captures[2].to_string(),
item_type,
})
}
}
|
import {
IsAny,
IsAnyOrUnknown,
IsUnknown,
Iteration,
KeyValuate
} from "@re-/utils"
import { ParseConfig, ShallowCycleError } from "./internal.js"
import { Root } from "../root.js"
import { References } from "../../references.js"
type CheckReferencesForShallowCycle<
References extends string[],
TypeSet,
Seen
> = References extends Iteration<string, infer Current, infer Remaining>
? CheckForShallowCycleRecurse<
KeyValuate<TypeSet, Current>,
TypeSet,
Seen | Current
> extends never
? CheckReferencesForShallowCycle<Remaining, TypeSet, Seen>
: CheckForShallowCycleRecurse<
KeyValuate<TypeSet, Current>,
TypeSet,
Seen | Current
>
: never
type CheckForShallowCycleRecurse<Def, TypeSet, Seen> = IsAny<Def> extends true
? never
: Def extends Seen
? Seen
: Def extends string
? CheckReferencesForShallowCycle<
References<Def, { asList: true }>,
TypeSet,
Seen
>
: never
type CheckForShallowCycle<Def, TypeSet> = CheckForShallowCycleRecurse<
Def,
TypeSet,
never
>
export namespace TypeSetMember {
export type Definition<Def extends Root.Definition = Root.Definition> = Def
export type Validate<Def, TypeSet> = IsAny<Def> extends true
? "any"
: CheckForShallowCycle<Def, TypeSet> extends never
? Root.Validate<Def, TypeSet>
: ShallowCycleError<Def & string, CheckForShallowCycle<Def, TypeSet>>
export type Parse<Def, TypeSet, Options extends ParseConfig> = Root.Parse<
Def,
TypeSet,
Options
>
}
|
---
layout: post
title: "/usr/libexec/mysqld: Incorrect information in file"
date: 2014-09-20 15:09:08 +0900
comments: true
categories: MySQL
published: true
---
[ERROR] /usr/libexec/mysqld: Incorrect information in fileと言うエラー文。
どうもテーブル参照ができないらしい。
mysqlcheckを実行してみる。
```
$ mysqlcheck -u root -p --all-databases
```
修復はしなかったが`mysql restart`したら回復した。
|
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Core Services API
//
// APIs for Networking Service, Compute Service, and Block Volume Service.
//
package core
import (
"github.com/oracle/oci-go-sdk/common"
)
// TunnelStatus Specific connection details for an IPSec tunnel.
type TunnelStatus struct {
// The IP address of Oracle's VPN headend.
// Example: `129.146.17.50`
IpAddress *string `mandatory:"true" json:"ipAddress"`
// The tunnel's current state.
LifecycleState TunnelStatusLifecycleStateEnum `mandatory:"false" json:"lifecycleState,omitempty"`
// The date and time the IPSec connection was created, in the format defined by RFC3339.
// Example: `2016-08-25T21:10:29.600Z`
TimeCreated *common.SDKTime `mandatory:"false" json:"timeCreated"`
// When the state of the tunnel last changed, in the format defined by RFC3339.
// Example: `2016-08-25T21:10:29.600Z`
TimeStateModified *common.SDKTime `mandatory:"false" json:"timeStateModified"`
}
func (m TunnelStatus) String() string {
return common.PointerString(m)
}
// TunnelStatusLifecycleStateEnum Enum with underlying type: string
type TunnelStatusLifecycleStateEnum string
// Set of constants representing the allowable values for TunnelStatusLifecycleState
const (
TunnelStatusLifecycleStateUp TunnelStatusLifecycleStateEnum = "UP"
TunnelStatusLifecycleStateDown TunnelStatusLifecycleStateEnum = "DOWN"
TunnelStatusLifecycleStateDownForMaintenance TunnelStatusLifecycleStateEnum = "DOWN_FOR_MAINTENANCE"
)
var mappingTunnelStatusLifecycleState = map[string]TunnelStatusLifecycleStateEnum{
"UP": TunnelStatusLifecycleStateUp,
"DOWN": TunnelStatusLifecycleStateDown,
"DOWN_FOR_MAINTENANCE": TunnelStatusLifecycleStateDownForMaintenance,
}
// GetTunnelStatusLifecycleStateEnumValues Enumerates the set of values for TunnelStatusLifecycleState
func GetTunnelStatusLifecycleStateEnumValues() []TunnelStatusLifecycleStateEnum {
values := make([]TunnelStatusLifecycleStateEnum, 0)
for _, v := range mappingTunnelStatusLifecycleState {
values = append(values, v)
}
return values
}
|
#!/usr/bin/env bash
state_file="sync/state"
# If state file exists remove it
[[ -f $state_file ]] && rm $state_file
# If State file does not exist create it
[[ ! -f $state_file ]] && touch $state_file
vagrant up
# Create docker context
docker context create remote --default-stack-orchestrator=swarm --docker host=tcp://localhost:2376
docker context use remote
# Create docker registry
docker service create --name registry --publish published=5000,target=5000 registry:2
|
#!/bin/sh
. ./include.sh
TEMP1=temp1.grib_index.py.txt
TEMP2=temp2.grib_index.py.txt
IDX_FILE=my.idx
rm -f $IDX_FILE
# First time it will create the index file
$PYTHON $examples_src/grib_index.py > $TEMP1
[ -f "$IDX_FILE" ]
# Second time it will use the file created before
$PYTHON $examples_src/grib_index.py > $TEMP2
# Check output in both cases is the same
diff $TEMP1 $TEMP2
rm -f $IDX_FILE $TEMP1 $TEMP2
|
<?php
return [
'our_outlets' => 'Data Instansi PPU',
];
|
<?php
/**
* @var \Bavix\GlowApi\Api $client
*/
$client = require __DIR__ . '/_client.php';
// create
$client->showOrCreateBucket('api');
// show
$client->showOrCreateBucket('api');
// get all
foreach ($client->allBuckets() as $bucket) {
var_dump($bucket);
var_dump($client->dropBucket($bucket['name']));
}
|
import {
createStyles,
Theme,
withStyles,
Typography,
Container
} from "@material-ui/core";
import * as React from "react";
import "typeface-roboto";
const CareersJpg = "/assets/jpg/careers.jpg";
const CooperationJpg = "/assets/jpg/cooperation.jpg";
const styles = (theme: Theme) =>
createStyles({
root: {
minHeight: "80vh",
backgroundColor: theme.palette.primary.light,
paddingBottom: "10vh"
},
title: {
color: theme.palette.text.primary,
paddingTop: theme.spacing(10),
paddingBottom: theme.spacing(3),
paddingLeft: theme.spacing(10),
paddingRight: theme.spacing(10),
fontSize: 80,
fontWeight: 700,
lineHeight: 1
},
slogan: {
paddingLeft: theme.spacing(10),
paddingRight: theme.spacing(10),
fontSize: 20,
lineHeight: 1
},
subtitle: {
paddingTop: theme.spacing(3),
fontSize: 50,
lineHeight: "150%",
fontWeight: 700
},
positionTitle: {
color: theme.palette.secondary.main,
marginTop: theme.spacing(3),
fontWeight: 700,
fontSize: "2rem",
lineHeight: "150%"
},
positionPart: {
color: theme.palette.text.secondary,
fontWeight: 400,
fontSize: "1rem",
lineHeight: "150%"
},
positionPrice: {
color: theme.palette.text.primary,
fontWeight: 400,
fontSize: "1rem",
lineHeight: "150%"
},
image: {
marginTop: theme.spacing(30),
marginBottom: theme.spacing(20),
maxWidth: "100%",
maxHeight: "100%",
width: "100%",
height: "auto"
}
});
const Careers: React.FC = ({ classes }: { classes: any }) => (
<div className={classes.root}>
<Container maxWidth="lg">
<Typography variant="h1" className={classes.title}>
Careers
</Typography>
<Typography variant="subtitle1" className={classes.slogan}>
At stasbar, we make the world a better place.
</Typography>
<img className={classes.image} src={CareersJpg} alt="Careers" />
<Typography variant="subtitle1" className={classes.slogan}>
Cooperate to achieve common goal.
</Typography>
<img className={classes.image} src={CooperationJpg} alt="Cooperation" />
<Typography variant="h2" className={classes.subtitle}>
Open positions
</Typography>
<div>
<Typography variant="body1" className={classes.positionTitle}>
📱Android Developer
</Typography>
<Typography variant="body2" className={classes.positionPart}>
Intern
</Typography>
<Typography variant="body2" className={classes.positionPrice}>
0 - 3000 PLN
</Typography>
</div>
<div>
<Typography variant="body1" className={classes.positionTitle}>
🍃Flutter Developer
</Typography>
<Typography variant="body2" className={classes.positionPart}>
Intern
</Typography>
<Typography variant="body2" className={classes.positionPrice}>
0 - 2000 PLN
</Typography>
</div>
<div>
<Typography variant="body1" className={classes.positionTitle}>
🎨Frontend Developer
</Typography>
<Typography variant="body2" className={classes.positionPart}>
Intern
</Typography>
<Typography variant="body2" className={classes.positionPrice}>
0 - 2000 PLN
</Typography>
</div>
<div>
<Typography variant="body1" className={classes.positionTitle}>
🛠️ Embedded Software Developer
</Typography>
<Typography variant="body2" className={classes.positionPart}>
Intern
</Typography>
<Typography variant="body2" className={classes.positionPrice}>
0 - 0 PLN
</Typography>
</div>
</Container>
</div>
);
export default withStyles(styles)(Careers);
|
<?php
namespace App\Http\Controllers;
use App\Commands\CreateAsset;
use App\Commands\DeleteAsset;
use App\Commands\GetAsset;
use App\Entities\Asset;
use App\Http\Responses\AjaxResponse;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
/**
* @Middleware({"web", "auth"})
*/
class AssetController extends AbstractController
{
/**
* Create an Asset via ajax from the Add Vulnerability view of the Ruggedy App
*
* @POST("/asset/create/{assetId}", as="asset.create", where={"fileId":"[0-9]+"})
*
* @param $fileId
* @return \Illuminate\Http\JsonResponse
*/
public function createAsset($fileId)
{
// Only allow ajax requests to access this endpoint
if (!$this->request->ajax()) {
throw new MethodNotAllowedHttpException([], "That route cannot be accessed in that way.");
}
$ajaxResponse = new AjaxResponse();
// Do validation but catch the ValidationExceptions to handle them here ourselves
// because this is a JSON response to an ajax request
try {
$this->validate($this->request, $this->getValidationRules(), $this->getValidationMessages());
} catch (ValidationException $e) {
$message = "<ul><li>" . implode("</li><li>", $e->validator->getMessageBag()->all()) . "</li></ul>";
$ajaxResponse->setMessage(
view('partials.custom-message', ['bsClass' => 'danger', 'message' => $message])->render()
);
return response()->json($ajaxResponse);
}
// Create a new Asset entity and populate it from the request
$asset = new Asset();
$asset->setName($this->request->get('asset-name'))
->setCpe($this->request->get('asset-cpe'))
->setVendor($this->request->get('asset-vendor'))
->setIpAddressV4($this->request->get('asset-ip_address_v4'))
->setIpAddressV6($this->request->get('asset-ip_address_v6'))
->setHostname($this->request->get('asset-hostname'))
->setMacAddress($this->request->get('asset-mac_address', ''))
->setOsVersion($this->request->get('asset-os_version'))
->setNetbios($this->request->get('asset-netbios'));
// Send the CreateAsset command over the command bus
$command = new CreateAsset(intval($fileId), $asset);
$asset = $this->sendCommandToBusHelper($command);
// Handle command errors, set the custom-message partial HTML on AjaxResponse::$html and exit early
if ($this->isCommandError($asset)) {
$ajaxResponse->setHtml(
view('partials.custom-message', [
'bsClass' => 'danger',
'message' => $asset->getMessage(),
])->render()
);
return response()->json($ajaxResponse);
}
// Set the asset partial HTML populated with the new Asset details on AjaxResponse::$html
$ajaxResponse->setHtml(view('partials.related-asset', ['asset' => $asset])->render());
$ajaxResponse->setMessage(view('partials.custom-message', [
'bsClass' => 'success',
'message' => 'A new Asset has been created.',
])->render());
$ajaxResponse->setError(false);
return response()->json($ajaxResponse);
}
/**
* Show a single Asset
*
* @GET("/file/asset/{assetId}", as="asset.view", where={"assetId":"[0-9]+"})
*
* @param $assetId
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/
public function showAsset($assetId)
{
$command = new GetAsset(intval($assetId));
$assetInfo = $this->sendCommandToBusHelper($command);
if ($this->isCommandError($assetInfo)) {
return redirect()->back();
}
return view('workspaces.asset', [
'asset' => $assetInfo->get('asset'),
'vulnerabilities' => $assetInfo->get('vulnerabilities'),
]);
}
/**
* Remove an Asset
*
* @GET("/asset/delete/{assetId}", as="asset.delete", where={"assetId":"[0-9]+"})
*
* @param $assetId
* @return \Illuminate\Http\JsonResponse
*/
public function removeAsset($assetId)
{
// Only allow ajax requests to access this endpoint
if (!$this->request->ajax()) {
throw new MethodNotAllowedHttpException([], "That route cannot be accessed in that way.");
}
$ajaxResponse = new AjaxResponse();
$command = new DeleteAsset(intval($assetId), true);
$asset = $this->sendCommandToBusHelper($command);
// If the command returned an error response then return the error message
if ($this->isCommandError($asset)) {
$ajaxResponse->setHtml(
view('partials.custom-message', [
'bsClass' => 'danger',
'message' => $asset->getMessage(),
])->render()
);
return response()->json($ajaxResponse);
}
// Return a success message
$ajaxResponse->setMessage(view('partials.custom-message', [
'bsClass' => 'success',
'message' => 'Asset deleted successfully.',
])->render());
$ajaxResponse->setError(false);
return response()->json($ajaxResponse);
}
/**
* @inheritdoc
*
* @return array
*/
protected function getValidationRules(): array
{
return [
'asset-name' => 'bail|required',
'asset-cpe' => 'bail|nullable|regex:' . Asset::REGEX_CPE,
'asset-vendor' => 'bail|nullable|in:' . Asset::getValidOsVendors()->implode(",")
. "," . Asset::OS_VENDOR_UNKNOWN,
'asset-ip_address_v4' => 'bail|nullable|ipv4',
'asset-ip_address_v6' => 'bail|nullable|ipv6',
'asset-hostname' => ['bail', 'nullable', 'regex:' . Asset::REGEX_HOSTNAME],
'asset-mac_address' => 'bail|nullable|regex:' . Asset::REGEX_MAC_ADDRESS,
'asset-netbios' => 'bail|nullable|regex:' . Asset::REGEX_NETBIOS_NAME,
];
}
/**
* @inheritdoc
*
* @return array
*/
protected function getValidationMessages(): array
{
return [
'asset-name.required' => 'An Asset name is required but it does not seem like you entered one. '
.'Please try again.',
'asset-cpe.regex' => 'The CPE you entered does not seem valid. Please try again.',
'asset-vendor.in' => 'The OS vendor you entered does not seem valid. Please try again.',
'asset-ip_address_v4.ipv4' => 'The IP address v4 you entered does not seem valid. Please try again.',
'asset-ip_address_v6.ipv6' => 'The IP address v6 you entered does not seem valid. Please try again..',
'asset-hostname.regex' => 'The hostname you entered does not seem to be a valid hostname. '
.'Please try again.',
'asset-mac_address.regex' => 'The MAC address you entered does not seem valid. Please try again.',
'asset-netbios.regex' => 'The NETBIOS name you entered does not seem valid. Please try again.',
];
}
} |
using PetStore.Data.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace PetStore.Data.Configuration
{
using static DataValidations;
public class BreedConfiguration : IEntityTypeConfiguration<Breed>
{
public void Configure(EntityTypeBuilder<Breed> breed)
{
breed
.HasKey(b => b.Id);
breed
.Property(b => b.Name)
.HasMaxLength(BREED_NAME_MAX_LENGTH)
.IsRequired(true)
.IsUnicode(true);
}
}
} |
# Analog2PWM
ATtiny85 converts analog in (0-Vcc) to PWM.
In response to a request on r/AskElectronics
Single-chip (+ bypass cap) solution.
This application uses a tiny fraction of the resources available and does the job quite well for less than USD 2.
Analog input must not exceed Vcc (5v max, although could be run on lower voltages, see datasheet)
PWM output is 8-bit, so only accurate to 1:255 or about 0.4%.
ATtiny85 fuses set to l:0xe2 h:0xdf e:0xff
(8 MHz internal clk, no BOD) -- Many other possibilities.
|
module Graham.A278818 (a278818) where
import Math.NumberTheory.Powers.Squares (isSquare')
import Graham.A277278 (a277278)
import Data.List (find)
import Data.Maybe (fromJust)
-- The least t such that there exists a sequence
-- n = b_1 < b_2 < ... < b_t = A277278(n)
-- such that b_1 + b_2 +...+ b_t is a perfect square.
a278818 :: Integer -> Integer
a278818 n = fromJust $ find (isSquare' . (+ n)) [n + 1..]
|
#![doc(html_root_url = "https://docs.rs/dav/0.1.0-alpha.1")]
//! ## Placeholder for WEBDAV crates.
//!
//! Just a placeholder. `webdav_handler`, `webdav_server` might move here.
//!
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
<?php
namespace inklabs\kommerce\EntityRepository;
use inklabs\kommerce\Entity\Pagination;
use inklabs\kommerce\Entity\Product;
use inklabs\kommerce\Lib\UuidInterface;
/**
* @method Product findOneById(UuidInterface $id)
*/
interface ProductRepositoryInterface extends RepositoryInterface
{
public function findOneBySku(string $sku): Product;
/**
* @param UuidInterface[] $productIds
* @param int $limit
* @return Product[]
*/
public function getRelatedProductsByIds(array $productIds, int $limit = 12);
/**
* Load product tags to avoid query in loop for pricing
*
* @param Product[] $products
*/
public function loadProductTags(array & $products);
/**
* @param UuidInterface $tagId
* @param Pagination $pagination
* @return Product[]
*/
public function getProductsByTagId(UuidInterface $tagId, Pagination & $pagination = null);
/**
* @param UuidInterface[] $productIds
* @param Pagination $pagination
* @return Product[]
*/
public function getProductsByIds(array $productIds, Pagination & $pagination = null);
/**
* @param string $queryString
* @param Pagination $pagination
* @return Product[]
*/
public function getAllProducts(string $queryString = null, Pagination & $pagination = null);
/**
* @param UuidInterface[] $productIds
* @param Pagination $pagination
* @return Product[]
*/
public function getAllProductsByIds(array $productIds, Pagination & $pagination = null);
/**
* @param int $limit
* @return Product[]
*/
public function getRandomProducts(int $limit);
}
|
(define-native set-x)
(define-native get-system-cursor)
(define-native is-grabbed)
(define-native is-visible)
(define-native get-cursor)
(define-native set-visible)
(define-native get-relative-mode)
(define-native set-grabbed)
(define-native set-cursor)
(define-native get-position)
(define-native has-cursor)
(define-native set-y)
(define-native is-down)
(define-native set-position)
(define-native get-x)
(define-native get-y)
(define-native new-cursor)
(define-native set-relative-mode)
|
#!/usr/bin/env bash
# Rash example mysql schema
# =========================
# This is an example schema file for mysql. Customize this
# and save it as "schema.sh".
# Path to the file which contains the current migration step.
# TODO: This should be stored in the db itself.
CURRENT_MIGRATION_FILE="current_migration"
# List only sql files.
function get_migrations_list {
ls [0-9]*.sql | sort -n
}
# Retrieve some connection parameters.
# TODO: Use some kind of env parameter when it's done.
function get_connection_params {
local env=$1
DB_HOST="localhost"
DB_PORT="3339"
DB_NAME="dbname"
DB_USER="root"
DB_PASS="somepassword"
}
# Get the connection parameters for the environment
# and print a notice about the connection attempts.
function setup {
local env=$1
get_connection_params $env
echo Using db $(bold DB_NAME) as $(bold ${DB_USER}@${DB_HOST})
}
# Return the current migration step id.
function get_current_migration_step {
if [[ -f "$CURRENT_MIGRATION_FILE" ]]; then
echo $(<$CURRENT_MIGRATION_FILE)
fi
}
# Save the current migration step.
# TODO: This should be stored in the db itself.
function save_current_migration_step {
local migration="$1"
echo "$migration" > "$CURRENT_MIGRATION_FILE"
}
# **REQUIRED**: Execute the migration step itself.
# It will be passed the extract from the migration file.
function execute_migration_step {
local query="$1"
mysql -h "$DB_HOST" -u "$DB_USER" --password="$DB_PASS" "$DB_NAME" <<< $query
return $?
}
|
package com.panosdim.moneytrack.viewmodel
import androidx.lifecycle.*
import com.panosdim.moneytrack.api.CategoriesRepository
import com.panosdim.moneytrack.api.ExpensesRepository
import com.panosdim.moneytrack.api.data.Resource
import com.panosdim.moneytrack.model.Category
import com.panosdim.moneytrack.model.Expense
import com.panosdim.moneytrack.utils.getCategoryName
import com.panosdim.moneytrack.utils.unaccent
import java.time.LocalDate
class ExpensesViewModel : ViewModel() {
enum class SortField {
DATE, AMOUNT, CATEGORY, COMMENT
}
enum class SortDirection {
ASC, DESC
}
private val expensesRepository = ExpensesRepository()
private val categoriesRepository = CategoriesRepository()
var sortField: SortField = SortField.DATE
var sortDirection: SortDirection = SortDirection.DESC
var filterDate: Pair<LocalDate, LocalDate>? = null
var filterAmount: List<Float>? = null
var filterComment: String? = null
var filterCategory: List<Int>? = null
val categories: LiveData<List<Category>> =
Transformations.switchMap(categoriesRepository.get()) { data ->
MutableLiveData<List<Category>>().apply {
this.value = data
}
}
private var _expenses: LiveData<List<Expense>> =
Transformations.switchMap(expensesRepository.get()) { data ->
MutableLiveData<List<Expense>>().apply {
this.value = data
}
}
val expenses = MediatorLiveData<List<Expense>>()
init {
expenses.addSource(_expenses) {
var data = filter(it)
data = sort(data)
expenses.value = data
}
}
fun removeExpense(expense: Expense): LiveData<Resource<Expense>> {
return expensesRepository.delete(expense)
}
fun addExpense(expense: Expense): LiveData<Resource<Expense>> {
return expensesRepository.add(expense)
}
fun updateExpense(expense: Expense): LiveData<Resource<Expense>> {
return expensesRepository.update(expense)
}
private fun sort(expenseList: List<Expense>): List<Expense> {
val data = expenseList.toMutableList()
when (sortField) {
SortField.DATE -> when (sortDirection) {
SortDirection.ASC -> data.sortBy { it.date }
SortDirection.DESC -> data.sortByDescending { it.date }
}
SortField.AMOUNT -> when (sortDirection) {
SortDirection.ASC -> data.sortBy { it.amount.toDouble() }
SortDirection.DESC -> data.sortByDescending { it.amount.toDouble() }
}
SortField.CATEGORY -> when (sortDirection) {
SortDirection.ASC -> data.sortBy { getCategoryName(it.category, categories) }
SortDirection.DESC -> data.sortByDescending {
getCategoryName(
it.category,
categories
)
}
}
SortField.COMMENT -> when (sortDirection) {
SortDirection.ASC -> data.sortBy { it.comment }
SortDirection.DESC -> data.sortByDescending { it.comment }
}
}
return data
}
fun clearFilters() = _expenses.value?.let {
filterAmount = null
filterDate = null
filterComment = null
filterCategory = null
expenses.value = sort(it)
}
private fun filter(expenseList: List<Expense>): List<Expense> {
val data = expenseList.map { it.copy() }.toMutableList()
// Date Filter
filterDate?.let { (first, second) ->
data.retainAll {
val date = LocalDate.parse(it.date)
(date.isAfter(first) || date.isEqual(first)) && (date.isBefore(second) || date.isEqual(
second
))
}
}
// Amount Filter
filterAmount?.let { range: List<Float> ->
data.retainAll {
it.amount >= range[0] && it.amount <= range[1]
}
}
// Comment Search
filterComment?.let { filter: String ->
data.retainAll {
it.comment.unaccent().contains(filter, ignoreCase = true)
}
}
// Category Filter
filterCategory?.let { categories: List<Int> ->
data.retainAll {
categories.contains(it.category)
}
}
return data
}
fun refreshExpenses() {
expenses.removeSource(_expenses)
_expenses = Transformations.switchMap(expensesRepository.get()) { data ->
MutableLiveData<List<Expense>>().apply {
this.value = data
}
}
expenses.addSource(_expenses) {
var data = filter(it)
data = sort(data)
expenses.value = data
}
}
} |
import React, { Fragment } from 'react';
import { Listbox, Transition } from '@headlessui/react';
import { TextSelectOption } from 'components/atoms';
import TextSelectProps from 'components/molecules/TextSelect/types';
import classNames from 'classnames';
export default function TextSelect({ options, state, className }: TextSelectProps) {
const [selectedOption, setSelectedOption] = state;
return (
<Listbox as="div" className={className} value={selectedOption} onChange={setSelectedOption}>
{({ open }) => (
<>
<Listbox.Button className="flex items-center px-4 py-2 text-gray-700 bg-white rounded-lg focus:outline-none focus:ring-2 ring-indigo-500">
{selectedOption.label}
<svg
className={classNames('w-4 h-4 ml-2 transition-transform transform', {
'rotate-180': open,
})}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
</Listbox.Button>
<Transition
show={open}
enter="duration-100 ease-out"
enterFrom="scale-90 opacity-0"
enterTo="scale-110 opacity-100"
leave="duration-75 ease-out"
leaveFrom="scale-110 opacity-100"
leaveTo="scale-90 opacity-0"
className="fixed z-20 transition duration-150 transform -translate-x-1/2 -translate-y-1/2 sm:translate-x-0 sm:translate-y-0 sm:mt-4 sm:absolute left-1/2 top-1/2 sm:left-auto sm:top-auto"
>
<Listbox.Options
static
className="overflow-hidden text-3xl bg-white shadow-md rounded-xl focus:outline-none focus:ring-2 ring-indigo-500 sm:text-base"
>
{options.map(option => (
<Listbox.Option as={Fragment} key={option.value} value={option}>
{({ active, selected }) => (
<TextSelectOption
active={active}
selected={selected}
onClick={() => setSelectedOption(option)}
>
{option.label}
</TextSelectOption>
)}
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</>
)}
</Listbox>
);
}
|
require 'rails_helper'
RSpec.describe GradingReview::ReviewableEvaluationGroup do
subject { described_class.new(evaluation_group: evaluation_group, evaluations: evaluations) }
let(:evaluations) { [] }
let(:evaluation_group) { instance_double(EvaluationGroup) }
describe 'delegation' do
it { is_expected.to delegate_method(:rating_group).to(:evaluation_group) }
it { is_expected.to delegate_method(:rating_group_id).to(:evaluation_group) }
it { is_expected.to delegate_method(:row_order).to(:rating_group) }
end
describe 'methods' do
describe 'evaluations?' do
let(:evaluation) { instance_double(Evaluation) }
it 'returns false if evaluations are empty' do
subject.evaluations = []
expect(subject.evaluations?).to be_falsey
end
it 'returns true if evaluations are present' do
subject.evaluations = [evaluation]
expect(subject.evaluations?).to be_truthy
end
end
describe '#sorted_evaluations' do
let(:evaluations) {
[
instance_double(Evaluation, row_order: 0),
instance_double(Evaluation, row_order: 2),
instance_double(Evaluation, row_order: 1)
]
}
it 'returns the evaluations sorted by the row order' do
expect(subject.sorted_evaluations).to eq([evaluations[0], evaluations[2], evaluations[1]])
end
end
end
end |
require 'byebug/command'
#
# TODO: Implement thread commands as a single command with subcommands, just
# like `info`, `var`, `enable` and `disable`. This allows consistent help
# format and we can go back to showing help for a single command in the `help`
# command.
#
module Byebug
#
# Utilities to assist commands related to threads.
#
module ThreadFunctions
def display_context(context, should_show_top_frame = true)
puts pr('thread.context',
thread_arguments(context, should_show_top_frame))
end
def thread_arguments(context, should_show_top_frame = true)
status_flag = if context.suspended?
'$'
else
context.thread == Thread.current ? '+' : ' '
end
debug_flag = context.ignored? ? '!' : ' '
if should_show_top_frame
if context == Byebug.current_context
file_line = "#{@state.file}:#{@state.line}"
else
backtrace = context.thread.backtrace_locations
if backtrace && backtrace[0]
file_line = "#{backtrace[0].path}:#{backtrace[0].lineno}"
end
end
end
{
status_flag: status_flag,
debug_flag: debug_flag,
id: context.thnum,
thread: context.thread.inspect,
file_line: file_line || ''
}
end
def parse_thread_num(subcmd, arg)
thnum, err = get_int(arg, subcmd, 1)
return [nil, err] unless thnum
Byebug.contexts.find { |c| c.thnum == thnum }
end
def parse_thread_num_for_cmd(subcmd, arg)
c, err = parse_thread_num(subcmd, arg)
case
when err
[c, err]
when c.nil?
[nil, pr('thread.errors.no_thread')]
when @state.context == c
[c, pr('thread.errors.current_thread')]
when c.ignored?
[c, pr('thread.errors.wrong_action', subcmd: subcmd, arg: arg)]
else
[c, nil]
end
end
end
#
# List current threads.
#
class ThreadListCommand < Command
include ThreadFunctions
self.allow_in_control = true
def regexp
/^\s* th(?:read)? \s+ l(?:ist)? \s*$/x
end
def execute
contexts = Byebug.contexts.sort_by(&:thnum)
thread_list = prc('thread.context', contexts) do |context, _|
thread_arguments(context)
end
print(thread_list)
end
class << self
def names
%w(thread)
end
def description
prettify <<-EOD
th[read] l[ist] Lists all threads.
EOD
end
end
end
#
# Show current thread.
#
class ThreadCurrentCommand < Command
include ThreadFunctions
def regexp
/^\s* th(?:read)? \s+ (?:cur(?:rent)?)? \s*$/x
end
def execute
display_context(@state.context)
end
class << self
def names
%w(thread)
end
def description
prettify <<-EOD
th[read] cur[rent] Shows current thread.
EOD
end
end
end
#
# Stop execution of a thread.
#
class ThreadStopCommand < Command
include ThreadFunctions
self.allow_in_control = true
self.allow_in_post_mortem = false
def regexp
/^\s* th(?:read)? \s+ stop \s* (\S*) \s*$/x
end
def execute
c, err = parse_thread_num_for_cmd('thread stop', @match[1])
return errmsg(err) if err
c.suspend
display_context(c)
end
class << self
def names
%w(thread)
end
def description
prettify <<-EOD
th[read] stop <n> Stops thread <n>.
EOD
end
end
end
#
# Resume execution of a thread.
#
class ThreadResumeCommand < Command
include ThreadFunctions
self.allow_in_control = true
self.allow_in_post_mortem = false
def regexp
/^\s* th(?:read)? \s+ resume \s* (\S*) \s*$/x
end
def execute
c, err = parse_thread_num_for_cmd('thread resume', @match[1])
return errmsg(err) if err
return errmsg pr('thread.errors.already_running') unless c.suspended?
c.resume
display_context(c)
end
class << self
def names
%w(thread)
end
def description
prettify <<-EOD
th[read] resume <n> Resumes thread <n>.
EOD
end
end
end
#
# Switch execution to a different thread.
#
class ThreadSwitchCommand < Command
include ThreadFunctions
self.allow_in_control = true
self.allow_in_post_mortem = false
def regexp
/^\s* th(?:read)? \s+ sw(?:itch)? (?:\s+(\S+))? \s*$/x
end
def execute
c, err = parse_thread_num_for_cmd('thread switch', @match[1])
return errmsg(err) if err
display_context(c)
c.switch
@state.proceed
end
class << self
def names
%w(thread)
end
def description
prettify <<-EOD
th[read] sw[itch] <n> Switches thread context to <n>.
EOD
end
end
end
end
|
package com.winterparadox.themovieapp.home;
import com.winterparadox.themovieapp.common.beans.Movie;
import com.winterparadox.themovieapp.common.room.FavoriteDao;
import com.winterparadox.themovieapp.common.room.RecentlyViewedDao;
import java.util.List;
import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;
public class HomeDatabaseInteractorImpl implements HomeDatabaseInteractor {
private FavoriteDao favoriteDao;
private RecentlyViewedDao recentlyViewedDao;
public HomeDatabaseInteractorImpl (FavoriteDao favoriteDao,
RecentlyViewedDao recentlyViewedDao) {
this.favoriteDao = favoriteDao;
this.recentlyViewedDao = recentlyViewedDao;
}
@Override
public Single<List<Movie>> getHomeFavorites () {
return favoriteDao.getHomeFavorites (4).subscribeOn (Schedulers.io ());
}
@Override
public Single<List<Movie>> getHomeRecents () {
return recentlyViewedDao.getRecent (4).subscribeOn (Schedulers.io ());
}
}
|
using System.Windows;
namespace Xe.Tools.Components.MapEditor.Models
{
public class Frame
{
public Rect Source { get; set; }
public Point Pivot { get; set; }
}
}
|
-- import_schema_stats.sql
-- import statistics for a schema
-- comment this line to see variable subtitution
set verify off
col stattab_owner new_value stattab_owner noprint
col stat_table new_value stat_table noprint
col schema new_value schema noprint
col noinvalidate new_value noinvalidate noprint
col statid new_value statid noprint
col force_import new_value force_import noprint
prompt Import Stats Table Owner:
set feed off term off
select upper('&1') stattab_owner from dual;
set term on
prompt Statistics Table Name:
set feed off term off
select upper('&2') stat_table from dual;
set term on
prompt Import Stats for Schema:
set feed off term off
select upper('&3') schema from dual;
set term on
prompt Import Stats for StatID:
set feed off term off
select upper('&4') statid from dual;
set term on
prompt NOINVALIDATE? YES/NO:
set feed off term off
select upper('&5') noinvalidate from dual;
set term on
prompt FORCE IMPORT? YES/NO:
set feed off term off
select upper('&6') force_import from dual;
set term on
set term on feed on
declare
v_noinvalidate boolean := true;
v_force_import boolean := false;
begin
case '&&noinvalidate'
when 'YES' then v_noinvalidate := true;
else v_noinvalidate := false;
end case;
case '&&force_import'
when 'YES' then v_force_import := true;
else v_force_import := false;
end case;
dbms_output.put_line('=======================');
dbms_output.put_line('schema : &&schema');
dbms_output.put_line('stattab : &&stat_table');
dbms_output.put_line('statid : &&statid');
if v_noinvalidate then
dbms_output.put_line('noinvalidate : TRUE' );
else
dbms_output.put_line('noinvalidate : FALSE' );
end if;
if v_force_import then
dbms_output.put_line('force_import : TRUE');
else
dbms_output.put_line('force_import : FALSE');
end if;
DBMS_STATS.IMPORT_SCHEMA_STATS (
ownname => '&&schema',
stattab => '&&stat_table',
statid => '&&statid',
statown => '&&stattab_owner',
force => v_force_import,
no_invalidate => v_noinvalidate
);
end;
/
|
require "spec_helper"
require "support"
RSpec.describe SimpleState::Machine do
let(:dsl_definition) do
proc do
state :pending, :outsourced, :printed, :matched, :dispatched, :cancelled
transition :print, from: [:pending, :outsourced], to: :printed
transition :match, from: :printed, to: :matched
transition :ship, from: :matched, to: :dispatched
transition :cancel, from: [:pending, :outsourced, :printed, :matched], to: :cancelled
end
end
let(:other_dsl_definition) do
proc do
state :pending, :outsourced, :printed, :matched, :dispatched, :cancelled
transition :match, from: :printed, to: :matched
transition :ship, from: :matched, to: :dispatched
transition :cancel, from: [:pending, :outsourced, :printed, :matched], to: :cancelled
end
end
describe "when two machine exists with different states" do
let(:unit) { Unit.new(state: :pending) }
let(:other_unit) { Unit.new(state: :cancelled) }
let(:state_machine) { described_class.new(unit, :state, &dsl_definition) }
let(:other_state_machine) { described_class.new(other_unit, :state, &other_dsl_definition) }
it "adds dynamic methods into singleton class (metaclass)" do
expect(state_machine.can_print?).to be_truthy
expect { other_state_machine.can_print? }.to raise_error
end
end
describe "correctly transition between states" do
describe "when unit is in pending state" do
let(:unit) { Unit.new(state: :pending) }
let(:state_machine) { described_class.new(unit, :state, &dsl_definition) }
it "allows to change to printed" do
state_machine.print!
expect(unit.state).to eq(:printed)
end
describe "when trying to transition to non-allowed state" do
it "raises error for transition method" do
expect { state_machine.match! }.to raise_error(SimpleState::TransitionError)
end
it "returns false for check method" do
expect(state_machine.can_match?).to be_falsey
end
end
describe "when transits to state which allow to change from multiple states" do
before do
unit.state = :matched
end
it "transits to cancel state" do
state_machine.cancel!
expect(unit.state).to eq(:cancelled)
end
it "raises error when changing to wrong state" do
expect { state_machine.print! }.to raise_error(SimpleState::TransitionError)
end
end
end
end
end
|
<?php
return [
'send_password_link' => 'Stuur wagwoord terugstel skakel',
'email_reset_password' => 'E-pos wagwoord herstel',
'reset_password' => 'Herstel wagwoord',
'login' => 'Teken aan',
'login_prompt' => 'Asseblief Login',
'forgot_password' => 'ek het my wagwoord vergeet',
'remember_me' => 'Onthou my',
];
|
import unittest
import import_ipynb
import pandas as pd
import pandas.testing as pd_testing
import numpy.testing as np_testing
from sklearn import datasets, svm, model_selection
class Test(unittest.TestCase):
def setUp(self):
import Exercise_8_2
self.exercises = Exercise_8_2
self.digits = datasets.load_digits()
self.y = self.digits.target
self.X = self.digits.data
self.clr = svm.SVC(gamma='scale')
self.grid = [
{'kernel': ['linear']},
{'kernel': ['poly'], 'degree': [2, 3, 4]}
]
self.cv_spec = model_selection.GridSearchCV(estimator=self.clr, param_grid=self.grid, scoring='accuracy', cv=10)
self.cv_spec.fit(self.X, self.y)
def test_result(self):
self.assertEqual(
self.exercises.cv_spec.cv_results_["mean_test_score"].max()
, self.cv_spec.cv_results_["mean_test_score"].max()
)
if __name__ == '__main__':
unittest.main()
|
CREATE TABLE Changes
(
ChangeId INTEGER NOT NULL UNIQUE CONSTRAINT PrimaryKeyChanges PRIMARY KEY,
TableName TEXT(255) NULL,
FieldName TEXT(255) NULL,
ActionType TEXT(255) NULL,
OldValue TEXT(255) NULL,
NewValue TEXT(255) NULL,
ChangeDate DATETIME NULL,
Message TEXT(255) NULL
); |
{-|
Copyright : (c) Dave Laing, 2017-2019
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Network.Wai (responseLBS)
import Network.HTTP.Types.Status (status200)
import Reflex.Backend.Warp (runAppForever)
main :: IO ()
main =
runAppForever 8080 $ \eReq -> do
let eRes = responseLBS status200 [] "Hi" <$ eReq
pure eRes |
<?php
declare(strict_types=1);
namespace Otis22\VetmanagerRestApi\URI;
use Otis22\VetmanagerRestApi\Model;
use PHPUnit\Framework\TestCase;
class OnlyModelTest extends TestCase
{
public function testAsString(): void
{
$this->assertTrue(
strpos(
(
new OnlyModel(
new Model('invoice')
)
)->asString(),
'invoice'
) !== false
);
}
}
|
package watchjs
import "sync"
// Hub dispatches Message to multiple listeners.
type Hub struct {
mu sync.RWMutex
conns map[Listener]struct{}
}
// NewHub creates a new Hub.
func NewHub() *Hub {
return &Hub{
conns: map[Listener]struct{}{},
}
}
// Listener is a connection that cares about the changes.
type Listener interface {
// Dispatch must not block
Dispatch(Message)
}
// Register adds connections to hub.
func (hub *Hub) Register(conn Listener) {
hub.mu.Lock()
defer hub.mu.Unlock()
hub.conns[conn] = struct{}{}
}
// Unregister removes connection from hub.
func (hub *Hub) Unregister(conn Listener) {
hub.mu.Lock()
defer hub.mu.Unlock()
delete(hub.conns, conn)
}
// Dispatch message to all registered connections.
func (hub *Hub) Dispatch(message Message) {
hub.mu.RLock()
defer hub.mu.RUnlock()
for conn := range hub.conns {
conn.Dispatch(message)
}
}
|
from functools import lru_cache
from importlib import import_module
from .basic import BasicSSHConnector
from .basic import set_max_startups # noqa
@lru_cache()
def get_connector_class(mod_cls_name=None):
if not mod_cls_name:
return BasicSSHConnector
mod_name, _, cls_name = mod_cls_name.rpartition(".")
mod_obj = import_module(mod_name)
return getattr(mod_obj, cls_name)
|
package kotlinmud.mob.skill.impl.malediction
import kotlinmud.affect.model.Affect
import kotlinmud.affect.type.AffectType
import kotlinmud.io.model.Message
import kotlinmud.mob.model.Mob
import kotlinmud.mob.skill.factory.easyForMage
import kotlinmud.mob.skill.factory.mageAt
import kotlinmud.mob.skill.type.SkillType
import kotlinmud.mob.skill.type.Spell
import kotlinmud.mob.type.Intent
class Curse : Spell {
override val type = SkillType.CURSE
override val levelObtained = mapOf(
mageAt(15)
)
override val difficulty = mapOf(
easyForMage()
)
override val intent = Intent.OFFENSIVE
override fun cast(caster: Mob, target: Mob) {
target.affects.add(Affect(AffectType.CURSE, caster.level / 2))
}
override fun createMessage(caster: Mob, target: Mob): Message {
TODO("Not yet implemented")
}
}
|
#Get the HyperflexExtFcStoragePolicy to delete
$HyperflexExtFcStoragePolicy = Remove-IntersightHyperflexExtFcStoragePolicy -Name HyperflexExtFcStoragePolicyName
$HyperflexExtFcStoragePolicy | Remove-IntersightHyperflexExtFcStoragePolicy
#Remove the server profile by Moid.
Remove-IntersightHyperflexExtFcStoragePolicy -Moid 123bc2222287wee
|
package com.corvisaAPI.notification;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/launch")
public class Notify extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
System.out.println("Hurrah!");
throw new ServletException("The requested action is not yet supported");
}
}
|
package main
import (
"flag"
)
var (
cmdHelp = flag.Bool("h", false, "帮助")
)
func init() {
flag.Parse()
}
func main() {
if *cmdHelp {
flag.PrintDefaults()
return
}
}
|
---
layout: page
title: Page Not Found - 404
showTitle: false
---
{% assign path="boilerplate/404/" | append: site.jaytch.page_404 | append: ".md" %}
{% include {{ path }} %} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Visualisation {
public static partial class Vis {
}
} |
# Create Docker image with Itamae
## install itamae
1. Create a new `Gemfile`
```bash
$ bundle init
$ vim Gemfile
```
2. Now open `Gemfile` and put `itamae` as dependency
```
gem "itamae"
```
3. Save, close file and install deps
```bash
$ bundle install --path vendor
```
## itamae init
1. Create a new `itamae` env
```bash
$ bundle exec itamae init test
```
2. Access `test` directory
3. Now open `Gemfile` and add `docker-api` as dependency
```
gem "docker-api"
```
4. Install new dependencies
```bash
$ bundle install --path vendor
```
## itamae generate role
1. Create a new server `role`
```bash
$ bundle exec itamae generate role test_server
```
2. Open `roles/test_server/default.rb` file and import a new cookbook
```ruby
include_recipe '../../cookbooks/vim'
```
3. Save and close file
## itamae generate cookbook
1. Create a new `vim` cookbook
```bash
$ bundle exec itamae generate cookbook vim
```
2. Open `cookbooks/vim/default.rb` file and create the `recipe`
```ruby
execute 'update apt' do
command 'apt -y update'
end
package 'vim' do
options '--force-yes'
end
```
3. Save and close file
## itamae docker
Now run the command bellow to create a docker image
```bash
$ bundle exec itamae docker --image=nginx --tag nginx_with_vim roles/test_server/default.rb
```
This command will create a new `docker image` named `nginx_with_vim` using your recipes.
## Credits
https://hawksnowlog.blogspot.com/2018/06/create-docker-image-with-itamae.html
|
package system
import (
"github.com/creasty/apperrors"
)
// ErrorCode represents error identifier specified for this application
type ErrorCode int
// Enum values for ErrorCode
const (
ErrorUnknown ErrorCode = iota
ErrorInvalidArgument
ErrorUnauthorized
ErrorForbbiden
ErrorNotFound
ErrorFailedToReadDB
ErrorFailedToWriteDB
)
var stringByErrorCode = map[ErrorCode]string{
ErrorUnknown: "Unknown",
ErrorInvalidArgument: "InvalidArgument",
ErrorUnauthorized: "Unauthorized",
ErrorForbbiden: "Forbbiden",
ErrorNotFound: "NotFound",
ErrorFailedToReadDB: "FailedToReadDB",
ErrorFailedToWriteDB: "FailedToWriteDB",
}
// New returns an error with a status code
func (c ErrorCode) New(msg string) error {
return apperrors.WithStatusCode(apperrors.New(msg), int(c))
}
// Wrap sets an error code to an error
func (c ErrorCode) Wrap(err error) error {
return apperrors.WithStatusCode(apperrors.Wrap(err), int(c))
}
// WithReport annotates an error reportability
func (c ErrorCode) WithReport(err error) error {
return apperrors.WithReport(c.Wrap(err))
}
func (c ErrorCode) String() string {
return stringByErrorCode[c]
}
|
<?php
namespace FKS\Channels;
class NodeJS
{
private $host='localhost';
private $port='1771';
private $socket;
private function connect()
{
if (($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))){
return socket_connect($this->socket,$this->host,$this->port);
}else
return false;
}
private function write($socket, $buffer)
{
return socket_write($socket, $buffer, strlen($buffer));
}
private function close($socket)
{
return socket_close($socket);
}
public function send($buffer)
{
try{
if ($this->connect()){
if ($this->write($this->socket, $buffer)){
$this->close($this->socket);
return true;
} else {
return false;
}
}
} catch(Exception $e){
// Include PSR-3 to Logging
return false;
}
}
} |
<?php
class Brivium_ExtraTrophiesAwarded_DataWriter_User extends XFCP_Brivium_ExtraTrophiesAwarded_DataWriter_User
{
protected function _getFields()
{
$fields = parent::_getFields();
$fields ['kmk_user']['breta_event_date'] = array('type' => self::TYPE_UINT, 'default' => 0);
$fields ['kmk_user']['breta_user_level'] = array('type' => self::TYPE_UINT, 'default' => 1);
$fields ['kmk_user']['breta_curent_level'] = array('type' => self::TYPE_UINT, 'default' => 0);
$fields ['kmk_user']['breta_next_level'] = array('type' => self::TYPE_UINT, 'default' => 0);
return $fields;
}
} |
package top.techqi.chaotic.util
import android.annotation.SuppressLint
import android.app.Application
import top.techqi.chaotic.R
/**
* 在任意模块中都能获取到常规信息的辅助类
*/
@SuppressLint("PrivateApi")
@Suppress("unused", "MemberVisibilityCanBePrivate", "HasPlatformType")
object PluginApp {
val INSTANCE: Application by lazy {
try {
val clazz = Class.forName("android.app.AppGlobals")
val method = clazz.getMethod("getInitialApplication")
return@lazy method.invoke(null) as Application
} catch (ex: Exception) {
throw IllegalStateException("CANNOT get Application Context", ex)
}
}
val NAME by lazy { INSTANCE.getString(R.string.name)!! }
}
|
# Leetcode Notes
[click here to return](https://annaleee.github.io/books.html)
1. <a href="DP/DP.md">动态规划</a>
2. <a href="Backtracking/Backtracking.md">回溯算法</a>
|
package de.mtorials.dialbot.listeners
import de.mtorials.dialbot.Config
import de.mtorials.dialphone.dialevents.MessageReceivedEvent
import de.mtorials.dialphone.listener.ListenerAdapter
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class WordListener(
private val moderationConfig : Config.Moderation
) : ListenerAdapter() {
override suspend fun onRoomMessageReceive(event: MessageReceivedEvent) {
if (event.sender.id == event.phone.ownId) return
for ((id, mod) in moderationConfig.roomModerationById) {
if (id != event.roomFuture.id) continue
mod.filteredWords.forEach {
if (event.message.body.contains(it)) {
delete(event)
return
}
}
}
}
private fun delete(event: MessageReceivedEvent) {
GlobalScope.launch { event.message.redact() }
}
} |
/*
* StatCraft Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.sql
class SpongeDatabaseManager : AbstractDatabaseManager() {
// We don't have access to commons lang < 3, so we don't have escapeSql, so just don't worry about it
// Our use case is only for where we can't user prepared statements, and it's already hardcoded on our input
// (they are our column names) so we don't actually have anything to worry about
override fun escapeSql(s: String) = s
} |
CREATE PROCEDURE [dbo].[spSRAGetEmployeeByToken]
@token_id nvarchar(50)
AS
SELECT
[TBL_SRA_EMPLOYEE].id,
[TBL_SRA_EMPLOYEE].area,
[TBL_SRA_EMPLOYEE].[role],
[TBL_SRA_PERSON].id as "person_id",
[TBL_SRA_PERSON].identification,
[TBL_SRA_PERSON].name,
[TBL_SRA_PERSON].middle_name,
[TBL_SRA_PERSON].last_name,
supervisor.id as "supervisor_id",
supervisor.area as "supervisor_area",
supervisor.[role] as "supervisor_role",
supervisor_person.id as "supervisor_person_id",
supervisor_person.name as "supervisor_name",
supervisor_person.middle_name as "supervisor_middle_name",
supervisor_person.last_name as "supervisor_last_name",
[TBL_SRA_EMPLOYEE].image_url
FROM [TBL_SRA_EMPLOYEE]
INNER JOIN [TBL_SRA_PERSON] ON [TBL_SRA_PERSON].id = [TBL_SRA_EMPLOYEE].person
INNER JOIN [TBL_SCMS_USER] ON [TBL_SCMS_USER].[user_id] = [TBL_SRA_EMPLOYEE].[user]
INNER JOIN [TBL_SRA_EMPLOYEE] supervisor ON supervisor.id = [TBL_SRA_EMPLOYEE].supervisor
INNER JOIN [TBL_SRA_PERSON] supervisor_person on supervisor_person.id = supervisor.person
INNER JOIN [TBL_SCMS_TOKEN] ON [TBL_SCMS_TOKEN].token_user_id = [TBL_SCMS_USER].[user_id]
AND [TBL_SCMS_TOKEN].token_id = @token_id
AND [TBL_SCMS_TOKEN].token_expires_at > GETDATE();
RETURN 0
|
/*
Copyright 1996-2008 Ariba, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
$Id: //ariba/platform/ui/aribaweb/ariba/ui/aribaweb/util/AWBookmarker.java#6 $
*/
package ariba.ui.aribaweb.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import ariba.ui.aribaweb.core.AWComponent;
import ariba.ui.aribaweb.core.AWDirectActionUrl;
import ariba.ui.aribaweb.core.AWRequestContext;
import ariba.ui.aribaweb.core.AWSessionValidationException;
import ariba.ui.aribaweb.util.AWEvaluateTemplateFile.FieldValue;
import ariba.util.core.Assert;
import ariba.util.core.Fmt;
import ariba.util.core.ListUtil;
import ariba.util.core.MapUtil;
import ariba.util.fieldvalue.FieldValueAccessorUtil;
public class AWBookmarker
{
private static String PageName = "page";
private static Class<?>[] BookmarkType = {AWBookmarkState.class};
protected BookmarkEncrypter _encrypter = new DefaultEncrypterImpl();
public boolean isBookmarkable (AWRequestContext requestContext)
{
if (requestContext.page() != null) {
AWComponent comp = requestContext.pageComponent();
if (comp instanceof AWPublicBookmarkable) {
return true;
}
else if (comp instanceof AWBookmarkURLProvider) {
return true;
}
}
return false;
}
public String getURLString (AWRequestContext requestContext)
{
AWComponent comp = requestContext.pageComponent();
if (comp instanceof AWBookmarkURLProvider) {
return ((AWBookmarkURLProvider)comp).bookmarkURL();
}
Map<String, Object> properties = null;
List<String> aprop =
ListUtil.collectionToList(getAnnotedProperties(comp.getClass()).keySet());
properties = MapUtil.map();
for (String prop : aprop) {
properties.put(prop, FieldValue.getFieldValue(comp, prop));
}
StringBuffer queryBuff = new StringBuffer();
queryBuff.append(Fmt.S("%s=%s", PageName, comp.componentReference().tagName()));
for (String key : properties.keySet()) {
Object val = properties.get(key);
String sval = AWBookmarkFormatter.format(val);
sval = AWUtil.encodeString(sval);
queryBuff.append(Fmt.S("&%s=%s", key, sval));
}
String urlString =
AWDirectActionUrl.fullUrlForDirectAction("restore", requestContext);
urlString = _encrypter.getEncryptedUrl(urlString, queryBuff.toString());
return urlString;
}
public Map<String, Class<?>> getAnnotedProperties(Class<?> aclass){
Map<String,Class<?>> properties = MapUtil.map();
Class<?> currClass = aclass;
while (currClass != null && !currClass.getName().equals(AWComponent.class.getName())) {
Map<Annotation, AnnotatedElement> annotations = AWJarWalker.annotationsForClassName(
currClass.getName(), BookmarkType);
for (AnnotatedElement element : annotations.values()) {
String fname = FieldValueAccessorUtil.normalizedFieldPathForMember((Member)element);
Class<?> type = null;
if (element instanceof Method) {
Method mtd =(Method)element;
type = mtd.getReturnType();
}
else if (element instanceof Field) {
Field fld = (Field) element;
type = ((Field)element).getType();
}
Assert.that(fname != null && type != null,
"Unable to access (possibly private): " + element.toString());
properties.put(fname, type);
}
currClass = currClass.getSuperclass();
}
return properties;
}
public AWComponent getComponent(AWRequestContext requestContext) {
String page = requestContext.request().formValueForKey(PageName);
if (page == null) return null;
AWComponent compRet = requestContext.pageWithName(page);
if (compRet instanceof AWProtectedBookmarkable) {
((AWProtectedBookmarkable)compRet).check();
}
Map<String,Class<?>> aprop = getAnnotedProperties(compRet.getClass());
try {
for (String prop : aprop.keySet()) {
Object val = AWBookmarkFormatter.parse(
requestContext.request().formValueForKey(prop), aprop.get(prop));
FieldValue.setFieldValue(compRet, prop, val);
}
((AWPublicBookmarkable)compRet).bookmarkPostInit();
if (compRet instanceof AWProtectedBookmarkable) {
if (!((AWProtectedBookmarkable)compRet).check()) {
throw new AWSessionValidationException();
}
}
}
catch (ParseException e) {
requestContext.application().handleException(requestContext, e);
}
return compRet;
}
/**
* Returns the current encrypter i.e. the implementation of BookmarkEncrypter
*
* @return BookmarkEncrypter
*/
public BookmarkEncrypter getEncrypter ()
{
return _encrypter;
}
/**
* Set the encrypter to be used for encrypting and decrypting urls.
*
* @param encryptor concrete implementation of BookmarkEncrypter.
*/
public void setEncrypter (BookmarkEncrypter encryptor)
{
this._encrypter = encryptor;
}
/**
* This interface is intended to be implemented by the Application.
* It should provide a way to encrypt the query string of the urls to prevent hacking.
*
*/
public static interface BookmarkEncrypter
{
public boolean isEncrypted(AWRequestContext requestContext);
public String getEncryptedUrl (String url, String queryToAppend);
public String getDecryptedUrl (AWRequestContext requestContext);
}
class DefaultEncrypterImpl implements BookmarkEncrypter
{
public boolean isEncrypted (AWRequestContext requestContext)
{
return false;
}
public String getEncryptedUrl (String url, String query)
{
return Fmt.S("%s&%s", url, query);
}
public String getDecryptedUrl (AWRequestContext requestContext)
{
return null;
}
}
}
|
import math
# inputs:
# thetadeg -> polar coordinate angle in degrees
# distancemm -> polar coordinate radius in mm
# xtxm/ytxm -> translations in the x & y dimensions
# outputs:
# x -> cartesian coordinate in x dimension in m
# y -> cartesian coordinate in y dimension in m
angleRad = (thetadeg + angulartxdeg) * math.pi / 180.0
x = distancemm/1000 * math.cos(angleRad) + xtxm
y = distancemm/1000 * math.sin(angleRad) + ytxm |
# Use duecredit (duecredit.org) to provide a citation to relevant work to
# be cited. This does nothing, unless the user has duecredit installed,
# And calls this with duecredit (as in `python -m duecredit script.py`):
from .external.due import due, Doi, BibTeX
due.cite(Doi("10.3389/fninf.2011.00013"),
description="A flexible, lightweight and extensible neuroimaging data"
" processing framework in Python",
path="nipype",
tags=["implementation"],)
due.cite(Doi("10.5281/zenodo.50186"),
description="A flexible, lightweight and extensible neuroimaging data"
" processing framework in Python",
path="nipype",
tags=["implementation"],)
|
require 'test_helper'
class PortfolioTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
def setup
@user = User.new(name: "Example User2", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
@user.save
@portfolio = Portfolio.new(user_id: @user.id, currency: "USD", amount: 10.0)
end
test "should be valid" do
assert @portfolio.valid?
end
test "user_id should be present" do
@portfolio.user_id = nil
assert_not @portfolio.valid?
end
test "currency should be present" do
@portfolio.currency = " "
assert_not @portfolio.valid?
end
test "type can only be USD or BTC" do
invalid_currency = %w[SGD USDOLLAR RPX FAS]
invalid_currency.each do |currency|
@portfolio.currency = currency
assert_not @portfolio.valid?, "#{currency.inspect} should be invalid"
end
end
end
|
import { getFullPathLabel, getTreeValue } from './helper';
import { TreeNode, TreeNodeValue, CascaderContextType } from '../interface';
/**
* input和treeStore变化的副作用
* @param inputVal
* @param treeStore
* @param setTreeNodes
* @returns
*/
export const treeNodesEffect = (
inputVal: CascaderContextType['inputVal'],
treeStore: CascaderContextType['treeStore'],
setTreeNodes: CascaderContextType['setTreeNodes'],
) => {
if (!treeStore) return;
let nodes = [];
if (inputVal) {
nodes = treeStore.nodes.filter((node: TreeNode) => {
const fullPathLabel = getFullPathLabel(node);
return fullPathLabel.indexOf(inputVal) > -1 && node.isLeaf();
});
} else {
nodes = treeStore.getNodes().filter((node: TreeNode) => node.visible);
}
setTreeNodes(nodes);
};
/**
* 初始化展开阶段与展开状态副作用
* @param treeStore
* @param treeValue
* @param expend
*/
export const treeStoreExpendEffect = (
treeStore: CascaderContextType['treeStore'],
value: CascaderContextType['value'],
expend: TreeNodeValue[],
) => {
const treeValue = getTreeValue(value);
if (!treeStore) return;
// init expanded, 无expend状态时设置
if (Array.isArray(treeValue) && expend.length === 0) {
const expandedMap = new Map();
const [val] = treeValue;
if (val) {
expandedMap.set(val, true);
const node = treeStore.getNode(val);
// 无匹配数据
if (!node) {
treeStore.refreshNodes();
return;
}
node.getParents().forEach((tn: TreeNode) => {
expandedMap.set(tn.value, true);
});
const expandedArr = Array.from(expandedMap.keys());
treeStore.replaceExpanded(expandedArr);
} else {
treeStore.resetExpanded();
}
}
// 本地维护 expend,更加可控,不需要依赖于 tree 的状态
if (treeStore.getExpanded() && expend.length) {
treeStore.replaceExpanded(expend);
}
treeStore.refreshNodes();
};
|
package com.cheise_proj.remote_source.mapper.user
import com.cheise_proj.data.model.user.UserData
import com.cheise_proj.remote_source.mapper.RemoteMapper
import com.cheise_proj.remote_source.model.dto.user.UserDto
internal class UserDtoDataMapper :
RemoteMapper<UserDto, UserData> {
override fun dtoToData(t: UserDto): UserData {
return UserData(
username = "",
uuid = t.uuid,
photo = t.imageUrl,
role = t.role,
level = t.level,
password = "",
name = t.name,
token = t.token
)
}
override fun dataToDto(d: UserData): UserDto {
return UserDto(
uuid = d.uuid,
name = d.name,
imageUrl = d.photo,
level = d.level,
status = 0,
message = "",
role = d.role,
token = d.token
)
}
} |
;;;-*- Mode: Lisp; Package: :cl-user -*-
;;;
;;; apex/system/asa/rat.lisp
;;;
;;; Copyright: See apex/LICENSE
;;; Version: $Id: rat.lisp,v 1.1 2006/03/13 19:22:37 will Exp $
(in-package :common-lisp-user)
;;; ------ Resource Allocation Tables
;;; The resource-allocation-table agent slot contains a structure of
;;; type RAT. The ASA uses it to keep track of owenerships and attempts
;;; to gain ownership by tasks. Note that each resource is assumed to
;;; be ownable at multiple levels ranging from 1 to 10, with each level
;;; representing a time-scale over which the designated task is the
;;; primary owner. Tasks controlling a resource over the smallest
;;; time-scale (10) can issue control-signals to the resource, thereby
;;; changing its state. (E.g. controlling the visual-attention resource
;;; at level 10 allows a task to shift attn locus).
;;; ! move from 1-10 notation to linear time units.
(defparameter *default-ownership-level* 10)
(defclass rat (appob)
((owners
:type list ; of own declarations of form (<res> <range> <task>)
:accessor owners
:initform nil
:initarg :owners)
(monitors
:type hash-table ; ! type?
:accessor monitors
:initform nil
:initarg :monitors)
(best
:type list ; of pending ownership changes: (<task> <ints> <bumps>)
:accessor best
:initform nil
:initarg :best)))
;;; The following is an ADT for RAT, under development.
;;; ! (KMD) RAT's slots would better be converted into structures
;;; ---- begin
(defun res-owner-resource (owner) ; (? (int int) ?) -> ?
(first owner))
(defun res-owner-range (owner) ; (? (int int) ?) -> (int int)
(second owner))
(defun res-owner-task (owner) ; (? (int int) ?) -> ?
(third owner))
;;; ---- end
;;; The <ints> value is a list of tasks to interrupt if the <task> remains best
;;; through to the point where the internal loop of ASAMain becomes quiescent.
;;; At that point, the listed interrupts are generated and the <ints> value set
;;; to nil. The <task> may still get bumped from the best list, particularly by
;;; a winddown task associated with an interrupted task.
;;; The <bumps> value lists tasks which were bumped from the best list by
;;; <task>. If <task> is itself bumped, these tasks get a new resource grab
;;; attempt. Entries in <bumps> are of the form (<task> <res> <low> <high>)
;;; indicating the task to be bumped and the resource conflict (possibly of
;;; several) that caused it.
(defun add-apex-resource-monitor (mon agent)
(when (null (monitors (resource-allocation-table agent)))
(setf (monitors (resource-allocation-table agent))
(make-hash-table :test 'eq)))
(setf (gethash (first (expr mon))
(monitors (resource-allocation-table agent)))
(cons mon (gethash (first (expr mon))
(monitors (resource-allocation-table agent))))))
(defun remove-resource-monitor (mon agent)
(when (null (monitors (resource-allocation-table agent)))
(setf (monitors (resource-allocation-table agent))
(make-hash-table :test 'eq)))
(setf (gethash (first (expr mon))
(monitors (resource-allocation-table agent)))
(remove mon (gethash (first (expr mon))
(monitors (resource-allocation-table agent))))))
|
package org.dhis2.utils.filters.workingLists
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceFilter
class TeiFilterToWorkingListItemMapper(
private val defaultWorkingListLabel: String
) {
fun map(teiFilter: TrackedEntityInstanceFilter): WorkingListItem {
return WorkingListItem(
teiFilter.uid(),
teiFilter.displayName() ?: defaultWorkingListLabel
)
}
}
|
<#
.Synopsis
Enable litigation hold for a user or for all users.
.Description
Enable litigation hold for a user or for all users.
.Parameter all
If litigation hold should be enabled for all users
.Parameter user
If all is $False, a user must be specified. Use their email address.
.Parameter username
Username of the Office 365 user.
.Example
# Redo permissions on the "Large Conference Room"" calendar.
Fix-SharedCalendarPermission -mailbox [email protected] -username [email protected]
Must be run in Microsoft Exchange Online Powershell Module
#>
function Enable-LitigationHold {
[CmdletBinding()]
Param(
[switch]$all,
[string]$user,
[Parameter(Mandatory=$True)]
[String]
$username
)
#Setup Session
Connect-EXOPSSession -UserPrincipalName $username
# Enable hold
# Must use the -all flag or specify a user
if ($all.IsPresent) {
Get-Mailbox -RecipientTypeDetails UserMailbox -ResultSize unlimited | Set-Mailbox -LitigationHoldEnabled $True
} elseif (!([string]::IsNullOrEmpty($user))) {
Get-Mailbox -Identity $user | Set-Mailbox -LitigationHoldEnabled $True
} else {
throw "Must provide a valid -user or use the -all parameter."
}
Get-PSSession | Remove-PSSession
}
Export-ModuleMember Enable-LitigationHold
|
CREATE DATABASE T_AutoPecas;
USE T_AutoPecas;
CREATE TABLE Pecas(
PecaId INT PRIMARY KEY IDENTITY NOT NULL,
PecaCodigo INT UNIQUE NOT NULL,
Descricao VARCHAR(255) NOT NULL,
Peso FLOAT NOT NULL,
PrecoCusto MONEY NOT NULL,
PrecoVenda MONEY NOT NULL,
FornecedorId INT FOREIGN KEY REFERENCES Fornecedores(FornecedorId)NOT NULL
);
CREATE TABLE Usuarios(
UsuarioId INT PRIMARY KEY IDENTITY NOT NULL,
Email VARCHAR(255) NOT NULL UNIQUE,
Senha VARCHAR(30) NOT NULL
);
CREATE TABLE Fornecedores(
FornecedorId INT PRIMARY KEY IDENTITY NOT NULL,
Cnpj VARCHAR(20) UNIQUE NOT NULL,
RazaoSocial VARCHAR(255) NOT NULL,
NomeFantasia VARCHAR(255) NOT NULL,
Endereco VARCHAR(255) NOT NULL,
UsuarioVinculado INT FOREIGN KEY REFERENCES Usuarios(UsuarioId) NOT NULL
);
|
import { getRandomNumber, getRandomColor } from './utils';
const registerTicket = function () {
const newTicket = {
number: getRandomNumber(),
color: getRandomColor()
};
this.setState((prevState) => {
prevState.tickets.push(newTicket);
return {
tickets: prevState.tickets,
remainingTickets: --prevState.remainingTickets
}
});
}
const removeTicket = function (index) {
this.setState((prevState) => {
prevState.tickets.splice(index, 1);
return {
tickets: prevState.tickets,
remainingTickets: ++prevState.remainingTickets
}
});
}
const finish = function () {
this.setState({ finished: true });
}
const reset = function () {
this.setState({
winningNumber: getRandomNumber(),
tickets: [],
remainingTickets: 5,
finished: false
});
}
export { registerTicket, removeTicket, finish, reset } |
package io.github.durun.lateko.model.inline
import io.github.durun.lateko.model.Element
import io.github.durun.lateko.model.Format
interface InlineElement : Element {
fun <R> accept(visitor: InlineVisitor<R>): R
fun renderedAs(format: Format): String
} |
import classes from "../Styles/Header.module.css"
import { NavLink } from "react-router-dom";
import logo from "../../src/img/Titile_logo.png"
import styles from "../Styles/Header.module.css"
import React from "react";
type Props_type = {
logout? : ()=>void,
auth? : boolean
}
const path = logo;
const Header_isAuthTrue :React.FC<Props_type> = (props) => {
return (
<section className={classes.Header}>
<div className={styles.Profile_mini}>
<img className={styles.logo} src={logo} alt="" />
</div>
<h1></h1>
<div className={styles.Head_nav_container}>
<ul className="nav">
<li>
<input type="text" placeholder="Find on page" id="Search_input"/>
<button type="button" id="search_button">Search</button>
</li>
<li>
<NavLink to="login/">
<button type="button" onClick={props.logout}>Log Out</button>
</NavLink>
</li>
</ul>
</div>
<hr />
</section>
)
}
const Header_isAuthFalse : React.FC<Props_type>= (props) => {
return (
<section className={classes.Header}>
<h1></h1>
<img className={styles.logo} src={logo} alt="" />
<div className={classes.Head_nav_container}>
<ul className="nav">
<li>
<input type="text" placeholder="Find on page" id="Search"/>
<button type="button" id="search_btn">Search</button>
</li>
<li>
<NavLink to="login/">
<button type="button">Log in</button>
</NavLink>
</li>
</ul>
</div>
<hr />
</section>
)
}
const Header:React.FC<Props_type> = (props) => {
if(props.auth === true){
return <Header_isAuthTrue logout={props.logout} />
}else{
return <Header_isAuthFalse />
}
};
export default Header; |
#!/bin/bash
cat >~/.config/user-dirs.dirs <<EOF
XDG_DESKTOP_DIR="$HOME/Desktop"
XDG_DOWNLOAD_DIR="$HOME/Downloads"
XDG_TEMPLATES_DIR="$HOME/Templates"
XDG_PUBLICSHARE_DIR="$HOME/Public"
XDG_DOCUMENTS_DIR="$HOME/Documents"
XDG_MUSIC_DIR="$HOME/Music"
XDG_PICTURES_DIR="$HOME/Pictures"
XDG_VIDEOS_DIR="$HOME/Video"
EOF
|
<?php
namespace Modules\Announcement\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Announcement\Repositories\AnnouncementRepository;
use Modules\Announcement\Http\Requests\CreateAnnouncementRequest;
use Modules\Announcement\Http\Requests\UpdateAnnouncementRequest;
use Modules\Helper\Helpers\AdminHelper;
/**
* Class AnnouncementController
*
* Announcement create, update, delete and view.
*
* PHP version 7.1.3
*
* @category Administration
* @package Modules\Announcement
* @author Vipul Patel <[email protected]>
* @author Another Author <[email protected]>
* @copyright 2019 Chetsapp Group
* @license Chetsapp Private Limited
* @version Release: @1.0@
* @link http://chetsapp.com
* @since Class available since Release 1.0
*/
class AnnouncementController extends Controller
{
protected $announcementRepo;
/**
* Instantiate a new repository instance.
*
* @param AnnouncementRepository $announcement [Object]
*
* @return void
*/
public function __construct(AnnouncementRepository $announcement)
{
$this->announcementRepo = $announcement;
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
return $this->announcementRepo->findAll();
}
/**
* Display a listing of the resource.
*
* @param Request $request [Request for get announcement]
*
* @return Response
*/
public function getAllAnnouncements(Request $request)
{
return $this->announcementRepo->getAllAnnouncements($request);
}
/**
* Show the specified resource.
*
* @param Int $id [Row id]
*
* @return Response
*/
public function show($id)
{
return $this->announcementRepo->findById($id);
}
/**
* Store a newly created resource in storage.
*
* @param CreateAnnouncementRequest $request [Request for create announcement]
*
* @return Response
*/
public function store(CreateAnnouncementRequest $request)
{
// --
// Check role/permission
if (!AdminHelper::can_action(13, 'created')) {
return response()->json("Access denied", 403);
}
if ($this->announcementRepo->create($request)) {
return response()->json('success');
} else {
return response()->json('error');
}
}
/**
* Update the specified resource in storage.
*
* @param Request $request [Request for update announcement]
* @param int $id [Row id]
*
* @return Response
*/
public function update(UpdateAnnouncementRequest $request, $id)
{
// --
// Check role/permission
if (!AdminHelper::can_action(13, 'edited')) {
return response()->json("Access denied", 403);
}
if ($this->announcementRepo->update($request, $id)) {
return response()->json('success');
} else {
return response()->json('error');
}
}
/**
* Remove the specified resource from storage.
*
* @param Request $request [Request for destroy announcement]
* @param int $id [Row id]
*
* @return Response
*/
public function destroy(Request $request, $id)
{
// --
// Check role/permission
if (!AdminHelper::can_action(13, 'deleted')) {
return response()->json("Access denied", 403);
}
if ($this->announcementRepo->delete($request, $id)) {
return response()->json('success');
} else {
return response()->json('error');
}
}
}
|
/*
* Copyright © 2016-2018 European Support Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openecomp.sdcrests.vsp.rest.services;
import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER;
import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME;
import static org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod.NetworkPackage;
import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID;
import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME;
import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.SUBMIT_DESCRIPTION;
import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_ID;
import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_NAME;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.inject.Named;
import javax.ws.rs.core.Response;
import org.apache.commons.collections4.MapUtils;
import org.openecomp.core.dao.UniqueValueDaoFactory;
import org.openecomp.core.util.UniqueValueUtil;
import org.openecomp.sdc.activitylog.ActivityLogManager;
import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
import org.openecomp.sdc.activitylog.dao.type.ActivityType;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.common.errors.ErrorCode;
import org.openecomp.sdc.common.errors.Messages;
import org.openecomp.sdc.datatypes.error.ErrorMessage;
import org.openecomp.sdc.datatypes.model.ItemType;
import org.openecomp.sdc.healing.factory.HealingManagerFactory;
import org.openecomp.sdc.itempermissions.PermissionsManager;
import org.openecomp.sdc.itempermissions.PermissionsManagerFactory;
import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.openecomp.sdc.notification.dtos.Event;
import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
import org.openecomp.sdc.notification.services.NotificationPropagationManager;
import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
import org.openecomp.sdc.versioning.AsdcItemManager;
import org.openecomp.sdc.versioning.AsdcItemManagerFactory;
import org.openecomp.sdc.versioning.VersioningManager;
import org.openecomp.sdc.versioning.VersioningManagerFactory;
import org.openecomp.sdc.versioning.dao.types.Version;
import org.openecomp.sdc.versioning.dao.types.VersionStatus;
import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
import org.openecomp.sdc.versioning.types.Item;
import org.openecomp.sdc.versioning.types.ItemStatus;
import org.openecomp.sdc.versioning.types.NotificationEventTypes;
import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
import org.openecomp.sdcrests.item.types.ItemCreationDto;
import org.openecomp.sdcrests.item.types.VersionDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Named
@Service("vendorSoftwareProducts")
@Scope(value = "prototype")
public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
private static final String VALIDATION_VSP_NAME = "validationOnlyVspName";
private static final String VALIDATION_VSP_USER = "validationOnlyVspUser";
private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
private static final String ATTACHMENT_FILENAME = "attachment; filename=";
private static final String SUBMIT_HEALED_VERSION_ERROR = "VSP Id %s: Error while submitting version %s created based on Certified version %s for healing purpose.";
private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class);
private static final Object VALIDATION_VSP_CACHE_LOCK = new Object();
private static ItemCreationDto cachedValidationVsp;
private final AsdcItemManager itemManager = AsdcItemManagerFactory.getInstance().createInterface();
private final PermissionsManager permissionsManager = PermissionsManagerFactory.getInstance().createInterface();
private final VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface();
private final VendorSoftwareProductManager vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
private final ActivityLogManager activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
private final NotificationPropagationManager notifier = NotificationPropagationManagerFactory.getInstance().createInterface();
private final UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface());
@Override
public Response createVsp(VspRequestDto vspRequestDto, String user) {
ItemCreationDto vspCreationDto = createVspItem(vspRequestDto, user);
return Response.ok(vspCreationDto).build();
}
private ItemCreationDto createVspItem(VspRequestDto vspRequestDto, String user) {
OnboardingMethod onboardingMethod = null;
try {
onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod());
} catch (IllegalArgumentException e) {
LOGGER.error("Error while creating VSP. Message: " + e.getMessage());
throwUnknownOnboardingMethodException(e);
}
ItemCreationDto itemCreationDto = null;
if (onboardingMethod == NetworkPackage || onboardingMethod == OnboardingMethod.Manual) {
itemCreationDto = createItem(vspRequestDto, user, onboardingMethod);
} else {
throwUnknownOnboardingMethodException(new IllegalArgumentException("Wrong parameter Onboarding Method"));
}
return itemCreationDto;
}
private ItemCreationDto createItem(VspRequestDto vspRequestDto, String user, OnboardingMethod onboardingMethod) {
Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class);
item.setType(ItemType.vsp.name());
item.setOwner(user);
item.setStatus(ItemStatus.ACTIVE);
item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name());
uniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
item = itemManager.create(item);
uniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
Version version = versioningManager.create(item.getId(), new Version(), null);
VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class);
vspDetails.setId(item.getId());
vspDetails.setVersion(version);
vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod());
vendorSoftwareProductManager.createVsp(vspDetails);
versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName());
ItemCreationDto itemCreationDto = new ItemCreationDto();
itemCreationDto.setItemId(item.getId());
itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class));
activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version, ActivityType.Create, user, true, "", ""));
return itemCreationDto;
}
private void throwUnknownOnboardingMethodException(IllegalArgumentException e) {
ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder.getInvalidOnboardingMethodErrorBuilder();
throw new CoreException(onboardingMethodUpdateErrorCode, e);
}
@Override
public Response listVsps(String versionStatus, String itemStatus, String user) {
GenericCollectionWrapper<VspDetailsDto> results = new GenericCollectionWrapper<>();
MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto();
getVspList(versionStatus, itemStatus, user).forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class)));
return Response.ok(results).build();
}
@Override
public Response getVsp(String vspId, String versionId, String user) {
Version version = versioningManager.get(vspId, new Version(versionId));
VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
try {
HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, version, ItemType.vsp, false).ifPresent(healedVersion -> {
vspDetails.setVersion(healedVersion);
if (version.getStatus() == VersionStatus.Certified) {
submitHealedVersion(vspDetails, versionId, user);
}
});
} catch (Exception e) {
LOGGER.error(String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId), e);
}
VspDetailsDto vspDetailsDto = new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class);
addNetworkPackageInfo(vspId, vspDetails.getVersion(), vspDetailsDto);
return Response.ok(vspDetailsDto).build();
}
@Override
public Response getLatestVsp(final String vspId, final String user) {
final List<Version> versions = versioningManager.list(vspId);
final Version version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
.max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
.orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
return getVsp(vspId, version.getId(), user);
}
private void submitHealedVersion(VspDetails vspDetails, String baseVersionId, String user) {
try {
if (vspDetails.getVlmVersion() != null) {
// sync vlm if not exists on user space
versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion());
}
submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user).ifPresent(validationResponse -> {
throw new IllegalStateException("Certified vsp after healing failed on validation");
});
vendorSoftwareProductManager.createPackage(vspDetails.getId(), vspDetails.getVersion());
} catch (Exception ex) {
LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(), baseVersionId), ex);
}
}
@Override
public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, String user) {
VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
vspDetails.setId(vspId);
vspDetails.setVersion(new Version(versionId));
vendorSoftwareProductManager.updateVsp(vspDetails);
updateVspItem(vspId, vspDescriptionDto);
return Response.ok().build();
}
@Override
public Response deleteVsp(String vspId, String user) {
Item vsp = itemManager.get(vspId);
if (!vsp.getType().equals(ItemType.vsp.name())) {
throw new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage(String.format("Vsp with id %s does not exist.", vspId)).build()));
}
Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) {
versioningManager.list(vspId).forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
itemManager.delete(vsp);
permissionsManager.deleteItemPermissions(vspId);
uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
notifyUsers(vspId, vsp.getName(), null, null, user, NotificationEventTypes.DELETE);
return Response.ok().build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build();
}
}
@Override
public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, String vspId, String versionId, String user)
throws IOException {
Version version = new Version(versionId);
if (request.getAction() == VendorSoftwareProductAction.Submit) {
if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
}
String message = request.getSubmitRequest() == null ? "Submit" : request.getSubmitRequest().getMessage();
Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
if (validationResponse.isPresent()) {
ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
.applyMapping(validationResponse.get(), ValidationResponseDto.class);
return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto).build();
}
notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
} else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
return createPackage(vspId, version);
}
return Response.ok().build();
}
@Override
public Response getValidationVsp(String user) {
ItemCreationDto validationVsp = retrieveValidationVsp();
return Response.ok(validationVsp).build();
}
private ItemCreationDto retrieveValidationVsp() {
synchronized (VALIDATION_VSP_CACHE_LOCK) {
if (cachedValidationVsp != null) {
return cachedValidationVsp;
}
VspRequestDto validationVspRequest = new VspRequestDto();
validationVspRequest.setOnboardingMethod(NetworkPackage.toString());
validationVspRequest.setName(VALIDATION_VSP_NAME);
try {
cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER);
return cachedValidationVsp;
} catch (CoreException vspCreateException) {
LOGGER.debug("Failed to create validation VSP", vspCreateException);
Predicate<Item> validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME
.equals(item.getName());
String validationVspId = itemManager.list(validationVspFilter).stream().findFirst().orElseThrow(() -> new IllegalStateException(
"Vsp with name " + VALIDATION_VSP_NAME + " does not exist even though the name exists according to " + "unique value util"))
.getId();
Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
cachedValidationVsp = new ItemCreationDto();
cachedValidationVsp.setItemId(validationVspId);
cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
return cachedValidationVsp;
}
}
}
@Override
public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
byte[] orchestrationTemplateFile = vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
if (orchestrationTemplateFile == null || orchestrationTemplateFile.length == 0) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
return response.build();
}
@Override
public Response listPackages(String status, String category, String subCategory, String user) {
List<String> vspsIds = getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user).stream().map(Item::getId)
.collect(Collectors.toList());
List<PackageInfo> packageInfoList = vendorSoftwareProductManager.listPackages(category, subCategory);
packageInfoList = packageInfoList.stream().filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())).collect(Collectors.toList());
GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
if (packageInfoList != null) {
for (PackageInfo packageInfo : packageInfoList) {
results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
}
}
return Response.ok(results).build();
}
@Override
public Response getTranslatedFile(String vspId, String versionId, String user) {
final List<Version> versions = versioningManager.list(vspId);
final Version version;
if (versionId == null) {
version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
.max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
.orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
} else {
version = versions.stream()
.filter(ver -> versionId.equals(ver.getName()) || versionId.equals(ver.getId()))
.findFirst()
.orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId, versionId).build()));
if (version.getStatus() != VersionStatus.Certified) {
throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
}
}
File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
Response.ResponseBuilder response = Response.ok(zipFile);
if (zipFile == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
return response.build();
}
@Override
public Response getQuestionnaire(String vspId, String versionId, String user) {
QuestionnaireResponse questionnaireResponse = vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
if (questionnaireResponse.getErrorMessage() != null) {
return Response.status(Response.Status.EXPECTATION_FAILED)
.entity(new MapQuestionnaireResponseToQuestionnaireResponseDto().applyMapping(questionnaireResponse, QuestionnaireResponseDto.class))
.build();
}
QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
.applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
return Response.ok(result).build();
}
@Override
public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) {
vendorSoftwareProductManager.updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
return Response.ok().build();
}
@Override
public Response heal(String vspId, String versionId, String user) {
HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
return Response.ok().build();
}
@Override
public Response getVspInformationArtifact(String vspId, String versionId, String user) {
File textInformationArtifact = vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
Response.ResponseBuilder response = Response.ok(textInformationArtifact);
if (textInformationArtifact == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
return response.build();
}
@Override
public Response listComputes(String vspId, String version, String user) {
Collection<ComputeEntity> computes = vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
for (ComputeEntity compute : computes) {
results.add(mapper.applyMapping(compute, VspComputeDto.class));
}
return Response.ok(results).build();
}
private void updateVspItem(String vspId, VspDescriptionDto vspDescriptionDto) {
Item retrievedItem = itemManager.get(vspId);
Item item = new MapVspDescriptionDtoToItem().applyMapping(vspDescriptionDto, Item.class);
item.setId(vspId);
item.setType(retrievedItem.getType());
item.setOwner(retrievedItem.getOwner());
item.setStatus(retrievedItem.getStatus());
item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
item.setCreationTime(retrievedItem.getCreationTime());
item.setModificationTime(new Date());
item.addProperty(VspItemProperty.ONBOARDING_METHOD, retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD));
itemManager.update(item);
}
private Optional<ValidationResponse> submit(String vspId, Version version, String message, String user) throws IOException {
VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
if (vspDetails.getVlmVersion() != null) {
vspDetails.setVlmVersion(versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion()));
}
ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspDetails);
Map<String, List<ErrorMessage>> compilationErrors = vendorSoftwareProductManager.compile(vspId, version);
if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
activityLogManager
.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, "Failed on validation before submit", ""));
return Optional.of(validationResponse);
}
versioningManager.submit(vspId, version, message);
activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
return Optional.empty();
}
private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) {
Map<String, Object> eventProperties = new HashMap<>();
eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
eventProperties.put(ITEM_ID, itemId);
if (version != null) {
eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName());
eventProperties.put(VERSION_ID, version.getId());
}
eventProperties.put(SUBMIT_DESCRIPTION, message);
eventProperties.put(PERMISSION_USER, userName);
Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
try {
notifier.notifySubscribers(syncEvent, userName);
} catch (Exception e) {
LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId, e);
}
}
private Response createPackage(String vspId, Version version) throws IOException {
Version retrievedVersion = versioningManager.get(vspId, version);
if (retrievedVersion.getStatus() != VersionStatus.Certified) {
throw new CoreException(new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version).build());
}
PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
return Response.ok(packageInfo == null ? null : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)).build();
}
private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
Optional<OrchestrationTemplateCandidateData> candidateInfo = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
.getInfo(vspId, version);
if (candidateInfo.isPresent()) {
if (candidateInfo.get().getValidationDataStructure() != null) {
vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure());
}
vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName());
vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix());
} else {
OrchestrationTemplateEntity orchestrationTemplateInfo = vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo.getFileSuffix())) {
if (orchestrationTemplateInfo.getValidationDataStructure() != null) {
vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
}
vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
}
}
}
private boolean userHasPermission(String itemId, String userId) {
return permissionsManager.getUserItemPermission(itemId, userId)
.map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false);
}
private Predicate<Item> createItemPredicate(String versionStatus, String itemStatus, String user) {
Predicate<Item> itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
if (ItemStatus.ARCHIVED.name().equals(itemStatus)) {
itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus()));
} else {
itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus()));
if (VersionStatus.Certified.name().equals(versionStatus)) {
itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified));
} else if (VersionStatus.Draft.name().equals(versionStatus)) {
itemPredicate = itemPredicate
.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user));
}
}
return itemPredicate;
}
private List<Item> getVspList(String versionStatus, String itemStatus, String user) {
Predicate<Item> itemPredicate = createItemPredicate(versionStatus, itemStatus, user);
return itemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
.collect(Collectors.toList());
}
private class SyncEvent implements Event {
private final String eventType;
private final String originatorId;
private final Map<String, Object> attributes;
private final String entityId;
SyncEvent(String eventType, String originatorId, Map<String, Object> attributes, String entityId) {
this.eventType = eventType;
this.originatorId = originatorId;
this.attributes = attributes;
this.entityId = entityId;
}
@Override
public String getEventType() {
return eventType;
}
@Override
public String getOriginatorId() {
return originatorId;
}
@Override
public Map<String, Object> getAttributes() {
return attributes;
}
@Override
public String getEntityId() {
return entityId;
}
}
}
|
package es.nimio.nimiogcs.jpa.entidades.artefactos.directivas;
import java.util.Map;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
import es.nimio.nimiogcs.Strings;
@Entity
@Access(AccessType.FIELD)
@Table(name = "GCS_DIRECTIVAS_COORMAVEN")
@DiscriminatorValue(value = "COOR_MAVEN")
public class DirectivaCoordenadasMaven extends DirectivaBase {
public DirectivaCoordenadasMaven() {}
// --------------------------------------
// Estado
// --------------------------------------
@Column(name="ID_GRUPO", nullable=false, length=100)
private String idGrupo;
@Column(name="ID_ARTEFACTO", nullable=false, length=100)
private String idArtefacto;
@Column(name="VERSION", nullable=false, length=30)
private String version;
@Column(name="EMPAQUETADO", nullable=false, length=15)
private String empaquetado;
@Column(name="CLASIFICADOR", nullable=true, length=100)
private String clasificador;
// --------------------------------------
// Lectura y escritura del estado
// --------------------------------------
public String getIdGrupo() {
return idGrupo;
}
public void setIdGrupo(String idGrupo) {
this.idGrupo = idGrupo;
}
public String getIdArtefacto() {
return idArtefacto;
}
public void setIdArtefacto(String idArtefacto) {
this.idArtefacto = idArtefacto;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getEmpaquetado() {
return empaquetado;
}
public void setEmpaquetado(String empaquetado) {
this.empaquetado = empaquetado;
}
public String getClasificador() {
return clasificador;
}
public void setClasificador(String clasificador) {
this.clasificador = clasificador;
}
public String getCoordenadaFinal() {
return
getIdGrupo()
+ ":" + getIdArtefacto()
+ ":" + getVersion()
+ ":" + getEmpaquetado()
+ (Strings.isNullOrEmpty(getClasificador())? "" : ":" + getClasificador());
}
// -------------------------------------
// Método de utilidad para generar
// un diccionario con todos los valores
// -------------------------------------
public Map<String, String> getMapaValores() {
Map<String, String> mapa = super.getMapaValores();
mapa.put("ID_GRUPO", idGrupo);
mapa.put("ID_ARTEFACTO", idArtefacto);
mapa.put("VERSION", version);
mapa.put("EMPAQUETADO", empaquetado);
mapa.put("CLASIFICADOR", clasificador);
return mapa;
}
}
|
@extends('layouts.app')
@section('title')
<title>Quản trị danh mục phim </title>
@endsection
@section('content')
<div class="container">
<h2 style="text-align: center">Chào mừng bạn đến với trang quản lí danh mục</h2>
<table class="table table-striped table-dark" style="background-color: white; color: black">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Tên Danh Mục</th>
<th scope="col">Mô Tả</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
@foreach ($allCate as $cate )
<tr>
<th scope="row">{{$cate->id}}</th>
<td>{{$cate->c_name}}</td>
<td>{{$cate->c_description}}</td>
<td>@mdo</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection |
/* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */
/* Permission to use this code is granted as long as the copyright */
/* notice remains in place. */
/* =========================== sim_debug.c ================================= */
/* Main (driving) routine of the Simulator/Debugger. */
/* to compile (the simulator/debugger) use: */
/* cc -o run sim_debug.c sym_tab.c stringI.c convert.c memory.c */
/* machine.c debugger.c loadexe.c print.c instruct.c format.c */
/* interupt.c instruct2.c -g -lm */
#include <stdio.h>
#include "constants.h"
#include "boolean.h"
#include "memory.h"
#include "machine.h"
#include "debugger.h"
#include "loadexe.h"
#include "print.h"
/* --------------------------------- Globals ------------------------------ */
/* MAIN_ROUTINE Name of (program) module declared with */
/* a START (main routine). */
char MAIN_ROUTINE[LABEL_SIZE_1+1];
/* -------------------------------- main ---------------------------------- */
int main(int argc,char **argv)
{
FILE *INPUT_STREAM; /* Input file stream */
BOOLEAN DEBUG_MODE = TRUE_1; /* Flag that can turn off the debugging */
/* feature. */
BOOLEAN ERROR = FALSE_1; /* Was there an error loading the */
/* executable? */
if (argc == 1) (void) printf("usage: run [-n] file\n");
else {
int ARGUMENT = 1; /* Which argument of the command line */
/* currently processing. */
BOOLEAN FLAG; /* Just a temporary boolean. */
/* --------------------------------- Process command directives */
if (ARGUMENT < argc) FLAG = (argv[ARGUMENT][0] == '-');
while ( (ARGUMENT < argc) && FLAG) {
if (!strcmp(argv[ARGUMENT],"-n")) DEBUG_MODE = FALSE_1;
else
(void) printf("Illegal command directive, '%s'. Ignoring.\n",
argv[ARGUMENT]);
if (ARGUMENT < argc) ARGUMENT ++;
if (ARGUMENT < argc) FLAG = (argv[ARGUMENT][0] == '-');
}
if (ARGUMENT >= argc)
(void) printf("run: requires a file name.\n");
INIT_SYM_TAB(&SYM_TAB); /* Initialize the symbol table */
CREATE_MEMORY(&MEMORY); /* Create/initialize the main memory. */
if ( (INPUT_STREAM = fopen(argv[ARGUMENT],"r")) == NULL) {
(void) printf("%s: No such file or directory\n",argv[ARGUMENT]);
} else {
/* --------------------------------- Have a valid file: run it */
LOAD(DEBUG_MODE,&ERROR,INPUT_STREAM);
if (!ERROR) DEBUGGER(DEBUG_MODE);
(void) fclose(INPUT_STREAM);
}
}
return 0;
}
|
systemctl --user enable onedrive
systemctl --user start onedrive
sudo apt install dphys-swapfile
sudo dphys-swapfile swapoff && \
sudo dphys-swapfile uninstall && \
sudo systemctl disable dphys-swapfile |
package com.fitbit.goldengate.bt.gatt.server.services.gattlink
import android.bluetooth.BluetoothGattService
import java.util.UUID
/**
* Represents the Gattlink Service hosted on mobile that allows reliable streaming of
* arbitrary data over a BLE connection using the GATT protocol, with support for BLE/GATT stacks
* that don't always have the necessary support for writing GATT characteristics back-to-back
* without dropping data
*
* Fitbit has registered the Gattlink Service to SIG with 16-bit UUID 0xFD62, which has a different
* service UUID from original one.
* https://www.bluetooth.com/specifications/assigned-numbers/16-bit-uuids-for-members/
*/
class FitbitGattlinkService : BluetoothGattService(
uuid,
BluetoothGattService.SERVICE_TYPE_PRIMARY) {
init {
addCharacteristic(ReceiveCharacteristic())
addCharacteristic(TransmitCharacteristic())
}
companion object {
val uuid: UUID = UUID.fromString("0000FD62-0000-1000-8000-00805F9B34FB")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.