text stringlengths 184 4.48M |
|---|
import Handlebars from 'handlebars/dist/handlebars';
import { v4 } from 'uuid';
type Tv4 = () => string;
import { EventBus } from './event-bus';
export type TEvents = { [key: string]: EventListenerOrEventListenerObject };
enum Events {
flowCDM = 'flow:component-did-mount',
flowCSU = 'flow:component-should-update',
flowCDU = 'flow:component-did-update',
flowRender = 'flow:render',
}
export type TProps = {
withInternalID?: boolean;
events?: TEvents;
attrs?: { [key: string]: string };
}
export type TagName = keyof HTMLElementTagNameMap;
export class Component<Props extends TProps = Record<string, unknown> & { attrs?: { [key: string]: string } }> {
readonly #element: HTMLElement;
readonly props: Props;
readonly children: { [key: string]: Component | Component[] };
readonly #id: string = (v4 as Tv4)();
eventBus: EventBus = new EventBus();
constructor(tagName: TagName = 'div', propsWithChildren: Props = <Props>{}) {
const { children, props } = this.#getChildren(propsWithChildren);
this.children = children;
this.props = this.#makePropsProxy(props);
this.#element = this.#createDocumentElement(tagName);
this.eventBus.on(Events.flowCSU, this.#componentShouldUpdate.bind(this));
this.eventBus.on(Events.flowRender, this.#render.bind(this));
this.eventBus.on(Events.flowCDU, this.#componentDidUpdate.bind(this));
this.eventBus.on(Events.flowCDM, this.#componentDidMount.bind(this));
this.eventBus.emit(Events.flowRender);
this.eventBus.emit(Events.flowCDU);
this.eventBus.emit(Events.flowCDM);
}
#componentDidMount(): void {
this.componentDidMount();
Object.values(this.children).forEach((child) => {
if (Array.isArray(child)) {
child.forEach((ch) => {
ch.dispatchComponentDidMount();
});
} else {
child.dispatchComponentDidMount();
}
});
}
public componentDidMount(): void {
return;
}
public dispatchComponentDidMount(): void {
this.eventBus.emit(Events.flowCDM);
}
#componentShouldUpdate(/*oldProps: Props, newProps: Props*/): void {
if (this.componentShouldUpdate(/*oldProps, newProps*/)) {
this.#render();
this.#componentDidUpdate();
}
}
public componentShouldUpdate(/*oldProps: Props, newProps: Props*/): boolean {
return true;
}
#componentDidUpdate(): void {
this.#render();
this.componentDidUpdate();
}
public componentDidUpdate(): void {
return undefined;
}
public setProps(nextProps: Props): void {
if (nextProps) {
Object.assign(this.props, nextProps);
this.eventBus.emit(Events.flowCSU);
}
}
#render(): void {
const block = this.render();
this.#removeEvents();
this.#element.innerHTML = '';
this.#element.appendChild(block);
this.#addEvents();
this.#addAttributes();
}
public render(): DocumentFragment {
return this.#createDocumentElement('template').content;
}
public get content(): HTMLElement {
return this.#element;
}
#makePropsProxy(props: Props): Props {
return new Proxy<Props>(props, {
get(target: Props, p: string): unknown {
const value: unknown = target[p as keyof TProps];
return typeof value === 'function' ? (value as () => void).bind(target) : value;
},
set: (target: Props, prop: string, value: unknown): boolean => {
Reflect.set(target, prop, value);
this.eventBus.emit(Events.flowCDU, { ...target }, target);
return true;
},
deleteProperty() {
throw new Error('нет доступа');
},
});
}
#createDocumentElement<K extends TagName>(
tagName: K
): HTMLElementTagNameMap[K] {
const element = document.createElement<K>(tagName);
if (this.props.withInternalID) {
element.setAttribute('data-id', this.#id);
}
return document.createElement<K>(tagName);
}
public show(): void {
this.#element.removeAttribute('hidden');
}
public hide(): void {
this.#element.hidden = true;
}
#getChildren(
propsWithChildren: Props
): { children: { [key: string]: Component<TProps> }, props: Props } {
const children: { [key: string]: Component<TProps> } = {};
const props: Props & { [key: string]: unknown } = <Props & { [key: string]: unknown }>{};
Object.entries(propsWithChildren).forEach(([key, value]) => {
if (value instanceof Component) {
Reflect.set(children, key, value);
} else if (Array.isArray(value) && value.every(v => v instanceof Component)) {
Reflect.set(children, key, value);
} else {
Reflect.set(props, key, value);
}
});
return { children, props };
}
public compile<P extends object = Props>(template: string, props: P = <P>{}): DocumentFragment {
const propsAndStubs = { ...props };
Object.entries(this.children).forEach(([key, child]) => {
if (Array.isArray(child)) {
Reflect.set(propsAndStubs, key, child.map(ch => `<div data-id="${ch.#id}"></div>`));
return;
}
Reflect.set(propsAndStubs, key, `<div data-id="${child.#id}"></div>`);
});
const fragment = this.#createDocumentElement('template');
fragment.innerHTML = Handlebars.compile(template)(propsAndStubs);
Object.values(this.children).forEach((child) => {
if (Array.isArray(child)) {
child.forEach((ch) => {
const stub = fragment.content.querySelector(`[data-id="${ch.#id}"]`);
stub?.replaceWith(ch.#element);
});
} else {
const stub = fragment.content.querySelector(`[data-id="${child.#id}"]`);
stub?.replaceWith(child.#element);
}
});
return fragment.content;
}
#addEvents = this.#events('addEventListener');
#removeEvents = this.#events('removeEventListener');
#events(eventChangeListener: 'addEventListener' | 'removeEventListener'): () => void {
return () => {
const { events = {} } = this.props;
Object.keys(events).forEach((eventName) => {
this.#element[eventChangeListener](eventName, events[eventName]);
});
};
}
#addAttributes(): void {
const { attrs = {} } = this.props;
Object.keys(attrs).forEach((attrName: string) => {
this.#element.setAttribute(attrName, attrs[attrName]);
});
}
} |
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../../../bower_components/polymer/polymer.html">
<link rel="import" href="../../../bower_components/app-layout/app-header/app-header.html">
<link rel="import" href="../../../bower_components/app-layout/app-header-layout/app-header-layout.html">
<link rel="import" href="../../../bower_components/app-layout/app-toolbar/app-toolbar.html">
<link rel="import" href="../../../bower_components/iron-ajax/iron-ajax.html">
<link rel="imort" href="../../../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../../../bower_components/paper-material/paper-material.html">
<link rel="import" href="../../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../../bower_components/paper-fab/paper-fab.html">
<link rel="import" href="../../../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../../../bower_components/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="../../../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../../bower_components/neon-animation/neon-shared-element-animatable-behavior.html">
<link rel="import" href="../../../bower_components/neon-animation/animations/scale-up-animation.html">
<link rel="import" href="../../../bower_components/neon-animation/animations/fade-out-animation.html">
<link rel="import" href="../../../bower_components/neon-animation/animations/ripple-animation.html">
<link rel="import" href="../../../bower_components/neon-animation/animations/reverse-ripple-animation.html">
<link rel="import" href="../../behaviours/cv-section.html">
<link rel="import" href="../../../bower_components/re-captcha/re-captcha.html">
<dom-module id="cv-contact">
<template>
<style>
:host {
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
paper-fab {
position: absolute;
bottom: -32px;
right: 24px;
}
.with-fab {
padding-bottom: 64px;
}
.g-recaptcha {
padding-top: 16px;
}
.header {
background-color: #fac800;
}
paper-material {
border-radius: 2px;
margin: 8px auto;
padding: 16px 0 32px 0;
box-shadow:0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);
width: calc(98.66% - 32px);
background: white;
}
#fixed {
position: fixed;
top: 0;
left: 0;
height: 100vh;
width: 100vw;
background-color: #fce8b2;
}
/* Breakpoints */
/* Small */
@media (max-width: 600px) {
.page-title {
font-size: 24px!important;
}
paper-material {
--menu-container-display: none;
width: calc(97.33% - 32px);
padding-left: 16px;
padding-right: 16px;
}
}
/* Tablet+ */
@media (min-width: 601px) {
paper-material {
width: calc(98% - 64px);
xmargin-bottom: 32px;
padding-left: 30px;
padding-right: 30px;
}
}
</style>
<div id="fixed"></div>
<app-header id="hero" class="header">
<app-toolbar>
<a href="/"><paper-icon-button icon="arrow-back" drawer-toggle></paper-icon-button></a>
<div title>Contact Alex</div>
</app-toolbar>
</app-header>
<neon-animated-pages id="content" attr-for-selected="data-route" selected="{{route}}" entry-animation="slide-from-right-animation" exi-animation="slitde-left-animation">
<neon-animatable data-route="form" tabindex="-1">
<div class="content">
<paper-material id="form" class="">
<p>If you've found an error, would like to suggest a feature or just want to say hi.</p>
<form>
<paper-input id="name" label="Name" type="text" auto-validate required error-message="Your name is required" value="{{name}}"></paper-input>
<paper-input id="email" label="Email" type="email" allowedPattern="[a-zA-z0-9\.-]+@[a-zA-Z0-9-]+" auto-validate required error-message="A valid email is required" value="{{email}}"></paper-input>
<paper-textarea id="message" label="Message" required="true" error-message="Don't forget to say something!" maxlength="1000" value="{{message}}"></paper-textarea>
<re-captcha id="recaptcha" class="g-recaptcha" sitekey="6LdFTh0TAAAAAAr-BQ0dJfe4r5_MHNKY8hO5Hn1u" response="{{grecaptcha}}"></re-captcha>
</form>
<paper-fab id="send" icon="send"></paper-fab>
</paper-material>
</div>
</neon-animatable>
<neon-animatable data-route="sending" tabindex="-1">
<div class="content">
<paper-material class="layout vertical center">
<paper-spinner-lite alt="Empty alt" active></paper-spinner-lite>
<div>Sending Message</div>
</paper-material>
</div>
</neon-animatable>
<neon-animatable data-route="sent" tabindex="-1">
<div class="content">
<paper-material class="with-fab">
<div>Message sent. Thank you for getting in touch.</div>
<paper-fab id="done" icon="done"></paper-fab>
</paper-material>
</div>
</neon-animatable>
</neon-animated-pages>
<iron-ajax id="sendmail"
url="https://ttt-chicken.appspot.com/mail/cfl"
method="POST"
contentType="application/x-www-form-urlencoded"
body="name=[[name]]&email=[[email]]&message=[[message]]&g-recaptcha-response=[[grecaptcha]]"
verbose
></iron-ajax>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'cv-contact',
behaviors: [
CvBehaviors.SectionBehavior
],
listeners: {
'send.tap': 'validateMessage',
'sendmail.response': 'processResponse',
'recaptcha.captcha-response': 'forceFocus',
'done.tap': 'showForm'
},
properties: {
email: {
type: String,
notify: true
},
name: {
type: String,
notify: true
},
message: {
type: String,
notify: true
},
grecaptcha: {
type: String,
notify: true
},
route: {
type: String,
value: 'form',
notify: true
}
},
_markErrors: function() {
if (!this.name) {
this.$.name.invalid = true;
}
if (!this.email) {
this.$.email.invalid = true;
}
if (!this.message) {
this.$.message.invalid = true;
}
},
validateMessage: function() {
this.forceFocus();
if (!this.grecaptcha
|| !this.name
|| !this.email
|| !this.message) {
this._markErrors();
return;
}
this.route = 'sending';
this.$.sendmail.generateRequest();
},
processResponse: function() {
this.route = 'sent';
this.resetForm();
},
showForm: function() {
this.route = 'form';
},
resetForm: function() {
this.$.name.autoValidate = false;
this.$.email.autoValidate = false;
this.name = '';
this.email = '';
this.message = '';
this.grecaptcha = '';
this.$.name.autoValidate = true;
this.$.email.autoValidate = true;
this.$.recaptcha.reset();
},
focusRecaptcha: function() {
this.$.recaptcha.focus();
},
forceFocus: function() {
this.$.name.querySelector('input').blur();
this.$.email.querySelector('input').blur();
this.$.message.querySelector('textarea').blur();
}
});
})();
</script>
</dom-module> |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/file_system_access/file_system_access_permission_context_factory.h"
#include "base/no_destructor.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/file_system_access/chrome_file_system_access_permission_context.h"
#include "chrome/browser/profiles/profile.h"
// static
ChromeFileSystemAccessPermissionContext*
FileSystemAccessPermissionContextFactory::GetForProfile(
content::BrowserContext* profile) {
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/1011535): Local FS portion of FSA API is not yet enabled on
// Android. Create the permission context instance when supported on Android.
return nullptr;
#else
return static_cast<ChromeFileSystemAccessPermissionContext*>(
GetInstance()->GetServiceForBrowserContext(profile, true));
#endif
}
// static
ChromeFileSystemAccessPermissionContext*
FileSystemAccessPermissionContextFactory::GetForProfileIfExists(
content::BrowserContext* profile) {
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/1011535): Local FS portion of FSA API is not yet enabled on
// Android. Create the permission context instance when supported on Android.
return nullptr;
#else
return static_cast<ChromeFileSystemAccessPermissionContext*>(
GetInstance()->GetServiceForBrowserContext(profile, false));
#endif
}
// static
FileSystemAccessPermissionContextFactory*
FileSystemAccessPermissionContextFactory::GetInstance() {
static base::NoDestructor<FileSystemAccessPermissionContextFactory> instance;
return instance.get();
}
FileSystemAccessPermissionContextFactory::
FileSystemAccessPermissionContextFactory()
: ProfileKeyedServiceFactory(
"FileSystemAccessPermissionContext",
ProfileSelections::Builder()
.WithRegular(ProfileSelection::kOwnInstance)
// TODO(crbug.com/1418376): Check if this service is needed in
// Guest mode.
.WithGuest(ProfileSelection::kOwnInstance)
.Build()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
FileSystemAccessPermissionContextFactory::
~FileSystemAccessPermissionContextFactory() = default;
std::unique_ptr<KeyedService>
FileSystemAccessPermissionContextFactory::BuildServiceInstanceForBrowserContext(
content::BrowserContext* profile) const {
return std::make_unique<ChromeFileSystemAccessPermissionContext>(profile);
}
void FileSystemAccessPermissionContextFactory::BrowserContextShutdown(
content::BrowserContext* context) {
auto* permission_context =
GetForProfileIfExists(Profile::FromBrowserContext(context));
if (permission_context)
permission_context->FlushScheduledSaveSettingsCalls();
} |
// 1. eval использовать запрещено
// eval('13 * 54 * 72 === 84240')
// 2. Если eval использовать нельзя, то нужно использовать объекты ответов и интерфейсы
export enum OperatorSymbol {
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
// POW
}
export const ALLOWED_OPERATORS: Operator[] = [
{
symbol: OperatorSymbol.PLUS,
label: "Суммирование",
displaySign: '+',
checked: false,
priority: 12,
resolve: (a, b) => a + b,
},
{
symbol: OperatorSymbol.MINUS,
label: "Разность",
displaySign: '-',
checked: false,
priority: 12,
resolve: (a, b) => a - b,
},
{
symbol: OperatorSymbol.MULTIPLY,
label: "Умножение",
displaySign: '*',
checked: false,
priority: 13,
resolve: (a, b) => a * b,
},
{
symbol: OperatorSymbol.DIVIDE,
label: "Деление",
displaySign: '/',
checked: false,
priority: 13,
resolve: (a, b) => a / b,
validate: (a, b) => b !== 0,
},
];
export interface Operator {
symbol: OperatorSymbol;
label: string;
displaySign: string;
checked: boolean,
priority: number,
resolve(left: number, right: number): number;
validate?(left: number, right: number): boolean;
}
export interface Task {
startValue: number;
operators: Operator[];
answer: number[];
result: number;
complexity:number
}
export interface GenerateTaskParams {
complexity: number;
allowedOperators: Operator[];
}
export interface Generator {
generateTask(params: GenerateTaskParams): Task;
MIN_ALLOWED_NUMBER: number;
MAX_ALLOWED_NUMBER: number;
}
export interface Resolver {
checkTask(task: Task): boolean;
}
export interface Statistics {
sessions: Session[];
}
export interface Config {
level: number;
}
export interface Session {
id: string;
startTime: Date;
endTime: Date | null;
score: number;
missed: number;
timer: number
}
export interface Game {
statistics: Statistics;
config: Config;
session: Session;
generator: Generator;
resolver: Resolver;
}
// theme,
// locale,
// language,
// timeFormat,
// dateFormat,
// numberFormat,
// currencyFormat,
// currencySymbol,
// currencyDecimalPlaces,
// currencyDecimalSeparator,
// currencyGroupSeparator,
// currencyNegativePattern,
// events,
// (() => {
// const game = useGame();
//
// checkbox.onClick((e) => {
// game.events.dispatch(Events.ADD_OPERATOR, operator, e);
// });
// })();
// const MODS = [
// (game: Game) => {
// game.config.ALLOWED_OPERATORS.push({
// symbol: OperatorSymbol.MAGIC,
// displaySign: 'O_o',
// resolve: (a, b) => (a * b) >> 32,
// });
//
// game.events.on(game.events.knownEvent.ADD_OPERATOR, (operator: Operator) => {
// game.config.complexity += 1;
// });
// },
// ];
/* Что нужно сделать:
1. Расширить интерфейс Operator всеми необходимыми для работы данными
2. Расширить объект ALLOWED_OPERATORS, заполнить все методы, кроме возведения в степень
2.1 Сложить все сущности и классы в папку Domain
3. Реализовать приложение
3.1 Реализовать поддержку порядка вычисления
3.2 Реализовать тесты на игровой движок
3.3 Реализовать плагин (this.$game)
3.4 Реализовать useGame();
4. Добавить функционал возведения в степень с помощью расширения ALLOWED_OPERATORS
*/ |
import * as React from "react";
import { useNavigate } from "react-router-dom";
import "./Trips.css";
import axios from "axios";
import EditTrip from "../EditTrip/EditTrip";
export default function Trips({
setOrigin,
setDestination,
setUser,
setStops,
setStopsDist,
setStopsTime,
setStopsFuel,
}) {
const [trips, setTrips] = React.useState([]);
const [currentUsers, setCurrentUsers] = React.useState([]);
let navigate = useNavigate();
let count = 0;
React.useEffect(() => {
async function fetchTrips() {
try {
const res = await axios.get("http://localhost:3001/trips");
setTrips(res.data.trips);
} catch (err) {
alert("Can not get information for trips");
}
}
fetchTrips();
}, []);
React.useEffect(() => {
async function fetchCurrentUser() {
try {
const res = await axios.get("http://localhost:3001/sessions");
setCurrentUsers((currentUsers) => [
...currentUsers,
res.data.sessions[0].user,
]);
} catch (err) {
alert("Can not get information of users");
}
}
fetchCurrentUser();
}, []);
return (
<>
<div className="trips">
<h1> All trips</h1>
<div className="listTrips">
{trips.map((trip, index) => (
<>
{trip.trip.user.username === currentUsers[0].username &&
trip.trip.user.password === currentUsers[0].password ? (
((count += 1),
(
<>
<div className="tripCard">
<div className="tripInformation">
<div className="tripSummary">
<h3>Trip #{count}</h3>
<p>
{" "}
<b>Origin: </b> {trip.trip.origin.name}{" "}
<b>Destination: </b> {trip.trip.destination.name}
</p>
{trip.trip.stops.map((stop, key) => (
<p>
<b>Name: </b>
{stop.name} <br />
<b>Address: </b>
{stop.address} <br />
<b>Lat: </b>
{stop.lat}, <b> Lng: </b> {stop.lng} <br />
<b>Rating: </b>
{stop.rating}
</p>
))}
</div>
<div className="images">
<img
className="tripImage"
src={trip.trip.origin_image}
alt={trip.trip.origin.name}
style={{
backgroundImage: `url(${trip.trip.origin_image})`,
}}
/>
<img
className="tripImage"
src={trip.trip.destination_image}
alt={trip.trip.destination.name}
style={{
backgroundImage: `url(${trip.trip.destination_image})`,
}}
/>
</div>
</div>
<EditTrip
origin={trip.trip.origin}
setOrigin={setOrigin}
destination={trip.trip.destination}
setDestination={setDestination}
user={trip.trip.user}
setUser={setUser}
stops={trip.trip.stops}
setStops={setStops}
stopsTime={trip.trip.stopsTime}
setStopsTime={setStopsTime}
stopsDist={trip.trip.stopsDist}
setStopsDist={setStopsDist}
stopsFuel={trip.trip.stopsFuel}
setStopsFuel={setStopsFuel}
/>
</div>
</>
))
) : (
<p></p>
)}
</>
))}
<button className="backFinish" onClick={() => navigate("../finish")}>
Back
</button>
</div>
</div>
</>
);
} |
//
// ContentView.swift
// MyPortfolio
//
// Created by Arnaud NOMMAY on 27/03/2023.
//
import SwiftUI
struct ContentView: View {
@EnvironmentObject var dataController: DataController
var body: some View {
List(selection: $dataController.selectedInterest) {
ForEach(dataController.interestsForSelectedFilter()) { interest in
InterestRow(interest: interest)
}.onDelete(perform: delete)
}
.navigationTitle("Interest")
.searchable(text: $dataController.filterText, tokens: $dataController.filterTokens, suggestedTokens: .constant(dataController.suggestedFilterTokens), prompt: "Filter interest, or type # to add tags") { tag in
Text(tag.tagName)
}
.toolbar {
Menu {
Button (dataController.filterEnabled ? "Turn Filter Off": "Turn Filter On") {
dataController.filterEnabled.toggle()
}
Divider()
Menu("Sort by") {
Picker("Sort by", selection: $dataController.sortType) {
Text ("Date Created" ).tag(SortType.dateCreated)
Text ("Date Modified" ).tag(SortType.dateModified)
}
Divider()
Picker ("Sort Order", selection: $dataController.sortNewestFirst) {
Text("New to Oldest").tag(true)
Text("Oldest to New").tag(false)
}
}
Picker("Satatus", selection: $dataController.filterStatus) {
Text("All").tag(Status.all)
Text("Doing").tag(Status.doing)
Text("Not Doing").tag(Status.notDoing)
}
.disabled(dataController.filterEnabled == false)
Picker("Priority", selection: $dataController.filterPriority) {
Text("All").tag(-1)
Text("Low").tag(0)
Text("Medium").tag(1)
Text("High").tag(2)
}
.disabled(dataController.filterEnabled == false)
} label: {
Label("Filter", systemImage: "line.3.horizontal.decrease.circle")
.symbolVariant(dataController.filterEnabled ? .fill : .none)
}
Button(action: dataController.newInterest) {
Label("New Interest", systemImage: "square.and.pencil")
}
}
}
func delete(_ offsets: IndexSet) {
let interests = dataController.interestsForSelectedFilter()
for offset in offsets {
let item = interests[offset]
dataController.delete(item)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
} |
// ---------------------------------------------------------------------
// Action Store Load Variable
// ---------------------------------------------------------------------
import * as CL3D from "../main.js";
/**
* @private
* @constructor
* @class
*/
export class ActionStoreLoadVariable extends CL3D.Action{
constructor() {
this.Type = 'StoreLoadVariable';
}
/**
* @private
*/
createClone(oldNodeId, newNodeId) {
var a = new CL3D.ActionStoreLoadVariable();
a.Load = this.Load;
a.VariableName = this.VariableName;
return a;
}
setCookie(cookieName, value, expdays) {
var expdate = new Date();
expdate.setDate(expdate.getDate() + expdays);
var cvalue = escape(value) + ("; expires=" + expdate.toUTCString());
document.cookie = cookieName + "=" + cvalue;
}
getCookie(cookieName) {
var ARRcookies = document.cookie.split(";");
for (var i = 0; i < ARRcookies.length; ++i) {
var cookie = ARRcookies[i];
var equalspos = cookie.indexOf("=");
var varname = cookie.substr(0, equalspos);
varname = varname.replace(/^\s+|\s+$/g, "");
if (varname == cookieName)
return unescape(cookie.substr(equalspos + 1));
}
return null;
}
/**
* @private
*/
execute(currentNode, sceneManager) {
if (this.VariableName == null || this.VariableName == "")
return;
var var1 = CL3D.CopperCubeVariable.getVariable(this.VariableName, this.Load, sceneManager);
if (var1 != null) {
try {
if (this.Load) {
// load
var1.setValueAsString(this.getCookie(var1.getName()));
}
else {
// save
this.setCookie(var1.getName(), var1.getValueAsString(), 99);
}
}
catch (e) {
//Debug.print("error loading/saving data");
}
}
}
}; |
import Link from 'next/link'
import { JSX } from 'react'
interface LinkButtonProps {
icon: JSX.Element
alt: string
content: string
href: string
focus?: boolean
setFocus?: () => void
}
export function LinkButton({
icon,
content,
href,
focus,
setFocus,
}: LinkButtonProps) {
return (
<Link
onClick={setFocus}
href={href}
className={
focus
? 'bg-balck flex w-[316px] items-center justify-between p-4 text-2xl text-amber-400 shadow-select'
: 'flex w-[316px] items-center justify-between bg-black p-4 text-2xl text-white shadow-no-select'
}
>
{icon}
{content}
</Link>
)
} |
from json import encoder
import pandas as pd
import logging
from pathlib import Path
from src.utils.encoding_utils import read_data, save_data
from src.utils.config_utils import get_config
from src.config_schemas.features.encoding_config_schema import encoding_Config
from src.features.encoding.encoding_model import Encoder
from sklearn.compose import ColumnTransformer
@get_config(config_path="../configs/features", config_name="encoding_config")
def preliminary_encoding(config: encoding_Config) -> None:
"""
Supported encoder names: "WOEEncoder", "CatBoostEncoder", "MEstimateEncoder", "OneHotEncoder"
"""
df_train_X, df_train_Y, df_test = read_data(config.local_data_dir, config.label)
logging.info("Data read successfully.")
encoder = Encoder(encoder_name=config.encoder_name, cat_validation=config.cat_validation)
logging.info("Start encoding the training set.")
df_train_X = encoder.fit_transform(df_train_X, df_train_Y)
logging.info("Finished encoding the training set.")
df_train = pd.concat([df_train_X, pd.Series(df_train_Y, name=config.label)], axis=1)
logging.info("Start encoding the test set.")
df_test = encoder.transform(df_test)
logging.info("Finished encoding the test set.")
if config.encoder_name == "CatBoostEncoder":
save_dir = config.local_save_dir + "/CatBoost"
elif config.encoder_name == "WOEEncoder":
save_dir = config.local_save_dir + "/WOE"
elif config.encoder_name == "MEstimateEncoder":
save_dir = config.local_save_dir + "/MEstimate"
elif config.encoder_name == "OneHotEncoder":
save_dir = config.local_save_dir + "/One-Hot"
else:
ValueError("Encoder not supported")
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True, exist_ok=True)
logging.info(f"Successfully created directory {save_dir}")
else:
logging.info(f"Directory {save_dir} already exists")
save_data(df_train, df_test, save_dir)
logging.info("Encoded data saved successfully.")
@get_config(config_path="../configs/features", config_name="encoding_config")
def encoding(config: encoding_Config) -> None:
df_train_X, df_train_Y, df_test = read_data(config.local_data_dir, config.label)
logging.info("Data read successfully.")
encoders = {
name: Encoder(encoder_name=name, cat_validation=config.cat_validation) for name in config.supported_encoders
}
# Creating a list of tuples for ColumnTransformer
transformers = [(name, encoders[name], getattr(config, f"{name}_cols")) for name in config.supported_encoders]
# Using ColumnTransformer to apply the encoders
mixed_encoder = ColumnTransformer(transformers=transformers, remainder="passthrough")
logging.info("Start encoding the training set.")
df_train_X_transformed = mixed_encoder.fit_transform(df_train_X, df_train_Y)
print(mixed_encoder.get_feature_names_out())
df_train_X = pd.DataFrame(
df_train_X_transformed, columns=[name.split("__")[-1] for name in mixed_encoder.get_feature_names_out()]
)
df_train = pd.concat([df_train_X, pd.Series(df_train_Y, name=config.label)], axis=1)
logging.info("Finished encoding the training set.")
logging.info("Start encoding the test set.")
df_test_transformed = mixed_encoder.transform(df_test)
df_test = pd.DataFrame(
df_test_transformed, columns=[name.split("__")[-1] for name in mixed_encoder.get_feature_names_out()]
)
logging.info("Finished encoding the test set.")
save_dir = Path(config.local_save_dir + "/Mixed")
if not save_dir.exists():
save_dir.mkdir(parents=True, exist_ok=True)
logging.info(f"Successfully created directory {save_dir}")
else:
logging.info(f"Directory {save_dir} already exists")
save_data(df_train, df_test, save_dir)
logging.info("Encoded data saved successfully.")
# Ensure proper logging setup:
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
preliminary_encoding() |
<?php
namespace Illuminate\Database\Console\Factories;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class FactoryMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:factory';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new model factory';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Factory';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->resolveStubPath('/stubs/factory.stub');
}
/**
* Resolve the fully-qualified path to the stub.
*
* @param string $stub
* @return string
*/
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
$namespaceModel = $this->option('model')
? $this->qualifyClass($this->option('model'))
: trim($this->rootNamespace(), '\\').'\\Model';
$model = class_basename($namespaceModel);
$replace = [
'NamespacedDummyModel' => $namespaceModel,
'{{ namespacedModel }}' => $namespaceModel,
'{{namespacedModel}}' => $namespaceModel,
'DummyModel' => $model,
'{{ model }}' => $model,
'{{model}}' => $model,
];
return str_replace(
array_keys($replace), array_values($replace), parent::buildClass($name)
);
}
/**
* Get the destination class path.
*
* @param string $name
* @return string
*/
protected function getPath($name)
{
$name = str_replace(
['\\', '/'], '', $this->argument('name')
);
return $this->laravel->databasePath()."/factories/{$name}.php";
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['model', 'm', InputOption::VALUE_OPTIONAL, 'The name of the model'],
];
}
} |
import { useForm } from "react-hook-form";
import { FormWrapper } from "../components/form/FormWrapper";
import { RHFTextField } from "../components/form/RHFTextField";
import { Button, Card, Container, Grid, Stack } from "@mui/material";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
export const SignUp = () => {
const defaultValues = {
first_name: "",
last_name: "",
email: "",
password: "",
};
const SignUpSchema = Yup.object().shape({
first_name: Yup.string().required("first name is required"),
last_name: Yup.string().required("last name is required"),
email: Yup.string().email("Enter a valid email").min(6).max(40),
password: Yup.string().required("Password is required"),
});
const methods = useForm({
mode: "onTouched",
reValidateMode: "onChange",
resolver: yupResolver(SignUpSchema),
defaultValues,
});
const { handleSubmit } = methods;
const onSubmit = (data) => {
console.log(data);
};
return (
<Stack flex={2} justifyContent={"center"}>
<Container>
<FormWrapper onSubmit={handleSubmit(onSubmit)} methods={methods}>
<Card sx={{ p: 4 }}>
<Grid container spacing={2}>
<Grid item xs={12}></Grid>
<Grid item xs={12} sm={6}>
<RHFTextField
name={"first_name"}
type={"text"}
label={"First Name"}
autoComplete={"off"}
/>
</Grid>
<Grid item xs={12} sm={6}>
<RHFTextField
name={"last_name"}
type={"text"}
label={"Last Name"}
autoComplete={"off"}
/>
</Grid>
<Grid item xs={12} sm={6}>
<RHFTextField
name={"email"}
type={"text"}
label={"Email"}
autoComplete={"off"}
/>
</Grid>
<Grid item xs={12} sm={6}>
<RHFTextField
name={"password"}
type={"password"}
label={"Password"}
autoComplete={"off"}
/>
</Grid>
<Grid item xs={12}>
<Button type="submit" variant="contained" fullWidth>
Register
</Button>
</Grid>
</Grid>
</Card>
</FormWrapper>
</Container>
</Stack>
);
}; |
package com.distributionlock.redis;
import redis.clients.jedis.Jedis;
/**
* @Author: Bojun Ji
* @Description:
* @Date: 2018/8/6_12:45 AM
*/
public class RedisUtil {
/**
* set if not existed, return 1 if ok, return 0 when not updated
*
* @param key
* @param value
* @return
*/
public static Long setnx(String key, String value) {
Long result = null;
try (Jedis jedis = RedisPool.getConnResource()) {
result = jedis.setnx(key, value);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* get value by key
*
* @param key
* @return
*/
public static String get(String key) {
String result = null;
try (Jedis jedis = RedisPool.getConnResource()) {
result = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* set value and return the old value
*
* @param key
* @param value
* @return
*/
public static String getSet(String key, String value) {
String result = null;
try (Jedis jedis = RedisPool.getConnResource()) {
result = jedis.getSet(key, value);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* delete value on the target key,return number of keys removed
*
* @param key
* @return
*/
public static Long del(String key) {
Long result = null;
try (Jedis jedis = RedisPool.getConnResource()) {
result = jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* set expire time for the key, 1 is ok, 0 is not set
*
* @param key
* @param seconds
* @return
*/
public static Long expire(String key, int seconds) {
Long result = null;
try (Jedis jedis = RedisPool.getConnResource()) {
result = jedis.expire(key, seconds);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* set if not existed, set expire time, return SET command's status code, when it's successful, it will be OK
*
* @param key
* @param value
* @param time
* @return
*/
public static String setNxWithExpireTime(String key, String value, long time) {
String result = null;
try (Jedis jedis = RedisPool.getConnResource()) {
result = jedis.set(key, value, "NX", "EX", time);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
} |
import { Routes } from "@angular/router";
import { ShoppingComponent } from "./shopping.component";
import { IndexComponent } from "./top-pages/index/index.component";
import { ProductListComponent } from "./top-pages/product-list/product-list.component";
import { ProductDetailComponent } from "./top-pages/product-detail/product-detail.component";
import { ProductQuickviewComponent } from "./top-pages/product-quickview/product-quickview.component";
import { CartComponent } from "./top-pages/cart/cart.component";
import { OrderListComponent } from "./top-pages/order-list/order-list.component";
import { OrderProcessComponent } from "./top-pages/order-process/order-process.component";
import { OrderTrackingCustomerInfoComponent } from "./components/order-process/order-tracking-customer-info/order-tracking-customer-info.component";
import { OrderTrackingPaymentMethodsComponent } from "./components/order-process/order-tracking-payment-methods/order-tracking-payment-methods.component";
import { OrderTrackingNotifyCustomerComponent } from "./components/order-process/order-tracking-notify-customer/order-tracking-notify-customer.component";
import { AuthenticatedRequiredGuard } from "../core/guards/authenticated-required.guard";
import { ProductCompareComponent } from "./top-pages/product-compare/product-compare.component";
import { AccountComponent } from "./top-pages/account/account.component";
import { RoleAdminGuard } from "../core/guards/role-admin.guard";
import { ProductWishListComponent } from "./top-pages/product-wishlist/product-wishlist.component";
export const shoppingRoutes: Routes = [
{
path: '',
component: ShoppingComponent,
children: [
{
path: '',
redirectTo: 'index',
pathMatch: 'full'
},
{
path: 'index',
component: IndexComponent
},
{
path: 'product-list',
component: ProductListComponent
},
{
path: 'product-compare',
component: ProductCompareComponent
},
{
canActivate: [AuthenticatedRequiredGuard],
path: 'product-wishlist',
component: ProductWishListComponent
},
{
path: 'product-detail/:productId',
component: ProductDetailComponent,
pathMatch: 'full'
},
{
path: 'product-quickview/:productId',
component: ProductQuickviewComponent
},
{
path: 'cart',
component: CartComponent
},
{
canActivate: [AuthenticatedRequiredGuard, RoleAdminGuard],
path: 'order-list',
component: OrderListComponent
},
{
canActivate: [AuthenticatedRequiredGuard],
path: 'account',
component: AccountComponent
},
{
canActivate: [AuthenticatedRequiredGuard],
path: 'order-process',
component: OrderProcessComponent,
children: [
{
path: 'customer-info',
component: OrderTrackingCustomerInfoComponent
},
{
path: 'payment-methods',
component: OrderTrackingPaymentMethodsComponent
},
{
path: 'notify-customer',
component: OrderTrackingNotifyCustomerComponent
}
]
}
]
}
] |
#tabela referenciada com Common Table Expression
WITH TotalGanhadores AS (
SELECT
COUNT(DISTINCT r.clientes_id) AS Total
FROM
`sapient-tractor-310701.H2Club.resultado` r
WHERE
r.Winning > 0
)
#consulta principal
SELECT
c.Sexo,
COUNT(DISTINCT r.clientes_id) AS Numero_Ganhadores,
ROUND(100 * COUNT(DISTINCT r.clientes_id) / Total, 0) AS Percentual
FROM
`sapient-tractor-310701.H2Club.resultado` r
JOIN
`sapient-tractor-310701.H2Club.clientes` c ON r.clientes_id = c.id
CROSS JOIN
TotalGanhadores
WHERE
r.Winning > 0
GROUP BY
c.Sexo, Total
#adicao da linha total
UNION ALL
SELECT
'Total' AS Sexo,
COUNT(DISTINCT r.clientes_id) AS Numero_Ganhadores,
100.00 AS Percentual
FROM
`sapient-tractor-310701.H2Club.resultado` r
WHERE
r.Winning > 0
ORDER BY
Percentual desc; |
import { readdirSync } from "fs";
import matter from "gray-matter";
import { GetStaticPaths, GetStaticProps, NextPage } from "next";
import remarkHtml from "remark-html";
import remarkParse from "remark-parse";
import { unified } from "unified";
const Post: NextPage<{ post: string }> = ({ post }) => {
return <h1>{post}</h1>;
};
export const getStaticProps: GetStaticProps = async (ctx) => {
console.log(ctx.params);
const { content } = matter.read(`./posts/${ctx.params?.slug}.md`);
const { value } = await unified()
.use(remarkParse)
.use(remarkHtml)
.process(content);
return {
props: {
post: value,
},
};
};
// 몇 개의 페이지를 미리 생성해야하는지
export const getStaticPaths: GetStaticPaths = () => {
const files = readdirSync("./posts").map((file) => {
const [name, extension] = file.split(".");
return { params: { slug: name } };
});
return {
paths: files,
fallback: false,
};
};
export default Post; |
import { EIP712Proxy } from '../../src/eip712-proxy';
import Contracts from '../components/Contracts';
import chai from './helpers/chai';
import { EAS, EIP712Proxy as EIP712ProxyContract, SchemaRegistry } from '@ethereum-attestation-service/eas-contracts';
import { ethers } from 'hardhat';
import { Signer } from 'ethers';
const { expect } = chai;
const EIP712_PROXY_NAME = 'EAS-Proxy';
describe('EIP712Proxy API', () => {
let registry: SchemaRegistry;
let eas: EAS;
let proxyContract: EIP712ProxyContract;
let proxy: EIP712Proxy;
let sender: Signer;
before(async () => {
[sender] = await ethers.getSigners();
});
beforeEach(async () => {
registry = await Contracts.SchemaRegistry.deploy();
eas = await Contracts.EAS.deploy(await registry.getAddress());
proxyContract = await Contracts.EIP712Proxy.deploy(await eas.getAddress(), EIP712_PROXY_NAME);
proxy = new EIP712Proxy(await proxyContract.getAddress(), { signerOrProvider: sender });
});
describe('construction', () => {
it('should properly create an EIP712Proxy API', async () => {
expect(await proxy.getVersion()).to.equal(await proxyContract.version());
expect(await proxy.getEAS()).to.equal(await eas.getAddress());
expect(await proxy.getName()).to.equal(EIP712_PROXY_NAME);
expect(await proxy.getDomainSeparator()).to.equal(await proxyContract.getDomainSeparator());
expect(await proxy.getAttestTypeHash()).to.equal(await proxyContract.getAttestTypeHash());
expect(await proxy.getRevokeTypeHash()).to.equal(await proxyContract.getRevokeTypeHash());
});
});
}); |
import {useFocusEffect, useNavigation, useRoute} from '@react-navigation/core';
import React, {useContext, useState} from 'react';
import colors from '../../assets/theme/colors';
import RegisterComponent from '../../components/Register';
import { LOGIN } from '../../constants/routeName';
import register, { clearAuthState } from '../../context/actions/auth/register';
import {GlobalContext} from '../../context/Provider';
const Register = () => {
const [form, setForm] = useState({});
const {navigate} = useNavigation();
const [errors, setErrors] = useState({});
const {authDispatch, authState:{error, loading, data} } = useContext(GlobalContext);
console.log('registration error :>>>>>',error);
useFocusEffect(
React.useCallback(() => {
return() =>{
if(data){
clearAuthState()(authDispatch)
}
}
}, [data, error])
);
const email_reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w\w+)+$/;
const formalidation = ({name, value,form, status}) => {
if(status === 1)
{
if (value !== '') {
if (name === 'password' ) {
if (value.length < 8) {
setErrors(prev => {
return {...prev, [name]: 'This field minimum 8 characters'};
});
} else {
setErrors(prev => {
return {...prev, [name]: null};
});
}
}else {
setErrors(prev => {
return {...prev, [name]: null};
});
}
if(name === 'email') {
if (email_reg.test(value) === false){
setErrors(prev => {
return {...prev, [name]: 'Enter valid email address'};
});
}
}
} else {
setErrors(prev => {
return {...prev, [name]: 'This field is required'};
});
}
}else{
if (!form.username) {
setErrors(prev => {
return {...prev, username: 'This field is required'};
});
}
if (!form.password) {
setErrors(prev => {
return {...prev, password: 'This field is required'};
});
}
if (!form.email) {
setErrors(prev => {
return {...prev, email: 'This field is required'};
});
}
if (!form.first_name) {
setErrors(prev => {
return {...prev, first_name: 'This field is required'};
});
}
if (!form.last_name) {
setErrors(prev => {
return {...prev, last_name: 'This field is required'};
});
}
if (form.password && form.password.length < 8) {
setErrors(prev => {
return {...prev, password: 'This field minimum 8 characters'};
});
}
}
};
const onChange = ({name, value}) => {
setForm({...form, [name]: value});
let status = 1;
formalidation({name, value,status});
};
const onSubmit = () => {
formalidation({form});
if (
Object.values(form).length === 5 &&
Object.values(form).every((item) => item.trim().length > 0) &&
Object.values(errors).every((item) => !item)
) {
register(form)(authDispatch)((response)=>{
navigate(LOGIN,{data:response});
});
}
}
return (
<RegisterComponent
onChange={onChange}
onSubmit={onSubmit}
form={form}
error={error}
errors={errors}
loading={loading}
/>
);
};
export default Register; |
import { Textarea } from '../textarea';
import { Icon } from '../icon';
import { Text } from '../text';
import { Devider } from '../devider';
import { iconDelete } from '../../../stories/assets/IconDelete';
import { iconYes } from '../../../stories/assets/IconYes';
import { iconNo } from '../../../stories/assets/IconNo';
import { iconEditWord } from '../../../stories/assets/IconEditWord';
import styles from './deckEditItem.module.scss';
import { useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
export const DeckEditItem = ({onEditWords, deleteWords, item, currentIndex }) => {
const [isEdit, setIsEdit] = useState(false);
const handleEditWords = () => {
setIsEdit(true);
}
const {
control,
handleSubmit,
reset
} = useForm({
defaultValues: {
word: item.word,
translation: item.translation
}
});
const inputReset = () => {
reset({
word: '',
translation: ''
});
}
const onSubmit = (data) => {
//alert(JSON.stringify(data));
if (Object.values(data).length) {
//mutate({ data: data });
setIsEdit(false);
onEditWords(data, currentIndex);
}
};
return (
<>
{isEdit ? (
<>
<form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
<div className={styles.inputs}>
<Controller
control={control}
name='word'
render={({ field: { value = item.word, onBlur, onChange } }) => (
<Textarea
placeholder={''}
name='word'
onBlur={onBlur}
onChange={onChange}
value={value}
/>
)}
/>
<Controller
control={control}
name='translation'
render={({ field: { value = item.translation, onBlur, onChange } }) => (
<Textarea
placeholder={''}
name='translation'
onBlur={onBlur}
onChange={onChange}
value={value}
/>
)}
/>
</div>
<div className={styles.controls}>
<button type='button' className={styles.btnNo} onClick={inputReset}>
<Icon iconTitle={iconNo} />
</button>
<button type='submit' className={styles.btnYes}>
<Icon iconTitle={iconYes} />
</button>
<div className={styles.count}>
<Text As='span' size='body2'>{'0%'}</Text>
</div>
<button onClick={deleteWords}>
<Icon iconTitle={iconDelete} />
</button>
</div>
</form>
<Devider />
</>
) : (
<>
<div className={styles.form} >
<div className={styles.inputs}>
<div className={styles.div}>
<Text As='span' size='body3'>{item.word}</Text>
</div>
<div className={styles.div}>
<Text As='span' size='body3'>{item.translation}</Text>
</div>
</div>
<div className={styles.controls}>
<div className={styles.empty}>
</div>
<button className={styles.btnEdit} onClick={handleEditWords}>
<Icon iconTitle={iconEditWord} />
</button>
<div className={styles.count}>
<Text As='span' size='body2'>{'0%'}</Text>
</div>
<button onClick={deleteWords}>
<Icon iconTitle={iconDelete} />
</button>
</div>
</div>
<Devider />
</>
)}
</>
)
} |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2005-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var SECTION = "15.1.3.3";
var VERSION = "ECMA_1";
startTest();
var TITLE = "encodeURI";
writeHeaderToLog( SECTION + " "+ TITLE);
var testcases = getTestCases();
test();
function getTestCases() {
var array = new Array();
var item = 0;
str1 = new String("h");
array[item++] = new TestCase( SECTION, "encodeURI('Empty String')", "", encodeURI("") );
array[item++] = new TestCase( SECTION, "encodeURI('Single Character')", "h", encodeURI(str1) );
str2 = new String("http://www.macromedia.com/flash player");
array[item++] = new TestCase( SECTION, "encodeURI(str2)", "http://www.macromedia.com/flash%20player", encodeURI(str2) );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com')", "http://www.macromedia.com", encodeURI("http://www.macromedia.com") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com')", "http://www.macromedia.com/flashA1player", encodeURI("http://www.macromedia.com/flash\u0041\u0031player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash player')", "http://www.macromedia.com/flash%20player", encodeURI("http://www.macromedia.com/flash player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flasha player')", "http://www.macromedia.com/flasha%20player", encodeURI("http://www.macromedia.com/flasha player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flashA player')", "http://www.macromedia.com/flashA%20player", encodeURI("http://www.macromedia.com/flashA player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash_ player')", "http://www.macromedia.com/flash_%20player", encodeURI("http://www.macromedia.com/flash_ player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash- player')", "http://www.macromedia.com/flash-%20player", encodeURI("http://www.macromedia.com/flash- player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash. player')", "http://www.macromedia.com/flash.%20player", encodeURI("http://www.macromedia.com/flash. player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash! player')", "http://www.macromedia.com/flash!%20player", encodeURI("http://www.macromedia.com/flash! player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash~ player')", "http://www.macromedia.com/flash~%20player", encodeURI("http://www.macromedia.com/flash~ player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash* player')", "http://www.macromedia.com/flash*%20player", encodeURI("http://www.macromedia.com/flash* player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/'flash player'')", "http://www.macromedia.com/'flash%20player'", encodeURI("http://www.macromedia.com/'flash player'") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/(flash player)')", "http://www.macromedia.com/(flash%20player)", encodeURI("http://www.macromedia.com/(flash player)") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com//tflash player')", "http://www.macromedia.com//tflash%20player", encodeURI("http://www.macromedia.com//tflash player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/\tflash player')", "http://www.macromedia.com/%09flash%20player", encodeURI("http://www.macromedia.com/\tflash player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/0987654321flash player')", "http://www.macromedia.com/0987654321flash%20player", encodeURI("http://www.macromedia.com/0987654321flash player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash; player')", "http://www.macromedia.com/flash;%20player", encodeURI("http://www.macromedia.com/flash; player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash player?')", "http://www.macromedia.com/flash%20player?", encodeURI("http://www.macromedia.com/flash player?") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash player@')", "http://www.macromedia.com/flash%20player@", encodeURI("http://www.macromedia.com/flash player@") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash player&')", "http://www.macromedia.com/flash%20player&", encodeURI("http://www.macromedia.com/flash player&") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash player=')", "http://www.macromedia.com/flash%20player=", encodeURI("http://www.macromedia.com/flash player=") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash player$')", "http://www.macromedia.com/flash%20player$", encodeURI("http://www.macromedia.com/flash player$") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash player,')", "http://www.macromedia.com/flash%20player,", encodeURI("http://www.macromedia.com/flash player,") );
array[item++] = new TestCase( SECTION, "encodeURI('aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ')", "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ", encodeURI("aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ") );
array[item++] = new TestCase( SECTION, "encodeURI('aA_bB-cC.dD!eE~fF*gG'hH(iI)jJ;kK/lL?mM:nN@oO&pP=qQ+rR$sS,tT9uU8vV7wW6xX5yY4zZ')", "aA_bB-cC.dD!eE~fF*gG'hH(iI)jJ;kK/lL?mM:nN@oO&pP=qQ+rR$sS,tT9uU8vV7wW6xX5yY4zZ", encodeURI("aA_bB-cC.dD!eE~fF*gG'hH(iI)jJ;kK/lL?mM:nN@oO&pP=qQ+rR$sS,tT9uU8vV7wW6xX5yY4zZ") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\n player,')", "http://www.macromedia.com/flash%0Aplayer", encodeURI("http://www.macromedia.com/flash\nplayer") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\v player,')", "http://www.macromedia.com/flash%0Bplayer", encodeURI("http://www.macromedia.com/flash\vplayer") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\f player,')", "http://www.macromedia.com/flash%0Cplayer", encodeURI("http://www.macromedia.com/flash\fplayer") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\r player,')", "http://www.macromedia.com/flash%0Dplayer", encodeURI("http://www.macromedia.com/flash\rplayer") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\" player,')", "http://www.macromedia.com/flash%22player", encodeURI("http://www.macromedia.com/flash\"player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\' player,')", "http://www.macromedia.com/flash'player", encodeURI("http://www.macromedia.com/flash\'player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\\ player,')", "http://www.macromedia.com/flash%5Cplayer", encodeURI("http://www.macromedia.com/flash\\player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash# player,')", "http://www.macromedia.com/flash#player", encodeURI("http://www.macromedia.com/flash#player") );
array[item++] = new TestCase( SECTION, "encodeURI('http://www.macromedia.com/flash\u0000\u0041player,')", "http://www.macromedia.com/flash%00Aplayer", encodeURI("http://www.macromedia.com/flash\u0000\u0041player") );
return ( array );
} |
package sandy.errors;
/**
* The SingletonError class is used as a workaround for private constructors not existing
* in ActionScript 3.0. Every singleton class in Sandy has a private static variable
* called <code>instance</code>. The <code>instance</code> variable is given a
* reference to an instance of the class the first time the class constructor or
* <code>getInstance()</code> is called. If an attempt is made to instantiate the
* class a the second time, a <code>SingletonError</code> will be thrown. Always
* use the static method <code>Class.getInstance()</code> to get an instance of the
* class.
*
* @author Dennis Ippel - ippeldv
* @author Niel Drummond - haXe port
* @version 3.1
* @date 26.07.2007
*/
class SingletonError
{
/**
* All the constructor does is passing the error message string to the
* superclass.
*/
public function new()
{
throw("Class cannot be instantiated");
}
} |
import React, { useEffect, useState } from "react";
import { Box, Stack, Typography } from "@mui/material";
import { fetchFromAPI } from "../utils/fetchFromAPI";
import { Videos, Sidebar } from "./";
const Feed = () => {
const [selectedCategory, setSelectedCategory] = useState("New");
const [videos, setVideos] = useState(null);
useEffect(() => {
setVideos(null);
fetchFromAPI(`search?part=snippet&q=${selectedCategory}`)
.then((data) => setVideos(data.items))
}, [selectedCategory]);
return (
<Stack sx = {{ flexDirection: { sx: "column", md: "row" } }}>
<Box sx = {{ height: { sx: "auto", md: "92vh" }, borderRight: "1px solid #3d3d3d", px: { sx: 0, md: 2 } }}>
<Sidebar selectedCategory = {selectedCategory} setSelectedCategory = {setSelectedCategory} />
<Typography className = "copyright" variant = "body2" sx = {{ mt: 1.5, color: "#fff", }}>
Copyright © 2022 JSM Media
</Typography>
</Box>
<Box p={2} sx = {{ overflowY: "auto", height: "90vh", flex: 2 }}>
<Typography variant = "h4" fontWeight = "bold" mb = {2} sx = {{ color: "white" }}>
{selectedCategory} <span style = {{ color: "#FC1503" }}>videos</span>
</Typography>
<Videos videos = {videos} />
</Box>
</Stack>
);
};
export default Feed; |
---
title: "[New] Unveiling the Secrets of YouTube to MP4/MPEG Mastery"
date: 2024-06-04T07:42:36.800Z
updated: 2024-06-05T07:42:36.800Z
tags:
- screen-recording
- ai video
- ai audio
- ai auto
categories:
- ai
- screen
description: "This Article Describes [New] Unveiling the Secrets of YouTube to MP4/MPEG Mastery"
excerpt: "This Article Describes [New] Unveiling the Secrets of YouTube to MP4/MPEG Mastery"
keywords: "YouTUBE to MP4,MP3 to MP4 Conversion,MPEG to MP4 Mastery,YouTube Video Export,YouTube MP4 Extraction,YouTube to MP4 Guide,MP4/MPEG YouTube Tutorial"
thumbnail: https://thmb.techidaily.com/fa134e33a19af2a6d89131747e3b5172ee7c3295829397bcf7ff50f7e4bad5d7.png
---
## Unveiling the Secrets of YouTube to MP4/MPEG Mastery
If you plan to watch converted YouTube videos on your TV set, checking your TV specification and learning if how to convert YouTube to MPEG output files are necessary.
There are many types of solutions available for **YouTube to MPEG 2** or MPEG 4 conversion. However, before choosing one, you should know which MPEG sub-type is compatible with your devices.
## What is MPEG?
MPEG stands for Moving Picture Experts Group and is an ISO-working group. It includes a wide range of file containers/formats and diverse compression standards for digital videos. As a result, it is suitable for different devices and platforms and assures high-quality video resolution.
Here is a comparative listing of the different types of MPEG and known factors about each.
| **MPEG-4** | **MPEG-3** | **MPEG 2** | **MPEG** | |
| -------------------------- | ------------------------------------------------------------- | -------------------------------------------- | ----------------------------------------------------------- | --------------------------------- |
| **Quality of Video** | High | Medium | High | Low |
| **Compression ratio** | Till 52:1 | Till 52:1 | 6:1 to 14:1 | 6:1, 26:1 |
| **File Size** | 4 GB - 2 per file | 4 GB - 2 per file | 2 GB | **\-** |
| **Filename Extensions** | MP4 | MPEG3, MP3 | MPEG2 | MPEG |
| **Bandwidth** | Strong bandwidth strength. | High bandwidth strength with zero data loss. | Mediocre bandwidth power. | Not the best bandwidth power. |
| **What is it useful for?** | This format works with online platforms and portable devices. | Initially built for HDTV use. | This encoding approach is used during DVD-based conversion. | Suitable for standard VCR videos. |
## The Top 5 YouTube to MPEG4 Converters \[Desktop only\]
Multiple software types are available to help **converts YouTube to MPEG** files, using various advanced editing features. For an easier understanding, here are the main points of concern about each in a table format.
| **Best For** | **Pricing** | **Supported Formats** | |
| ----------------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| **FreeMake Video Downloader** | Easy to use software to encode and convert multiple media files into different codec-based types. | Free | MP4, MPEG-4, AVI, MP3, FLV, WMV, MKV, Apple, PSP, Android, etc. |
| **Filmora** | Comprehensive video editing software with advanced features and convert files to the preferred format. | Free Trial;Monthly- USD 19.99;Annual- USD 49.99;Perpetual- USD 79.99 | MP4, MKV, MOV, MPEG-2, AVI, TS, 3GP, GIF, WEBM, MP3, WMV, F4V, MPG |
| **HitPaw** | Download videos from social media platforms like YouTube and convert them to MPEG format directly. | Trial; Monthly- USD 19.95; Annual- USD 39.95; Lifetime- USD 79.95 | MP4, MKV, MOV, MPEG-2, AVI, TS, 3GP, GIF, WEBM, MP3, WMV, F4V, etc. |
| **Aura Video Downloader** | Buy the software for Windows and download converted file types after previewing the output video. | USD 24.95 | MPEG-1, MPEG-2, MP4, AVI, WMV, FLV, 3G2, 3GP |
| **Wondershare Uniconverter** | One software to convert different file formats, DVD burn, screen recording, etc. | Quarterly- USD 29.99; Annual- USD 39.99; Perpetual- USD 55.99 | MP4, MKV, MOV, MPEG-1, MPEG-2, AVI, TS, 3GP, GIF, WEBM, M2TS, MP3, WMV, etc. |
Now, onto a detailed explanation of each type of **YouTube to MPEG4 converter** software.
### [Freemake Video Downloader](https://www.freemake.com/free%5Fvideo%5Fconverter2/)
Freemake Video Downloader is a suitable software to **convert YouTube to MPEG4** format and download it. It works with different types of devices, browsers, and file formats. You have to install the software, add the file through the device library, URL, or drag it to the editor, and choose the necessary customizations to convert. The whole process took us a few taps to complete.

**Main Features**:
* Works with ready-made settings for Huawaii, Android, Google, Sony, etc.
* Supports different video codecs like MPEG4, and AV1.
* Convert files to over 500 formats.
* Prepare image slideshows.
Pros
* All features are available for free.
* Burning and ripping DVD files.
* Easy-to-use video editing functions.
Cons
* Mainly for Windows users.
* Slightly complex to operate encoding functions at first.
### [Filmora](https://tools.techidaily.com/wondershare/filmora/download/)
Filmora is one of the top-most tools to **convert YouTube to MPEG** or any other format after making many video edits. When we tried it out, there was no option to download a video from YouTube directly, but we could upload it to the site easily. Besides that, it supports MPEG-2 as one of the conversion options after doing many personalized changes.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit)
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later

**Main Features**:
* Choose the specifications and output codec choices for videos.
* Chroma Key support for background change.
* Adjust the speed and volume of sound clips.
* Wide range of additional stock media.
Pros
* Supports a wide range of video input and output formats.
* Edit multiple files together.
* Standard and advancing video editing features are available, like cropping, rotating, etc.
Cons
* Some codecs are not supported in specific systems.
* 4K output quality for videos is not available for free.
**How to convert YouTube to mpeg2**
Step1Launch the software on Mac or Windows device.
Step2Press New Project > Click to insert the media file.

Step3Drag the videos you added for editing to the editor timeline at the lower end of the screen.
Step4Click on the editing icons like Chroma Key, Keyframing, Splitting, Speed Revamp, Motion Tracking, etc., for custom changes.

Step5After completing all edits, click on the Export button at the top of the screen.
Step6Click Local > MPEG-2\. Press the Settings button to make output configurations, rename the file, and choose a saving destination.

Step7Finally, hit Export.
### [HitPaw](https://www.hitpaw.com/video-converter.html)
With HitPaw, it is simple to **download YouTube MPEG** files after adding the preferred file type into the converter. In addition, it supports different types of output formats for the videos. Choose the one you want to convert the YouTube video or playlist into, and begin the processing quickly.

**Main Features**:
* Utilizes built-in GPU and CPU to ensure faster conversions.
* Over 1000 devices and formats are supported.
* Download channels and playlists in bulk without speed loss.
* Convert different types of files from iTunes, Apple Music, etc.
Pros
* Runs with the OpenGL driver version.
* Edit video clips with cut, merge, split, etc.
* You can convert podcasts with the Windows-based software version.
Cons
* Some video file formats cannot play on it if the driver is not updated.
* Processing slows down highly for bigger files.
### Aura Video Converter
Freemake Video DownloaderFilmoraHitPawAura Video Converter
Aura Video Converter is a simple software to direct download files from YouTube into whichever format you prefer. During the conversion process, we made many customization choices for the video files, like the filters and bitrate count. Before downloading, it is possible to preview the final file and then make the conversion.

**Main Features**:
* Convert files from devices like PSP, iPhone, Android, etc.
* Multiple input/output formats are available.
* Download from Google, Nico, and YouTube.
* You can make video customizations like bitrate, codec, filters, etc.
Pros
* Compatible with multiple devices.
* The quality of the output video does not waver after conversion.
* Preview the files before encoding.
Cons
* Advanced unlimited conversions required payment to get.
* Only supports MPEG-1 or MPEG-2 for output.
### [Wondershare Uniconverter](https://tools.techidaily.com/wondershare/videoconverter/download/)
With Uniconverter, you can quickly get high-quality converted video files from different locations, like your cloud account or saved device files. You can insert more than one file into the converter and begin the conversion process quickly. For the output file, it is easy to choose between diverse formats, web-based accounts, or cloud as the location.

**Main Features**:
* Strong cloud support for file input and output.
* Around 1000+ different formats are supported for conversion.
* You can merge multiple files during conversion.
* Batch processing is allowed.
Pros
* Burn DVD-based files with a specialized tool.
* Drag and drop functionality available for insertion.
* Convert and download as MPEG files or upload to YouTube or Cloud.
Cons
* It does not allow direct YouTube URLs for video download.
* MPEG-4 is not supported for output.
## The Best 5 Tools to Convert YouTube to MPEG4 \[Online\]
Like the software types, you can select and use a **YouTube to MPEG converter online.** These work with no installation necessary and are mainly free to use for this conversion.
Here is a tabular breakdown of their differences.
| **Best For** | **Pricing** | **Supported Formats** | |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| **Convertio** | Downloading files in various types of MPEG format. | Free Trial; Light- USD 9.99/month; Basic- USD 14.99/month; Unlimited- USD 25.99/month | MPEG-2, TS, FLV, MP4, AVI, MOV, MTS, 3GP, WEBM, GIF, MKV, M4V, etc. |
| **Media** | Quick and easy tool to **convert YouTube to MPEG**. | Free; Basic- USD 2.95/month; Pro- USD 6.66/month | MPEG-1, MPEG-2, MP4, AVI, FLV, MOV, 3GP, WEBM, MKV, SWF, MXF, YouTube, WMV, etc. |
| **Veed.io** | Make customized editing to the videos with subtitles and cropping before downloading them in MPEG-supported containers. | Free; Basic- USD 3.74/month; Pro- USD 7.50/month; Business- USD 18.80/month | MPEG, MP4, MOV, MP3, WEBM, M4V, FLV, 3GP, WMV, etc |
| **Y2Mate** | Directly download YouTube devices in different resolutions. | Free | MP4, MO, MP3, WEBM, M4V, FLV, 3GP, WMV, etc. |
| **Video Converter** | Adjust the type of video output size, codec, and audio sound. | Free;Premium- USD 4.75/month | MPEG, MP4, AVI, FLV, MOV, 3GP, WEBM, MKV, Android, Blackberry, and other devices. |
Now, go ahead and read about each **YouTube converter MPEG 4** or MPEG 2 version available in more detail.
### [Convertio](https://convertio.co/mpeg2-converter/)
You can add the file to convert **YouTube to MPEG 4** and get file output in high resolution. While trying this out, we needed to download the YouTube file separately in MP4 or another format and add it through Dropbox or Google Drive. Then, it would help if you made customization choices like what format to convert in and activate the process.

**Main Features**:
* Accessible through any browser, like Safari, Opera, or Chrome.
* Over 125 different MPEG-2 conversions are available.
* Free tool to use for quick conversions.
* Adjust video specifications like frame rate, quality, codec, and duration.
Pros
* The performance quality of the conversion is speedy.
* You can add from Cloud platforms like DropBox or Google Drive.
* Simple and intuitive user interface available.
Cons
* Cannot add a YouTube file directly to convert- you have to download it first.
* It does not help in the conversion to MPEG-4 format.
### [Veed.io](https://www.veed.io/edit/70dd7fde-d2f7-4883-83b1-a83f69207dc4)
You can use this software to quickly **convert YouTube to MPEG** files, with customizations to a new video or stock file. After adding the video you want to convert through YouTube, Cloud, or device, make changes like splitting the video, adding audio, setting duration, removing background, and more. Finally, download the file in MPEG format.

**Main Features**:
* Quickly share the output videos across social media.
* A sample video conversion option is available.
* Directly include the video from YouTube or Dropbox.
Pros
* Lorem Ipsum is simply
* printing and typesetting industry
* the leap into electronic typesetting
* versions of Lorem Ipsum
Cons
* Uploading big files can get slow.
* Also, only registered users can save files for later.
### [Y2mate](https://www.y2mate.com/en373)
With this online **YouTube MPEG converter**, users find it very simple to add the YouTube video link and convert the file. Press the Start button for the process to start, and multiple format options will appear. Specific videos are available in different formats like MPEG, but most are in MP4 format. Make your preferred choice and press Download.

**Main Features**:
* Add multiple URLs and download many files.
* The speed of conversion is instantaneous with no loss in quality.
* No limit to the file size for conversion.
* Add files from any platform like YouTube, Vimeo, DailyMotion, etc.
Pros
* The very straightforward process of conversion.
* Supports multiple formats for the output of files.
* Free download with no registration necessary.
Cons
* Many ads would come up, which can get distracting.
* You cannot customize the output format for file downloads.
### [Video Converter](https://video-converter.com/)
To convert **YouTube to MPEG online,** use this software to add the file using the URL of the YouTube video. Alternatively, you can add files through Dropbox, Google Drive, or the device library. Then, choose the video and audio formats, codecs, and file size. Next, select if you want audio or not, and then press the Convert button.

**Main Features**:
* Batch processing for converting multiple video files at the same time.
* The online converter supports MPEG-4 video format.
* Over 300 video formats are supported.
* The file size limit for each video is around 4 GB.
Pros
* Supports a wide range of languages.
* No registration is necessary to make conversions.
* The servers do not store the files and automatically remove them within hours.
Cons
* No MPEG-2 video codec is allowed here.
* Lack of advanced editing features.
## Hot FAQs on YouTube to MPEG Converting
### 1\. Is MPEG 4 the same as MP4? Which is better?
MPEG 4 is a type of overall term developed under the Moving Pictures Experts Group that includes multiple media containers. Therefore, it is suitable for sharing multiple video-based contents across the internet. In comparison, MP4 is one of the media containers under this broad umbrella, which focuses on file compression, e.g., videos/images.
MPEG4 does not use up bandwidth must and holds high compression, which makes it a suitable choice for many media players.
### 2\. Is MPEG YouTube's Preferred Video Format?
The preferred video format for YouTube is mainly MPEG-2 type, with Dolby AC-3 video or MPEG Layer 11 video codecs. Alternatively, one can **download YouTube video MPEG** 4 formatted types.
Other formats that the streaming platform mainly supports include FLV, MP4, MOV, WMV, AVI, 3GPP, MPGEGPS, and WebM. However, for best results, **download YouTube videos in MPEG** format only.
## Final Words
Multiple tools, both software-based and online, are available for quick conversion of YouTube into MPEG files.
If you require stable software for editing functions in a long run, [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a suitable choice, with MPEG-2 format available as an output option. Besides that, HitPaw among the software types among the online converters are high-quality alternatives for direct YouTube to MPEG conversion. So, give them serious consideration while making your choice.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit)
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
The Top 5 YouTube to MPEG4 Converters \[Desktop only\]
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://some-skills.techidaily.com/updated-superior-online-emporiums-where-boxes-reflect-your-style/"><u>[Updated] Superior Online Emporiums Where Boxes Reflect Your Style</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-top-ten-cyber-shops-where-every-gift-tells-a-story/"><u>[New] Top Ten Cyber Shops Where Every Gift Tells a Story</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-the-complete-process-for-selecting-top-online-photo-edits/"><u>[New] The Complete Process for Selecting Top Online Photo Edits</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-the-efficient-use-of-slug-lines-in-content-writing/"><u>In 2024, The Efficient Use of Slug Lines in Content Writing</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-the-inconspicuous-footprint-of-social-media-engagements/"><u>In 2024, The Inconspicuous Footprint of Social Media Engagements</u></a></li>
<li><a href="https://some-skills.techidaily.com/vertex-productions-summary-pinnacle-studio-assessment-2023-for-2024/"><u>Vertex Productions Summary Pinnacle Studio Assessment, 2023 for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-top-tunes-choosing-best-offline-audio-to-text-tools/"><u>[New] Top Tunes Choosing Best Offline Audio-to-Text Tools</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-the-definitive-iphone-hdr-technique/"><u>In 2024, The Definitive iPhone HDR Technique</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-unrivaled-narratives-crafted-in-eight-film-fields/"><u>[New] Unrivaled Narratives Crafted in Eight Film Fields</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-the-writers-toolkit-dialogue-and-narration-techniques-for-success/"><u>In 2024, The Writer's Toolkit Dialogue and Narration Techniques for Success</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-the-illustrator-way-adding-realistic-blur-to-your-pics/"><u>[New] The Illustrator Way Adding Realistic Blur to Your Pics</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-stellar-spectrum-10-sites-cutting-edge-of-hd-astronomy/"><u>[New] Stellar Spectrum 10 Sites Cutting-Edge of HD Astronomy</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-unlocking-10plus-top-free-subtitle-converter-websites/"><u>[New] Unlocking 10+ Top Free Subtitle Converter Websites</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-the-new-era-advancements-in-vr-technology/"><u>2024 Approved The New Era Advancements in VR Technology</u></a></li>
<li><a href="https://some-skills.techidaily.com/the-creme-de-la-meme-collection-10-for-2024/"><u>The Crème De La Meme Collection - #10 for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/unlocking-the-secrets-pro-level-iphone-landscape-tips-for-2024/"><u>Unlocking the Secrets Pro-Level iPhone Landscape Tips for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-understanding-key-aspects-of-gif-animation/"><u>In 2024, Understanding Key Aspects of GIF Animation</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-unlocking-top-notch-visuals-a-cost-free-approach/"><u>In 2024, Unlocking Top-Notch Visuals A Cost-Free Approach</u></a></li>
<li><a href="https://some-skills.techidaily.com/the-comprehensive-guide-to-using-viva-video-for-2024/"><u>The Comprehensive Guide to Using Viva Video for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-unravel-the-power-of-wmp-in-audio-transition-from-cds/"><u>2024 Approved Unravel the Power of WMP in Audio Transition From Cds</u></a></li>
<li><a href="https://some-skills.techidaily.com/tailored-touch-up-top-6-apps-to-exclude-unwanted-elements-from-photos-for-2024/"><u>Tailored Touch-Up Top 6 Apps to Exclude Unwanted Elements From Photos for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-unveiling-iphonepcs-best-video-conversion-software-8/"><u>[New] Unveiling iPhone/PC's Best Video Conversion Software #8</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-the-untold-story-10-pro-vlc-tricks-for-better-playback/"><u>In 2024, The Untold Story 10 Pro-VLC Tricks for Better Playback</u></a></li>
<li><a href="https://some-skills.techidaily.com/unveiling-secrets-phantoms-slow-motion-techniques-for-2024/"><u>Unveiling Secrets Phantom's Slow Motion Techniques for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-the-5-best-tools-to-convert-videos-directly-to-twitter/"><u>2024 Approved The 5 Best Tools to Convert Videos Directly to Twitter</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-the-ultimate-video-upgrade-pathway-sdr-to-hdri-transformation-techniques/"><u>[New] The Ultimate Video Upgrade Pathway SDR to HDRI Transformation Techniques</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-stream-undoing-masterclass-twenty-one-tactics-to-learn-and-use/"><u>In 2024, Stream Undoing Masterclass Twenty-One Tactics to Learn and Use</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-the-ultimate-insights-into-audio-memos/"><u>2024 Approved The Ultimate Insights Into Audio Memos</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-understanding-imovies-editing-edge/"><u>In 2024, Understanding iMovie's Editing Edge</u></a></li>
<li><a href="https://some-skills.techidaily.com/summers-best-10-nostalgic-films-for-the-whole-family-for-2024/"><u>Summer's Best 10 Nostalgic Films for the Whole Family for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/updated-understanding-vr-limitations/"><u>[Updated] Understanding VR Limitations</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-stunning-evaluation-and-different-paths/"><u>In 2024, Stunning Evaluation & Different Paths</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-streamline-your-footage-iphones-shortening-methods/"><u>[New] Streamline Your Footage IPhone's Shortening Methods</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-streamline-your-multi-tasking-pip-settings-in-safari/"><u>2024 Approved Streamline Your Multi-Tasking PIP Settings in Safari</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-the-ultimate-guide-to-font-customization-in-ae/"><u>[New] The Ultimate Guide to Font Customization in AE</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-tapping-into-creative-potential-with-luts-in-premiere-pro/"><u>[New] Tapping Into Creative Potential with LUTs in Premiere Pro</u></a></li>
<li><a href="https://fake-location.techidaily.com/can-life360-track-or-see-text-messages-what-can-you-do-with-life360-on-infinix-smart-7-hd-drfone-by-drfone-virtual-android/"><u>Can Life360 Track Or See Text Messages? What Can You Do with Life360 On Infinix Smart 7 HD? | Dr.fone</u></a></li>
<li><a href="https://location-social.techidaily.com/3-things-you-must-know-about-fake-snapchat-location-on-honor-x50-drfone-by-drfone-virtual-android/"><u>3 Things You Must Know about Fake Snapchat Location On Honor X50 | Dr.fone</u></a></li>
<li><a href="https://video-capture.techidaily.com/streamlining-video-conferencing-with-efficient-use-of-snap-features-on-google-meet-for-2024/"><u>Streamlining Video Conferencing with Efficient Use of Snap Features on Google Meet for 2024</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/in-2024-best-3-vivo-y200-emulator-for-mac-to-run-your-wanted-android-apps-drfone-by-drfone-android/"><u>In 2024, Best 3 Vivo Y200 Emulator for Mac to Run Your Wanted Android Apps | Dr.fone</u></a></li>
<li><a href="https://video-capture.techidaily.com/in-2024-your-ultimate-guide-to-perfectly-recorded-lol-gaming/"><u>In 2024, Your Ultimate Guide to Perfectly Recorded LOL Gaming</u></a></li>
<li><a href="https://android-transfer.techidaily.com/how-to-transfer-photos-from-tecno-pop-7-pro-to-laptop-without-usb-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>How to Transfer Photos from Tecno Pop 7 Pro to Laptop Without USB | Dr.fone</u></a></li>
<li><a href="https://twitter-videos.techidaily.com/new-2024-approved-hashtag-hype-unveiling-twitters-toptiktok-videos/"><u>[New] 2024 Approved Hashtag Hype Unveiling Twitter's #TopTikTok Videos</u></a></li>
<li><a href="https://extra-approaches.techidaily.com/new-leveraging-hdrs-potential-for-ultimate-video-visualization/"><u>[New] Leveraging HDR's Potential for Ultimate Video Visualization</u></a></li>
<li><a href="https://screen-mirroring-recording.techidaily.com/the-ultimate-pathway-to-premium-webcam-footage/"><u>The Ultimate Pathway to Premium Webcam Footage</u></a></li>
<li><a href="https://techidaily.com/how-to-transfer-data-from-apple-iphone-8-plus-to-other-iphone-drfone-by-drfone-transfer-data-from-ios-transfer-data-from-ios/"><u>How To Transfer Data From Apple iPhone 8 Plus To Other iPhone? | Dr.fone</u></a></li>
<li><a href="https://extra-guidance.techidaily.com/updated-sony-a6400-fixing-the-invisible-video-playback/"><u>[Updated] Sony A6400 Fixing the Invisible Video Playback</u></a></li>
<li><a href="https://tiktok-videos.techidaily.com/updated-in-2024-the-ultimate-tutorial-crafting-magnetic-tiktok-openers-with-macos/"><u>[Updated] In 2024, The Ultimate Tutorial Crafting Magnetic TikTok Openers with MacOS</u></a></li>
<li><a href="https://sound-tweaking.techidaily.com/silencing-soundscape-guiding-you-to-audio-deletion-in-mov-files-for-both-operating-systems-for-2024/"><u>Silencing Soundscape Guiding You to Audio Deletion in MOV Files for Both Operating Systems for 2024</u></a></li>
<li><a href="https://video-creation-software.techidaily.com/in-2024-the-best-of-the-best-top-12-audio-converters-for-any-format/"><u>In 2024, The Best of the Best Top 12 Audio Converters for Any Format</u></a></li>
<li><a href="https://techidaily.com/complete-tutorial-for-lava-storm-5g-hard-reset-drfone-by-drfone-reset-android-reset-android/"><u>Complete Tutorial for Lava Storm 5G Hard Reset | Dr.fone</u></a></li>
<li><a href="https://screen-activity-recording.techidaily.com/updated-comprehensive-tips-for-film-recording-on-multiple-platforms/"><u>[Updated] Comprehensive Tips for Film Recording on Multiple Platforms</u></a></li>
<li><a href="https://ios-pokemon-go.techidaily.com/in-2024-planning-to-use-a-pokemon-go-joystick-on-apple-iphone-11-pro-drfone-by-drfone-virtual-ios/"><u>In 2024, Planning to Use a Pokemon Go Joystick on Apple iPhone 11 Pro? | Dr.fone</u></a></li>
<li><a href="https://visual-screen-recording.techidaily.com/updated-top-obs-substitutes-for-live-streaming-success/"><u>[Updated] Top OBS Substitutes for Live-Streaming Success</u></a></li>
<li><a href="https://youtube-help.techidaily.com/incorporating-cards-and-annotations-in-youtube-content-for-2024/"><u>Incorporating Cards and Annotations in YouTube Content for 2024</u></a></li>
<li><a href="https://screen-sharing-recording.techidaily.com/updated-the-comprehensive-guide-to-zoom-screen-casts-for-2024/"><u>[Updated] The Comprehensive Guide to Zoom Screen Casts for 2024</u></a></li>
<li><a href="https://extra-information.techidaily.com/2024-approved-a-visual-journey-mastering-the-art-of-incorporating-text-into-images-on-pcmacos/"><u>2024 Approved A Visual Journey Mastering the Art of Incorporating Text Into Images on PC/MacOS</u></a></li>
<li><a href="https://extra-tips.techidaily.com/balancing-main-and-supplemental-filmmaking-elements-for-2024/"><u>Balancing Main & Supplemental Filmmaking Elements for 2024</u></a></li>
</ul></div> |
/*
* Arduino nfc door lock with remote card database on webserver.
* Copyright 2014 Alberto Panu alberto[at]panu.it
*
* Pin layout for the MFRC522 board should be as follows:
* Signal Pin
* Arduino Uno
* ------------------------
* Reset 8
* SPI SS 9
* SPI MOSI 11
* SPI MISO 12
* SPI SCK 13
*
* The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
*/
#include <SPI.h>
#include <MFRC522.h>
#include <Ethernet.h>
/* DEBUG levels
0 no
1 normal
2 verbose */
#define DEBUG 2
/* tentativi set ne try connection number to webserver */
#define tentativi 5
/* pin_della_serratura is the lock pin */
#define pin_della_serratura 5
/* chose the ip setup 0 for DHCP */
#define IPSETUP 1
/* portaserver set the remote server port */
#define portaserver 80
/* rficodemaxlenght rfid uuid max lenght, i don't read the nfc spec */
#define rficodemaxlenght 16
/* MFRC522 module variables */
#define SS_PIN 9
#define RST_PIN 8
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
unsigned char lettura;
unsigned char rfidcode[rficodemaxlenght];
unsigned char rficodelenght;
char risposta;
String reponse = "test";
unsigned int prove;
EthernetClient client;
/* remote server ip, change wth your server ip */
byte server[] = { 81, 208, 22, 71 };
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x4D, 0x49 };
// DHCP
#if IPSETUP == 0
#warning Ethernet configured by DHCP
#endif
// Lavoro
#if IPSETUP == 1
#warning Ethernet Lavoro
byte ip[] = { 10, 63, 0, 183 };
byte mydns[] = { 8, 8, 8, 8 };
byte gateway[] = { 10, 63, 0, 1 };
byte netmask[] = { 255, 255, 254, 0 };
#endif
// Casa
#if IPSETUP == 2
#warning Ethernet Casa
byte ip[] = { 192, 168, 1, 17 };
byte mydns[] = { 8, 8, 8, 8 };
byte gateway[] = { 192, 168, 1, 1 };
byte netmask[] = { 255, 255, 255, 0 };
#endif
void setup() {
pinMode(pin_della_serratura,OUTPUT);
digitalWrite(pin_della_serratura,LOW);
#if DEBUG > 0
Serial.begin(9600); // Initialize serial communications with the PC
#endif
// removed because already done by ethernet
// SPI.begin(); // Init SPI bus
#if IPSETUP > 0
Ethernet.begin(mac, ip, mydns, gateway, netmask);
#else
while ( Ethernet.begin(mac) == 0 ) {
#if DEBUG > 0
Serial.println("DHCP configuration error!");
Serial.println("retry in 5 seconds");
#endif
delay(5000);
}
#if DEBUG > 0
Serial.println("Ethernet DHCP configured.");
#endif
#endif
delay(1000);
mfrc522.PCD_Init(); // Init MFRC522 card
#if DEBUG > 0
Serial.println("Nfc toker reader ready!");
#endif
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
rficodelenght = mfrc522.uid.size;
if ( rficodelenght > rficodemaxlenght ) {
#if DEBUG > 0
Serial.println("Rfid uid too long!");
#endif
mfrc522.PICC_HaltA();
return;
}
for (byte i = 0; i < mfrc522.uid.size; i++) {
rfidcode[i]=mfrc522.uid.uidByte[i];
}
mfrc522.PICC_HaltA();
#if DEBUG > 0
Serial.print("Card UID:");
for ( byte i = 0 ; i < rficodelenght; i++) {
Serial.print(rfidcode[i] < 0x10 ? "0" : "");
Serial.print(rfidcode[i], HEX);
}
Serial.println();
#endif
prove = tentativi;
while (prove > 0) {
risposta='E';
// EthernetClient client;
#if DEBUG > 1
Serial.println("connecting...");
#endif
if ( client.connect(server, portaserver) ) {
#if DEBUG > 1
Serial.println("connected");
#endif
// this should be the page on your server that check the rfid code ar return in text act=O for open or act=C for close
client.print("GET /tcpnfclockduino/x.shtml?rfid=");
// this is a test page on my webserver that randomly respond open or close and do not check the rfid code
// client.print("GET /tcpnfclockduino/random.shtml?rfid=");
// this is a test page on my webserver that every time open the door and do not check the rfid code
// client.print("GET /tcpnfclockduino/lock_open.html?rfid=");
// this is a test page on my webserver that every time don't open the door and do not check the rfid code
// client.print("GET /tcpnfclockduino/lock_close.html?rfid=");
for ( byte i = 0; i < rficodelenght; i++) {
if (rfidcode[i] < 10)
client.print("0");
client.print(rfidcode[i],HEX);
}
client.println(" HTTP/1.1");
client.println("Host: www.panu.it");
client.println("");
delay(200);
reponse = "";
// Be aware the response must be in the fist 340 characters!
while (client.available() && reponse.length() < 350) {
risposta = client.read();
reponse = reponse + risposta;
#if DEBUG > 1
Serial.print(risposta);
#endif
}
#if DEBUG > 1
Serial.println("");
Serial.println("-----------------------");
Serial.println(reponse);
Serial.println("-----------------------");
#endif
client.stop();
if ( reponse.indexOf("act=O") > 0 ) {
// Here we open the door
digitalWrite(pin_della_serratura,HIGH);
delay(100);
digitalWrite(pin_della_serratura,LOW);
#if DEBUG > 0
Serial.println("Door opened!");
#endif
break;
}
#if DEBUG > 0
else if ( reponse.indexOf("act=C") > 0) {
Serial.println("Unauthorized card");
break;
} else {
Serial.print("Door command not found on page");
}
#endif
}
#if DEBUG > 0
else {
Serial.println("connection failed");
}
#endif
#if DEBUG > 1
Serial.print("Connect server try number: ");
Serial.print(prove);
Serial.println(" falied!");
#endif
prove--;
}
#if DEBUG > 0
if (prove == 0) {
Serial.println("Remote server connect error!");
}
#endif
} |
import { ApiProperty, OmitType, PickType } from "@nestjs/swagger"
import { Type } from "class-transformer"
import { IsObject, IsOptional, IsString, ValidateNested } from "class-validator"
import { UserDto } from "src/user/dto/create-user.dto"
// export class DeskripsiMobil {
// @ApiProperty()
// @IsOptional()
// id: string
// @ApiProperty()
// @IsString()
// cc: string
// @ApiProperty()
// @IsString()
// diameter_pistion: string
// @ApiProperty()
// @IsString()
// langkah_mesin: string
// @ApiProperty()
// @IsString()
// jumlah_silinder: string
// @ApiProperty()
// @IsString()
// tipe_mesin: string
// @ApiProperty()
// @IsString()
// toris_maksimum: string
// @ApiProperty()
// @IsString()
// type: string
// @ApiProperty()
// @IsString()
// sistem_pendinginan: string
// @ApiProperty()
// @IsString()
// sistem_pembakaran: string
// }
// export class CreateDeskripsiMobil extends OmitType(DeskripsiMobil, ['id']) { }
export class JualMobilDto {
@ApiProperty({ default: '', required: false })
@IsOptional()
id: string
@ApiProperty({ default: '', required: false })
@IsString()
merek_mobil: string
@ApiProperty({ default: '', required: false })
@IsString()
model: string
@ApiProperty({ default: '', required: false })
@IsString()
no_polisi: string
@ApiProperty({ default: '', required: false })
@IsString()
jarak_tempuh: string
@ApiProperty({ default: '', required: false })
@IsString()
tipe: string
@ApiProperty({ default: '', required: false })
@IsString()
tahun_kendaraan: string
@ApiProperty({ default: '', required: false })
@IsString()
warna: string
@ApiProperty({ default: '', required: false })
@IsString()
lokasi: string
@ApiProperty({ default: '', required: false })
@IsString()
harga: string
@ApiProperty({ default: '', required: false })
@IsString()
kondisi: string
@ApiProperty({ default: '', required: false })
@IsString()
deskripsi: string
@IsObject()
user: UserDto
// @ApiProperty({ isArray: true, type: CreateDeskripsiMobil })
// @Type(() => CreateDeskripsiMobil)
// @ValidateNested({ each: true })
// deskripsi: CreateDeskripsiMobil[];
}
export class CreateJualMobilDto extends OmitType(JualMobilDto, ['id']) { }
export class JualMobilIdDto extends PickType(JualMobilDto, ['id']) { } |
import type { PackageCacheNamespace } from '../../cache/package/types';
export interface GithubDatasourceItem {
version: string;
releaseTimestamp: string;
}
/**
* Datasource-specific structure
*/
export interface GithubGraphqlDatasourceAdapter<
Input,
Output extends GithubDatasourceItem,
> {
/**
* Used for creating datasource-unique cache key
*/
key: PackageCacheNamespace;
/**
* Used to define datasource-unique GraphQL query
*/
query: string;
/**
* Used for transforming GraphQL nodes to objects
* that have `version` and `releaseTimestamp` fields.
*
* @param input GraphQL node data
*/
transform(input: Input): Output | null;
}
export type RawQueryResponse<Payload> = [Payload, null] | [null, Error];
export interface GithubGraphqlPayload<T> {
nodes: T[];
pageInfo?: {
hasNextPage?: boolean;
endCursor?: string;
};
}
export interface GithubGraphqlRepoResponse<T> {
repository: {
isRepoPrivate?: boolean;
payload: GithubGraphqlPayload<T>;
};
}
export interface GithubPackageConfig {
/**
* Example: renovatebot/renovate
*/
packageName: string;
/**
* Default: https://api.github.com
*/
registryUrl?: string | undefined;
}
/**
* Result of GraphQL response transformation for releases (via adapter)
*/
export interface GithubReleaseItem extends GithubDatasourceItem {
isStable?: boolean;
url: string;
id?: number;
name?: string;
description?: string;
}
/**
* Result of GraphQL response transformation for tags (via tags)
*/
export interface GithubTagItem extends GithubDatasourceItem {
hash: string;
gitRef: string;
}
/**
* Parameters being passed as GraphQL variables
*/
export interface GithubGraphqlRepoParams {
owner: string;
name: string;
cursor: string | null;
count: number;
}
export interface GithubGraphqlCacheRecord<
GithubItem extends GithubDatasourceItem,
> {
items: Record<string, GithubItem>;
createdAt: string;
}
export interface GithubGraphqlCacheStrategy<
GithubItem extends GithubDatasourceItem,
> {
reconcile(items: GithubItem[]): Promise<boolean>;
finalizeAndReturn(): Promise<GithubItem[]>;
} |
import { BaseSyntheticEvent } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addToCart, deleteToCart } from '../../redux/cart/cartSlice';
import { ProductComponent } from '../../types/components';
import { State } from '../../types/redux';
function Product({ product, name, desc, price, type, onDeleteProduct }: ProductComponent) {
const dispatch = useDispatch();
const products = useSelector((state: State) => state.cart.cartItems);
const isProductsInCart = products.some((i) => i._id === product._id);
function handleClick(e: Event | BaseSyntheticEvent) {
e.stopPropagation();
if (isProductsInCart) {
dispatch(deleteToCart(product));
} else {
dispatch(addToCart(product));
}
}
function handleDeleteProduct(e: Event | BaseSyntheticEvent) {
e.stopPropagation();
onDeleteProduct(product._id);
}
return (
<article onClick={handleClick} className="product-list__item">
<button className="product-list__delete-button" onClick={(e) => handleDeleteProduct(e)} />
<span className="product-list__announcement">Удаление для администратора:</span>
<div className={type !== 'pizza' ? 'product-list__border' : 'product-list__border product-list__border_disable'}>
<img className="product-list__image" src={product.image.path} alt={name} />
</div>
<h3 className="product-list__name">{name}</h3>
<p className="product-list__about">{desc}</p>
<span className="product-list__price">{`${price} руб.`}</span>
<button className={`product-list__button ${isProductsInCart && 'product-list__button_inactive'}`}>
{isProductsInCart ? 'Убрать из корзины' : 'В корзину'}
</button>
</article>
);
}
export default Product; |
# Query Saver Chrome Extension (React, TypeScript, Webpack)
This project demonstrates how to build a Chrome extension using [React](https://react.dev/) with TypeScript and Webpack. It showcases key features such as interacting with Chrome APIs ([storage](https://developer.chrome.com/docs/extensions/reference/api/storage), [contextMenus](https://developer.chrome.com/docs/extensions/reference/api/contextMenus)), testing with [Jest](https://jestjs.io/) and [Sinon](https://sinonjs.org/), and structuring a React app with separation of concerns.
## Features
- Capture queries of text from web pages using a [**context menu**](https://developer.chrome.com/docs/extensions/reference/api/contextMenus)
- View, edit, and delete saved queries in a [**popup window**](https://developer.chrome.com/docs/extensions/reference/api/action#show_a_popup) triggered by an [**action button**](https://developer.chrome.com/docs/extensions/reference/api/action)
- Persist queries using [Chrome's storage API](https://developer.chrome.com/docs/extensions/reference/api/storage)
- Interact with the extension using content scripts and background scripts
- Comprehensive testing setup using [Jest](https://jestjs.io/), [Sinon](https://sinonjs.org/), and [sinon-chrome](https://github.com/acvetkov/sinon-chrome/) for mocking Chrome API
## Screenshots
The first screenshot showcases the **popup window** with saved queries and the **action button** (SC in the top-right corner):

The second screenshot shows the **context menu** that appears when you right-click on a web page to capture a query (this context menu is registered and its events are handled in the `background.js` script):

## Installation
### Install From Release
- Download the latest release from the [Releases](https://github.com/jlumbroso/chrome-extension-text-collector/releases)
- Unzip the downloaded ZIP file
- Open Chrome and navigate to `chrome://extensions`
- Enable "Developer mode"
- Drag and drop the unzipped folder into the extensions page
### Install From Source
1. Clone the repository:
```bash
git clone https://github.com/jlumbroso/chrome-extension-text-collector
```
2. Install dependencies:
```bash
cd chrome-extension-text-collector
npm install
```
3. Build the extension:
```bash
npm run build
```
4. Load the extension in Chrome:
- Open Chrome and navigate to `chrome://extensions`
- Enable "Developer mode"
- Click "Load unpacked" and select the `dist` directory from the project
## Usage
- Right-click on a web page and select "Capture Query" from the context menu to save the selected text as a query
- Click on the extension icon to open the popup window
- In the popup, you can view, edit, and delete saved queries
## Development
- Run the development server with hot reloading:
```bash
npm run watch
```
- Load the unpacked extension in Chrome from the `dist` directory
- Make changes to the source code and the extension will automatically reload
## Chrome Extension Architecture
This project follows the Manifest V3 architecture for Chrome extensions. Key components of the architecture include:
- `manifest.json`: Defines the extension's metadata, permissions, and script configurations
- `background.js`: Runs in the background and handles events and long-running tasks
- `contentScript.js`: Injected into web pages to interact with the DOM and communicate with the background script
- Popup window: Displays the extension's user interface when the extension icon is clicked
### Manifest V3
This extension is built using the latest version of the Chrome extension manifest (Manifest V3). The `manifest.json` file defines the extension's properties, permissions, and scripts.
Key aspects of the Manifest V3 configuration include:
- `manifest_version`: Set to `3` to use Manifest V3
- `background`: Specifies the background script as a service worker
- `action`: Defines the popup HTML file
- `permissions`: Declares the required permissions for the extension (storage, activeTab, contextMenus)
- `content_scripts`: Specifies the content script to be injected into web pages
## Project Architecture
The project follows a modular architecture with separation of concerns:
- `App`: The main component that manages the state and renders the `QueryList`
- `QueryList`: Renders a list of `QueryItem` components based on the saved queries
- `QueryItem`: Represents an individual query with options to edit and delete
The communication between the extension's scripts is handled as follows:
- `contentScript.js`: Injected into web pages, captures selected text and sends a message to the background script
- `background.js`: Listens for messages from the content script, saves queries to storage, and manages the context menu
## Testing
The project includes a comprehensive testing setup using Jest, Sinon, and sinon-chrome. The tests cover various aspects of the extension, including component rendering, user interactions, and mocking of Chrome APIs.
To run the tests:
```bash
npm run test
```
To generate a coverage report:
```bash
npm run coverage
```
### Mocking Chrome APIs
One of the key aspects of testing a Chrome extension is mocking the Chrome APIs. This project uses the following libraries to achieve this:
- [Jest](https://jestjs.io/): The test runner and assertion library
- [Sinon](https://sinonjs.org/): A library for creating spies, stubs, and mocks
- [sinon-chrome](https://github.com/acvetkov/sinon-chrome/): A collection of pre-built mocks for Chrome APIs
- [jest-sinon](https://github.com/djkf/jest-sinon): An extension for Jest to work seamlessly with Sinon
Here's an example test that demonstrates mocking the Chrome storage API:
```typescript
it('sets initial state with empty array when queries key is an empty array in local storage', async () => {
chrome.storage.local.get.withArgs('queries').yields({ queries: [] });
render(<App />);
const queryElements = screen.queryAllByRole('listitem');
expect(queryElements).toHaveLength(0);
});
```
In this test, we mock the `chrome.storage.local.get` method to return an empty array for the 'queries' key. This allows us to test how the `App` component behaves when there are no saved queries.
## Duplicating Project: Using This Project As A Starting Point
You are welcome to use this repository as a starting point for your own work. The best way to do so is to import the repository into your own GitHub account: You can do so either [using the GitHub Importer (recommended)](https://docs.github.com/en/migrations/importing-source-code/using-github-importer/importing-a-repository-with-github-importer) or [manually using the command-line](https://docs.github.com/en/repositories/creating-and-managing-repositories/duplicating-a-repository).
## Ideas for Enhancements
Here are a few ideas to enhance the functionality of this Chrome extension:
- Support rich formatting
- Implement syntax highlighting when selecting code
- Make it easy to copy a query to clipboard
- Add tags or categories to queries for better organization
- Implement search functionality to filter queries
- Allow users to export and import queries as JSON files
- Integrate with a note-taking service or a cloud storage provider
- Add a feature to share queries with others
## Credits
The initial setup of this project was based on the tutorial by [Harshita Joshi](https://github.com/Harshita-mindfire) on creating a Chrome extension with React and TypeScript. The corresponding Medium article can be found [here](https://medium.com/@tharshita13/creating-a-chrome-extension-with-react-a-step-by-step-guide-47fe9bab24a1).
The project has been extended with additional functionality, testing setup, and documentation. The most difficult part was figuring out the right combination of packages for the testing suite (for instance, I would avoid `jest-chrome`, `mockzilla`, `mockzilla-webextension`, to name but a few). |
import _ from 'radash'
import type { Props, ApiFunction } from '@exobase/core'
import { errors } from '@exobase/core'
import { verify } from '@octokit/webhooks-methods'
export async function withGithubWebhook(func: ApiFunction, secret: string, props: Props) {
const signature = props.req.headers['x-hub-signature-256'] as string
if (!signature) {
throw errors.badRequest({
details: 'Missing required github signature header',
key: 'exo.with-github-webhook.nana'
})
}
const validate = _.try(async () => {
// See: https://github.com/octokit/webhooks-methods.js/#sign
const eventPayloadString = JSON.stringify(props.req.body) + '\n'
return await verify(secret, eventPayloadString, signature)
})
const [err, isValid] = await validate()
if (err) {
throw errors.unknown({
details: 'Error encountered while trying to validate webhook signature',
key: 'exo.with-github-webhook.marlin'
})
}
if (!isValid) {
throw errors.badRequest({
details: 'Request body failed webhook signature validation',
key: 'exo.with-github-webhook.statix'
})
}
return await func({
...props,
args: {
...props.args,
event: props.req.body
}
})
}
/**
* Validates the signature of the incoming webhook payload
* given the provided secret.
*/
export const useGithubWebhook = <TServices = Record<string, any>> (secret: string) => {
return (func: ApiFunction) => _.partial(withGithubWebhook, func, secret)
} |
import { useEffect, useState } from "react";
const DataFetch = () => {
const [todos, setTodos] = useState(null); //for data fetching
const [isLoading, setIsLoading] = useState(true); // if data loding
const [error, setError] = useState(null); //if catch error
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => {
// data convert to json data
if (!response.ok) {
throw Error("data loding is unsuccessful"); //if get error in data fetching
}
return response.json();
})
.then((data) => {
setTodos(data); // data send to use state
setIsLoading(false); // if get data not need loading
})
.catch((error) => {
// for get any error in data fetching
setError(error.message);
setIsLoading(false); //if get error not need data loading
});
}, []);
const todoElement =
todos &&
todos.map((todo) => {
//if todos is true then map work
return <p key={todo.id}>{todo.name}</p>;
});
return (
<div>
<h1>DataFatch</h1>
{todoElement}
{isLoading && "Data is loading"}
{/* if data is loding then it will be give message */}
{error && error}{" "}
{/* if get any error then error will work and it will give error message */}
</div>
);
};
export default DataFetch; |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package account.connections;
import account.requests.ConnectionRequestCreate;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author El Jefe
*/
@WebServlet(name = "ConnectionCreateServlet", urlPatterns = {"/ConnectionCreateServlet"})
public class ConnectionCreateServlet extends HttpServlet
{
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ConnectionCreateServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet ConnectionCreateServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ConnectionSearch connectionExistsSearch = null;
boolean connectionExists = false;
ConnectionRequestCreate connectionRequest = null;
long accountNumber = -1;
long sessionClientID = -1;
if (request.getParameter("connect-request-account-number") != null)
{
accountNumber = Long.parseLong(request.getParameter("connect-request-account-number"));
}
if (request.getParameter("connect-request-client-id") != null)
{
sessionClientID = Long.parseLong(request.getParameter("connect-request-client-id"));
}
connectionExistsSearch = new ConnectionSearch(accountNumber, sessionClientID);
connectionExists = connectionExistsSearch.search();
if (accountNumber != -1)
{
if (connectionExists == false)
{
connectionRequest = new ConnectionRequestCreate(accountNumber, sessionClientID);
}
}
response.sendRedirect("clients/home.jsp");
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo()
{
return "Short description";
}// </editor-fold>
} |
from django.db import models
from django.core.validators import FileExtensionValidator
from django.contrib.auth.models import User
from django.contrib import admin
from django.utils import timezone
# Address model
class Address(models.Model):
"""
Modèle représentant une adresse.
Attributes:
street (str): Rue de l'adresse.
city (str): Ville de l'adresse.
state (str): État ou région de l'adresse.
zip_code (str): Code postal de l'adresse.
country (str): Pays de l'adresse.
latitude (DecimalField): Latitude de l'adresse.
longitude (DecimalField): Longitude de l'adresse.
"""
street = models.CharField(max_length=255)
city = models.CharField(max_length=255)
state = models.CharField(max_length=255)
zip_code = models.CharField(max_length=255)
country = models.CharField(max_length=255)
latitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True)
longitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True)
# ClientProfile model, using OneToOneField for a one-to-one relationship with User
class ClientProfile(models.Model):
"""
Modèle représentant le profil d'un client.
Attributes:
user (User): Utilisateur associé au profil client.
age (int): Âge du client.
gender (str): Genre du client.
phone_number (str): Numéro de téléphone du client.
address (Address): Adresse du client (facultatif).
"""
user = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.IntegerField()
gender = models.CharField(max_length=255)
phone_number = models.CharField(max_length=255)
# address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self):
return f'{self.user.first_name} {self.user.last_name}'
@admin.display(ordering='user__first_name')
def first_name(self):
return self.user.first_name
@admin.display(ordering='user__last_name')
def last_name(self):
return self.user.last_name
class Meta:
ordering = ['user__first_name', 'user__last_name']
# LawyerProfile model, using OneToOneField for a one-to-one relationship with User
class LawyerProfile(models.Model):
"""
Modèle représentant le profil d'un avocat.
Attributes:
user (User): Utilisateur associé au profil de l'avocat.
specialization (str): Spécialisation de l'avocat.
phone_number (str): Numéro de téléphone de l'avocat.
bio (str): Biographie de l'avocat.
language (str): Langues parlées par l'avocat.
approved (bool): Indique si le profil de l'avocat est approuvé.
rating (int): Évaluation moyenne de l'avocat.
"""
user = models.OneToOneField(User, on_delete=models.CASCADE)
specialization = models.CharField(max_length=255)
phone_number = models.CharField(max_length=255)
bio = models.CharField(max_length=255)
#address = models.ForeignKey(Address, on_delete=models.CASCADE , related_name='lawyer_address')
language = models.CharField(max_length=255)
approved = models.BooleanField(default=True)
rating = models.IntegerField(null=True, blank=True)
def __str__(self):
return f'{self.user.first_name} {self.user.last_name}'
@admin.display(ordering='user__first_name')
def first_name(self):
return self.user.first_name
@admin.display(ordering='user__last_name')
def last_name(self):
return self.user.last_name
class Meta:
ordering = ['user__first_name', 'user__last_name']
# Administrator model, using OneToOneField for a one-to-one relationship with User
class Administrator(models.Model):
"""
Modèle représentant un administrateur.
Attributes:
user (User): Utilisateur associé à l'administrateur.
name (str): Nom de l'administrateur.
"""
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
# TimeSlot model
class TimeSlot(models.Model):
"""
Modèle représentant un créneau horaire pour un avocat.
Attributes:
day (str): Jour du créneau horaire.
start_time (TimeField): Heure de début du créneau.
end_time (TimeField): Heure de fin du créneau.
lawyer (LawyerProfile): Avocat associé au créneau horaire.
"""
day = models.CharField(max_length=255)
start_time = models.TimeField()
end_time = models.TimeField()
lawyer = models.ForeignKey(LawyerProfile, on_delete=models.CASCADE , related_name='time_slots')
# Appointment model
class Appointment(models.Model):
"""
Modèle représentant un rendez-vous entre un client et un avocat.
Attributes:
time_slot (TimeSlot): Créneau horaire du rendez-vous.
lawyer (LawyerProfile): Avocat avec lequel le rendez-vous est pris.
client (ClientProfile): Client qui prend le rendez-vous.
date (DateField): Date du rendez-vous.
status (str): Statut du rendez-vous.
"""
time_slot = models.ForeignKey(TimeSlot, on_delete=models.CASCADE)
lawyer = models.ForeignKey(LawyerProfile, on_delete=models.CASCADE)
client = models.ForeignKey(ClientProfile, on_delete=models.CASCADE)
date = models.DateField(default=timezone.now)
status = models.CharField(max_length=255)
# Review model
class Review(models.Model):
"""
Modèle représentant un avis laissé par un client pour un avocat.
Attributes:
lawyer (LawyerProfile): Avocat évalué.
client (ClientProfile): Client laissant l'avis.
rating (int): Note attribuée à l'avocat.
comment (str): Commentaire sur l'avocat.
date (DateField): Date de l'avis.
"""
lawyer = models.ForeignKey(LawyerProfile, on_delete=models.CASCADE)
client = models.ForeignKey(ClientProfile, on_delete=models.CASCADE)
rating = models.IntegerField()
comment = models.CharField(max_length=255)
date = models.DateField(auto_now_add=True)
# LawyerDocument model
class LawyerImage(models.Model):
"""
Modèle représentant une image d'un avocat.
Attributes:
lawyer (LawyerProfile): Avocat associé à l'image.
image (ImageField): Image de l'avocat.
"""
lawyer = models.ForeignKey(LawyerProfile, on_delete=models.CASCADE, related_name='images')
image = models.ImageField(upload_to='core/images', blank=True, null=True)
def __str__(self):
return f"Image for {self.lawyer.user.username}"
class LawyerDocument(models.Model):
"""
Modèle représentant un document d'un avocat.
Attributes:
lawyer (LawyerProfile): Avocat associé au document.
pdf_file (FileField): Fichier PDF du document.
"""
lawyer = models.ForeignKey(LawyerProfile, on_delete=models.CASCADE, related_name='documents')
pdf_file = models.FileField(upload_to='core/docs', validators=[FileExtensionValidator(['pdf'])])
def __str__(self):
return f"Document for {self.lawyer.user.username}" |
"""
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
"""
class Solution:
def trap(self, height: list[int]) -> int:
if not height:
return 0
l,r = 0, len(height)-1
l_max, r_max = height[l], height[r]
res = 0
while l <r:
if l_max < r_max:
l +=1
l_max = max(l_max, height[l])
res += l_max - height[l]
else:
r -=1
r_max = max(r_max, height[r])
res += r_max - height[r]
return res |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.wpilibj2.command.Command;
import frc.robot.LimelightHelpers;
import frc.robot.RobotContainer;
import frc.robot.drivetrain.OmniSpeeds;
import frc.robot.subsystems.DriveTrainSubsystem;
public class CenterAprilTagCommand extends Command {
private final RobotContainer robot;
private final PIDController pid;
private final int id;
public CenterAprilTagCommand(RobotContainer robot, PIDController pid, int id) {
this.robot = robot;
this.pid = pid;
this.id = id;
addRequirements(robot.getDriveTrainSubsystem());
}
@Override
public void execute() {
DriveTrainSubsystem driveTrainSubsystem = robot.getDriveTrainSubsystem();
double x = LimelightHelpers.getTX("") - 12;
double heading = Math.toRadians(robot.getGyro().getAngle());
driveTrainSubsystem.drive(OmniSpeeds.from(MathUtil.clamp(pid.calculate(-x, 0), -1, 1), Math.PI / 2, 0, heading));
}
@Override
public void end(boolean interrupted) {
robot.getDriveTrainSubsystem().drive(OmniSpeeds.from(0, 0, 0, Math.toRadians(robot.getGyro().getAngle())));
pid.reset();
}
@Override
public boolean isFinished() {
return LimelightHelpers.getFiducialID("") != id || pid.atSetpoint();
}
} |
<template>
<div id="container">
<!-- Header -->
<header id="main-header">
<div id="bio-container">
<h1 id="header-name">Ethan Printz</h1>
<h3 id="header-major">New Grad from NYU IMA/ITP</h3>
<h3 id="header-role">UX // XR // Mobile Dev // Web Dev</h3>
</div>
<img :src="require(`@/assets/img/nyc-skyline.png`)" alt id="skyline" />
<nuxt-link to="/contact">
<div id="contact">
About + Contact
</div>
</nuxt-link>
</header>
<!-- Content -->
<main id="indexMain">
<div id="project-container" class="content-container">
<nuxt-link
:to="{ path: `/${post.classes[0].slug}/project/${post.slug}` }"
v-for="(post, index) in projects"
:key="index">
<div class="project-card content-card" v-if="post.visible == true">
<div :id="'project' + index" class="project-image-container">
<img
:src="$config.STRAPI_URL + post.cardImage.url"
:alt="`Illustration of ${post.title}`"
class="project-image"/>
</div>
<div class="project-title">{{ post.title }}</div>
<div class="project-description">{{ post.classes.term }}</div>
<div class="project-term">{{ terms.find(term => term.id === post.classes[0].term).name.toUpperCase()}}</div>
</div>
</nuxt-link>
</div>
<span class="background-container" id="experiment-background">
<div class="title" id="experiments-title">Experiments </div>
<!-- <div class="experiment-filter">
<div class="filter-title">Filter</div>
<div
class="filter-tag"
v-for="(category, index) in categories"
:style="{ 'background-color': category.color }"
v-on:click="selectedFilter = category.name"
:key="index">
{{category.name}}
</div>
</div> -->
<div id="experiment-container" class="content-container">
<nuxt-link
v-for="(experiment, index) in experiments"
:to="{ path: `/${experiment.classes[0].slug}/experiment/${experiment.slug}` }"
:key="index">
<div
class="experiment-card content-card">
<div class="experiment-emoji">{{ experiment.emoji }}</div>
<div class="experiment-title">{{ experiment.title }}</div>
<!-- <div class="experiment-dot-container">
<div
class="experiment-dot"
v-for="(category, index) in categories"
:style="{'background-color': category.color}"
:key="index">
</div>
</div> -->
</div>
</nuxt-link>
</div>
</span>
</main>
</div>
</template>
<script>
import { getAllPostsOfType, getAllClasses, getAllTerms, getAllCategories } from "../api/posts";
export default {
// Query data from headless CMS
asyncData: async () => {
const terms = await getAllTerms();
const projects = await getAllPostsOfType("project");
projects.forEach(post => post.date = new Date(post.date));
projects.sort((a, b) => b.date - a.date);
const experiments = await getAllPostsOfType("experiment");
experiments.forEach(post => post.date = new Date(post.date));
experiments.sort((a, b) => b.date - a.date);
const classes = await getAllClasses();
const categories = await getAllCategories();
return { projects, experiments, classes, terms, categories };
},
// Inject head meta information
head(){
return {
title: `Ethan Printz | Portfolio`
}
},
// Declare reactive data
// data(){
// return {
// selectedFilter: 'none'
// }
// },
// // Setup computed data
// computed: {
// selectedExperiments: function(){
// // return this.experiments;
// return this.experiments.filter(experiment => {
// experiment.categories.some(cat => cat.name === selectedFilter)
// })
// }
// },
// Code to execute on page mount
// Add hover effect to project images
mounted() {
document.querySelectorAll(".project-image-container").forEach(projectImage => {
pivot.init({
selector: `#${projectImage.id}`,
shine: true,
invert: true,
sensitivity: 14
})
});
}
};
</script>
<style lang="scss">
#container {
background-color: #e0e0e0;
color: $primary-text;
width: 100vw;
min-height: 100vh;
font-family: $sans;
}
/* Header Styling */
#main-header {
width: 100vw;
height: 40vmin;
display: flex;
flex-direction: row;
align-items: center;
justify-content: left;
padding: 10vmin;
position: relative;
/* Biographical Info - Name, Major, Role */
#bio-container {
position: relative;
z-index: 2;
#header-name {
font-weight: 700;
font-family: $sans;
}
#header-major,
#header-role {
font-weight: 700;
color: $secondary-text;
font-size: 1.2rem;
font-family: $sans;
}
}
#skyline {
position: absolute;
z-index: 1;
bottom: 0;
right: 0;
width: 130vmin;
}
#contact{
position: absolute;
z-index: 1;
top: 1.2rem;
right: 2rem;
font-size: 1.2rem;
font-weight: bold;
color: grey!important;
}
#contact:hover{
border-bottom: 2px solid grey;
}
}
/* Content Styling */
#indexMain {
background-color: $secondary-background;
min-height: 60vh;
max-width: 100vw;
display: flex;
flex-direction: column;
align-items: center;
.title {
align-self: flex-start;
margin: 2.8vmin 0 0 5vmax;
font-size: 1.75rem;
font-weight: 700;
font-family: $sans;
color: $primary-text;
}
.background-container{
&#experiment-background{
background-color: #F5F5F5;
.experiment-filter{
margin: 2.8vmin 0 0 5vmax;
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
.filter-title{
font-weight: 600;
font-size: 1.3rem;
}
.filter-tag{
margin: 0 1vmin;
padding: 0.4rem 0.6rem;
border-radius: 0.5rem;
color: #F5F5F5;
font-weight: bold;
cursor: pointer;
transition: 0.1s;
&:hover{
opacity: 0.75;
}
}
}
}
}
.content-container {
width: 100vw;
margin: 2vmin;
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: center;
flex-wrap: wrap;
a {
text-decoration: none;
}
&#project-container {
/* Mobile */
@media only screen and (max-aspect-ratio: 4/5){
padding-top: 4vh;
}
.content-card {
width: 30vh;
margin: 0 3vmin 3vmin;
padding: 1vh 0;
@media only screen and (max-aspect-ratio: 4/5){
width: 70vw;
}
/* Mobile */
@media only screen and (max-aspect-ratio: 0.67){
/* width: 30vh;
margin: 0 3vmin 3vmin;
padding: 1vh 0; */
}
/* Tablet + Desktop */
@media only screen and (min-aspect-ratio: 0.67){
}
.project-image {
width: 100%;
border-radius: 0.4rem;
}
.project-title {
color: $primary-text;
font-weight: 700;
margin-top: 1vh;
font-size: 1.3rem;
line-height: 1.5rem;
}
.project-description {
color: $secondary-text;
font-family: $sans;
font-weight: 700;
margin-top: 0.5vmin;
}
.project-term {
color: $tertiary-text;
font-family: $sans;
font-weight: 500;
font-size: 0.9rem;
margin-top: 0.5vmin;
}
}
}
&#experiment-container {
justify-content: flex-start;
padding: 0 5vmax;
.content-card {
font-weight: 700;
margin: 0 0.5rem 3.2rem;
.experiment-emoji {
font-size: 1.8rem;
float: left;
background-color: white;
border-top-left-radius: 0.6rem;
border-bottom-left-radius: 0.6rem;
padding: 0 0.6rem;
}
.experiment-title {
color: $primary-text;
float: left;
font-size: 1.2rem;
padding: 0.44rem 0.5rem 0.44rem 0;
background-color: white;
border-top-right-radius: 0.6rem;
border-bottom-right-radius: 0.6rem;
}
.experiment-dot-container{
.experiment-dot{
width: 0.4rem;
height: 0.4rem;
}
}
}
}
}
}
</style> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Password Generator</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div class="container">
<h1>hello world</h1>
<h1>
Generate a <br />
<span>Random Password</span>
</h1>
<div class="display">
<input type="text" id="Password" placeholder="Password" />
<img src="./copyimage.webp" alt="copy" onclick="copyText()" />
</div>
<button onclick="createPassword()">Generate password</button>
</div>
<h1 id="value"></h1>
<div>
<form id="form" method="get">
<input type="text" placeholder="name" id="name" />
<button type="submit">click</button>
</form>
</div>
<script>
const passwordBox = document.getElementById("Password");
const lenth = 12;
const upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const lowerCase = "abcdefghijklmnopqrstuvwxyz";
const number = "1234567890";
const symbol = "!@#$%^&*()_-+={}[];:'/?><";
const allMix = upperCase + lowerCase + number + symbol;
function createPassword() {
let password = "";
password += upperCase[Math.floor(Math.random() * upperCase.length)];
password += lowerCase[Math.floor(Math.random() * lowerCase.length)];
password += number[Math.floor(Math.random() * number.length)];
password += symbol[Math.floor(Math.random() * symbol.length)];
while (lenth > password.length) {
password += allMix[Math.floor(Math.random() * allMix.length)];
}
passwordBox.value = password;
}
function copyText() {
passwordBox.select();
document.execCommand("copy");
}
</script>
<script>
const inputValue = document.getElementsById("name");
const errorMessage = document.getElementById("value");
const form = document.getElementById("form");
form.addEventListener("submit", (e) => {
const message = [];
if (inputValue.value.length > 8) {
message.push("its must be greater than 8 digits");
}
if (message.length > 0) {
e.preventDefault();
errorMessage.innerText = message.join(', ');
}
});
</script>
</body>
</html> |
import 'package:flutter/material.dart';
import 'package:yitaku/common/widget/text_style.dart';
import 'package:yitaku/utils/asset_res.dart';
import 'package:yitaku/utils/colorRes.dart';
class BlueBotton extends StatelessWidget {
final double height;
final String buttonText;
final Color color;
final VoidCallback onPressed;
const BlueBotton(
{super.key,
required this.height,
required this.buttonText,
required this.onPressed,
required this.color});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPressed,
child: Container(
alignment: Alignment.center,
width: double.infinity,
height: height,
decoration: const BoxDecoration(
color: ColorRes.buttonColor,
borderRadius: BorderRadius.all(Radius.circular(18))),
child: Text(buttonText,
style: overpassRegular(fontWeight: FontWeight.bold, color: color,height: 1.8)),
),
);
}
} |
package app
import (
"flag"
"os"
"strconv"
"github.com/AaronSaikovski/golotteryservice/config"
"github.com/AaronSaikovski/golotteryservice/router"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// Setup logging from .env file
func setupLogging() error {
//get debug flag
debug_flag, err := strconv.ParseBool(os.Getenv("DEBUG"))
if err != nil {
return err
}
//setup logging
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
debug := flag.Bool("debug", debug_flag, "sets log level to debug")
flag.Parse()
// Default level for this example is info, unless debug flag is present
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
return nil
}
// Setup and run
func SetupAndRunApp() error {
// load env
errEnv := config.LoadENV()
if errEnv != nil {
return errEnv
}
//setup logging
errLog := setupLogging()
if errLog != nil {
return errLog
}
log.Debug().Msg("calling SetupAndRunApp()")
// create app
app := fiber.New()
// Uses API key header - 'XApiKey'
// app.Use(keyauth.New(keyauth.Config{
// KeyLookup: "header:XApiKey",
// Validator: middleware.ValidateAPIKey,
// }))
// attach middleware
app.Use(recover.New())
app.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path} ${latency}\n",
}))
//Use CORS - change AllowOrigins to suit
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowHeaders: "Origin, Content-Type, Accept",
}))
// setup routes
router.SetupRoutes(app)
// attach swagger
config.AddSwaggerRoutes(app)
// get the port and start
port := os.Getenv("PORT")
app.Listen(":" + port)
return nil
} |
import React, { useEffect, useState } from 'react'
import BottomBar from '../components/BottomBar/BottomBar'
import Feed from '../components/feed/Feed'
import Leftbar from '../components/leftbar/LeftBar'
import RightBar from '../components/rightbar/RightBar'
import TopBar from '../components/topbar/TopBar'
import TopBar2 from '../components/TopBar2/TopBar2'
import './homePage.css'
export const WindowWidth = () =>
{
const [windowWidth, setWindowWidth] = useState(window.innerHeight);
function getWindowWidth ()
{
setWindowWidth(window.innerWidth);
}
useEffect(()=>
{
window.addEventListener("resize", getWindowWidth);
return () =>
{
window.removeEventListener("resize", getWindowWidth);
}
}, [windowWidth]);
return windowWidth;
}
function HomePage() {
const windowWidth = WindowWidth();
return (
<div>
{windowWidth <= 480 ? <TopBar2 />: <TopBar />}
<div className="homePageContainer">
{windowWidth <= 480 ? '' : <Leftbar />}
<Feed />
{windowWidth <= 480 ? '' :<RightBar />}
</div>
{windowWidth <= 480 ?<BottomBar />: ''}
</div>
)
}
export default HomePage |
// Copyright (C),2006-2012 HandCoded Software Ltd.
// All rights reserved.
//
// This software is the confidential and proprietary information of HandCoded
// Software Ltd. ("Confidential Information"). You shall not disclose such
// Confidential Information and shall use it only in accordance with the terms
// of the license agreement you entered into with HandCoded Software.
//
// HANDCODED SOFTWARE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
// SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE, OR NON-INFRINGEMENT. HANDCODED SOFTWARE SHALL NOT BE
// LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
// OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
using System;
using System.Collections;
using System.IO;
using System.Xml;
using HandCoded.Classification;
using HandCoded.FpML;
using HandCoded.FpML.Classification;
using HandCoded.FpML.Identification;
using HandCoded.FpML.Infoset;
using HandCoded.Framework;
using HandCoded.Meta;
using HandCoded.Xml;
using log4net;
using log4net.Config;
namespace Classify
{
/// <summary>
/// This application demonstrates the classification components being used to
/// identify the type of product within an FpML document based on its structure.
/// </summary>
sealed class Classify : Application
{
/// <summary>
/// Creates an application instance and invokes its <see cref="Run"/>
/// method passing the command line arguments.
/// </summary>
/// <param name="arguments">The command line arguments.</param>
[STAThread]
static void Main (string [] arguments)
{
log4net.Config.DOMConfigurator.Configure ();
new Classify ().Run (arguments);
}
/// <summary>
/// Processes the command line options and gets ready to start file
/// processing.
/// </summary>
protected override void StartUp ()
{
base.StartUp ();
if (Arguments.Length == 0) {
log.Fatal ("No files are present on the command line");
Environment.Exit (1);
}
XmlUtility.DefaultSchemaSet.XmlSchemaSet.Compile ();
}
/// <summary>
/// Perform the file processing while timing the operation.
/// </summary>
protected override void Execute ()
{
DirectoryInfo directory = new DirectoryInfo (Environment.CurrentDirectory);
ArrayList files = new ArrayList ();
try {
for (int index = 0; index < Arguments.Length; ++index) {
String location = directory.ToString ();
string target = Arguments [index];
while (target.StartsWith (@"..\")) {
location = location.Substring (0, location.LastIndexOf (Path.DirectorySeparatorChar));
target = target.Substring (3);
}
FindFiles (files, Path.Combine (location, target));
}
}
catch (Exception error) {
log.Fatal ("Invalid command line argument", error);
Finished = true;
return;
}
XmlDocument document;
NodeIndex nodeIndex;
try {
for (int index = 0; index < files.Count; ++index) {
string filename = (files [index] as FileInfo).FullName;
FileStream stream = File.OpenRead (filename);
document = XmlUtility.NonValidatingParse (stream);
System.Console.WriteLine (">> " + filename);
Release release = Specification.ReleaseForDocument (document);
if (release != null) {
if (release is DTDRelease)
System.Console.WriteLine ("= " + release
+ " {" + (release as DTDRelease).PublicId + "}");
else if (release is SchemaRelease)
System.Console.WriteLine ("= " + release
+ " {" + (release as SchemaRelease).NamespaceUri + "}");
else
System.Console.WriteLine ("= " + release);
}
if (isdaOption.Present) {
if (release != Releases.R5_3_CONFIRMATION) {
Conversion conversion = Conversion.ConversionFor (release, Releases.R5_3_CONFIRMATION);
if (conversion == null) {
Console.WriteLine ("!! The contents of the file can not be converted to FpML 5.3 (Confirmation)");
continue;
}
document = conversion.Convert (document, new DefaultHelper ());
if (document == null) {
Console.WriteLine ("!! Automatic conversion to FpML 5.3 (Confirmation) failed");
continue;
}
}
nodeIndex = new NodeIndex (document);
DoIsdaClassify (nodeIndex.GetElementsByName ("trade"));
}
else {
nodeIndex = new NodeIndex (document);
DoClassify (nodeIndex.GetElementsByName ("trade"), "Trade");
DoClassify (nodeIndex.GetElementsByName ("contract"), "Contract");
}
stream.Close ();
}
}
catch (Exception error) {
log.Fatal ("Unexpected exception during processing", error);
}
Finished = true;
}
/// <summary>
/// Provides a text description of the expected arguments.
/// </summary>
/// <returns>A description of the expected application arguments.</returns>
protected override string DescribeArguments ()
{
return (" files ...");
}
/// <summary>
/// The <see cref="ILog"/> instance used to record problems.
/// </summary>
private static ILog log
= LogManager.GetLogger (typeof (Classify));
/// <summary>
/// A command line option that allows the default taxonomy to be overridden.
/// </summary>
private Option isdaOption
= new Option ("-isda", "Use the ISDA taxonomy");
/// <summary>
/// Constructs a <b>Classify</b> instance.
/// </summary>
private Classify ()
{ }
/// <summary>
/// Creates a list of files to be processed by expanding a path and handling
/// wildcards.
/// </summary>
/// <param name="files">The set of files to be processed.</param>
/// <param name="path">The path to be processed.</param>
private void FindFiles (ArrayList files, string path)
{
if (Directory.Exists (path)) {
foreach (string subdir in Directory.GetDirectories (path)) {
if ((new DirectoryInfo (subdir).Attributes & FileAttributes.Hidden) == 0)
FindFiles (files, subdir);
}
foreach (string file in Directory.GetFiles (path, "*.xml")) {
FileInfo info = new FileInfo (file);
if ((info.Attributes & FileAttributes.Hidden) == 0)
files.Add (info);
}
}
else {
foreach (string file in Directory.GetFiles (path)) {
FileInfo info = new FileInfo (file);
if ((info.Attributes & FileAttributes.Hidden) == 0)
files.Add (info);
}
}
}
/// <summary>
/// Uses the predefined FpML product types to attempt to classify a
/// product within the document.
/// </summary>
/// <param name="list">A set of context elements to analyze.</param>
/// <param name="container">The type of product container for display.</param>
private void DoClassify (XmlNodeList list, string container)
{
foreach (XmlElement element in list) {
Category category = FpMLTaxonomy.FPML.Classify (element);
System.Console.Write (": " + container + "(");
System.Console.Write ((category != null) ? category.ToString () : "UNKNOWN");
System.Console.WriteLine (")");
}
}
/// <summary>
/// Attempts to classify the trades within the document using the ISDA
/// taxonomy defined for regulatory reporting and generate an example
/// UPI.
/// </summary>
/// <param name="list">A set of context elements to analyse.</param>
private void DoIsdaClassify (XmlNodeList list)
{
foreach (XmlElement element in list) {
XmlDocument infoset = ProductInfoset.CreateInfoset (element);
XmlElement infosetRoot = infoset.DocumentElement;
Category assetClass = ISDATaxonomy.AssetClassForInfoset (infosetRoot);
Category productType = ISDATaxonomy.ProductTypeForInfoset (infosetRoot);
UPI upi = UPI.ForProductInfoset (infosetRoot, productType);
System.Console.Write (": Trade (");
System.Console.Write ((assetClass != null) ? assetClass.ToString () : "UNKNOWN");
System.Console.Write (" / ");
System.Console.Write ((productType != null) ? productType.ToString () : "UNKNOWN");
System.Console.Write (" / ");
System.Console.Write ((upi != null) ? upi.ToString () : "UNKNOWN");
System.Console.WriteLine (")");
}
}
}
} |
import { render, screen } from "@testing-library/react";
import { Todo } from "types/todo";
import TodoList from "../TodoList";
const mockTodos = [
{
id: 1,
content: "운동하기",
done: false,
},
{
id: 2,
content: "개발 공부하기",
done: false,
},
] as Array<Todo>;
function renderTodoList() {
const onToggle = jest.fn();
const onRemove = jest.fn();
render(
<TodoList todos={mockTodos} onToggle={onToggle} onRemove={onRemove} />
);
const checkTodo = () => {
return screen.getByText(mockTodos[0].content);
};
const removeButton = () => {
return screen.getAllByText("삭제")[0];
};
return {
onToggle,
onRemove,
checkTodo,
removeButton,
};
}
describe("<TodoList />", () => {
it("할 일 리스트가 렌더링 되는지 확인한다.", () => {
const { checkTodo } = renderTodoList();
expect(checkTodo()).toBeInTheDocument();
});
it("onToggle과 onRemove 함수의 동작을 확인한다.", () => {
const { checkTodo, removeButton, onToggle, onRemove } = renderTodoList();
checkTodo().click();
expect(onToggle).toBeCalledWith(mockTodos[0].id);
removeButton().click();
expect(onRemove).toBeCalledWith(mockTodos[0].id);
});
}); |
import { assets } from './spritePreview/assets'
import { loadAsset } from './gameUtils/loadAsset'
import constants from './spritePreview/constants'
import sprites from './sprites'
let frame = 0
let spriteFrame = 0
const $sprites = document.getElementById('ctdl-game-sprites')
const $direction = document.getElementById('ctdl-game-direction')
const $status = document.getElementById('ctdl-game-status')
if (window.location.hash) {
$status.value = window.location.hash.replace('#', '')
}
let sprite
let spriteData
let direction = $direction.value
let status = $status.value
const clearCanvas = () => {
constants.baseContext.clearRect(0, 0, constants.baseCanvas.width, constants.baseCanvas.height)
}
const loadSprite = async id => {
sprite = await loadAsset(assets[id.replace(/-/g, '')])
spriteData = sprites[id.replace(/\d|-/g, '')]
}
const renderSprite = () => {
for (let x = constants.baseCanvas.width + 16; x > -16; x -= 4) {
for (let y = constants.baseCanvas.height + 16; y > -16; y -= 4) {
if (x % 8 === 0) {
constants.baseContext.fillStyle = y % 8 === 0 ? '#040' : '#440'
} else {
constants.baseContext.fillStyle = y % 8 === 0 ? '#440' : '#040'
}
let offset = Math.round(frame / 8) % 8
constants.baseContext.fillRect(x + offset, y + offset, 4, 4)
}
}
if (!sprite || !spriteData[direction] || !spriteData[direction][status]) return
let data = spriteData[direction][status]
if (spriteFrame >= data.length) {
spriteFrame = 0
}
data = data[spriteFrame]
constants.baseContext.globalAlpha = data.opacity ?? 1
constants.baseContext.drawImage(
sprite,
data.x, data.y, data.w, data.h,
0, 0, data.w, data.h
)
constants.baseContext.globalAlpha = 1
spriteFrame++
}
init()
/**
* @description Method to init the game
* @returns {void}
*/
async function init() {
await loadSprite($sprites.value)
tick()
}
/**
* @description Method to to execute game logic for each tick
* It also takes care of rendering a frame at specified framerate
*/
function tick() {
if (frame % constants.FRAMERATE === 0) {
clearCanvas()
renderSprite()
if (frame > constants.FRAMERESET) {
frame = 0
}
}
frame++
return window.requestAnimationFrame(tick)
}
$sprites.addEventListener('change', e => loadSprite(e.target.value))
$direction.addEventListener('change', e => direction = e.target.value)
$status.addEventListener('change', e => {
status = e.target.value
window.location.hash = status
}) |
package config;
import javax.servlet.annotation.WebFilter;
import domain.dao.UserDao;
import domain.dao.UserDaoImpl;
import lombok.Getter;
import service.UserService;
import service.UserServiceImpl;
@Getter
public class ServletContextConfig {
private static ServletContextConfig instance = null;
/*
* Custom IoC (객체관리)
*
* 매번 implement하는 것이 아닌 여기서 모아놓고 한번만 가져다 쓰는 용도
*/
//Repository
private UserDao userDao;
//service
private UserService userService;
private ServletContextConfig() {}
public static ServletContextConfig getInstance() {
if(instance == null) {
instance = new ServletContextConfig();
instance.setIoC();
}
return instance;
}
private void setIoC() {
if(userDao == null) {
userDao = new UserDaoImpl();
}
if(userService == null) {
userService = new UserServiceImpl();
}
}
} |
import { Button, Card, Col, Form, Input, notification, Row } from "antd";
import React, { Fragment, useState } from "react";
import { useHistory } from "react-router-dom";
const Signup = () => {
const [form] = Form.useForm();
const history = useHistory();
const [usersList, setUsersList] = useState(
JSON.parse(localStorage.getItem("usersList")) || []
);
/**
*
* Method to validate if the User Credentials entered in the form are not empty.
* If valid, credentials are added to the localstorage. Else, it remains in the same page.
* Notifications are thrown in both the cases.
*/
const handleSignup = (values) => {
if (values.username && values.password) {
let newUsersList = [...usersList, { username: values.username, password: values.password }];
setUsersList(newUsersList);
localStorage.setItem("usersList", JSON.stringify(newUsersList));
openNotificationwithIcon("success");
setTimeout(() => {
history.push("/login");
}, 3000);
} else {
openNotificationwithIcon("error");
}
};
const openNotificationwithIcon = (type) => {
type=="success" && notification["success"]({
message: "Signup successful",
description: "You will be redirected to Login Page"
});
type=="error" && notification["error"]({
message: "Signup Failed",
});
};
return (
<Fragment>
<div>
<Row align="middle" justify="center">
<Col
xs={{ span: 20 }}
sm={{ span: 16 }}
md={{ span: 16 }}
lg={{ span: 8 }}
xl={{ span: 6 }}
className="add-todo-container"
>
<Form
name="form"
form={form}
layout="vertical"
className="add-todo-form"
onFinish={handleSignup}
>
<Row align="top" gutter={[8, 16]}>
<Col span={24}>
<Form.Item label="Username" name="username">
<Input className="text-box"></Input>
</Form.Item>
</Col>
<Col span={24}>
<Form.Item label="Password" name="password">
<Input className="text-box"></Input>
</Form.Item>
</Col>
<Col span={24}>
<Form.Item>
<Button htmlType="submit" className="add-btn">
Signup
</Button>
</Form.Item>
</Col>
</Row>
</Form>
</Col>
</Row>
</div>
</Fragment>
);
};
export default Signup; |
/*
This file is part of Memory Patcher.
Memory Patcher is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Memory Patcher is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Memory Patcher. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef COREMANAGER_H
#define COREMANAGER_H
#include <string>
#include <vector>
#include <map>
#include <utility>
#include <thread>
#include <mutex>
#include <stdint.h>
#ifdef _WIN32
namespace win32
{
#include <winsock2.h>
#include <windows.h>
}
#else
namespace posix
{
#include <unistd.h>
using ::pid_t; // We shouldn't need to do this, but <string> causes everything in <pthreads.h> to be included in the global namespace
}
#endif
#include "Socket.h"
#include "Misc.h"
class MANAGER_EXPORT CoreManager final
{
public:
using CoreId = uint8_t;
using receiveHandler_t = void (*)(CoreId, const std::vector<uint8_t>& data);
using ProcessId =
#ifdef _WIN32
win32::PROCESS_INFORMATION;
#else
posix::pid_t;
#endif
CoreId startCore();
void endCoreConnection(const CoreId coreId);
void endCore(const CoreId coreId);
std::vector<CoreId> getConnectedCores() const;
void addReceiveHandler(const Socket::ClientOpCode opCode, receiveHandler_t receiveHandler);
void removeReceiveHandler(const Socket::ClientOpCode opCode, receiveHandler_t receiveHandler);
void sendPacket(const Socket::ServerOpCode opCode, const std::vector<uint8_t>& data) const;
void sendCustomPacket(const size_t opCode, const std::vector<uint8_t>& data) const;
void sendPacketTo(const CoreId coreId, const Socket::ServerOpCode opCode, const std::vector<uint8_t>& data) const;
void sendCustomPacketTo(const CoreId coreId, const size_t opCode, const std::vector<uint8_t>& data) const;
static CoreManager& getSingleton();
private:
CoreManager();
CoreManager(const CoreManager&) = delete;
CoreManager& operator=(const CoreManager&) = delete;
~CoreManager();
void initQuitSockets_();
Socket::Socket startConnectCore_() const;
ProcessId startCore_(const std::string& applicationName, const std::string& parameters, const std::string& libraryPath, const std::string& coreName);
CoreId finishConnectCore_(ProcessId pid, Socket::Socket listenSocket, const std::string& coreName);
void endAllCoreConnections_();
static void logReceiveHandler_(CoreId coreId, const std::vector<uint8_t>& data);
static void coreListener_(CoreManager* self);
std::map<Socket::ClientOpCode, std::map<receiveHandler_t, size_t>> receiveHandlers_;
std::map<CoreId, std::pair<ProcessId, Socket::Socket>> cores_;
std::recursive_mutex receiveHandlersMutex_; // Should be just a normal mutex
mutable std::recursive_mutex coresMutex_;
#if !defined(_GLIBCXX_HAS_GTHREADS) && defined(_WIN32)
win32::HANDLE coreListenerThread_;
#else
std::thread coreListenerThread_;
#endif
Socket::Socket listenerThreadServerSocket_, listenerThreadClientSocket_; // Communication between listener thread and main thread
CoreId getNextAvailableCoreId_() const;
};
#endif |
import React, { useEffect, useState } from "react";
import { useOrderStore } from "../../hooks/useOrderStore";
import { usePaymentStore } from "../../hooks/usePaymentStore";
import { useForm } from "../../hooks/useForm";
import { useParams, Link, useNavigate } from "react-router-dom";
import Swal from "sweetalert2";
import axios from "axios";
export const AdminOrdersInformationId = () => {
const navigate = useNavigate();
const params = useParams();
const {
orders,
setActiveOrder,
activeOrder,
startSavingOrders,
} = useOrderStore();
const { payments} = usePaymentStore();
const URL = import.meta.env.VITE_API_URL;
const [formValues, setFormValues] = useState({
status: "",
trackingCode: "",
});
const statusData = [
"Sin Informar",
"En Proceso de Confirmación",
"En Producción",
"En Camino",
"Completado",
];
const onInputChange = ({ target }) => {
setFormValues({
...formValues,
[target.name]: target.value,
});
};
console.log(formValues);
const payInformation = payments.filter(
(payment) => payment.paymentId === activeOrder._id
);
useEffect(() => {
if (activeOrder == null && orders.length > 0) {
const { 0: orders } = orders.filter((order) => order._id === params._id);
setActiveOrder(order);
}
}, [orders, activeOrder, params._id]);
useEffect(() => {
if (activeOrder !== null) {
setFormValues({ ...activeOrder });
}
}, [activeOrder]);
const redirect = () => {
navigate('/administracion/pedidos')
window.location.reload();
}
const handleSave = async (e) => {
e.preventDefault();
try {
const res = await axios.put(`${URL}/orders/${activeOrder._id}`, {
status: formValues.status,
trackingCode: formValues.trackingCode,
});
if (res) {
Swal.fire({
position: "top-end",
icon: "success",
title: "El estado del pedido fue editado con exito!",
showConfirmButton: false,
timer: 1500,
});
setTimeout(() => {
redirect()
}, 1000)
}
} catch (error) {
console.log(error);
}
};
return (
<>
<section className="text-dark container text-center">
<div className="row">
<Link to="/administracion/pedidos" className="text-decoration-none">
<button className=" btn btn-warning text-light w-100">
Volver atrás
</button>
</Link>
<div className="col-sm-12 col-md-4">
<div className=" w-100 p-3 border text-dark shadow-lg">
<div>
<div>
<h3 className=" bg-dark text-light p-2">
Detalles del cliente
</h3>
<hr />
<p>
Nombre completo:{" "}
<b>
{activeOrder?.name} {activeOrder?.lastname}
</b>
</p>
<p>
Telefono: <b>{activeOrder?.phone}</b>
</p>
<p>
Email: <b>{activeOrder?.email}</b>
</p>
<p>
RUT: <b>{activeOrder?.rut}</b>
</p>
</div>
</div>
</div>
<div className="bg-primary w-100 p-3 text-light">
<p>
<b>Estado del pedido: {activeOrder?.status}</b>
</p>
</div>
<div>
<form>
<label className="form-label mt-3 bg-dark p-2 text-light w-100">
Actualizar estado del pedido
</label>
<select
className="form-select"
onChange={onInputChange}
name="status"
value={formValues.status}
>
{statusData.map((status) => (
<option >{status}</option>
))}
</select>
<label className=" mt-2 form-label bg-dark p-2 text-light w-100" >Ingresar codigo de seguimiento</label>
<input className="form-control" type="text" name="trackingCode" value={formValues.trackingCode} placeholder="Ingrese codigo de tracking" onChange={onInputChange} />
<button
className="btn btn-success w-100 mt-1"
onClick={handleSave}
>
Actualizar
</button>
</form>
</div>
</div>
<div className="col-sm-12 col-md-8 ">
<div className="border p-2 shadow-lg">
<div>
<h3 className=" bg-dark text-light p-2">Facturación y envío</h3>
<hr />
<p>
Pais: <b>{activeOrder?.country}</b>
</p>
<p>
Región: <b>{activeOrder?.region}</b>
</p>
<p>
Comuna: <b>{activeOrder?.comuna}</b>
</p>
<p>
Dirección: <b>{activeOrder?.address}</b>
</p>
<p>
Total:{" "}
<b className="text-success">${activeOrder?.totalPrice} CLP</b>
</p>
<p>
Productos:{" "}
<b>{activeOrder?.details.map((detail) => detail + " ")}</b>
</p>
</div>
<div>
<h3 className="mt-3 bg-dark text-light p-2 w-100">
Informe de pago
</h3>
<hr />
{payInformation !== null ? (
payInformation.map((pay) => (
<div>
<p>Fecha de informe: {pay.date.slice(0, 10)}</p>
<p>
nombre de Banco / Caja vecina: <b>{pay.bank}</b>
</p>
<p>
Numero de comprobante / operación:{" "}
<b>{pay.numberOperation}</b>
</p>
<p>
Monto Transferido:{" "}
<b className="text-success">${pay.transferred}</b>
</p>
<p>
Comentario: <b>{pay.comments}</b>
</p>
</div>
))
) : (
<div className="alert alert-warning p-3">
<p className="text-dark">
El cliente no ingreso un informe de pago todavía
</p>
</div>
)}
</div>
</div>
</div>
</div>
</section>
</>
);
}; |
// To parse this JSON data, do
//
// final sectors = sectorsFromJson(jsonString);
import 'dart:convert';
Sectors sectorsFromJson(String str) => Sectors.fromJson(json.decode(str));
String sectorsToJson(Sectors data) => json.encode(data.toJson());
class Sectors {
Sectors({
this.error,
this.errorMsg,
this.data,
});
bool error;
dynamic errorMsg;
Data data;
factory Sectors.fromJson(Map<String, dynamic> json) => Sectors(
error: json["error"] == null ? null : json["error"],
errorMsg: json["errorMsg"],
data: json["data"] == null ? null : Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"error": error == null ? null : error,
"errorMsg": errorMsg,
"data": data == null ? null : data.toJson(),
};
}
class Data {
Data({
this.data,
this.count,
});
List<InstanceOfSector> data;
int count;
factory Data.fromJson(Map<String, dynamic> json) => Data(
data: json["data"] == null
? null
: List<InstanceOfSector>.from(
json["data"].map((x) => InstanceOfSector.fromJson(x))),
count: json["count"] == null ? null : json["count"],
);
Map<String, dynamic> toJson() => {
"data": data == null
? null
: List<dynamic>.from(data.map((x) => x.toJson())),
"count": count == null ? null : count,
};
}
class InstanceOfSector {
InstanceOfSector({
this.id,
this.name,
this.createdAt,
this.updatedAt,
});
int id;
String name;
DateTime createdAt;
DateTime updatedAt;
factory InstanceOfSector.fromJson(Map<String, dynamic> json) =>
InstanceOfSector(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
createdAt: json["created_at"] == null
? null
: DateTime.parse(json["created_at"]),
updatedAt: json["updated_at"] == null
? null
: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null : name,
"created_at": createdAt == null ? null : createdAt.toIso8601String(),
"updated_at": updatedAt == null ? null : updatedAt.toIso8601String(),
};
} |
/******************************************************************************
NAME: ias_math_convert_month_day_to_doy
PURPOSE: Converts month/day for a specific year to day of year.
RETURN VALUE: ERROR or SUCCESS
******************************************************************************/
#include "ias_logging.h"
#include "ias_math.h"
/* Calculate day of year given year, month, and day of month */
int ias_math_convert_month_day_to_doy
(
int month, /* I: Month */
int day, /* I: Day of month */
int year, /* I: Year */
int *doy /* O: Day of year */
)
{
/* Days in month for non-leap years */
static const int noleap[12]
= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/* Days in month for leap years */
static const int leap[12]
= {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int i; /* Counter */
int doy_sum;
/* Check to make sure month entered is OK */
if ((month < 1) || (month > 12))
{
IAS_LOG_ERROR ("Invalid month requested: %d", month);
return ERROR;
}
/* Calculate day of year */
doy_sum = 0;
if (ias_math_is_leap_year(year))
{
for (i = 0; i < month - 1; i++)
doy_sum += leap[i];
}
else
{
for (i = 0; i < month - 1; i++)
doy_sum += noleap[i];
}
doy_sum += day;
*doy = doy_sum;
return SUCCESS;
} |
#### Отпечатване на резултата
Накрая остава да изведем резултата на конзолата. По задание, ако студентът е дошъл точно на време (**без нито една минута разлика**), не трябва да изваждаме втори резултат. Затова правим следната **проверка**:

Реално за целите на задачата извеждането на резултата **на конзолата** може да бъде направен и в по-ранен етап - още при самите изчисления. Това като цяло не е много добра практика. **Защо?**
Нека разгледаме идеята, че кодът ни не е 10 реда, а 100 или 1000! Някой ден ще се наложи извеждането на резултата да не бъде в конзолата, а да бъде записан във **файл** или показан на **уеб приложение**. Тогава на колко места в кода ще трябва да бъдат нанесени корекции поради тази смяна? И дали няма да пропуснем някое място?
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td>Винаги си мислете за кода с логическите изчисления, като за отделна част от, различна от обработката на входните и изходните данни. Той трябва да може да работи без значение как му се подават данните и къде ще трябва да бъде показан резултатът.</td></tr></table>
### Тестване в Judge системата
Тествайте решението си тук: [https://judge.softuni.org/Contests/Practice/Index/509#0](https://judge.softuni.org/Contests/Practice/Index/509#0). |
"""Test module for client list use case"""
# pylint: disable=w0621
# pylint: disable=c0116
import pytest
from src.domain.category import Category
from src.repository.in_memory.memrepo_category import MemRepoCategory
@pytest.fixture
def category_dicts():
return [
{
'descricao': 'categoria A',
'dt_inclusao': '18/11/2023, 14:44:12',
'dt_alteracao': None,
'ativo': True,
'client_id': [1],
},
{
'descricao': 'categoria B',
'dt_inclusao': '18/11/2023, 14:44:12',
'dt_alteracao': None,
'ativo': True,
'client_id': [1],
},
{
'descricao': 'categoria C',
'dt_inclusao': '18/11/2023, 14:44:12',
'dt_alteracao': None,
'ativo': False,
'client_id': [2],
},
{
'descricao': 'categoria D',
'dt_inclusao': '18/11/2023, 14:44:12',
'dt_alteracao': None,
'ativo': False,
'client_id': [2],
},
]
def test_repository_create_category(category_dicts):
repo = MemRepoCategory(category_dicts)
new_category = {
'descricao': 'description text',
'dt_inclusao': '18/11/2023, 14:44:12',
'dt_alteracao': None,
'ativo': True,
'client_id': [1],
}
repo.create_category(new_category)
assert len(category_dicts) == 5
def test_repository_list_category_without_params(category_dicts):
repo = MemRepoCategory(category_dicts)
result = [Category.from_dict(c) for c in category_dicts]
assert repo.list_category() == result
def test_repository_list_with_ativo_equal_filter(category_dicts):
repo = MemRepoCategory(category_dicts)
categories = repo.list_category({'ativo__eq': True})
assert len(categories) == 2
def test_repository_list_with_id_equal_true_filter(category_dicts):
repo = MemRepoCategory(category_dicts)
categories = repo.list_category({'ativo__eq': True})
assert len(categories) == 2
def test_repository_update_client(category_dicts):
repo = MemRepoCategory(category_dicts)
new_category_data = {
'descricao': 'categoria D',
'dt_inclusao': '18/11/2023, 14:44:12',
'dt_alteracao': None,
'ativo': True,
'client_id': [2],
}
repo.update_category(new_category_data)
updated_client = {}
for client in category_dicts:
if client['descricao'] == 'categoria D':
updated_client = client
assert len(category_dicts) == 4
assert updated_client['ativo'] is True |
using Eddy.Core.Validation;
using Eddy.Tests.x12;
using Eddy.x12.Mapping;
using Eddy.x12.Models.Elements;
using Eddy.x12.Models.v3030;
namespace Eddy.x12.Tests.Models.v3030;
public class W21Tests
{
[Fact]
public void Parse_ShouldReturnCorrectObject()
{
string x12Line = "W21*w*BV*C*bz*2*8*g*9*1*i*b*2*3*2*5*8*6*4";
var expected = new W21_ItemDetailInventory()
{
WarehouseLotNumber = "w",
ReferenceNumberQualifier = "BV",
ReferenceNumber = "C",
UnitOrBasisForMeasurementCode = "bz",
QuantityOnHand = 2,
Weight = 8,
WeightQualifier = "g",
WeightUnitCode = "9",
Weight2 = 1,
WeightQualifier2 = "i",
WeightUnitCode2 = "b",
QuantityDamaged = 2,
QuantityOnHold = 3,
QuantityCommitted = 2,
QuantityAvailable = 5,
QuantityInTransit = 8,
QuantityBackordered = 6,
QuantityDeferred = 4,
};
var actual = Map.MapObject<W21_ItemDetailInventory>(x12Line, MapOptionsForTesting.x12DefaultEndsWithNewline);
Assert.Equivalent(expected, actual);
}
[Theory]
[InlineData("", false)]
[InlineData("w", true)]
public void Validation_RequiredWarehouseLotNumber(string warehouseLotNumber, bool isValidExpected)
{
var subject = new W21_ItemDetailInventory();
//Required fields
subject.UnitOrBasisForMeasurementCode = "bz";
subject.QuantityOnHand = 2;
//Test Parameters
subject.WarehouseLotNumber = warehouseLotNumber;
TestHelper.CheckValidationResults(subject, isValidExpected, ErrorCodes.Required);
}
[Theory]
[InlineData("", false)]
[InlineData("bz", true)]
public void Validation_RequiredUnitOrBasisForMeasurementCode(string unitOrBasisForMeasurementCode, bool isValidExpected)
{
var subject = new W21_ItemDetailInventory();
//Required fields
subject.WarehouseLotNumber = "w";
subject.QuantityOnHand = 2;
//Test Parameters
subject.UnitOrBasisForMeasurementCode = unitOrBasisForMeasurementCode;
TestHelper.CheckValidationResults(subject, isValidExpected, ErrorCodes.Required);
}
[Theory]
[InlineData(0, false)]
[InlineData(2, true)]
public void Validation_RequiredQuantityOnHand(decimal quantityOnHand, bool isValidExpected)
{
var subject = new W21_ItemDetailInventory();
//Required fields
subject.WarehouseLotNumber = "w";
subject.UnitOrBasisForMeasurementCode = "bz";
//Test Parameters
if (quantityOnHand > 0)
subject.QuantityOnHand = quantityOnHand;
TestHelper.CheckValidationResults(subject, isValidExpected, ErrorCodes.Required);
}
} |
<?php
namespace App\Factory;
use App\Entity\PokemonStat;
use App\Repository\PokemonStatRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
use Zenstruck\Foundry\RepositoryProxy;
/**
* @extends ModelFactory<PokemonStat>
*
* @method PokemonStat|Proxy create(array|callable $attributes = [])
* @method static PokemonStat|Proxy createOne(array $attributes = [])
* @method static PokemonStat|Proxy find(object|array|mixed $criteria)
* @method static PokemonStat|Proxy findOrCreate(array $attributes)
* @method static PokemonStat|Proxy first(string $sortedField = 'id')
* @method static PokemonStat|Proxy last(string $sortedField = 'id')
* @method static PokemonStat|Proxy random(array $attributes = [])
* @method static PokemonStat|Proxy randomOrCreate(array $attributes = [])
* @method static PokemonStatRepository|RepositoryProxy repository()
* @method static PokemonStat[]|Proxy[] all()
* @method static PokemonStat[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static PokemonStat[]|Proxy[] createSequence(iterable|callable $sequence)
* @method static PokemonStat[]|Proxy[] findBy(array $attributes)
* @method static PokemonStat[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
* @method static PokemonStat[]|Proxy[] randomSet(int $number, array $attributes = [])
*/
final class PokemonStatFactory extends ModelFactory
{
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services
*
* @todo inject services if required
*/
public function __construct()
{
parent::__construct();
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories
*
* @todo add your default values here
*/
protected function getDefaults(): array
{
return [
'pokemon' => PokemonFactory::randomOrCreate(),
'baseStat' => self::faker()->numberBetween(0, 100),
'effort' => self::faker()->boolean ? 1 : 0,
'stat' => StatFactory::randomOrCreate(),
];
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
*/
protected function initialize(): self
{
return $this
// ->afterInstantiate(function(PokemonStat $pokemonStat): void {})
;
}
protected static function getClass(): string
{
return PokemonStat::class;
}
} |
import 'package:api/api.dart';
import 'package:badges/badges.dart' as badge;
import 'package:common/constant/constant.dart';
import 'package:common/function/function.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:sales/config/app_pages.dart';
import 'package:sales/main_controller.dart';
import 'package:sales/presentation/pages/cart/cart_page.dart';
import 'package:sales/presentation/pages/cart/provider/cart_provider.dart';
import 'package:sales/presentation/pages/product/provider/product_provider.dart';
import 'package:sales/presentation/pages/product/view/product_search_view.dart';
import 'package:sales/presentation/widgets/app_alert_dialog.dart';
import 'package:sales/presentation/widgets/app_image_widget.dart';
import 'package:sales/presentation/widgets/app_smart_refresher_widget.dart';
final brandStateNotifierProvider =
StateNotifierProvider.autoDispose<BrandNotifier, List<Brand>>((ref) {
return BrandNotifier(ref);
});
class BrandNotifier extends StateNotifier<List<Brand>> {
BrandNotifier(AutoDisposeRef ref) : super([]) {
api = ref.watch(apiProvider);
error = '';
controller = RefreshController(initialRefresh: true);
}
late final Api api;
late String error;
late final RefreshController controller;
void onRefresh() async {
try {
controller.resetNoData();
final result = await api.brand.all();
state = result;
controller.refreshCompleted();
return;
} catch (e) {
error = e.toString();
controller.refreshFailed();
}
}
void onLoading() async {
try {
controller.loadNoData();
final result = await api.brand.all();
state.addAll(result);
controller.loadComplete();
return;
} catch (e) {
error = e.toString();
controller.loadFailed();
}
}
}
class ProductPage extends ConsumerStatefulWidget {
final ArgProductList arg;
const ProductPage({super.key, required this.arg});
@override
ConsumerState<ProductPage> createState() => _ProductPageState();
}
class _ProductPageState extends ConsumerState<ProductPage> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
final brand = ref.watch(brandStateNotifierProvider);
final brandWatch = ref.watch(brandStateNotifierProvider.notifier);
final productNew = ref.watch(newProductProvider);
final productPopular = ref.watch(productLarisProvider);
final productDiscount = ref.watch(productDiskonProvider);
final scrollController = ScrollController();
final theme = Theme.of(context);
final size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: const Text('Produk'),
actions: [
IconButton(
icon: Builder(builder: (_) {
final stateWatch = ref.watch(cartStateNotifier);
final carts = stateWatch.toSet().toList();
if (carts.isEmpty) {
return const Icon(Icons.shopping_cart_outlined);
}
return badge.Badge(
badgeContent: Text(carts.length.toString(),
style: const TextStyle(color: Colors.white)),
badgeStyle: const badge.BadgeStyle(
badgeColor: Colors.red,
),
child: const Icon(Icons.shopping_cart_outlined),
);
}),
onPressed: () {
Navigator.of(context).pushNamed(AppRoutes.cartPage);
},
),
],
),
floatingActionButton: _currentIndex == 0
? FloatingActionButton(
onPressed: () => ProductSearchView.showCustomerSearch(context),
child: const Icon(Icons.search),
)
: null,
body: NotificationListener(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
if (notification.metrics.extentAfter == 0.0) {
setState(
() {
_currentIndex = 1;
},
);
}
if (notification.metrics.extentBefore == 0.0) {
setState(
() {
_currentIndex = 0;
},
);
}
}
return true;
},
child: SmartRefresherWidget(
controller: brandWatch.controller,
onRefresh: () {
brandWatch.onRefresh();
},
onLoading: () {
brandWatch.onLoading();
},
child: CustomScrollView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
SliverPadding(
padding: const EdgeInsets.only(top: Dimens.px16),
sliver: SliverToBoxAdapter(
child: SizedBox(
height: size.height * 0.12,
child: ListView.separated(
controller: scrollController,
shrinkWrap: true,
padding:
const EdgeInsets.symmetric(horizontal: Dimens.px16),
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return SizedBox(
width: size.height * 0.12,
child: Card(
clipBehavior: Clip.hardEdge,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
Dimens.px12,
),
),
elevation: 1.5,
shadowColor: theme.highlightColor,
child: InkWell(
onTap: () {
Navigator.of(context).pushNamed(
AppRoutes.productListByBrand,
arguments: ArgProductList(
title: brand[index].name,
idBrand: brand[index].id,
),
);
},
child: Container(
padding: const EdgeInsets.all(Dimens.px10),
color: theme.highlightColor.withOpacity(0.3),
child: AppImagePrimary(
isOnTap: false,
imageUrl: brand[index].imageUrl,
fit: BoxFit.contain,
),
),
),
),
);
},
separatorBuilder: (context, index) {
return const SizedBox(
width: Dimens.px8,
);
},
itemCount: brand.length,
),
),
),
),
productNew.when(
loading: () => const SliverPadding(
padding: EdgeInsets.only(bottom: Dimens.px16),
sliver: SliverToBoxAdapter(
child: SizedBox(
height: 350,
child: Center(
child: CircularProgressIndicator(),
),
),
),
),
data: (data) {
if (data.isEmpty) {
return const SliverToBoxAdapter(child: SizedBox());
}
return listProduct(
context: context,
menu: "Produk terbaru",
data: data,
onTap: () => Navigator.pushNamed(
context,
AppRoutes.productAllPage,
arguments: ArgProductList(title: "Terbaru"),
),
);
},
error: (error, stackTrace) => SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(error.toString()),
)),
),
productPopular.when(
loading: () => const SliverPadding(
padding: EdgeInsets.only(bottom: Dimens.px16),
sliver: SliverToBoxAdapter(
child: SizedBox(
height: 350,
child: Center(
child: CircularProgressIndicator(),
),
),
),
),
data: (data) {
if (data.isEmpty) {
return const SliverToBoxAdapter(child: SizedBox());
}
return listProduct(
context: context,
menu: "Produk terlaris",
data: data,
onTap: () => Navigator.pushNamed(
context,
AppRoutes.productAllPage,
arguments: ArgProductList(title: "Terlaris"),
),
);
},
error: (error, stackTrace) => SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(error.toString()),
)),
),
productDiscount.when(
loading: () => const SliverPadding(
padding: EdgeInsets.only(bottom: Dimens.px16),
sliver: SliverToBoxAdapter(
child: SizedBox(
height: 350,
child: Center(
child: CircularProgressIndicator(),
),
),
),
),
data: (data) {
if (data.isEmpty) {
return const SliverToBoxAdapter(child: SizedBox());
}
return listProduct(
context: context,
menu: "Produk promo",
data: data,
onTap: () => Navigator.pushNamed(
context,
AppRoutes.productAllPage,
arguments: ArgProductList(title: "Promo"),
),
);
},
error: (error, stackTrace) => SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(error.toString()),
)),
),
],
),
),
),
);
}
}
Widget listProduct(
{required BuildContext context,
required String menu,
required List<Product> data,
required Function() onTap}) {
return SliverPadding(
padding: const EdgeInsets.symmetric(
horizontal: Dimens.px16,
),
sliver: SliverToBoxAdapter(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.5,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
menu,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
InkWell(
onTap: onTap,
child: const Text(
"Lihat semua",
style: TextStyle(
color: Colors.black,
),
),
),
],
),
),
Expanded(
child: data.isEmpty
? Container()
: ListView.separated(
padding: EdgeInsets.zero,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => SizedBox(
width: MediaQuery.of(context).size.width * 0.45,
child: ProductCart(price: data[index]),
),
separatorBuilder: (context, index) => const SizedBox(
width: 8,
),
itemCount: data.length,
),
),
],
),
),
),
);
}
class ProductCart extends ConsumerWidget {
const ProductCart({
Key? key,
required this.price,
}) : super(key: key);
final Product price;
@override
Widget build(BuildContext context, WidgetRef ref) {
final size = MediaQuery.of(context).size;
final theme = Theme.of(context);
return Card(
clipBehavior: Clip.hardEdge,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(Dimens.px12),
),
elevation: 1.5,
shadowColor: theme.highlightColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
InkWell(
onTap: () {
Navigator.of(context).pushNamed(
AppRoutes.productDetail,
arguments: price,
);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(Dimens.px10),
color: theme.highlightColor.withOpacity(0.3),
width: size.width,
child: AppImagePrimary(
imageUrl: price.imageUrl,
height: size.height * 0.16,
fit: BoxFit.contain,
),
),
Padding(
padding: const EdgeInsets.all(Dimens.px8),
child: Column(
children: [
Text(
price.name,
maxLines: 2,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodyLarge!.copyWith(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
Text(
price.size,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleSmall,
),
TextPrice(product: price),
],
),
),
],
),
),
_ButtonCart(price: price),
],
),
);
}
}
class _ButtonCart extends ConsumerWidget {
const _ButtonCart({Key? key, required this.price}) : super(key: key);
final Product price;
@override
Widget build(BuildContext context, WidgetRef ref) {
final stateWatch = ref.watch(cartStateNotifier);
final statereadNotifier = ref.read(cartStateNotifier.notifier);
final theme = Theme.of(context);
final size = MediaQuery.of(context).size;
int qty =
stateWatch.where((element) => element.id == price.id).toList().length;
if (qty == 0) {
return Material(
color: theme.primaryColor,
child: InkWell(
onTap: () => statereadNotifier.add(price),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Dimens.px10,
vertical: Dimens.px10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.add_outlined,
color: Colors.white,
),
const SizedBox(width: 4),
Flexible(
child: Text(
'keranjang',
maxLines: 1,
style: theme.textTheme.labelLarge?.copyWith(
color: Colors.white,
),
),
),
],
),
),
),
);
}
return GestureDetector(
onTap: () {
showBottomSheetUpdateQty(
context,
price: price,
ref: ref,
);
},
child: SizedBox(
width: size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Material(
color: theme.primaryColor,
child: InkWell(
onTap: () {
if (qty <= 1) {
AppActionDialog.show(
context: context,
isAction: true,
title: "Konfirmasi",
content:
"Apakah Anda yakin ingin menghapus item ini dari keranjang?",
onPressNo: () {
Navigator.pop(context);
},
onPressYes: () {
statereadNotifier.remove(price.id);
Navigator.pop(context);
},
);
} else {
statereadNotifier.remove(price.id);
}
},
child: const Padding(
padding: EdgeInsets.all(Dimens.px10),
child: Icon(Icons.remove, color: Colors.white),
),
),
),
Text(qty.toString()),
Material(
color: theme.primaryColor,
child: InkWell(
onTap: () {
statereadNotifier.add(price);
},
child: const Padding(
padding: EdgeInsets.all(Dimens.px10),
child: Icon(Icons.add, color: Colors.white),
),
),
),
],
),
),
);
}
}
class TextPrice extends ConsumerWidget {
final Product product;
final bool? isFront;
final bool isPromo;
const TextPrice(
{Key? key,
required this.product,
this.isFront = true,
this.isPromo = false})
: super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final cart = ref.watch(cartStateNotifier.notifier);
final c = ref.watch(cartStateNotifier).where((element) {
return element.productId == product.productId;
});
final customer = ref.watch(customerStateProvider);
final price = product.kPrice(customer.business?.priceList.id);
Widget dcText() {
final disc = price.discount;
if (price.discount.isEmpty) return Container();
if (disc.length == 1) {
if (c.length < disc.first.min || c.length > (disc.first.max ?? 0)) {
return Column(
crossAxisAlignment: isFront == true
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
Text(
'${c.length < (price.discount.first.min) ? 'Min Pembelian ${price.discount.first.min}' : 'Maks Pembelian ${(price.discount.first.max ?? '-')}'} ',
maxLines: 1,
),
Text(
'Disc ${price.discount.first.discount.currency()}',
maxLines: 1,
),
],
);
} else {
return Column(
crossAxisAlignment: isFront == true
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
Text(
'Min Pembelian ${c.isEmpty ? price.discount.first.min : cart.discount(product.productId).min}',
style: const TextStyle(
color: Colors.red,
),
maxLines: 1,
),
Text(
'Disc ${cart.discount(product.productId).discount.currency()}',
style: const TextStyle(
color: Colors.red,
),
maxLines: 1,
),
],
);
}
} else {
if (c.length < disc.first.min) {
return Column(
crossAxisAlignment: isFront == true
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
Text(
'Min Pembelian ${disc.first.min}',
maxLines: 1,
),
Text(
'Disc ${disc.first.discount.currency()}',
maxLines: 1,
),
],
);
}
if (cart.discount(product.productId).discount != 0) {
return Column(
crossAxisAlignment: isFront == true
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
Text(
'${c.length == cart.discount(product.productId).min ? 'Min Pembelian ${cart.discount(product.productId).min}' : 'Maks Pembelian ${cart.discount(product.productId).max ?? '-'}'} ',
style: const TextStyle(color: Colors.red),
maxLines: 1,
),
Text(
'Disc ${cart.discount(product.productId).discount.currency()}',
style: const TextStyle(color: Colors.red),
maxLines: 1,
),
],
);
}
return Column(
crossAxisAlignment: isFront == true
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
Text(
'Maks Pembelian ${disc.last.max ?? '-'}',
maxLines: 1,
),
Text(
'Disc ${disc.last.discount.currency()}',
maxLines: 1,
),
],
);
}
}
return Column(
crossAxisAlignment: isFront == true
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
cart.discount(product.productId).discount == 0
? Text(
price.price.currency(),
maxLines: 1,
)
: Text(
price.price.currency(),
style: TextStyle(
decoration: TextDecoration.lineThrough,
decorationColor: Colors.black,
decorationThickness:
Theme.of(context).brightness == Brightness.dark ? 3 : 1.5,
fontSize: 13,
),
maxLines: 1,
),
const SizedBox(height: 2),
cart.discount(product.productId).discount == 0
? Container()
: isFront == true
? Text(
(price.price - cart.discount(product.productId).discount)
.currency(),
style: const TextStyle(
color: Colors.red,
),
maxLines: 1,
)
: Text(
(price.price - cart.discount(product.productId).discount)
.currency(),
style: const TextStyle(
color: Colors.red,
),
maxLines: 1,
),
dcText(),
],
);
}
}
// class TextPrice extends ConsumerWidget {
// final PriceList price;
// final bool? isFront;
// final bool isPromo;
// const TextPrice(
// {Key? key,
// required this.price,
// this.isFront = true,
// this.isPromo = false})
// : super(key: key);
// @override
// Widget build(BuildContext context, WidgetRef ref) {
// final cart = ref.watch(cartStateNotifier.notifier);
// final c =
// ref.watch(cartStateNotifier).where((element) => element.id == price.id);
// Widget dcText() {
// final disc = price.discount;
// if (price.discount.isEmpty) return Container();
// if (disc.length == 1) {
// if (c.length < disc.first.min || c.length > (disc.first.max ?? 0)) {
// return Column(
// crossAxisAlignment: isFront == true
// ? CrossAxisAlignment.center
// : CrossAxisAlignment.start,
// children: [
// Text(
// '${c.length < (price.discount.first.min) ? 'Min Pembelian ${price.discount.first.min}' : 'Maks Pembelian ${(price.discount.first.max ?? '-')}'} ',
// ),
// Text(
// 'Disc ${price.discount.first.discount.currency()}',
// ),
// ],
// );
// } else {
// return Column(
// crossAxisAlignment: isFront == true
// ? CrossAxisAlignment.center
// : CrossAxisAlignment.start,
// children: [
// Text(
// 'Min Pembelian ${c.isEmpty ? price.discount.first.min : cart.discount(price.id).min}',
// style: const TextStyle(
// color: Colors.red,
// ),
// ),
// Text(
// 'Disc ${cart.discount(price.id).discount.currency()}',
// style: const TextStyle(
// color: Colors.red,
// ),
// ),
// ],
// );
// }
// } else {
// if (c.length < disc.first.min) {
// return Column(
// crossAxisAlignment: isFront == true
// ? CrossAxisAlignment.center
// : CrossAxisAlignment.start,
// children: [
// Text('Min Pembelian ${disc.first.min}'),
// Text('Disc ${disc.first.discount.currency()}'),
// ],
// );
// }
// if (cart.discount(price.id).discount != 0) {
// return Column(
// crossAxisAlignment: isFront == true
// ? CrossAxisAlignment.center
// : CrossAxisAlignment.start,
// children: [
// Text(
// '${c.length == cart.discount(price.id).min ? 'Min Pembelian ${cart.discount(price.id).min}' : 'Maks Pembelian ${cart.discount(price.id).max ?? '-'}'} ',
// style: const TextStyle(color: Colors.red),
// ),
// Text('Disc ${cart.discount(price.id).discount.currency()}',
// style: const TextStyle(color: Colors.red)),
// ],
// );
// }
// return Column(
// crossAxisAlignment: isFront == true
// ? CrossAxisAlignment.center
// : CrossAxisAlignment.start,
// children: [
// Text('Maks Pembelian ${disc.last.max ?? '-'}'),
// Text('Disc ${disc.last.discount.currency()}'),
// ],
// );
// }
// }
// return Column(
// crossAxisAlignment: isFront == true
// ? CrossAxisAlignment.center
// : CrossAxisAlignment.start,
// children: [
// cart.discount(price.id).discount == 0
// ? Text(price.price.currency())
// : Text(
// price.price.currency(),
// style: TextStyle(
// decoration: TextDecoration.lineThrough,
// decorationColor: Colors.black,
// decorationThickness:
// Theme.of(context).brightness == Brightness.dark ? 3 : 1.5,
// fontSize: 13,
// ),
// ),
// const SizedBox(height: 2),
// cart.discount(price.id).discount == 0
// ? Container()
// : isFront == true
// ? Text(
// (price.price - cart.discount(price.id).discount).currency(),
// style: const TextStyle(
// color: Colors.red,
// ),
// )
// : Text(
// (price.price - cart.discount(price.id).discount).currency(),
// style: const TextStyle(
// color: Colors.red,
// ),
// ),
// dcText(),
// ],
// );
// }
// } |
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Header from "../components/Header/Header";
import Footer from "../components/Footer/Footer"
import HomePage from "../pages/HomePage/HomePage";
import LoginPage from "../pages/Login/LoginPage";
import EventosPage from "../pages/EventosPage/EventosPage";
import EventosAlunoPage from "../pages/EventosAlunoPage/EventosAlunoPage"
import TipoEventos from "../pages/TiposEventoPage/TiposEventoPage";
import TesteEffect from "../pages/Teste/TesteEffect";
const Rotas = () => {
return (
<BrowserRouter>
<Header />
<Routes>
<Route element={<HomePage />} path={"/"} exact />
<Route element={<LoginPage />} path={"/login"} exact />
<Route element={<EventosPage />} path={"/eventos"} exact />
<Route element={<EventosAlunoPage />} path={"/eventos-aluno"} exact />
<Route element={<TipoEventos />} path={"/tipo-eventos"} exact />
<Route element={<TesteEffect />} path={"/testeEffect"} exact />
</Routes>
<Footer />
</BrowserRouter>
);
};
export default Rotas; |
//
// Stock.swift
// MasteringChartsInSwiftUI4
//
// Created by DevTechie on 9/14/22.
//
import Foundation
struct Stock: Identifiable {
var id = UUID()
var name: String
var date: String
var openPrice: Double
var highPrice: Double
var lowPrice: Double
var closePrice: Double
}
extension Stock {
static var exampleData: [Stock] {
[
.init(name: "Company",
date: "Jun 17",
openPrice: 130.07,
highPrice: 143.08,
lowPrice: 119.81,
closePrice: 121.56),
.init(name: "Company",
date: "Jun 16",
openPrice: 95.07,
highPrice: 113.08,
lowPrice: 79.81,
closePrice: 99.56),
.init(name: "Company",
date: "Jun 15",
openPrice: 70.07,
highPrice: 123.08,
lowPrice: 59.81,
closePrice: 75.56),
.init(name: "Company",
date: "Jun 14",
openPrice: 130.07,
highPrice: 163.08,
lowPrice: 119.81,
closePrice: 141.56),
.init(name: "Company",
date: "Jun 13",
openPrice: 109.07,
highPrice: 163.08,
lowPrice: 100.81,
closePrice: 121.56)
]
}
} |
type Color8 = 'negro' | 'rojo' | 'azul' | 'amarillo' | 'blanco';
enum LiquidoVehiculo {
Agua,
Aceite,
LiquidoFrenos
}
enum PiezasExterna {
Llantas = 5,
Pintura
}
class Vehiculo8 {
_numeroRuedas: number;
_marca: string;
_color: Color8;
constructor(marca: string, color: Color8, numeroRuedas: number) {
this._marca = marca;
this._color = color;
this._numeroRuedas = numeroRuedas;
}
hacerMantenimiento(elemento: LiquidoVehiculo): void;
hacerMantenimiento(elementoExterno: PiezasExterna): void;
hacerMantenimiento(elemento: LiquidoVehiculo | PiezasExterna): void {
if (elemento in LiquidoVehiculo) {
console.log('Cambiando líquido del vehiculo...');
} else {
console.log('Cambiando una pieza del vehiculo');
}
}
}
const vehiculo8 = new Vehiculo8('Nissan', 'azul', 4);
vehiculo8.hacerMantenimiento(PiezasExterna.Llantas);
vehiculo8.hacerMantenimiento(LiquidoVehiculo.Aceite); |
const Koa = require('koa')
const app = new Koa()
const errHandler = require('./errHandler')
const { secret } = require('../constant/secretKey')
const { handleTokenError } = require('../utils/token')
const cors = require('koa2-cors')
// 导入数据库
require('../db/index.js')
const userRouter = require('../router/users.routes')
const projectRouter = require('../router/project.routes')
const interfaceRouter = require('../router/interface.routes')
const downloaRouter = require('../router/download.routes')
// 处理静态资源
const koaStatic = require('koa-static')
const path = require('path')
// 导入koaBody中间件,处理post请求参数
const { koaBody } = require('koa-body')
// 导入koajwt,可以用来校验token
const koajwt = require('koa-jwt')
app.use(cors())
// 使用中间件以便于接收post请求参数
app.use(koaBody({ multipart: true }))
// 检验token
app.use(handleTokenError)
// 使用koajwt中间件来检验token
app.use(
koajwt({ secret }).unless({
// 设置某些接口请求时不做校验
path: [/^\/user\/login/, /^\/user\/register/, /index.html$/, /assets/]
})
)
// doc
app.use(koaStatic(path.join(__dirname, '../..', '/apidoc')))
// 注册路由
app.use(userRouter.routes(), userRouter.allowedMethods())
app.use(projectRouter.routes(), projectRouter.allowedMethods())
app.use(interfaceRouter.routes(), interfaceRouter.allowedMethods())
app.use(downloaRouter.routes(), downloaRouter.allowedMethods())
// 对错误的处理
app.on('error', errHandler)
module.exports = app |
//
// Double+Extensiosn.swift
// Jia Jie's DCA Calculator
//
// Created by Jia Jie Chan on 5/10/21.
//
import Foundation
extension Double {
var stringValue: String {
return String(describing: self)
}
var twoDecimalPlaceString: String {
return String(format: "%.2f", self)
}
var zeroDecimalPlaceString: String {
return String(format: "%.0f", self)
}
var currencyFormat: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter.string(from: self as NSNumber) ?? twoDecimalPlaceString
}
var percentageFormat: String {
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 2
return formatter.string(from: self/100 as NSNumber) ?? twoDecimalPlaceString
}
func toCurrencyFormat(hasDollarSymbol: Bool = true, hasDecimalPlaces: Bool = true) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
if hasDollarSymbol == false {
formatter.currencySymbol = ""
}
if hasDecimalPlaces == false {
formatter.maximumFractionDigits = 0
}
return formatter.string(from: self as NSNumber) ?? twoDecimalPlaceString
}
}
extension Double {
var roundedWithAbbreviations: String {
let number = self
let thousand = number / 1000
let million = number / 1000000
if number >= 0 {
if million >= 1.0 {
return "\((self/1000000).round(to: 2))M"
}
else if thousand >= 1.0 {
return "\((self/1000).round(to: 2))K"
}
else {
return "\(self.round(to: 2))"
}
} else {
if million <= -1.0 {
return "\((self/1000000).round(to: 2))M"
}
else if thousand <= -1.0 {
return "\((self/1000).round(to: 2))K"
}
else {
return "\(self.round(to: 2))"
}
}
}
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
} |
class Node{
constructor(value){
this.value = value;
this.next = null; // pointer reference to next node
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
// adding/inserting node to the end
push(value){
let newNode = new Node(value);
if(this.length < 1 || !this.head){
this.head = newNode;
this.tail = newNode;
}
else{
// set prevous tail's next
this.tail.next = newNode;
// set new node as new tail label
this.tail = newNode;
}
this.length += 1;
return this;
}
// remove node from the end
pop(){
// check for empty list
if(!this.head){
return null;
}
// check for single node
if(this.length === 1 || !this.head.next){
let poppedNode = this.head;
this.head = null;
this.tail = null;
this.length = 0;
return poppedNode;
}
// else, continue process w/ multiple nodes
let currentNode = this.head;
let penultimateNode = null;
while(currentNode.next != null){
penultimateNode = currentNode;
currentNode = currentNode.next;
}
if(penultimateNode){
penultimateNode.next = null; // break the chain
}
this.tail = penultimateNode; // set new tail
this.length -= 1; // reduce length
// if after removing, and list becomes empty
// if(this.length === 0) {
// this.head = null;
// this.tail = null;
// }
return currentNode;
}
// remove node from begining of linked list
shift(){
// check if list is empty => if length is not what i like => guard clause
if(!this.length){
console.log("empty");
return null;
}
let currentHeadToRemove = this.head;
let nextNode = this.head.next;
this.head = nextNode;
this.length -= 1;
// if list becomes empty after biginner node removal
if(this.length === 0){
this.tail = null;
// head not set to null cus it will be set when this.head.next is null
}
currentHeadToRemove.next = null; // strip its chain
return currentHeadToRemove;
}
// adding node to the begining
unshift(value){
let newNode = new Node(value);
// if linked list is empty
if(!this.head){
this.head = newNode;
this.tail = newNode;
this.length += 1;
return this;
}
// if linked list in not empty
newNode.next = this.head;
this.head = newNode;
this.length += 1;
return this;
}
// get a node by its position
// getting the 100th node means traversing through 99 nodes which is inefficient...cus can't be accessed outright
// this is where array beats linkedlist...cus element can be access directly without traversing through any other elements
get(index){
// check if not within range
if(index < 0 || index >= this.length){
return null;
}
if(index === 0) return this.head;
let currentNode = this.head;
let counter = 0;
while(currentNode.next){
currentNode = currentNode.next;
counter++;
if(counter === index){
break;
}
}
return currentNode;
// while (index != counter) {
// currentNode = currentNode.next;
// counter++;
// }
// return currentNode;
}
// change the value of node based on its position
set(value, index){
let node = this.get(index);
if(!node){
return false;
}
node.value = value;
return true;
}
// adding new node to a specific position
insert(value, index){
// if tryna insert outside the boundary
if(index < 0 || index > this.length){
return false;
}
// if tryna add to the start then use unshift
let lengthBefore = this.length;
if(index === 0){
// return !!this.unshift(value); // bang-banb, !!, convert other types to respective boolean
this.unshift(value);
return this.length === lengthBefore+1;
}
// if tryna add to the end then use push
if(index === this.length){
this.push(value);
return this.length === lengthBefore+1;
}
// otherwise, inserting in the middle
let penultimateNode = this.get(index - 1);
let nextNode = penultimateNode.next;
let newNode = new Node(value);
penultimateNode.next = newNode;
newNode.next = nextNode;
this.length += 1;
return true;
}
// remove a node from specific position
remove(index){
// invalid range
if(index < 0 || index >= this.length) return null;
// at start
if(index === 0) {
let removedNode = this.shift();
return removedNode;
}
// at end
if(index === this.length-1){
let poppedNode = this.pop();
return poppedNode;
}
// at middle
let penultimateNode = this.get(index-1); // access to penultimateNode gives info about its forward node, hence accessing penultimateNode
let removedNodeMiddle = penultimateNode.next;
penultimateNode.next = removedNodeMiddle.next;
this.length -= 1;
return removedNodeMiddle;
}
print(){
let currentNode = this.head;
let arr = [];
while (currentNode) {
arr.push(currentNode.value);
currentNode = currentNode.next;
}
return arr;
}
// reverse the linkedlist in place
// a -> b -> c -> d
reverse(){
if(!this.head) return null;
if(this.length === 1) return this.head;
let previousNode = null
let currentNode = this.head;
// let nextNode = currentNode.next; // can't be here cus doesnt get updated
while(currentNode){
// temp keep next node
let nextNode = currentNode.next;
// set link of currentNode to reverse
currentNode.next = previousNode;
// shift all pointers forward;
previousNode = currentNode;
currentNode = nextNode;
}
// swap head and tail
[this.head, this.tail] = [this.tail, this.head]
return this;
}
// sum values in linked list
sum(){
if(!this.head) return 0;
let currentNode = this.head;
let sum = 0
while (currentNode) {
sum += currentNode.value;
currentNode = currentNode.next;
}
return sum;
}
}
// a -> b -> c
let sl = new SinglyLinkedList();
sl.push(23);
sl.push(24);
sl.push(25);
sl.push(26);
// sl.pop();
// console.log(sl.sum());
console.log(sl.print());
console.log(sl.reverse());
console.log(sl.print());
let sl2 = new SinglyLinkedList();
sl2.push(10);
sl2.push(20);
// sl2.pop();
console.log(sl2.shift());
// nb:
// check for
// - -ve
// - empty/zero
// - one and
// - many
// linkedlist operations
// - add to the end/tail => push
// - remove from the end => pop
// - add to the start => unshift
// - remove from the start => shift
// - add to anywhere => insert
// - get anywhere => get
// - change anywhere => set
// - remove from anywhere => remove
// SUMMARY
// Time Complexity of major opertations
// - Insertion: O(1) / O(n) depending on position
// ...0(1) => head/tail..it doesn't matter the number of items in the list
// ...for arrays
// ...O(n) => all item needs to be shifted if added to end or middle, ie. O(n)
// ...O(1) => adding item to the end of array, which is rare
// - Removal: O(1) or O(n) depending on the position
// ...O(1) => removing node at the head
// ...O(n) => removing node anywhere else
// - Search/Access: O(n)
// ...O(1) => search at head
// ...O(n) => search anywhere
// ...O(1) => for arrays
// - Recap:
// ...LinkedList is the best alternative where INSERTION / DELETION is VERY frequent
// ...Arrays contains a built-in index, whereas LinkedList does not
// ...Data structures containing Node is the foundation of other data structures like Stacks, Queues
// Reminder Tip
// ...take shift() as hospital queue where the first person is called by doc and the entire patience has to shift forward after first person is removed from the array |
import {Module} from "vuex";
import {Nullable} from "@/core/Common/Common";
export interface AppStateStates {
isLoading: boolean;
loadingErrorText: Nullable<string>;
}
export const appState: Module<AppStateStates, any> = {
namespaced: true,
state: {
isLoading: false,
loadingErrorText: null,
},
getters: {
isLoading(state) {
return state.isLoading;
},
loadingErrorText(state) {
return state.loadingErrorText;
},
},
mutations: {
setLoadingState(state, payload: { result: boolean; error: Nullable<string> }) {
state.isLoading = payload.result;
state.loadingErrorText = payload.error || null;
},
isLoading(state, payload){
state.isLoading = payload;
}
},
actions: {
appDidLoad({commit}, payload) {
commit("setLoadingState", {result: payload.result, error: payload.error || null});
},
startLoading({commit}){
commit("isLoading", true);
},
stopLoading({commit}){
commit("isLoading", false);
}
},
}; |
import { Component, OnInit, Injector } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Router } from '@angular/router';
@Component({
selector: 'app-app-home',
templateUrl: './app-home.component.html',
styleUrls: ['./app-home.component.css']
})
export class AppHomeComponent extends AppComponentBase implements OnInit {
_AppConsts = AppConsts;
userName = '';
action: any;
filteredActions: { link: string, action: string, module: string }[] = new Array();
actions: { link: string, action: string, module: string }[] = new Array();
constructor(
injector: Injector,
private _router: Router
) {
super(injector);
this.actions = [
{link: '/app/admin/organization-units', action: 'RCSA Management', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/main/lossEvents', action: 'Loss Database', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/admin/organization-units', action: 'Business units', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/admin/processes', action: 'Processes', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/main/risks/risks', action: 'Risks', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/main/controls/controls', action: 'Controls', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/main/projects/projects', action: 'Projects', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/main/exceptionIncidents/exceptionIncidents', action: 'Exceptions', module: AppConsts.ModuleKeyValueInternalControl},
{link: '/app/main/home/oprisk', action: 'Operational Risk', module: AppConsts.ModuleKeyValueOpRisk},
{link: '/app/main/home', action: 'Internal Audit', module: AppConsts.ModuleKeyValueInternalAudit},
{link: '/app/main/home', action: 'Internal Control', module: AppConsts.ModuleKeyValueInternalControl}
];
}
ngOnInit() {
this.userName = this.appSession.user.name;
}
setSelectedModule(module: string) {
localStorage.setItem(AppConsts.SelectedModuleKey, module);
}
filterActions(event): void {
this.filteredActions = new Array();
let search = event.query.toLowerCase();
this.filteredActions = this.actions.filter(obj => obj.action.toLowerCase().search(search) !== -1);
}
selectAction(event): void {
this.setSelectedModule(event.module);
this._router.navigate([event.link]);
}
} |
import style from "../../../assets/style/homePage/aboutHome.module.css";
import AboutCard from "./AboutCard";
import { useTranslation } from "react-i18next";
import Slider from "react-slick";
function AboutHome({aboutData}){
const [t] = useTranslation();
let cards = aboutData?.map((item, index) =>
<AboutCard key={index} order={index} description = {item.description} image = {item.image} title = {item.title} id = {item.id}/>
)
const settings = {
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 3,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
},
},
{
breakpoint: 800,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
},
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
},
},
{
breakpoint: 380,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
},
},
],
};
return(
<>
<div className={style.mainDiv}>
<div className="container">
<div className={style.titleDiv}>
<p className={style.littleTitle}>{t("Get To Know Us")}</p>
<h1 className={style.mainTitle}>{t("about us")}</h1>
</div>
<div className={`row ${style.cardsRowCenter}`}>
<Slider {...settings}>
{cards}
</Slider>
</div>
</div>
</div>
</>
);
}
export default AboutHome; |
package ru.spb.leti.g6351.kinpo.adressbook.main.forms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.swing.text.JTextComponent;
import ru.spb.leti.g6351.kinpo.adressbook.data.DefaultDataSource;
import ru.spb.leti.g6351.kinpo.adressbook.data.IsDataSource;
import ru.spb.leti.g6351.kinpo.adressbook.gui.FieldsController;
import ru.spb.leti.g6351.kinpo.adressbook.gui.StringConstants;
import ru.spb.leti.g6351.kinpo.adressbook.handler.ButtonListener;
import ru.spb.leti.g6351.kinpo.adressbook.handler.CheckValuesHandler;
import ru.spb.leti.g6351.kinpo.adressbook.handler.InsertNewHandler;
import ru.spb.leti.g6351.kinpo.adressbook.handler.ShowTableHandler;
import ru.spb.leti.g6351.kinpo.adressbook.handler.UpdateHandler;
import ru.spb.leti.g6351.kinpo.adressbook.validators.DateValidator;
import ru.spb.leti.g6351.kinpo.adressbook.validators.DefaultValidator;
import ru.spb.leti.g6351.kinpo.adressbook.validators.DoubleIntervalValidator;
import ru.spb.leti.g6351.kinpo.adressbook.validators.IntegerIntervalValidator;
import ru.spb.leti.g6351.kinpo.adressbook.validators.NameValidator;
import ru.spb.leti.g6351.kinpo.adressbook.validators.SymbolValidator;
import ru.spb.leti.g6351.kinpo.adressbook.validators.UrlValidator;
import ru.spb.leti.g6351.kinpo.common.Interval;
/**
*
* @author nikita
*/
public class MainFrame extends javax.swing.JFrame implements StringConstants {
private static MainFrame s_instance;
public static MainFrame getInstance() {
return s_instance;
}
/**
*
*/
private static final long serialVersionUID = -6576112152489961075L;
/** Creates new form MainFrame */
public MainFrame() {
s_instance = this;
setTitle(TITLE);
initComponents();
initFields();
initHandlers();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSurnameField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jStreetField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jCityField = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jHomePhoneField = new javax.swing.JFormattedTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jMobilePhoneField = new javax.swing.JFormattedTextField();
jLabel9 = new javax.swing.JLabel();
jPostalCodeField = new javax.swing.JFormattedTextField();
jHouseField = new javax.swing.JFormattedTextField();
jNameField = new javax.swing.JFormattedTextField();
jPanel2 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
jEmailField = new javax.swing.JFormattedTextField();
jSiteField = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jBurthDay = new javax.swing.JFormattedTextField();
jLabel11 = new javax.swing.JLabel();
jOpenListButton = new javax.swing.JButton();
jSaveButton = new javax.swing.JButton();
jButtonInsert = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jHeightField = new javax.swing.JFormattedTextField();
jLabel14 = new javax.swing.JLabel();
jLocationField = new javax.swing.JFormattedTextField();
jCacheField = new javax.swing.JFormattedTextField();
jVoditCatField = new javax.swing.JFormattedTextField();
jLabel15 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Основные данные"));
jLabel1.setText("Имя");
jLabel2.setText("Фамилия");
jLabel3.setText("Улица");
jLabel4.setText("Дом/корп");
jCityField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCityFieldActionPerformed(evt);
}
});
jLabel5.setText("Город");
try {
jHomePhoneField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(***)***-**-**")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jLabel7.setText("Телефон(дом)");
jLabel8.setText("Телефон(моб)");
try {
jMobilePhoneField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("+*(***)***-**-**")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jLabel9.setText("Индекс");
try {
jPostalCodeField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("******")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel8).addComponent(jLabel7).addComponent(jLabel1).addComponent(jLabel2).addComponent(jLabel5).addComponent(jLabel3).addComponent(jLabel4).addComponent(jLabel9)).addGap(35, 35, 35).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap()).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jHouseField, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap()).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jPostalCodeField, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap()).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jStreetField, javax.swing.GroupLayout.PREFERRED_SIZE, 411, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jCityField, javax.swing.GroupLayout.PREFERRED_SIZE, 411, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jSurnameField, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)).addGap(140, 140, 140)).addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false).addComponent(jMobilePhoneField, javax.swing.GroupLayout.Alignment.LEADING).addComponent(jHomePhoneField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)).addContainerGap())))))));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addComponent(jLabel1)).addComponent(jNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jSurnameField, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel2)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jCityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel5)).addGap(11, 11, 11).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jStreetField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel3)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jLabel4).addComponent(jHouseField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(7, 7, 7).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jHomePhoneField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel7)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jMobilePhoneField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel8)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel9).addComponent(jPostalCodeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap(18, Short.MAX_VALUE)));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Дополнительные данные"));
jLabel6.setText("Email");
jSiteField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jSiteFieldActionPerformed(evt);
}
});
jLabel10.setText("Сайт");
jLabel11.setText("Дата рождения");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel6).addComponent(jLabel10).addComponent(jLabel11)).addGap(47, 47, 47).addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false).addComponent(jSiteField, javax.swing.GroupLayout.Alignment.LEADING).addComponent(jEmailField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)).addComponent(jBurthDay, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap(260, Short.MAX_VALUE)));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jLabel6).addComponent(jEmailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jSiteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel10)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jBurthDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel11)).addContainerGap(59, Short.MAX_VALUE)));
jOpenListButton.setText("Открыть список");
jSaveButton.setText("Сохранить");
jButtonInsert.setText("Добавить");
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Специальные сведения"));
jLabel14.setText("Жилплощадь (кв.м)");
jLabel15.setText("Водит. кат.");
jLabel13.setText("Состояние счета");
jLabel12.setText("Рост");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel3Layout.createSequentialGroup().addContainerGap().addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel12).addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addComponent(jHeightField).addComponent(jLocationField, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 120, Short.MAX_VALUE).addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel13).addComponent(jLabel15)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false).addComponent(jVoditCatField).addComponent(jCacheField, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)).addContainerGap()));
jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup().addContainerGap(25, Short.MAX_VALUE).addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jHeightField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jCacheField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel13)).addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jLocationField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jVoditCatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel15).addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(jSaveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jButtonInsert, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 315, Short.MAX_VALUE).addComponent(jOpenListButton, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)).addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addContainerGap()));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(11, 11, 11).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jSaveButton).addComponent(jButtonInsert, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jOpenListButton)).addContainerGap(50, Short.MAX_VALUE)));
pack();
}
private void jSiteFieldActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jCityFieldActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
private javax.swing.JFormattedTextField jBurthDay;
private javax.swing.JButton jButtonInsert;
private javax.swing.JFormattedTextField jCacheField;
private javax.swing.JTextField jCityField;
private javax.swing.JFormattedTextField jEmailField;
private javax.swing.JFormattedTextField jHeightField;
private javax.swing.JFormattedTextField jHomePhoneField;
private javax.swing.JFormattedTextField jHouseField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JFormattedTextField jLocationField;
private javax.swing.JFormattedTextField jMobilePhoneField;
private javax.swing.JFormattedTextField jNameField;
private javax.swing.JButton jOpenListButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JFormattedTextField jPostalCodeField;
private javax.swing.JButton jSaveButton;
private javax.swing.JTextField jSiteField;
private javax.swing.JTextField jStreetField;
private javax.swing.JTextField jSurnameField;
private javax.swing.JFormattedTextField jVoditCatField;
private void initFields() {
jEmailField.setName("Email");
new DefaultValidator(jEmailField, REGEXP_EMAIL, "Нестандартный формат адреса email", true);
jSiteField.setName("Сайт");
new UrlValidator(jSiteField);
new DefaultValidator(jHouseField, REGEXP_HOUSE, "Номер дома не соответствует формату.", true);
new NameValidator(jNameField, false);
new NameValidator(jSurnameField, false);
new NameValidator(jStreetField, true);
new NameValidator(jCityField, true);
new DateValidator(jBurthDay);
new DefaultValidator(jPostalCodeField, "(\\s*|\\d{6})", "Неправильный формат почтового индекса", true);
new DefaultValidator(jHomePhoneField, REGEXP_HOME_PHONE, "Номер телефона не соответствует формату.", true);
new DefaultValidator(jMobilePhoneField, REGEXP_CELL_PHONE, "Номер телефона не соответствует формату.", true);
new IntegerIntervalValidator(jHeightField, new Interval<Integer>(30, true, 300, true));
ArrayList<Interval<Double>> list = new ArrayList<Interval<Double>>();
list.add(new Interval<Double>(-500000.0, false, 0.0, false));
list.add(new Interval<Double>(10000.0, false, 100000.0, true));
new DoubleIntervalValidator(jCacheField, list);
new DoubleIntervalValidator(jLocationField, new Interval<Double>(18.0, true, Double.POSITIVE_INFINITY, false));
new SymbolValidator(jVoditCatField, new Interval<Character>('A', true, 'E', true));
}
private void initHandlers() {
FieldsController.initController();
jOpenListButton.addActionListener(new ButtonListener(new ShowTableHandler()));
jSaveButton.addActionListener(new ButtonListener(new CheckValuesHandler(s_fieldsMap.values()), new UpdateHandler()));
jButtonInsert.addActionListener(new ButtonListener(new CheckValuesHandler(s_fieldsMap.values()), new InsertNewHandler()));
}
public static IsDataSource getDefaultDataSource() {
return DefaultDataSource.getInstance();
}
public HashMap<String, JTextComponent> getFieldsMap() {
if (s_fieldsMap.isEmpty()) initFieldsMap();
return s_fieldsMap;
}
private static HashMap<String, JTextComponent> s_fieldsMap = new HashMap<String, JTextComponent>(20);
private void initFieldsMap() {
s_fieldsMap.put(FD_FNAME, jNameField);
s_fieldsMap.put(FD_SNAME, jSurnameField);
s_fieldsMap.put(FD_HOUSE, jHouseField);
s_fieldsMap.put(FD_HPHONE, jHomePhoneField);
s_fieldsMap.put(FD_CPHONE, jMobilePhoneField);
s_fieldsMap.put(FD_WEBSITE, jSiteField);
s_fieldsMap.put(FD_EMAIL, jEmailField);
s_fieldsMap.put(FD_CITY, jCityField);
s_fieldsMap.put(FD_STREET, jStreetField);
s_fieldsMap.put(FD_CACHE, jCacheField);
s_fieldsMap.put(FD_HEIGHT, jHeightField);
s_fieldsMap.put(FD_VODIT, jVoditCatField);
s_fieldsMap.put(FD_LOCATION, jLocationField);
s_fieldsMap.put(FD_POSTCODE, jPostalCodeField);
s_fieldsMap.put(FD_BURTHDAY, jBurthDay);
}
public void cleanFields() {
for (Entry<String, JTextComponent> e : getFieldsMap().entrySet()) e.getValue().setText("");
}
} |
from flask import Flask, jsonify
import random
app = Flask(__name__)
quotes = {
"Albert Einstein": "The important thing is not to stop questioning. Curiosity has its own reason for existing.",
"Maya Angelou": "Still I rise.",
"Nelson Mandela": "The greatest glory in living lies not in never falling, but in rising every time we fall.",
"APJ Abdul Kalam": "You have to dream before your dream can come true.",
"Marie Curie": "One never notices what has been done; one can only see what remains to be done.",
"Mark Twain": "The secret of getting ahead is getting started.",
"Oscar Wilde": "Be yourself; everyone else is already taken.",
"Mahatma Gandhi": "Be the change that you wish to see in the world.",
"Friedrich Nietzsche": "That which does not kill us makes us stronger.",
"Vincent Van Gogh": "I dream my painting and I paint my dream.",
"Charles Darwin": "It is not the strongest of the species that survive, nor the most intelligent, but the one most responsive to change.",
"Stephen Hawking": "Intelligence is the ability to adapt to change.",
"Elon Musk": "When something is important enough, you do it even if the odds are not in your favor.",
"Steve Jobs": "Innovation distinguishes between a leader and a follower.",
"Walt Disney": "The way to get started is to quit talking and begin doing."
}
def get_random_quote():
"""
Selects a random quote and author from the dictionary.
Returns:
A tuple containing a string quote and a string author.
"""
author, quote = random.choice(list(quotes.items()))
return quote, author
@app.route('/quote', methods=['GET'])
def quote():
"""
Returns a random quote and author as a JSON response.
"""
quote, author = get_random_quote()
return jsonify({'quote': quote, 'author': author})
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080) |
'use client';
import styles from './live.module.css';
import { useEffect, useRef, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import Hls from 'hls.js';
import Plyr from 'plyr';
import 'plyr/dist/plyr.css';
import useSWR from 'swr';
import FollowBtn from '@/util/followBtn';
export default function Live({ idx }) {
const fetcher = (...args) => fetch(...args, { method: 'POST', cache: 'no-store', next: { revalidate: 0 } }).then((res) => res.json());
const { data, error, isLoading } = useSWR(`/api/video/${idx}`, fetcher, {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateOnMount: true,
});
if (error) {
return (
<>
<div className={styles.wrapper}>
<div className={styles.playerWrapper}>
<div className={styles.overlay}>
<div className={styles.loading}>
<p>오류 발생</p>
</div>
</div>
<video id='streamingvideo' className={styles.player}></video>
</div>
</div>
<div className={styles.streamwrapper}>
<h2 className={styles.streamname}>에러 발생</h2>
</div>
</>
);
}
if (isLoading) {
return (
<>
<div className={styles.wrapper}>
<div className={styles.playerWrapper}>
<div className={styles.overlay}>
<div className={styles.loading}>
<p>로딩중</p>
</div>
</div>
<video id='streamingvideo' className={styles.player}></video>
</div>
</div>
<div className={styles.streamwrapper}>
<h2 className={styles.streamname}>로딩중 입니다</h2>
<div className={styles.streamerwrapper}>
<Image className={styles.streamerLogo} src={''} height={0} width={60} alt='스트리머로고' />
<div className={styles.streamer}>
<div className={styles.streamerName}>
<span>로딩중 입니다.</span>
</div>
<p className={styles.streamCategory}>카테고리</p>
<div className={styles.streamInfoWrapper}>
<span>로딩중 입니다</span>
</div>
</div>
<div className={styles.btns}>
<button className={styles.followBtn}>팔로우</button>
</div>
</div>
</div>
</>
);
}
// const sampleurl = 'https://sesac4-vod.s3.ap-northeast-1.amazonaws.com/output/EP04.m3u8';
// const sampleurl = 'https://sesac4-vod.s3.ap-northeast-1.amazonaws.com/output/EP04/720p/720p.m3u8';
const data_ = data.data;
// const data_ = {
// streamurl: sampleurl,
// };
console.log(data_);
return (
<>
<Content data={data_} />
</>
);
}
/**
*
* @param {object} param0
* @param {{idx,userid,userlogo, username, streamname, replay_url, viewer_count, category,recording_start,recording_end,duration}} param0.data
* @returns
*/
function Content({ data }) {
const videoRef = useRef(null);
useEffect(() => {
const video = videoRef.current;
let videourl;
data.duration ? (videourl = `${data.replay_url}master.m3u8`) : (videourl = `${data.replay_url}media/hls/master.m3u8`);
if (!Hls.isSupported()) {
const defaultOptions = {};
video.src = videourl;
video.controls = true;
const player = new Plyr(video, defaultOptions);
} else {
/**
* @type {Plyr.Options}
*/
const defaultOptions = {
controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'settings', 'fullscreen'],
settings: ['quality', 'speed'],
debug: false,
};
const hls = new Hls({ smoothQualityChange: true });
hls.loadSource(videourl);
hls.on(Hls.Events.MANIFEST_PARSED, (event, data) => {
const availableQualities = hls.levels.map((l) => l.height);
availableQualities.unshift(0);
// console.log(availableQualities);
defaultOptions.quality = {
default: 0,
options: availableQualities,
forced: true,
onChange: (e) => {
updateQuality(e);
},
};
defaultOptions.i18n = {
qualityLabel: {
0: 'Auto',
},
};
// console.log(defaultOptions);
const player = new Plyr(video, defaultOptions);
});
hls.on(Hls.Events.LEVEL_SWITCHED, function (event, data) {
var span = document.querySelector(".plyr__menu__container [data-plyr='quality'][value='0'] span");
if (hls.autoLevelEnabled) {
span.innerHTML = `AUTO (${hls.levels[data.level].height}p)`;
} else {
span.innerHTML = `AUTO`;
}
});
hls.attachMedia(video);
window.hls = hls;
}
function updateQuality(newQuality) {
if (newQuality === 0) {
console.log('다음 ts파일부터', newQuality, '해상도로 재생됩니다.');
window.hls.nextLevel = -1; //Enable AUTO quality if option.value = 0
} else {
window.hls.levels.forEach((level, levelIndex) => {
// console.log(level);
// console.log(levelIndex);
if (level.height === newQuality) {
console.log('다음 ts파일부터', newQuality, '해상도로 재생됩니다.');
window.hls.nextLevel = levelIndex;
}
});
}
// console.log(newQuality);
}
return () => {
videoRef.current = null;
};
}, []);
const date = new Date(data.recording_start).toLocaleDateString();
return (
<>
<div className={styles.wrapper}>
<div className={styles.playerWrapper}>
<video ref={videoRef} className={styles.player}></video>
</div>
</div>
<div className={styles.streamwrapper}>
<h2 className={styles.streamname}>{data.streamname}</h2>
<div className={styles.streamerwrapper}>
<Image className={styles.streamerLogo} src={data.userlogo} height={60} width={60} alt='스트리머로고' />
<div className={styles.streamer}>
<Link className={styles.link} href={`/user/${data.userid}`}>
<div className={styles.streamerName}>
<span>{data.username}</span>
</div>
</Link>
<p className={styles.streamCategory}>{data.category}</p>
<div className={styles.streamInfoWrapper}>
<p>조회수 {data.viewer_count}회</p>
<p>{date}</p>
</div>
</div>
<FollowBtn target_userid={data.userid} />
</div>
</div>
</>
);
} |
import time
import sys
import json
import os
import grpc
import bank_pb2
import bank_pb2_grpc
import concurrent.futures
class Customer:
def __init__(self, id, events):
self.id = id
self.events = events
self.recvMsg = list()
self.channel = None
self.stub = None
self.port = 50051 + id
self.lastProcessedId = -1
self.clock = 1
def appendEvents(self, events):
self.events.extend(events)
def createStub(self):
self.channel = grpc.insecure_channel(f"localhost:{self.port}")
stub = bank_pb2_grpc.BankStub(self.channel)
return stub
def executeEvents(self):
if self.stub is None:
self.stub = self.createStub()
result = {
"id": self.id,
"type": "customer",
"events": []
}
for i in range(self.lastProcessedId+1, len(self.events)):
self.lastProcessedId = i
# print(f"processing {self.events[i]['interface']} Event with Index: {i}")
if (self.events[i]["interface"] == "deposit"):
response = self.stub.MsgDelivery(bank_pb2.MsgDeliveryRequest(
id=self.id, event_id=self.events[i]["customer-request-id"], interface="deposit", money=self.events[i]["money"], clock=self.clock))
result["events"].append({
"customer-request-id": self.events[i]["customer-request-id"],
"interface": self.events[i]["interface"],
"logical_clock": self.clock,
"comment": f"event_sent from customer {self.id}"
})
# self.clock = response.clock
if (self.events[i]["interface"] == "withdraw"):
response = self.stub.MsgDelivery(bank_pb2.MsgDeliveryRequest(
id=self.id, event_id=self.events[i]["customer-request-id"], money=self.events[i]["money"], interface="withdraw", clock=self.clock))
result["events"].append({
"customer-request-id": self.events[i]["customer-request-id"],
"interface": self.events[i]["interface"],
"logical_clock": self.clock,
"comment": f"event_sent from customer {self.id}"
})
# self.clock = response.clock
self.clock += 1
return result
def execute_customer(customer):
return customer.executeEvents()
if __name__ == '__main__':
file_path = f'{sys.argv[1]}'
with open(file_path, 'r') as json_file:
data = json.load(json_file)
customerData = []
customers = {}
response = []
for i in range(len(data)):
if (data[i]["type"] == "customer"):
if data[i]["id"] not in customers:
customers[data[i]["id"]] = Customer(
data[i]["id"], data[i]["customer-requests"])
else:
customers[data[i]["id"]].appendEvents(
data[i]["customer-requests"])
with concurrent.futures.ThreadPoolExecutor(max_workers=len(customers)) as executor:
customer_futures = [executor.submit(
execute_customer, customer) for customer in customers.values()]
concurrent.futures.wait(customer_futures)
customer_data = []
for future in customer_futures:
if future.done():
result = future.result()
customer_data.append(result)
else:
print("Task was not completed")
# Generate 1st output file. CUSTOMER
output_path = os.path.join("output", "output-1.json")
with open(output_path, 'w') as json_file:
json.dump(customer_data, json_file)
# Generate 2nd output file. BRANCH
branch_data = []
for i in range(len(data)):
if (data[i]["type"] == "branch"):
output_path = os.path.join(
"output", f"branch-{data[i]['id']}.json")
with open(output_path, 'r') as branch_outputs:
branch_data.append(json.load(branch_outputs))
if os.path.exists(output_path):
os.remove(output_path)
output_path = os.path.join("output", "output-2.json")
with open(output_path, 'w') as json_file:
json.dump(branch_data, json_file)
# Generate 3rd output file. ALL EVENTS
flattened_data = []
for branch in branch_data:
branch_id = branch["id"]
branch_type = branch["type"]
for event in branch["events"]:
flattened_event = {
"id": branch_id,
"type": branch_type,
"customer-request-id": event["customer-request-id"],
"logical_clock": event["logical_clock"],
"interface": event["interface"],
"comment": event["comment"]
}
flattened_data.append(flattened_event)
all_events = []
for i in range(len(customer_data)):
id = customer_data[i]["id"]
for j in range(len(customer_data[i]["events"])):
all_events.append({
"id": id,
"customer-request-id": customer_data[i]["events"][j]["customer-request-id"],
"type": "customer",
"logical_clock": customer_data[i]["events"][j]["logical_clock"],
"interface": customer_data[i]["events"][j]["interface"],
"comment": customer_data[i]["events"][j]["comment"]
})
customer_request_id = customer_data[i]["events"][j]["customer-request-id"]
filtered_events = filter(
lambda event: event["customer-request-id"] == customer_request_id, flattened_data)
sorted_events = sorted(
filtered_events, key=lambda event: event["logical_clock"])
for event in sorted_events:
all_events.append(event)
output_path = os.path.join("output", "output-3.json")
with open(output_path, 'w') as json_file:
json.dump(all_events, json_file)
print("Task done, generated required files in output folder.") |
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entity/User';
import { UserService } from './user.service';
describe('UserService', () => {
let userService: UserService;
let userRepository: Repository<User>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UserService,
{
provide: getRepositoryToken(User),
useClass: Repository,
useValue: {
findOne: jest.fn(),
},
},
],
}).compile();
userService = module.get<UserService>(UserService);
userRepository = module.get<Repository<User>>(getRepositoryToken(User));
});
it('should be defined', () => {
expect(userService).toBeDefined();
});
it('should be find by username success', async () => {
const mockUser: User = {
id: 1,
username: 'test_user',
passwordHash: 'test_password',
salt: 'test_salt',
createdAt: new Date(),
updatedAt: new Date(),
};
jest.spyOn(userRepository, 'findOne').mockResolvedValueOnce(mockUser);
const actualResult = await userService.findByUsername('test_user');
expect(actualResult).toEqual(mockUser);
});
}); |
// Copyright 2024 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package fifo
import (
"math/rand"
"testing"
"github.com/stretchr/testify/require"
)
var pool = MakeQueueBackingPool[int]()
func TestQueue(t *testing.T) {
q := MakeQueue[int](&pool)
require.Nil(t, q.PeekFront())
require.Equal(t, 0, q.Len())
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
require.Equal(t, 3, q.Len())
require.Equal(t, 1, *q.PeekFront())
q.PopFront()
require.Equal(t, 2, *q.PeekFront())
q.PopFront()
require.Equal(t, 3, *q.PeekFront())
q.PopFront()
require.Nil(t, q.PeekFront())
for i := 1; i <= 1000; i++ {
q.PushBack(i)
require.Equal(t, i, q.Len())
}
for i := 1; i <= 1000; i++ {
require.Equal(t, i, *q.PeekFront())
q.PopFront()
require.Equal(t, 1000-i, q.Len())
}
}
func TestQueueRand(t *testing.T) {
q := MakeQueue[int](&pool)
l, r := 0, 0
for iteration := 0; iteration < 100; iteration++ {
for n := rand.Intn(100); n > 0; n-- {
r++
q.PushBack(r)
require.Equal(t, r-l, q.Len())
}
for n := rand.Intn(q.Len() + 1); n > 0; n-- {
l++
require.Equal(t, l, *q.PeekFront())
q.PopFront()
require.Equal(t, r-l, q.Len())
}
}
} |
import { useState, useEffect } from "react";
/**
* Finish the PlayerStatus component so that it follows the current status of the player.
* - The status can be either "online" or "away".
* - When the component first renders, the player should be "online".//
* - The toggleStatus function should change the status variable.//
* - The component should count how many times the user changed their status,
* using the counter.//
* - When the component first renders, the counter should be 1.
* - The counter should be updated within useEffect when status changes.
*
* For example, after the first render, the div element with id root
* should look like this:
*
* <div>
* <h1>Online</h1>
* <h3>1</h3>
* <button>Toggle status</button>
* </div>
*/
const statusDictionary = {
Online: "Away",
Away: "Online",
};
export function PlayerStatus() {
const [status, setStatus] = useState("Online");
const [counter, setCounter] = useState(0);
// Toggle between the two status values - 'Away' and 'Online'
function onToggleStatus() {
setStatus((prevStatus) => statusDictionary[prevStatus]);
}
// Implement effect hook below.
// Update the counter when status changes.
useEffect(() => {
//first render
if (counter === 0) {
setCounter(1);
setStatus("Online");
return;
}
setCounter((prevCounter) => prevCounter + 1);
}, [status]);
return (
<div>
<h1>{status}</h1>
<h3>{counter}</h3>
<button onClick={onToggleStatus}>Toggle status</button>
</div>
);
} |
package com.geckotools.recipe.repository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geckotools.recipe.model.Recipe;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@DataJpaTest
public class RecipeRepositoryTest {
@Autowired
private RecipeRepository recipeRepository;
@BeforeEach
public void setUp() {
recipeRepository
.findAll()
.forEach(entity -> recipeRepository.delete(entity));
}
@Test
public void should_add_new_recipe() throws IOException {
// Given
final var recipeName = "test_add_recipe";
final var jsonFile = new ClassPathResource("init/recipe.json").getFile();
final var recipe = new ObjectMapper().readValue(jsonFile, Recipe.class);
// When
final var dbRecipe = recipeRepository.save(recipe);
// Then
assertNotNull(dbRecipe);
assertEquals(recipeName, dbRecipe.getName());
}
@Test
public void should_find_recipe_by_id() throws IOException {
// Given
final var recipeJsonFile = new ClassPathResource("init/recipe.json").getFile();
final var recipe = new ObjectMapper().readValue(recipeJsonFile, Recipe.class);
final var existingRecipe = recipeRepository.save(recipe);
// When
Optional<Recipe> dbRecipe = recipeRepository.findById(existingRecipe.getId());
// Then
assertTrue(dbRecipe.isPresent());
assertEquals(existingRecipe.getId(), dbRecipe.get().getId());
}
} |
# SPDX-FileCopyrightText: Copyright (c) 2022-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mrc
import cudf
from morpheus.config import Config
from morpheus.messages import MessageMeta
from morpheus.pipeline import SingleOutputSource
from morpheus.pipeline.stage_schema import StageSchema
class StaticMessageSource(SingleOutputSource):
def __init__(self, c: Config, df: cudf.DataFrame):
super().__init__(c)
self._batch_size = c.pipeline_batch_size
self._df = df
@property
def name(self) -> str:
return "static-data"
def supports_cpp_node(self):
return False
@property
def input_count(self) -> int:
return len(self._df)
def compute_schema(self, schema: StageSchema):
schema.output_schema.set_type(MessageMeta)
def _build_source(self, builder: mrc.Builder) -> mrc.SegmentObject:
return builder.make_source(self.unique_name, self._generate_frames())
def _generate_frames(self):
yield MessageMeta(self._df) |
package structural.decorator
abstract class LanternDecorator(val wrappe: ILantern): ILantern {
public override fun on(){
beforeOn()
wrappe.on()
afterOn()
}
public override fun off(){
beforeOff()
wrappe.off()
afterOff()
}
open fun beforeOn() {}
open fun afterOn() {}
open fun beforeOff() {}
open fun afterOff() {}
} |
import { injectable } from "tsyringe";
import { JwtPayload, sign, verify } from "jsonwebtoken";
import { TokenManagerServiceInterface } from "../../domain/services/token-manager-service.interface";
import { VerifyTokenOutput } from "../../domain/services/verify-token.output";
@injectable()
export class TokenManagerService implements TokenManagerServiceInterface {
private secret!: string;
public constructor() {
this.secret = process.env.JWT_SECRET ??'bull-secret';
}
public async create(id: string): Promise<string> {
const config = {
subject: id,
issuer: 'bull-back',
expiresIn: process.env.JWT_EXPIRES || '1h',
};
return sign({ id }, this.secret, config);
}
public async verify(jwt: string): Promise<VerifyTokenOutput> {
const { iss, exp, sub, id } = verify(jwt, this.secret) as JwtPayload;
return { iss, exp, sub, id } as unknown as VerifyTokenOutput;
}
} |
import { Construct } from 'constructs';
import { App, TerraformStack, Testing } from 'cdktf';
import * as NullProvider from './.gen/providers/null';
const token = process.env.TERRAFORM_CLOUD_TOKEN;
export class HelloTerra extends TerraformStack {
constructor(scope: Construct, id: string) {
super(scope, id);
const nullResouce = new NullProvider.Resource(this, 'test', {})
nullResouce.addOverride('provisioner', [{
'local-exec': {
command: `echo "hello deploy"`
}
}]);
this.addOverride('terraform.backend', {
remote: {
organization: 'cdktf-team',
workspaces: {
name: 'test'
},
token: token
}
});
}
}
const app = Testing.stubVersion(new App({}));
new HelloTerra(app, 'hello-terra');
app.synth(); |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateQuotationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('quotations', function (Blueprint $table) {
$table->id();
$table->foreignId('supplier_id')->nullable()->constrained('suppliers');
$table->date('date_agreed');
$table->string('way_to_pay');
$table->string('type_quotation');
$table->foreignId('request_id')->nullable()->constrained('requests');
$table->string('status');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('quotations');
}
} |
import express from 'express';
import path from 'path';
import hbs from 'hbs'
import 'dotenv/config'
const app = express();
const port = process.env.PORT;
const __dirname = path.resolve();
hbs.registerPartials(__dirname + '/views/partials');
app.set('view engine', 'hbs');
app.use( express.static( 'public' ));
app.get('/', (req, res)=> {
res.render('home', {
nombre: 'Jesus Carvajal',
langue: 'node js',
})
})
app.get('/generic', (req, res)=> {
res.render('generic', {
nombre: 'Jesus Carvajal',
langue: 'node js',
})
})
app.get('/elements', (req, res)=> {
res.render('elements', {
nombre: 'Jesus Carvajal',
langue: 'node js',
})
})
app.get('*', (req, res)=> {
res.render('401')
})
app.listen(port, () => {
console.log(`La aplicación corre en el puerto: ${port}`)
}) |
use std::vec;
use nannou::prelude::*;
use crate::boid::*;
const VISUAL_RANGE : f32 = 130.;
const SEPARATION_RANGE : f32 = 40.;
const V_LIM : f32 = 10.;
const COHESION_PERCENT : f32 = 20.;
const SEPARATION_PERCENT : f32 = 40.;
pub fn move_boids(flocks: &mut Vec<Boid>, width: &u32 , height:&u32) {
let mut v1: Vec2;
let mut v2: Vec2;
let mut v3: Vec2;
let mut v4: Vec2;
let flocks_copy: Vec<Boid> = flocks.clone();
for b in &mut *flocks {
v1 = cohesion(&flocks_copy, b);
v2 = separation(&flocks_copy, b);
v3 = alignment(&flocks_copy, b);
v4 = bound_position(b, *width, *height);
b.vel = b.vel +v1+ v2 +v3 + v4;
limit_vel(b);
b.pos += b.vel;
}
}
fn cohesion(flocks:&Vec<Boid>, boid : &Boid) -> Vec2 {
let mut nears: Vec<Vec2> = vec![];
//finding in view area
for current in flocks {
if boid != current {
if boid.pos.distance(current.pos) < VISUAL_RANGE {
nears.push(current.pos);
}
}
}
println!("nears frjh3r:{:?}", nears);
if nears.is_empty() {
return boid.vel; // return a default value when there are no near boids
}
let mut sum : Vec2 = vec2(0.,0.);
for vec in &nears{
sum += *vec;
}
//finding average
let avg:Vec2;
if nears.len() > 0 {
avg = sum / (nears.len() as f32);
} else {
avg = Vec2::new(0.0, 0.0);
}
return (avg-boid.pos) * (COHESION_PERCENT/100.);
}
fn separation(flocks:&Vec<Boid>, boid : &Boid)-> Vec2{
let mut separation: Vec2 = vec2(0., 0.);
for b in flocks{
if boid != b{
if abs(boid.pos.distance(b.pos)) < SEPARATION_RANGE{
separation = separation - (b.pos - boid.pos);
}
}
}
//println!("{} {}" , separation, separation*SEPARATION_PERCENT);
return separation * (SEPARATION_PERCENT)/100.;
}
fn alignment(flocks:&Vec<Boid>, boid : &Boid)-> Vec2{
let mut nears: Vec<Vec2> = vec![];
//finding in view area
for current in flocks {
if boid != current {
if boid.pos.distance(current.pos) < VISUAL_RANGE {
nears.push(current.vel);
}
}
}
let mut sum : Vec2 = vec2(0.,0.);
for vec in &nears{
sum += *vec;
}
//finding average
let avg:Vec2;
if nears.len() > 0 {
avg = sum / (nears.len() as f32);
return avg - boid.vel;
} else {
return Vec2::new(0.0, 0.0);
}
}
fn limit_vel(boid:&mut Boid){
let magnitude = abs(boid.vel.x.powi(2) + boid.vel.y.powi(2)).sqrt();
if magnitude > V_LIM {
boid.vel = boid.vel / magnitude * V_LIM;
}
}
pub fn bound_position(b: &Boid, width: u32, height: u32) -> Vec2 {
let mut v = Vec2::new(0.0, 0.0);
const TURN: f32 = 1.;
if b.pos.x < -(width as f32 / 2.0) {
v.x = TURN;
} else if b.pos.x > (width as f32 / 2.0) {
v.x = -TURN;
}
if b.pos.y < -(height as f32 / 2.0) {
v.y = TURN;
} else if b.pos.y > (height as f32 / 2.0) {
v.y = -TURN;
}
return v
} |
package dev.oddsystems.fpkata.todolist.webserver
import dev.oddsystems.fpkata.todolist.domain.ListName
import dev.oddsystems.fpkata.todolist.domain.ToDoItem
import dev.oddsystems.fpkata.todolist.domain.User
import dev.oddsystems.fpkata.todolist.domain.ZettaiHub
import dev.oddsystems.fpkata.todolist.ui.HtmlPage
import dev.oddsystems.fpkata.todolist.ui.renderPage
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.body.form
import org.http4k.routing.bind
import org.http4k.routing.path
import org.http4k.routing.routes
class Zettai(val hub: ZettaiHub) : HttpHandler {
val httpHandler = routes(
"/ping" bind Method.GET to { Response(Status.OK) },
"/todo/{user}/{listname}" bind Method.GET to ::getToDoList,
"/todo/{user}/{listname}" bind Method.POST to ::addNewItem
)
override fun invoke(request: Request): Response = httpHandler(request)
fun toResponse(htmlPage: HtmlPage): Response =
Response(Status.OK).body(htmlPage.raw)
private fun getToDoList(request: Request): Response {
val user = request.path("user").orEmpty().let(::User)
val listName = request.path("listname").orEmpty().let(ListName.Companion::fromUntrusted)
return listName
?.let { hub.getList(user, it) }
?.let(::renderPage)
?.let(::toResponse)
?: Response(Status.NOT_FOUND)
}
private fun addNewItem(request: Request): Response {
val user = request.path("user")
?.let(::User)
?: return Response(Status.BAD_REQUEST)
val listName = request.path("listname")
?.let(ListName.Companion::fromUntrusted)
?: return Response(Status.BAD_REQUEST)
val item = request.form("itemname")
?.let { ToDoItem(it) }
?: return Response(Status.BAD_REQUEST)
return hub.addItemToList(user, listName, item)
?.let {
Response(Status.SEE_OTHER).header(
"Location",
"/todo/${user.name}/${listName.name}"
)
}
?: Response(Status.NOT_FOUND)
}
} |
{% extends 'core/base.html' %}
{% load static %}
{% block title %}TICKETS{% endblock title %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-6">
<h1>Elementos Agregados</h1>
<table id="elementos-tabla" class="col-12">
<thead>
<tr>
<th>Producto</th>
<th>Cantidad</th>
<th>Precio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="col-md-6">
<h1>Agregar Elemento</h1>
<form id="agregar-form" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" id="agregar" class="btn btn-primary col-12">Agregar</button>
</form>
<br>
<button id="agregar-todos" class="btn btn-primary col-12">Cerrar ticket</button>
</div>
</div>
<div class="row">
<div class='col-md-12'>
{% if messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
</div></div>
</div>
<script>
const successMessage = localStorage.getItem('successMessage');
// Mostrar el mensaje de éxito si está presente
if (successMessage) {
const alertDiv = document.createElement('div');
alertDiv.className = 'alert alert-success alert-dismissible fade show';
alertDiv.role = 'alert';
alertDiv.innerHTML = `
${successMessage}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
`;
document.querySelector('.container').prepend(alertDiv);
// Limpiar el mensaje de éxito guardado en el almacenamiento local
localStorage.removeItem('successMessage');
}
const items = []; // Objeto JavaScript para almacenar los elementos
document.getElementById('agregar-form').addEventListener('submit', function (event) {
event.preventDefault();
const selectElement = document.querySelector('#id_product');
const product = selectElement.value;
const nombre_producto = selectElement.options[selectElement.selectedIndex].textContent;
const quantity = document.querySelector('#id_quantity').value;
fetch(`/product/get-price/${product}/`)
.then(response => response.json())
.then(data => {
const price = data.price;
items.push({ product, quantity, price });
updateTabla(nombre_producto);
});
});
function updateTabla(name) {
const tablaBody = document.querySelector('#elementos-tabla tbody');
tablaBody.innerHTML = '';
items.forEach(item => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${name}</td>
<td>${item.quantity}</td>
<td>${item.price}</td>
<td>${(item.quantity * item.price)}</td>
`;
tablaBody.appendChild(row);
});
}
document.getElementById('agregar-todos').addEventListener('click', function () {
// Obtener el ID del usuario logeado
const userId = {{ request.user.id }};
// Crear el Ticket y obtener el ticket_id
fetch('/tickets/get-ticket-id/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({ user_id: userId })
}).then(response => response.json()).then(data => {
const ticketId = data.ticket_id;
// Agregar ticket_id a cada elemento
items.forEach(item => {
item.ticket_id = ticketId;
});
// Ahora enviar la lista de elementos a la vista create_ticket
fetch('/tickets/create/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({ items: items })
}).then(() => {
// Redireccionar a la página de creación de ticket
localStorage.setItem('successMessage', 'Productos agregados exitosamente');
window.location.href = '{{ success_url }}';
});
});
});
</script>
{% endblock content %} |
import React, {useContext} from 'react';
import { CartContext } from '../../context/CartContext';
import { Link } from 'react-router-dom';
import CartItem from '../CartItem/CartItem';
const Cart = () => {
const {cart,vaciarCarrito,eliminarItem,totalCarrito} = useContext(CartContext)
return (
<div>
{cart.length == 0
?
<>
<h1>NO HAY PRODUCTOS EN EL CARRITO</h1>
<Link to={"/"}><button>Volver al inicio</button></Link>
</>
:
<>
<h1>Carrito de compras</h1>
{cart.map((p)=>(
<CartItem key={p.producto.id} producto={p} eliminarItem={eliminarItem}/>
))}
<h1>Total: ${totalCarrito()}</h1>
<button onClick={vaciarCarrito}>Vaciar carrito</button>
<br></br><br></br>
<Link to={"/checkout"}>
<button>Ir al checkout</button>
</Link>
</>
}
</div>
);
};
export default Cart; |
import { CronJob } from 'cron'
import { BigNumber, BigNumberish } from 'ethers'
import { ICronJobs, INode, INodeData, INodeOptionsValue, INodeParams, NodeType } from '../../src/Interface'
import { returnNodeExecutionData } from '../../src/utils'
import EventEmitter from 'events'
import axios from 'axios'
import { FLOWNetworks, getNetworkProvidersList, NETWORK, networkExplorers } from '../../src/ChainNetwork'
import { formatUnits, parseUnits } from 'ethers/lib/utils'
class FlowBalanceTrigger extends EventEmitter implements INode {
label: string
name: string
type: NodeType
description?: string
version: number
icon: string
category: string
incoming: number
outgoing: number
networks?: INodeParams[]
credentials?: INodeParams[]
inputParameters?: INodeParams[]
cronJobs: ICronJobs
constructor() {
super()
this.label = 'Flow Balance Trigger'
this.name = 'FlowBalanceTrigger'
this.icon = 'flow.png'
this.type = 'trigger'
this.category = 'Cryptocurrency'
this.version = 1.0
this.description = 'Start workflow whenever FLOW balance in wallet changes'
this.incoming = 0
this.outgoing = 1
this.cronJobs = {}
this.networks = [
{
label: 'Network',
name: 'network',
type: 'options',
options: [...FLOWNetworks],
default: 'homestead'
}
] as INodeParams[]
this.inputParameters = [
{
label: 'Wallet Address',
name: 'address',
type: 'string',
default: ''
},
{
label: 'Trigger Condition',
name: 'triggerCondition',
type: 'options',
options: [
{
label: 'When balance increased',
name: 'increase'
},
{
label: 'When balance decreased',
name: 'decrease'
}
],
default: 'increase'
},
{
label: 'Polling Time',
name: 'pollTime',
type: 'options',
options: [
{
label: 'Every 15 secs',
name: '15s'
},
{
label: 'Every 30 secs',
name: '30s'
},
{
label: 'Every 1 min',
name: '1min'
},
{
label: 'Every 5 min',
name: '5min'
},
{
label: 'Every 10 min',
name: '10min'
}
],
default: '30s'
}
] as INodeParams[]
}
loadMethods = {
async getNetworkProviders(nodeData: INodeData): Promise<INodeOptionsValue[]> {
const returnData: INodeOptionsValue[] = []
const networksData = nodeData.networks
if (networksData === undefined) return returnData
const network = networksData.network as NETWORK
return getNetworkProvidersList(network)
}
}
async runTrigger(nodeData: INodeData): Promise<void> {
const networksData = nodeData.networks
const inputParametersData = nodeData.inputParameters
if (networksData === undefined || inputParametersData === undefined) {
throw new Error('Required data missing')
}
const network = networksData.network as NETWORK
const baseUrl =
network === NETWORK.FLOW_TESTNET
? `https://rest-testnet.onflow.org/v1/accounts/`
: `https://rest-mainnet.onflow.org/v1/accounts/`
const emitEventKey = nodeData.emitEventKey as string
const address = (inputParametersData.address as string) || ''
const pollTime = (inputParametersData.pollTime as string) || '30s'
const triggerCondition = (inputParametersData.triggerCondition as string) || 'increase'
const cronTimes: string[] = []
if (pollTime === '15s') {
cronTimes.push(`*/15 * * * * *`)
} else if (pollTime === '30s') {
cronTimes.push(`*/30 * * * * *`)
} else if (pollTime === '1min') {
cronTimes.push(`*/1 * * * *`)
} else if (pollTime === '5min') {
cronTimes.push(`*/5 * * * *`)
} else if (pollTime === '10min') {
cronTimes.push(`*/10 * * * *`)
}
const responseFlow: any = await axios.get(`${baseUrl}${address}`)
let lastBalance: BigNumber = BigNumber.from(responseFlow.data.balance)
const executeTrigger = async () => {
const responseFlow: any = await axios.get(`${baseUrl}${address}`)
const newBalance: BigNumber = BigNumber.from(responseFlow.data.balance)
if (!newBalance.eq(lastBalance)) {
if (triggerCondition === 'increase' && newBalance.gt(lastBalance)) {
const balanceInFlow = this.formatFlow(BigNumber.from(newBalance.toString()))
const diffInFlow = newBalance.sub(lastBalance)
const returnItem = {
newBalance: `${balanceInFlow} FLOW`,
lastBalance: `${this.formatFlow(BigNumber.from(lastBalance.toString()))} FLOW`,
difference: `${this.formatFlow(BigNumber.from(diffInFlow.toString()))} FLOW`,
explorerLink: `${networkExplorers[network]}/address/${address}`,
triggerCondition: 'FLOW balance increase'
}
lastBalance = newBalance
this.emit(emitEventKey, returnNodeExecutionData(returnItem))
} else if (triggerCondition === 'decrease' && newBalance.lt(lastBalance)) {
const balanceInFlow = this.formatFlow(BigNumber.from(newBalance.toString()))
const diffInFlow = lastBalance.sub(newBalance)
const returnItem = {
newBalance: `${balanceInFlow} FLOW`,
lastBalance: `${this.formatFlow(BigNumber.from(lastBalance.toString()))} FLOW`,
difference: `${this.formatFlow(BigNumber.from(diffInFlow.toString()))} FLOW`,
explorerLink: `${networkExplorers[network]}/address/${address}`,
triggerCondition: 'FLOW balance decrease'
}
lastBalance = newBalance
this.emit(emitEventKey, returnNodeExecutionData(returnItem))
} else {
lastBalance = newBalance
}
}
}
// Start the cron-jobs
if (Object.prototype.hasOwnProperty.call(this.cronJobs, emitEventKey)) {
for (const cronTime of cronTimes) {
// Automatically start the cron job
this.cronJobs[emitEventKey].push(new CronJob(cronTime, executeTrigger, undefined, true))
}
} else {
for (const cronTime of cronTimes) {
// Automatically start the cron job
this.cronJobs[emitEventKey] = [new CronJob(cronTime, executeTrigger, undefined, true)]
}
}
}
async removeTrigger(nodeData: INodeData): Promise<void> {
const emitEventKey = nodeData.emitEventKey as string
if (Object.prototype.hasOwnProperty.call(this.cronJobs, emitEventKey)) {
const cronJobs = this.cronJobs[emitEventKey]
for (const cronJob of cronJobs) {
cronJob.stop()
}
this.removeAllListeners(emitEventKey)
}
}
formatFlow(balance: BigNumberish): string {
return formatUnits(balance, 8)
}
parseFlow(flow: string): BigNumber {
return parseUnits(flow, 8)
}
}
module.exports = { nodeClass: FlowBalanceTrigger } |
WITRAY
wmii-@VERSION@
May, 2010
%!includeconf: header.t2t
= NAME =
witray - The wmii system tray
= SYNOPSIS =
witray [-a <address>] [-NESW] [-HV] [-p <padding>] [-s <iconsize>] [-t tags] +
witray -v
= DESCRIPTION =
`witray` is a simple system tray program meant to be used with wmii.
It supports the Freedesktop System Tray Protocol Specification
common among all newer applications and desktop environments. The
tray is only visible when applications require it. While there are
many standalone system tray applications, this one is explicitly
tailored to wmii. It's simple, stays out of the user's way, is easy
to configure, and generally Just Works.
= ARGUMENTS =
: -a
The address at which to connect to `wmii`.
: -N -E -S -W
Sets the screen edge where `witray` is to appear to the
_North_, _South_, _East_, or _West_ edge, respectively.
Options may be combined, for instance *-NE* gives the _North
East_ corner of the screen. If no options are given,
`witray` opens to the West of whichever part of the screen
the wmii bar occupies.
: -H -V
Specifies whether icons are to be aligned horizontally or
vertically, respectively. Also determines from which edge of
the screen windows are shunted to make room for the tray.
: -n
Do not replace an already running system tray.
: -p <padding>
Sets the padding between icons and around the edge of the
tray. In pixels.
: -s <iconsize>
Sets the size of the icons, in pixels. If not provided,
icons are sized so that the tray is the same height as the
`wmii` bar.
: -t <tags>
The tags on which to open. Default: _/./_
: -v
Display version information.
= CAVEATS =
`witray` is not XRandR aware.
= SEE ALSO =
wmii(1), wimenu(1) |
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AuthService} from 'src/app/services/auth.service';
import {ApiService} from '../../../services/api.service';
import {NotificationService} from '../../../services/notification.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss'],
})
export class RegisterComponent implements OnInit {
userName = '';
name = '';
email = '';
password = '';
confirmPassword = '';
errorMessage = '';
loading = false;
constructor(
private api: ApiService,
private auth: AuthService,
private router: Router,
private notificationService: NotificationService,
) {
}
ngOnInit(): void {
}
onSubmit(): void {
this.errorMessage = '';
if (this.password && this.email && this.confirmPassword && this.userName && this.name) {
if (this.password !== this.confirmPassword) {
this.errorMessage = 'Passwords need to match';
}
if (!this.password || !this.email || !this.confirmPassword || !this.userName || !this.name) {
alert('Hãy bổ sung thông tin còn thiếu!');
} else {
this.loading = true;
this.auth
.register({
email: this.email,
password: this.password,
userName: this.userName,
name: this.name
})
.subscribe(
(res) => {
if (res.errorCode == '00') {
this.notificationService.showMessage('success', 'Tạo tài khoản thành công');
this.loading = false;
this.router.navigate(['/auth/login']);
} else {
this.notificationService.showMessage('error', 'Tài khoản đã tồn tại');
this.loading = false;
}
},
(err) => {
this.errorMessage = err.error.message;
this.loading = false;
}
);
}
} else {
this.errorMessage = 'Make sure to fill everything ;)';
}
}
canSubmit(): boolean {
return (
this.email &&
this.password &&
this.confirmPassword &&
this.userName &&
this.name
)
? true
: false;
}
} |
import { fireEvent, render, screen } from "@testing-library/react";
import { GifExpertApp } from "../src/GifExpertApp";
describe("Pruebas en <GifExpertApp />", () => {
test("Debe de mostrar el componente correctamente", () => {
const { container } = render(<GifExpertApp />);
expect(container).toMatchSnapshot();
});
test("Debe de poder escribir en el input y agregar una nueva categoría", () => {
const category = "Deku";
render(<GifExpertApp />);
const input = screen.getByRole("textbox");
const form = screen.getByRole("form");
fireEvent.input(input, { target: { value: category } });
fireEvent.submit(form);
expect(screen.getByText(category).innerHTML).toBeTruthy();
});
test("Debe de no agregar una categoría si ya existe", () => {
const category = "Deku";
render(<GifExpertApp />);
const input = screen.getByRole("textbox");
const form = screen.getByRole("form");
fireEvent.input(input, { target: { value: category } });
fireEvent.submit(form);
fireEvent.input(input, { target: { value: category } });
fireEvent.submit(form);
expect(screen.getAllByText("Deku").length).toBe(1);
});
}); |
Final Project for CPSC 431 Spring 2013, Yale University
Kenta Koga, Cezar Mocan
After loading final.lhs into ghci, run finalProject.
Important comments:
Controls (not case sensitive):
Same note as before: G
Next note in scale: H
Second next in scale: J
Third next in scale: K
Fourth next in scale: L
Previous note in scale: F
Second previous in scale: D
Third previous in scale: S
Fourth previous in scale: A
Volume up: . or >
Volume down: , or <
Reset pitch value to key value: R
Always before using the keyboard controls select the text box (aka write in the textbox), that is where the program takes its input from.
We made the textbox always store the last typed character and delete it exactly after storing, such that its buffer won't overflow. (rec str <- textbox " " -< " ").
According to the character found in str, we create events. (one event for one character - these are the pressEvPlusXB / pressEvMinusXB / pressEvResetB).
In the same way we create events for the buttons corresponding to the keyboard actions (these are the ones without a B in the end, pressEvPlusX / pressEvMinusX ...)
We have the currPitch variable, managed with the "accum" mediator and the functions newPitchBPlus and newPitchBMinus (for a given scale, key, current pitch
and distance to the new pitch (between -4 and and +4) they return the new pitch that respects the scale and the key)
> {-# LANGUAGE Arrows #-}
> {-# LANGUAGE ForeignFunctionInterface #-}
> module Final where
> import Euterpea
> import Control.Arrow
> import Codec.Midi
> import Data.Maybe (mapMaybe)
> import Control.SF.AuxFunctions ((=>>), (->>), (.|.), snapshot, snapshot_)
> import Data.Char
> import Foreign.C.Types
> import Euterpea.IO.MUI
> import Euterpea.IO.MUI.UISF
> import qualified Codec.Midi as Midi
> stringToPitch :: String -> AbsPitch
> stringToPitch [] = -1
> stringToPitch s = (if (null (reads s :: [(Pitch, String)])) then -1 else absPitch(read s::Pitch))
For default scales (modes) that users can choose to play from. Depending on the scale/mode of the song to improvise, user should set the right key with right scale before improvising.
> normalScale = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> bluesScale = [3, 5, 6, 7, 10, 12]
> dorianScale = [2, 3, 5, 7, 9, 10, 12]
> phrygianScale = [1, 3, 5, 7, 8, 10, 12]
> findElementPos t list (-1) = -1
> findElementPos t list index = (if ((list !! index) == t) then index else findElementPos t list (index - 1))
> getElement key pitch = let ret = (pitch + 144 - key) `mod` 12
> in if (ret == 0) then 12 else ret
> newPitch 48 n = 48
> newPitch x n = if (n + x >= 0) then
> if (n + x < 128) then n + x
> else 127
> else 1
> newPitchBMinus list key x n = let position = findElementPos (getElement key n) list ((length list) - 1)
> value = (((list !! position) - (list !! ((position + x + (length list)) `mod` (length list))) + 12) `mod` 12)
> in if (n - value > 0 && n - value < 128) then n - value else n
> newPitchBPlus list key 48 n = key
> newPitchBPlus list key x n = let position = findElementPos (getElement key n) list ((length list) - 1)
> value = ((((list !! ((position + x + (length list)) `mod` (length list))) + 12 - (list !! position))) `mod` 12)
> in if (n + value > 0 && n + value < 128) then n + value else n
> newVolume x n = if (n + x >= 0) then
> if (n + x <= 100) then n + x
> else 100
> else 0
> ui0_8 :: UISF () ()
> ui0_8 = proc _ -> do
> devidOut <- selectOutput -< ()
> (str) <- (|(setSize(200, 80) . title "Type in here") (do
> rec str <- textbox " " -< " "
> returnA -< (str))|)
> (pressEvMinus1, pressEvMinus2, pressEvMinus3, pressEvMinus4, pressEvPlay, pressEvPlus1, pressEvPlus2, pressEvPlus3, pressEvPlus4, pressEvReset) <- (|(setSize(800, 60) . title "Control" . leftRight) (do
> pressEvMinus4 <- edge <<< button "-4 (A)" -< ()
> pressEvMinus3 <- edge <<< button "-3 (S)" -< ()
> pressEvMinus2 <- edge <<< button "-2 (D)" -< ()
> pressEvMinus1 <- edge <<< button "-1 (F)" -< ()
> pressEvPlay <- edge <<< button "0 (G)" -< ()
> pressEvPlus1 <- edge <<< button "+1 (H)" -< ()
> pressEvPlus2 <- edge <<< button "+2 (J)" -< ()
> pressEvPlus3 <- edge <<< button "+3 (K)" -< ()
> pressEvPlus4 <- edge <<< button "+4 (L)" -< ()
> pressEvReset <- edge <<< button "Reset (R)" -< ()
> returnA -< (pressEvMinus1, pressEvMinus2, pressEvMinus3, pressEvMinus4, pressEvPlay, pressEvPlus1, pressEvPlus2, pressEvPlus3, pressEvPlus4, pressEvReset))|)
> pressEvPlayB <- edge -< (if ((last str) == 'g' || (last str) == 'G') then True else False)
> pressEvPlus1B <- edge -< (if ((last str) == 'h' || (last str) == 'H') then True else False)
> pressEvPlus2B <- edge -< (if ((last str) == 'j' || (last str) == 'J') then True else False)
> pressEvPlus3B <- edge -< (if ((last str) == 'k' || (last str) == 'K') then True else False)
> pressEvPlus4B <- edge -< (if ((last str) == 'l' || (last str) == 'L') then True else False)
> pressEvMinus1B <- edge -< (if ((last str) == 'f' || (last str) == 'F') then True else False)
> pressEvMinus2B <- edge -< (if ((last str) == 'd' || (last str) == 'D') then True else False)
> pressEvMinus3B <- edge -< (if ((last str) == 's' || (last str) == 'S') then True else False)
> pressEvMinus4B <- edge -< (if ((last str) == 'a' || (last str) == 'A') then True else False)
> pressEvResetB <- edge -< (if ((last str) == 'r' || (last str) == 'R') then True else False)
> pressEvVolumeUp <- edge -< (if ((last str) == '.' || (last str) == '>') then True else False)
> pressEvVolumeDown <- edge -< (if ((last str) == ',' || (last str) == '<') then True else False)
Create Radio buttons for setting the scale
> scale <- setSize (600, 60) . title "Scale select" . leftRight $ radio ["Normal", "Blues", "Dorian", "Phrygian"] 0 -< ()
> changedScale <- unique -< scale
> let currentScale = if (scale == 0) then normalScale
> else if (scale == 1) then bluesScale
> else if (scale == 2) then dorianScale
> else if (scale == 3) then phrysianScale
> else normalScale
Create Radio buttons for setting the key
> key <- setSize (600, 60) . title "Key select" . leftRight $ radio ["C", "D", "E", "F", "G", "A", "B"] 0 -< ()
> changedKey <- unique -< key
> let currentKey = if (key == 0) then 48
> else if (key == 1) then 50
> else if (key == 2) then 52
> else if (key == 3) then 53
> else if (key == 4) then 55
> else if (key == 5) then 57
> else if (key == 6) then 59
> else 48
> currPitch <- accum 48 -< (((pressEvPlus1 .|. pressEvPlus1B) ->> (newPitchBPlus currentScale currentKey 1)) .|.
> ((pressEvPlus2 .|. pressEvPlus2B) ->> (newPitchBPlus currentScale currentKey 2)) .|.
> ((pressEvPlus3 .|. pressEvPlus3B) ->> (newPitchBPlus currentScale currentKey 3)) .|.
> ((pressEvPlus4 .|. pressEvPlus4B) ->> (newPitchBPlus currentScale currentKey 4)) .|.
> ((pressEvMinus1 .|. pressEvMinus1B) ->> (newPitchBMinus currentScale currentKey (-1))) .|.
> ((pressEvMinus2 .|. pressEvMinus2B) ->> (newPitchBMinus currentScale currentKey (-2))) .|.
> ((pressEvMinus3 .|. pressEvMinus3B) ->> (newPitchBMinus currentScale currentKey (-3))) .|.
> ((pressEvMinus4 .|. pressEvMinus4B) ->> (newPitchBMinus currentScale currentKey (-4))) .|.
> ((pressEvReset .|. pressEvResetB .|. (changedScale ->> ()) .|. (changedKey ->> ()) ) ->> (newPitchBPlus currentScale currentKey 48)))
> volume <- accum 50 -< ((pressEvVolumeUp ->> newVolume 5) .|. (pressEvVolumeDown ->> newVolume (-5)))
> title "Current Pitch" display -< pitch currPitch
> dur <- setSize (600,60) . title "Note length" . leftRight $
> radio ["Whole","Half","Quarter","Eighth","Sixteenth"] 2 -< ()
> instr <- setSize (800,60) . title "Instrument" . leftRight $
> radio ["Acous Piano","Elec Piano","Violin","Saxophone","Flute"] 0 -< ()
> let note = (pressEvPlay .|. pressEvPlus1 .|.
> pressEvMinus1 .|. pressEvMinus2 .|.
> pressEvMinus3 .|. pressEvMinus4 .|.
> pressEvPlus1 .|. pressEvPlus2 .|.
> pressEvPlus3 .|. pressEvPlus4 .|.
> pressEvPlayB .|. pressEvPlus1B .|.
> pressEvMinus1B .|. pressEvMinus2B .|.
> pressEvMinus3B .|. pressEvMinus4B .|.
> pressEvPlus1B .|. pressEvPlus2B .|.
> pressEvPlus3B .|. pressEvPlus4B) ->> [ANote instr currPitch volume (1 / fromIntegral(2^dur))]
> nowE <- now -< ()
> let progChan = nowE ->> (map Std $
> zipWith Midi.ProgramChange [0,1,2,3,4] [0,4,40,66,73])
> midiMsgs = progChan .|. note
> midiOut -< (devidOut, midiMsgs)
> finalProject = runUIEx (800, 500) "Simple Pitch" ui0_8 |
<?php
/**
* The template for displaying the Breadcrumb
*
* @package Catch Themes
* @subpackage Catch Base
* @since Catch Base 1.0
*/
if ( ! defined( 'CATCHBASE_THEME_VERSION' ) ) {
header( 'Status: 403 Forbidden' );
header( 'HTTP/1.1 403 Forbidden' );
exit();
}
/**
* Add breadcrumb.
*
* @action catchbase_after_header
*
* @since Catch Base 1.0
*/
if ( !function_exists( 'catchbase_add_breadcrumb' ) ) :
function catchbase_add_breadcrumb() {
$options = catchbase_get_theme_options(); // Get options
if ( isset ( $options['breadcumb_option'] ) && $options['breadcumb_option'] ){
$showOnHome = ( isset ( $options['breadcumb_onhomepage'] ) && $options['breadcumb_onhomepage'] ) ? '1' : '0';
$delimiter = '<span class="sep">'. $options['breadcumb_seperator'] .'</span><!-- .sep -->'; // delimiter between crumbs
echo catchbase_custom_breadcrumbs( $showOnHome, $delimiter );
}
else
return false;
}
endif;
add_action( 'catchbase_after_header', 'catchbase_add_breadcrumb', 50 );
/**
* Breadcrumb Lists
* Allows visitors to quickly navigate back to a previous section or the root page.
*
* Adopted from Dimox
*
* @since Catch Base 1.0
*/
if ( !function_exists( 'catchbase_custom_breadcrumbs' ) ) :
function catchbase_custom_breadcrumbs( $showOnHome, $delimiter ) {
/* === OPTIONS === */
$text['home'] = __( 'Home', 'catch-base' ); // text for the 'Home' link
$text['category'] = __( '%1$s Archive for %2$s', 'catch-base' ); // text for a category page
$text['search'] = __( '%1$sSearch results for: %2$s', 'catch-base' ); // text for a search results page
$text['tag'] = __( '%1$sPosts tagged %2$s', 'catch-base' ); // text for a tag page
$text['author'] = __( '%1$sView all posts by %2$s', 'catch-base' ); // text for an author page
$text['404'] = __( 'Error 404', 'catch-base' ); // text for the 404 page
$showCurrent = 1; // 1 - show current post/page title in breadcrumbs, 0 - don't show
$before = '<span class="breadcrumb-current">'; // tag before the current crumb
$after = '</span>'; // tag after the current crumb
/* === END OF OPTIONS === */
global $post, $paged, $page;
$homeLink = home_url( '/' );
$linkBefore = '<span class="breadcrumb" typeof="v:Breadcrumb">';
$linkAfter = '</span>';
$linkAttr = ' rel="v:url" property="v:title"';
$link = $linkBefore . '<a' . $linkAttr . ' href="%1$s">%2$s ' . $delimiter . '</a>' . $linkAfter;
if ( is_front_page() ) {
if ( $showOnHome ) {
echo '<div id="breadcrumb-list">
<div class="wrapper">';
echo $linkBefore . '<a href="' . esc_url( $homeLink ) . '">' . $text['home'] . '</a>' . $linkAfter;
echo '</div><!-- .wrapper -->
</div><!-- #breadcrumb-list -->';
}
}
else {
echo '<div id="breadcrumb-list">
<div class="wrapper">';
echo sprintf( $link, esc_url( $homeLink ), $text['home'] );
if ( is_home() ) {
if ( $showCurrent == 1 ) {
echo $before . get_the_title( get_option( 'page_for_posts', true ) ) . $after;
}
}
elseif ( is_category() ) {
$thisCat = get_category( get_query_var( 'cat' ), $after );
if ( $thisCat->parent != 0 ) {
$cats = get_category_parents( $thisCat->parent, true, false );
$cats = str_replace( '<a', $linkBefore . '<a' . $linkAttr, $cats );
$cats = str_replace( '</a>', $delimiter .'</a>' . $linkAfter, $cats );
echo $cats;
}
echo $before . sprintf( $text['category'], '<span class="archive-text">', ' </span>' . single_cat_title( '', false ) ) . $after;
}
elseif ( is_search() ) {
echo $before . sprintf( $text['search'], '<span class="search-text">', ' </span>' . get_search_query() ) . $after;
}
elseif ( is_day() ) {
echo sprintf( $link, get_year_link( get_the_time( 'Y' ) ), get_the_time( 'Y' ) ) ;
echo sprintf( $link, get_month_link( get_the_time( 'Y' ), get_the_time( 'm' ) ), get_the_time( 'F' ) );
echo $before . get_the_time( 'd' ) . $after;
}
elseif ( is_month() ) {
echo sprintf( $link, get_year_link( get_the_time( 'Y' ) ), get_the_time( 'Y' ) ) ;
echo $before . get_the_time( 'F' ) . $after;
}
elseif ( is_year() ) {
echo $before . get_the_time( 'Y' ) . $after;
}
elseif ( is_single() && !is_attachment() ) {
if ( get_post_type() != 'post' ) {
$post_type = get_post_type_object( get_post_type() );
$slug = $post_type->rewrite;
printf( $link, esc_url( $homeLink ) . '/' . $slug['slug'] . '/', $post_type->labels->singular_name );
if ( $showCurrent == 1 ) {
echo $before . get_the_title() . $after;
}
}
else {
$cat = get_the_category();
$cat = $cat[0];
$cats = get_category_parents( $cat, true, '' );
if ( $showCurrent == 0 ) {
$cats = preg_replace( "#^(.+)$#", "$1", $cats );
}
$cats = str_replace( '<a', $linkBefore . '<a' . $linkAttr, $cats );
$cats = str_replace( '</a>', $delimiter .'</a>' . $linkAfter, $cats );
echo $cats;
if ( $showCurrent == 1 ) {
echo $before . get_the_title() . $after;
}
}
}
elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
$post_type = get_post_type_object( get_post_type() );
echo isset( $post_type->labels->singular_name ) ? $before . $post_type->labels->singular_name . $after : '';
}
elseif ( is_attachment() ) {
$parent = get_post( $post->post_parent );
$cat = get_the_category( $parent->ID );
if ( isset( $cat[0] ) ) {
$cat = $cat[0];
}
if ( $cat ) {
$cats = get_category_parents( $cat, true );
$cats = str_replace( '<a', $linkBefore . '<a' . $linkAttr, $cats );
$cats = str_replace( '</a>', $delimiter .'</a>' . $linkAfter, $cats );
echo $cats;
}
printf( $link, get_permalink( $parent ), $parent->post_title );
if ( $showCurrent == 1 ) {
echo $before . get_the_title() . $after;
}
}
elseif ( is_page() && !$post->post_parent ) {
if ( $showCurrent == 1 ) {
echo $before . get_the_title() . $after;
}
}
elseif ( is_page() && $post->post_parent ) {
$parent_id = $post->post_parent;
$breadcrumbs = array();
while( $parent_id ) {
$page_child = get_post( $parent_id );
$breadcrumbs[] = sprintf( $link, get_permalink( $page_child->ID ), get_the_title( $page_child->ID ) );
$parent_id = $page_child->post_parent;
}
$breadcrumbs = array_reverse( $breadcrumbs );
for( $i = 0; $i < count( $breadcrumbs ); $i++ ) {
echo $breadcrumbs[$i];
}
if ( $showCurrent == 1 ) {
echo $before . get_the_title() . $after;
}
}
elseif ( is_tag() ) {
echo $before . sprintf( $text['tag'], '<span class="tag-text">', ' </span>' . single_tag_title( '', false ) ) . $after;
}
elseif ( is_author() ) {
global $author;
$userdata = get_userdata( $author );
echo $before . sprintf( $text['author'], '<span class="author-text">', ' </span>' . $userdata->display_name ) . $after;
}
elseif ( is_404() ) {
echo $before . $text['404'] . $after;
}
if ( get_query_var( 'paged' ) ) {
if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) {
echo ' (';
}
echo sprintf( __( 'Page %s', 'catch-base' ), max( $paged, $page ) );
if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) {
echo ')';
}
}
echo '</div><!-- .wrapper -->
</div><!-- #breadcrumb-list -->';
}
} // end catchbase_breadcrumb_lists
endif; |
import React from 'react';
import {mount} from 'enzyme';
import {expect} from '../../../../util/reconfiguredChai';
import InternationalOptIn from '@cdo/apps/code-studio/pd/international_opt_in/InternationalOptIn';
describe('InternationalOptInTest', () => {
const defaultProps = {
options: {
schoolCountry: ['schoolCountry', 'Colombia'],
workshopCourse: ['workshopCourse'],
emailOptIn: ['emailOptIn'],
legalOptIn: ['legalOptIn'],
workshopOrganizer: ['workshopOrganizer'],
colombianSchoolData: {
department: {
municipality: {
city: ['branch'],
},
},
},
},
accountEmail: 'test@code.org',
apiEndpoint: '/api/v1/pd/international_opt_ins',
labels: {
firstName: 'First Name',
firstNamePreferred: 'Preferred First Name',
lastName: 'Last Name',
email: 'Email',
school: 'School',
schoolCity: 'School City',
schoolCityDistrict: 'School City/District',
schoolCountry: 'School Country',
schoolDepartmentRegion: 'School Department/Region',
schoolName: 'School Name',
workshopOrganizer: 'Workshop Organizer',
workshopCourse: 'Workshop Course',
emailOptIn:
'Can we email you about Code.org’s international program, updates to our courses, or other computer science news?',
legalOptIn:
'By submitting this form, you are agreeing to allow Code.org to share information on how you use Code.org and the Professional Learning resources with the Code.org International Partner(s) in your country. We will share with these partners your contact information (such as name and email address), the information you provide about your school, which courses/units you are using, and aggregate data about these courses (such as the number of students using each course). We will not share any information about individual students with our partners: all student information will be de-identified and aggregated. Our International Partners and facilitators are contractually obliged to treat this information with the same level of confidentiality as Code.org.',
colombianSchoolCity: 'School City',
colombianChileanSchoolDepartment: 'School Department',
colombianSchoolMunicipality: 'School Municipality',
colombianChileanSchoolName: 'School Name',
chileanSchoolCommune: 'School Commune',
chileanSchoolId: 'School ID',
},
};
describe('Colombian school interface', () => {
it('requires you to select a country before enabling school name and city inputs', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
const inputIds = ['schoolName', 'schoolCity'];
inputIds.forEach(id => {
const node = wrapper.find(`input#${id}`);
expect(node.prop('disabled')).to.be.true;
});
wrapper.setState({data: {schoolCountry: 'selected country'}});
inputIds.forEach(id => {
const node = wrapper.find(`input#${id}`);
expect(node.prop('disabled')).to.be.false;
});
});
it('displays school name and city as selects rather than inputs when Colombia is selected', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(1);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolCity')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({
data: {schoolCountry: 'someplace other than Colombia'},
});
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(1);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolCity')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({data: {schoolCountry: 'Colombia'}});
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(0);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolCity')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(1);
});
it('displays extra inputs when Colombia is selected', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolMunicipality')).to.have.lengthOf(0);
wrapper.setState({
data: {schoolCountry: 'someplace other than Colombia'},
});
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolMunicipality')).to.have.lengthOf(0);
wrapper.setState({data: {schoolCountry: 'Colombia'}});
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolMunicipality')).to.have.lengthOf(1);
});
it('requires each Colombian school data field be selected in order', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
wrapper.setState({data: {schoolCountry: 'Colombia'}});
expect(wrapper.find('select#schoolMunicipality').prop('disabled')).to.be
.true;
expect(wrapper.find('select#schoolCity').prop('disabled')).to.be.true;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolDepartment: 'department', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolMunicipality').prop('disabled')).to.be
.false;
expect(wrapper.find('select#schoolCity').prop('disabled')).to.be.true;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolMunicipality: 'municipality', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolMunicipality').prop('disabled')).to.be
.false;
expect(wrapper.find('select#schoolCity').prop('disabled')).to.be.false;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolCity: 'city', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolMunicipality').prop('disabled')).to.be
.false;
expect(wrapper.find('select#schoolCity').prop('disabled')).to.be.false;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.false;
});
it('populates the Colombian school data fields based on earlier selections', () => {
const expandedColombianSchoolData = {
'department 1': {
'municipality 1-1': {
'city 1-1-1': ['branch 1-1-1-1', 'branch 1-1-1-2'],
'city 1-1-2': ['branch 1-1-2-1', 'branch 1-1-2-2'],
},
'municipality 1-2': {
'city 1-2-1': ['branch 1-2-1-1', 'branch 1-2-1-2'],
'city 1-2-2': ['branch 1-2-2-1', 'branch 1-2-2-2'],
},
},
'department 2': {
'municipality 2-1': {
'city 2-1-1': ['branch 2-1-1-1', 'branch 2-1-1-2'],
'city 2-1-2': ['branch 2-1-2-1', 'branch 2-1-2-2'],
},
'municipality 2-2': {
'city 2-2-1': ['branch 2-2-1-1', 'branch 2-2-1-2'],
'city 2-2-2': ['branch 2-2-2-1', 'branch 2-2-2-2'],
},
},
};
const props = {
...defaultProps,
options: {
...defaultProps.options,
colombianSchoolData: expandedColombianSchoolData,
},
};
const wrapper = mount(<InternationalOptIn {...props} />);
wrapper.setState({data: {schoolCountry: 'Colombia'}});
// initially, only departments are available; everything else is empty
const departments = wrapper
.find('select#schoolDepartment')
.children()
.map(option => option.prop('value'));
expect(departments).to.eql([
'',
'Not applicable',
'department 1',
'department 2',
]);
expect(
wrapper.find('select#schoolMunicipality').children()
).to.have.lengthOf(2);
expect(wrapper.find('select#schoolCity').children()).to.have.lengthOf(2);
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(2);
// after selecting a department, municipality becomes available
wrapper.setState({
data: {schoolDepartment: 'department 1', ...wrapper.state().data},
});
let municipalities = wrapper
.find('select#schoolMunicipality')
.children()
.map(option => option.prop('value'));
expect(municipalities).to.eql([
'',
'Not applicable',
'municipality 1-1',
'municipality 1-2',
]);
// selecting a different department will change the municipalities available
wrapper.setState({
data: {...wrapper.state().data, schoolDepartment: 'department 2'},
});
municipalities = wrapper
.find('select#schoolMunicipality')
.children()
.map(option => option.prop('value'));
expect(municipalities).to.eql([
'',
'Not applicable',
'municipality 2-1',
'municipality 2-2',
]);
// likewise, municipality and city selections unlock in turn
expect(wrapper.find('select#schoolCity').children()).to.have.lengthOf(2);
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(2);
wrapper.setState({
data: {...wrapper.state().data, schoolMunicipality: 'municipality 2-1'},
});
expect(wrapper.find('select#schoolCity').children()).to.have.lengthOf(4);
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(2);
wrapper.setState({
data: {...wrapper.state().data, schoolCity: 'city 2-1-1'},
});
expect(wrapper.find('select#schoolCity').children()).to.have.lengthOf(4);
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(4);
});
});
describe('Chilean school interface', () => {
it('displays school name and city as selects rather than inputs when Chile is selected', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(1);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({
data: {schoolCountry: 'someplace other than Chile'},
});
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(1);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({data: {schoolCountry: 'Chile'}});
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(0);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(1);
});
it('displays extra inputs when Chile is selected', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolCommune')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolId')).to.have.lengthOf(0);
wrapper.setState({
data: {schoolCountry: 'someplace other than Chile'},
});
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolCommune')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolId')).to.have.lengthOf(0);
wrapper.setState({data: {schoolCountry: 'Chile'}});
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolCommune')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolId')).to.have.lengthOf(1);
});
it('requires each Chilean school data field be selected in order', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
wrapper.setState({data: {schoolCountry: 'Chile'}});
expect(wrapper.find('select#schoolCommune').prop('disabled')).to.be.true;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.true;
expect(wrapper.find('select#schoolId').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolDepartment: 'department', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolCommune').prop('disabled')).to.be.false;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.true;
expect(wrapper.find('select#schoolId').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolCommune: 'commune', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolCommune').prop('disabled')).to.be.false;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.false;
expect(wrapper.find('select#schoolId').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolName: 'name', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolCommune').prop('disabled')).to.be.false;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.false;
expect(wrapper.find('select#schoolId').prop('disabled')).to.be.false;
});
it('populates the Chilean school data fields based on earlier selections', () => {
const expandedChileanSchoolData = {
'department 1': {
'commune 1-1': {
'name 1-1-1': ['id 1-1-1-1', 'id 1-1-1-2'],
'name 1-1-2': ['id 1-1-2-1', 'id 1-1-2-2'],
},
'commune 1-2': {
'name 1-2-1': ['id 1-2-1-1', 'id 1-2-1-2'],
'name 1-2-2': ['id 1-2-2-1', 'id 1-2-2-2'],
},
},
'department 2': {
'commune 2-1': {
'name 2-1-1': ['id 2-1-1-1', 'id 2-1-1-2'],
'name 2-1-2': ['id 2-1-2-1', 'id 2-1-2-2'],
},
'commune 2-2': {
'name 2-2-1': ['id 2-2-1-1', 'id 2-2-1-2'],
'name 2-2-2': ['id 2-2-2-1', 'id 2-2-2-2'],
},
},
};
const props = {
...defaultProps,
options: {
...defaultProps.options,
chileanSchoolData: expandedChileanSchoolData,
},
};
const wrapper = mount(<InternationalOptIn {...props} />);
wrapper.setState({data: {schoolCountry: 'Chile'}});
// initially, only departments are available; everything else is empty
const departments = wrapper
.find('select#schoolDepartment')
.children()
.map(option => option.prop('value'));
expect(departments).to.eql([
'',
'Not applicable',
'department 1',
'department 2',
]);
expect(wrapper.find('select#schoolCommune').children()).to.have.lengthOf(
2
);
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(2);
expect(wrapper.find('select#schoolId').children()).to.have.lengthOf(2);
// after selecting a department, municipality becomes available
wrapper.setState({
data: {schoolDepartment: 'department 1', ...wrapper.state().data},
});
let commune = wrapper
.find('select#schoolCommune')
.children()
.map(option => option.prop('value'));
expect(commune).to.eql([
'',
'Not applicable',
'commune 1-1',
'commune 1-2',
]);
// selecting a different department will change the communes available
wrapper.setState({
data: {...wrapper.state().data, schoolDepartment: 'department 2'},
});
commune = wrapper
.find('select#schoolCommune')
.children()
.map(option => option.prop('value'));
expect(commune).to.eql([
'',
'Not applicable',
'commune 2-1',
'commune 2-2',
]);
// likewise, name and id selections unlock in turn
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(2);
expect(wrapper.find('select#schoolId').children()).to.have.lengthOf(2);
wrapper.setState({
data: {...wrapper.state().data, schoolCommune: 'commune 2-1'},
});
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(4);
expect(wrapper.find('select#schoolId').children()).to.have.lengthOf(2);
wrapper.setState({
data: {...wrapper.state().data, schoolName: 'name 2-1-1'},
});
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(4);
expect(wrapper.find('select#schoolId').children()).to.have.lengthOf(4);
});
});
describe('Uzbekistan school interface', () => {
it('displays school name and city as selects rather than inputs when Uzbekistan is selected', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(1);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({
data: {schoolCountry: 'someplace other than Uzbekistan'},
});
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(1);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({data: {schoolCountry: 'Uzbekistan'}});
expect(wrapper.find('input#schoolCity')).to.have.lengthOf(0);
expect(wrapper.find('input#schoolName')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(1);
});
it('displays extra inputs when Uzbekistan is selected', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolMunicipality')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({
data: {schoolCountry: 'someplace other than Uzbekistan'},
});
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolMunicipality')).to.have.lengthOf(0);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(0);
wrapper.setState({data: {schoolCountry: 'Uzbekistan'}});
expect(wrapper.find('select#schoolDepartment')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolMunicipality')).to.have.lengthOf(1);
expect(wrapper.find('select#schoolName')).to.have.lengthOf(1);
});
it('requires each Uzbekistan school data field be selected in order', () => {
const wrapper = mount(<InternationalOptIn {...defaultProps} />);
wrapper.setState({data: {schoolCountry: 'Uzbekistan'}});
expect(wrapper.find('select#schoolMunicipality').prop('disabled')).to.be
.true;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolDepartment: 'department', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolMunicipality').prop('disabled')).to.be
.false;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.true;
wrapper.setState({
data: {schoolMunicipality: 'district', ...wrapper.state().data},
});
expect(wrapper.find('select#schoolMunicipality').prop('disabled')).to.be
.false;
expect(wrapper.find('select#schoolName').prop('disabled')).to.be.false;
});
it('populates the Uzbekistan school data fields based on earlier selections', () => {
const expandedUzbekistanSchoolData = {
'department 1': {
'district 1-1': ['name 1-1-1', 'name 1-1-2'],
'district 1-2': ['name 1-2-1', 'name 1-2-2'],
},
'department 2': {
'district 2-1': ['name 2-1-1', 'name 2-1-2'],
'district 2-2': ['name 2-2-1', 'name 2-2-2'],
},
};
const props = {
...defaultProps,
options: {
...defaultProps.options,
uzbekistanSchoolData: expandedUzbekistanSchoolData,
},
};
const wrapper = mount(<InternationalOptIn {...props} />);
wrapper.setState({data: {schoolCountry: 'Uzbekistan'}});
// initially, only departments are available; everything else is empty
const departments = wrapper
.find('select#schoolDepartment')
.children()
.map(option => option.prop('value'));
expect(departments).to.eql([
'',
'Not applicable',
'department 1',
'department 2',
]);
expect(
wrapper.find('select#schoolMunicipality').children()
).to.have.lengthOf(2);
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(2);
// after selecting a department, district becomes available
wrapper.setState({
data: {schoolDepartment: 'department 1', ...wrapper.state().data},
});
let commune = wrapper
.find('select#schoolMunicipality')
.children()
.map(option => option.prop('value'));
expect(commune).to.eql([
'',
'Not applicable',
'district 1-1',
'district 1-2',
]);
// selecting a different department will change the districts available
wrapper.setState({
data: {...wrapper.state().data, schoolDepartment: 'department 2'},
});
commune = wrapper
.find('select#schoolMunicipality')
.children()
.map(option => option.prop('value'));
expect(commune).to.eql([
'',
'Not applicable',
'district 2-1',
'district 2-2',
]);
// after selecting a district, school becomes available
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(2);
wrapper.setState({
data: {...wrapper.state().data, schoolMunicipality: 'district 2-1'},
});
expect(wrapper.find('select#schoolName').children()).to.have.lengthOf(4);
});
});
}); |
programa
{
/*
2- Obtenha um número digitado pelo usuário e repita a operação de multiplicar ele por três
(imprimindo o novo valor) até que ele seja maior do que 100. Ex.: se o usuário digita 5,
deveremos observar na tela a seguinte sequência: 5 15 45 135.
*Autor: Melqui Santos - Turma 39
*Data: 29/10/21
*/
funcao inicio()
{
inteiro num = 0, cont = 0
escreva("Digite um número: ")
leia(num)
enquanto(num < 100){
escreva(num + " ")
num = num * 3
// Caso o último laço seja maior que 100 ele imprime na tela.
se(num > 100){
escreva(num)
}
}
}
}
/* $$$ Portugol Studio $$$
*
* Esta seção do arquivo guarda informações do Portugol Studio.
* Você pode apagá-la se estiver utilizando outro editor.
*
* @POSICAO-CURSOR = 10;
* @PONTOS-DE-PARADA = ;
* @SIMBOLOS-INSPECIONADOS = ;
* @FILTRO-ARVORE-TIPOS-DE-DADO = inteiro, real, logico, cadeia, caracter, vazio;
* @FILTRO-ARVORE-TIPOS-DE-SIMBOLO = variavel, vetor, matriz, funcao;
*/ |
part of '../auth_part.dart';
enum AuthStatus { authenticated, unauthenticated }
@copyWith
@props
class AuthState extends Equatable {
final AuthStatus status;
final UserModel user;
const AuthState({
required this.status,
required this.user,
});
@override
List<Object?> get props => _$AuthStateProps(this);
}
class AuthInitial extends AuthState {
const AuthInitial()
: super(status: AuthStatus.unauthenticated, user: UserModel.empty);
}
class AuthLoading extends AuthState {
const AuthLoading({required super.status, required super.user});
}
class AuthError extends AuthState {
final Object error;
const AuthError({
required this.error,
required super.status,
required super.user,
});
} |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
提取图像的特征,并保存
"""
import argparse
import glob
import os
import sys
import torch.nn.functional as F
import cv2
import numpy as np
import tqdm
from torch.backends import cudnn
sys.path.append('.')
from fastreid.config import get_cfg
from fastreid.utils.logger import setup_logger
from fastreid.utils.file_io import PathManager
from predictor import FeatureExtractionDemo
# import some modules added in project like this below
# sys.path.append("projects/PartialReID")
# from partialreid import *
cudnn.benchmark = True
setup_logger(name="fastreid")
# 读取配置文件
def setup_cfg(args):
# load config from file and command-line arguments
cfg = get_cfg()
# add_partialreid_config(cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
return cfg
def get_parser():
parser = argparse.ArgumentParser(description="Feature extraction with reid models")
parser.add_argument(
"--config-file", # config路径,通常包含模型配置文件
metavar="FILE",
help="path to config file",
)
parser.add_argument(
"--parallel", # 是否并行
action='store_true',
help='If use multiprocess for feature extraction.'
)
parser.add_argument(
"--input", # 输入图像路径
nargs="+",
help="A list of space separated input images; "
"or a single glob pattern such as 'directory/*.jpg'",
)
parser.add_argument(
"--output", # 输出结果路径
default='demo_output',
help='path to save features'
)
parser.add_argument(
"--opts",
help="Modify config options using the command-line 'KEY VALUE' pairs",
default=[],
nargs=argparse.REMAINDER,
)
return parser
def postprocess(features):
# Normalize feature to compute cosine distance
features = F.normalize(features) # 特征归一化
features = features.cpu().data.numpy()
return features
if __name__ == '__main__':
args = get_parser().parse_args() # 解析输入参数
# 调试使用,使用的时候删除下面代码
# ---
args.config_file = "./configs/Market1501/bagtricks_R50.yml" # config路径
args.input = "./datasets/Market-1501-v15.09.15/query/*.jpg" # 图像路径
# ---
cfg = setup_cfg(args) # 读取cfg文件
demo = FeatureExtractionDemo(cfg, parallel=args.parallel) # 加载特征提取器,也就是加载模型
PathManager.mkdirs(args.output) # 创建输出路径
if args.input:
if PathManager.isdir(args.input[0]): # 判断输入的是否为路径
# args.input = glob.glob(os.path.expanduser(args.input[0])) # 原来的代码有问题
args.input = glob.glob(os.path.expanduser(args.input)) # 获取输入路径下所有的文件路径
assert args.input, "The input path(s) was not found"
for path in tqdm.tqdm(args.input): # 逐张处理
img = cv2.imread(path)
feat = demo.run_on_image(img) # 提取图像特征
feat = postprocess(feat) # 后处理主要是特征归一化
np.save(os.path.join(args.output, os.path.basename(path).split('.')[0] + '.npy'), feat) # 保存图像对应的特征,以便下次使用 |
C doesn't have any built-in boolean types, see: https://stackoverflow.com/a/1921557
Standard C header files:
<assert.h> Program assertion functions
<ctype.h> Character type functions
<locale.h> Localization functions
<math.h> Mathematics functions
<setjmp.h> Jump functions
<signal.h> Signal handling functions
<stdarg.h> Variable arguments handling functions
<stdio.h> Standard Input/Output functions
<stdlib.h> Standard Utility functions
<string.h> String handling functions
<time.h> Date time functions
<unistd.h> Standard symbolic constants and types
<sys/types.h> Data types
Program arguments:
The system starts a C program by calling the function main. It is up to you to write a function named main—otherwise, you won’t even be able to link your program without errors.
In ISO C you can define main either to take no arguments, or to take two arguments that represent the command line arguments to the program, like this:
int main (int argc, char *argv[])
The command line arguments are the whitespace-separated tokens given in the shell command used to invoke the program; thus, in ‘cat foo bar’, the arguments are ‘foo’ and ‘bar’. The only way a program can look at its command line arguments is via the arguments of main. If main doesn’t take arguments, then you cannot get at the command line.
The value of the argc argument is the number of command line arguments. The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element. A null pointer always follows the last element: argv[argc] is this null pointer.
For the command ‘cat foo bar’, argc is 3 and argv has three elements, "cat", "foo" and "bar".
In Unix systems you can define main a third way, using three arguments:
int main (int argc, char *argv[], char *envp[])
The first two arguments are just the same. The third argument envp gives the program’s environment; it is the same as the value of environ.
Compiling programs without header files:
In C, when the compiler does not find the definition of a function, it assumes it's an external function returning an integer. So the code compiles, and if the linker then finds a function with a corresponding name it will use it, but possibly with unexpected results.
Needed header: <stdio.h>
int printf(const char *format, ...): print formatted data to stdout
int fprintf(FILE *stream, const char *format, ...): print formatted data to stream
int dprintf(int fd, const char *format, ...): print formatted data to file descriptor
int sprintf(char *str, const char *format, ...): print formatted data to string buffer (requires large enough buffer)
int asprintf(char **restrict str, const char *restrict format, ...): print formatted data to automatically sized and allocated string buffer
See: man 3 printf
scanf(const char *format, ...): reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments
See: man scanf
Note: restrict can be used in pointer declarations, by adding this type qualifier, a programmer hints to the compiler that for the lifetime of the pointer, no other pointer will be used to access the object to which it points
Format specifiers define the type of data to be printed on standard output. You need to use format
specifiers whether you're printing formatted output with printf() or accepting input with scanf().
%c a single character
%s a string
%hi short (signed)
%hu short (unsigned)
%Lf long double
%n prints nothing
%d a decimal integer (assumes base 10)
%i a decimal integer (detects the base automatically)
%o an octal (base 8) integer
%x a hexadecimal (base 16) integer
%p an address (or pointer)
%f a floating point number for floats
%u int unsigned decimal
%e a floating point number in scientific notation
%E a floating point number in scientific notation
%% the % symbol
Needed header: <stdlib.h>
char* getenv(const char *var): get an environment variable
int system(const char *cmd): execute a shell command
void exit(int status): cause normal process termination
Needed header: <err.h>
noreturn void err(int eval, const char *fmt, ...): display formatted error on stderr and exit with the value 'eval'
Note: noreturn indicates the function does not return by executing the return statement or by reaching the end of the function body
Getting and setting user privileges:
Needed header: <unistd.h>
getuid() returns the real user ID of the calling process.
geteuid() returns the effective user ID of the calling process.
getgid() analogous to getuid()
getegid() analogous to geteuid()
setresuid() sets the real user ID, the effective user ID, and the saved set-user-ID of the calling process.
setresgid() analogous to setresuid() for group IDs
Needed header: <fcntl.h>
int open(const char *pathname, int flags): open and possibly create a file, returns fd to the file
The argument flags must include one of the following access modes: O_RDONLY (read-only), O_WRONLY (write-only), or O_RDWR (read-write).
A file descriptor (fd) is a low-level integer "handle" used to identify an opened file (or socket, or whatever) at the kernel level, in Linux and other Unix-like systems.
A FILE pointer is a C standard library-level construct, used to represent a file. The FILE wraps the file descriptor, and adds buffering and other features to make I/O easier.
Needed header: <unistd.h>
ssize_t read(int fd, void *buf, size_t count): read from a fd, returns the num of bytes read or -1 on error
ssize_t write(int fd, const void *buf, size_t count): write to a fd, returns the num of bytes written or -1 on error
Read files whose name doesn't include "token" up to 1024 chars and output the content to stdout:
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <err.h>
int main(int argc, char **argv, char **envp) {
char buf[1024];
if (argc == 1) {
printf("%s [file to read]\n", argv[0]);
exit(EXIT_FAILURE);
}
if (strstr(argv[1], "token") != NULL) {
printf("You may not access '%s'\n", argv[1]);
exit(EXIT_FAILURE);
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
err(EXIT_FAILURE, "Unable to open %s", argv[1]);
}
int rc = read(fd, buf, sizeof(buf));
if (rc == -1) {
err(EXIT_FAILURE, "Unable to read fd %d", fd);
}
write(1, buf, rc);
}
Needed header: <string.h>
char *strstr(const char *haystack, const char *needle): return a pointer to the beginning of the located substring, or NULL if the substring is not found |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.15;
import 'forge-std/Test.sol';
import {UniversalRouter} from '../../contracts/UniversalRouter.sol';
import {Payments} from '../../contracts/modules/Payments.sol';
import {Constants} from '../../contracts/libraries/Constants.sol';
import {Commands} from '../../contracts/libraries/Commands.sol';
import {MockERC20} from './mock/MockERC20.sol';
import {MockERC1155} from './mock/MockERC1155.sol';
import {Callbacks} from '../../contracts/base/Callbacks.sol';
import {ExampleModule} from '../../contracts/test/ExampleModule.sol';
import {RouterParameters} from '../../contracts/base/RouterImmutables.sol';
import {ERC20} from 'solmate/src/tokens/ERC20.sol';
import 'permit2/src/interfaces/IAllowanceTransfer.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol';
contract UniversalRouterTest is Test {
address constant RECIPIENT = address(10);
uint256 constant AMOUNT = 10 ** 18;
UniversalRouter router;
ExampleModule testModule;
MockERC20 erc20;
MockERC1155 erc1155;
Callbacks callbacks;
function setUp() public {
RouterParameters memory params = RouterParameters({
permit2: address(0),
weth9: address(0),
seaportV1_5: address(0),
seaportV1_4: address(0),
openseaConduit: address(0),
nftxZap: address(0),
x2y2: address(0),
foundation: address(0),
sudoswap: address(0),
elementMarket: address(0),
nft20Zap: address(0),
cryptopunks: address(0),
looksRareV2: address(0),
routerRewardsDistributor: address(0),
looksRareRewardsDistributor: address(0),
looksRareToken: address(0),
v2Factory: address(0),
v3Factory: address(0),
pairInitCodeHash: bytes32(0),
poolInitCodeHash: bytes32(0)
});
router = new UniversalRouter(params);
testModule = new ExampleModule();
erc20 = new MockERC20();
erc1155 = new MockERC1155();
callbacks = new Callbacks();
}
event ExampleModuleEvent(string message);
function testCallModule() public {
uint256 bytecodeSize;
address theRouter = address(router);
assembly {
bytecodeSize := extcodesize(theRouter)
}
emit log_uint(bytecodeSize);
}
function testSweepToken() public {
bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.SWEEP)));
bytes[] memory inputs = new bytes[](1);
inputs[0] = abi.encode(address(erc20), RECIPIENT, AMOUNT);
erc20.mint(address(router), AMOUNT);
assertEq(erc20.balanceOf(RECIPIENT), 0);
router.execute(commands, inputs);
assertEq(erc20.balanceOf(RECIPIENT), AMOUNT);
}
function testSweepTokenInsufficientOutput() public {
bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.SWEEP)));
bytes[] memory inputs = new bytes[](1);
inputs[0] = abi.encode(address(erc20), RECIPIENT, AMOUNT + 1);
erc20.mint(address(router), AMOUNT);
assertEq(erc20.balanceOf(RECIPIENT), 0);
vm.expectRevert(Payments.InsufficientToken.selector);
router.execute(commands, inputs);
}
function testSweepETH() public {
bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.SWEEP)));
bytes[] memory inputs = new bytes[](1);
inputs[0] = abi.encode(Constants.ETH, RECIPIENT, AMOUNT);
assertEq(RECIPIENT.balance, 0);
router.execute{value: AMOUNT}(commands, inputs);
assertEq(RECIPIENT.balance, AMOUNT);
}
function testSweepETHInsufficientOutput() public {
bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.SWEEP)));
bytes[] memory inputs = new bytes[](1);
inputs[0] = abi.encode(Constants.ETH, RECIPIENT, AMOUNT + 1);
erc20.mint(address(router), AMOUNT);
vm.expectRevert(Payments.InsufficientETH.selector);
router.execute(commands, inputs);
}
function testSweepERC1155NotFullAmount() public {
bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.SWEEP_ERC1155)));
bytes[] memory inputs = new bytes[](1);
uint256 id = 0;
inputs[0] = abi.encode(address(erc1155), RECIPIENT, id, AMOUNT / 2);
erc1155.mint(address(router), id, AMOUNT);
assertEq(erc1155.balanceOf(RECIPIENT, id), 0);
router.execute(commands, inputs);
assertEq(erc1155.balanceOf(RECIPIENT, id), AMOUNT);
}
function testSweepERC1155() public {
bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.SWEEP_ERC1155)));
bytes[] memory inputs = new bytes[](1);
uint256 id = 0;
inputs[0] = abi.encode(address(erc1155), RECIPIENT, id, AMOUNT);
erc1155.mint(address(router), id, AMOUNT);
assertEq(erc1155.balanceOf(RECIPIENT, id), 0);
router.execute(commands, inputs);
assertEq(erc1155.balanceOf(RECIPIENT, id), AMOUNT);
}
function testSweepERC1155InsufficientOutput() public {
bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.SWEEP_ERC1155)));
bytes[] memory inputs = new bytes[](1);
uint256 id = 0;
inputs[0] = abi.encode(address(erc1155), RECIPIENT, id, AMOUNT + 1);
erc1155.mint(address(router), id, AMOUNT);
vm.expectRevert(Payments.InsufficientToken.selector);
router.execute(commands, inputs);
}
function testSupportsInterface() public {
bool supportsERC1155 = callbacks.supportsInterface(type(IERC1155Receiver).interfaceId);
bool supportsERC721 = callbacks.supportsInterface(type(IERC721Receiver).interfaceId);
bool supportsERC165 = callbacks.supportsInterface(type(IERC165).interfaceId);
assertEq(supportsERC1155, true);
assertEq(supportsERC721, true);
assertEq(supportsERC165, true);
}
} |
import React, { useState, useEffect } from "react";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import Accordion from "@mui/material/Accordion";
import AccordionDetails from "@mui/material/AccordionDetails";
import AccordionSummary from "@mui/material/AccordionSummary";
import Typography from "@mui/material/Typography";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemText from "@mui/material/ListItemText";
import ListItemAvatar from "@mui/material/ListItemAvatar";
import Avatar from "@mui/material/Avatar";
import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";
import SportsScoreIcon from "@mui/icons-material/SportsScore";
import BorderAllIcon from "@mui/icons-material/BorderAll";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import EditRoundedIcon from "@mui/icons-material/EditRounded";
import DeleteForeverRoundedIcon from "@mui/icons-material/DeleteForeverRounded";
import { connect } from "react-redux";
import GradeForm from "./GradeForm";
import WorkForm from "./WorkForm";
import { get_works_teacher, get_work_types } from "../../../helpers/workplace";
import { parse_date } from "../../../helpers/other";
import { Container, Box } from "@mui/material";
const Alert = React.forwardRef(function Alert(props, ref) {
return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});
function Homeworks({ profile, currentWorkplace }) {
const [expanded, setExpanded] = useState(false);
const [works, setWorks] = useState([]);
const [work_types, setWorkTypes] = useState({});
const [open, setOpen] = useState(false);
const [openWork, setOpenWork] = useState(false);
const [openToast, setOpenToast] = useState(false);
const [toastSeverity, setToastSeverity] = useState("success");
const [toastMessage, setToastMessage] = useState("success");
const [openWorkType, setOpenWorkType] = useState(""); // "CREATE", "EDIT", "DELETE"
const [work_id_form, setWorkIdForm] = useState(null);
useEffect(() => {
get_work_types().then((res_arr) => {
let result_types = {};
function setPlace(work_type) {
result_types[work_type.id] = work_type.name;
}
res_arr.forEach(setPlace);
setWorkTypes(result_types);
});
get_works_teacher(currentWorkplace).then(setWorks);
}, [currentWorkplace, openWork]);
const handleChange = (panel) => (event, isExpanded) => {
setExpanded(isExpanded ? panel : false);
};
const handleClickOpen = (work_id) => {
setWorkIdForm(work_id);
setOpen(true);
};
const handleClickOpenWork = (open_type, work_id = null) => {
setOpenWorkType(open_type);
work_id && setWorkIdForm(work_id);
setOpenWork(true);
};
const handleOpenToast = (reason) => {
switch (reason) {
case "MARK_OK":
setToastSeverity("success");
setToastMessage("Оцінка виставлена успішно!");
break;
case "WORK_OK":
setToastSeverity("success");
setToastMessage("Робота створена успішно!");
break;
case "WORK_EDIT":
setToastSeverity("success");
setToastMessage("Робота успішно оновлена!");
break;
case "WORK_DELETE":
setToastSeverity("warning");
setToastMessage("Робота успішно видалена!");
break;
case "ERROR":
setToastSeverity("error");
setToastMessage("Помилка запиту!");
break;
case "CLOSE_FORM":
setToastSeverity("info");
setToastMessage("Ви відмінили зміни у формі");
break;
}
setOpenToast(true);
};
const handleCloseToast = (event, reason) => {
if (reason === "clickaway") {
return;
}
setOpenToast(false);
};
return (
<Container>
{Array.isArray(works) ? (
works.map((work) => (
<Box key={work.id} sx={{ display: "flex", p: 1, width: "lg" }}>
<Accordion
sx={{ flex: 1.6 }}
expanded={expanded === work.id}
onChange={handleChange(work.id)}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls={`panel${work.id}bh-content`}
id={`panel${work.id}bh-header`}
>
<Typography sx={{ width: "33%", flexShrink: 0 }}>
{work.headline}
</Typography>
<Typography sx={{ color: "text.secondary", ml: "250px" }}>
{`Дедлайн: ${parse_date(work.deadline)}`}
</Typography>
</AccordionSummary>
<AccordionDetails>
<List
sx={{
width: "100%",
maxWidth: 360,
bgcolor: "background.paper",
}}
>
<ListItem>
<ListItemAvatar>
<Avatar>
<BorderAllIcon />
</Avatar>
</ListItemAvatar>
<ListItemText
primary={work_types[work.work_type_id]}
secondary={`Опис: ${work.description}`}
/>
</ListItem>
<ListItem>
<ListItemAvatar>
<Avatar>
<SportsScoreIcon />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="Створено -- Дедлайн"
secondary={`${parse_date(
work.creation_date
)} -- ${parse_date(work.deadline)}`}
/>
</ListItem>
<ListItem>
<Button
variant="text"
onClick={() => handleClickOpen(work.id)}
>
Виставити оцінку
</Button>
</ListItem>
</List>
</AccordionDetails>
</Accordion>
<Box sx={{ ml: 2, flex: 0.1 }}>
<IconButton
sx={{ mb: 0.5, color: "green", border: 1, borderRadius: "50%" }}
onClick={() => handleClickOpenWork("EDIT", work.id)}
>
<EditRoundedIcon />
</IconButton>
<IconButton
sx={{ mt: 0.5, color: "red", border: 1, borderRadius: "50%" }}
onClick={() => handleClickOpenWork("DELETE", work.id)}
>
<DeleteForeverRoundedIcon />
</IconButton>
</Box>
</Box>
))
) : (
<>{typeof works}</>
)}
<Button
sx={{ mt: 1, color: "green" }}
onClick={() => handleClickOpenWork("CREATE", null)}
>
Створити нову роботу
</Button>
<GradeForm
{...{ currentWorkplace, open, setOpen, work_id_form, handleOpenToast }}
/>
<WorkForm
{...{
currentWorkplace,
openWork,
setOpenWork,
openWorkType,
work_id_form,
handleOpenToast,
}}
/>
<Snackbar
open={openToast}
autoHideDuration={5000}
onClose={handleCloseToast}
>
<Alert
onClose={handleCloseToast}
severity={toastSeverity}
sx={{ width: "100%" }}
>
{toastMessage}
</Alert>
</Snackbar>
</Container>
);
}
// secondary={`Оцінки: ${work.marks[0].comment}`}
// primary={parse_date(work.marks[0].creation_date)}
// secondary={`Оцінки: ${work.marks[0].comment}`}
// work.marks.length ? "" : ""}
const mapStateToProps = (rootState) => ({
profile: rootState?.profile,
currentWorkplace: rootState?.currentWorkplace,
});
const mapDispatchToProps = {};
export default connect(mapStateToProps, mapDispatchToProps)(Homeworks); |
import React from "react";
import PropTypes from "prop-types";
import style from "./FeedbackOptions.module.css";
const FeedbackOptions = ({ options, onLeaveFeedback }) => {
return (
<>
{options.map((buttonList) => (
<button
type="button"
onClick={onLeaveFeedback}
key={buttonList}
name={buttonList}
className={style.button}
>
{buttonList}{" "}
</button>
))}
</>
);
};
FeedbackOptions.propeTypes = {
options: PropTypes.arrayOf(PropTypes.string).isRequired,
onLeaveFeedback: PropTypes.func.isRequired,
};
export default FeedbackOptions; |
// Create Twinkling Stars
function createTwinklingStars() {
const starsContainer = document.querySelector('.stars');
const numberOfStars = window.innerWidth * window.innerHeight / 8000;
for (let i = 0; i < numberOfStars; i++) {
const star = document.createElement('div');
const size = Math.random() * 3 + 1;
const positionX = Math.random() * 100;
const positionY = Math.random() * 100;
const brightness = Math.random() * 0.5 + 0.5;
const zIndex = Math.floor(Math.random() * 5);
star.classList.add('star');
star.style.width = `${size}px`;
star.style.height = `${size}px`;
star.style.left = `${positionX}vw`;
star.style.top = `${positionY}vh`;
star.style.opacity = brightness;
star.style.zIndex = zIndex;
star.style.animationDuration = `${0.5 + Math.random()}s`;
star.style.animationDelay = `${Math.random()}s`;
starsContainer.appendChild(star);
}
}
createTwinklingStars();
// Twinkling Stars Animation
function animateStars() {
if (!animationsPaused) {
document.querySelectorAll('.star').forEach(star => {
const opacity = parseFloat(star.style.opacity);
const delta = Math.random() * 0.02;
star.style.opacity = opacity + (Math.random() > 0.5 ? delta : -delta);
});
requestAnimationFrame(animateStars);
}
}
// Create Rotating Planets
function createRotatingPlanets() {
const planetsContainer = document.querySelector('.planets');
const planets = ['path-to-planet1.png', 'path-to-planet2.png', 'path-to-planet3.png'];
planets.forEach((planetSrc, index) => {
const planet = document.createElement('img');
planet.src = planetSrc;
planet.classList.add('planet');
planet.alt = "Planet Image";
planet.setAttribute('role', 'img');
planet.setAttribute('aria-label', 'Planet');
const size = (Math.random() * 10) + 5;
const positionX = Math.random() * 80;
const positionY = Math.random() * 80;
planet.style.width = `${size}vw`;
planet.style.left = `${positionX}vw`;
planet.style.top = `${positionY}vh`;
planet.style.zIndex = Math.floor(Math.random() * 10);
planet.style.opacity = Math.random() * (1 - 0.5) + 0.5;
const rotationSpeed = Math.random() * 10 + 5;
const rotationDirection = Math.random() > 0.5 ? 1 : -1;
planet.style.animation = `rotation ${rotationSpeed}s infinite linear ${rotationDirection}`;
planetsContainer.appendChild(planet);
});
}
createRotatingPlanets();
// Rotating Planets Animation
function animatePlanets() {
if (!animationsPaused) {
document.querySelectorAll('.planet').forEach(planet => {
const rotation = parseFloat(planet.dataset.rotation || 0);
const delta = 0.5;
planet.style.transform = `rotate(${rotation + delta}deg)`;
planet.dataset.rotation = rotation + delta;
});
requestAnimationFrame(animatePlanets);
}
}
// Drifting Nebula Clouds Animation
function animateNebulaClouds() {
if (!animationsPaused) {
document.querySelectorAll('.nebula-cloud').forEach(nebula => {
const positionX = parseFloat(nebula.style.left);
const delta = 0.2;
nebula.style.left = `${positionX + delta}vw`;
});
requestAnimationFrame(animateNebulaClouds);
}
}
// Portal/Wormhole Animation
function createPortalAnimation() {
// Logic for swirling patterns and light streaks
// Use Three.js functionalities to create the desired effects
}
// Animation Control
const animationControlBtn = document.getElementById('animationControl');
animationControlBtn.addEventListener('click', () => {
if (animationsPaused) {
animateStars();
animatePlanets();
animateNebulaClouds();
} else {
// pause animations
}
animationsPaused = !animationsPaused;
}); |
<?php
// OOP 정적 METHOD, 정적 PROPERTY STATIC
class Car{
private static $count = 0;
private static $carList = [];
private $name;
function __construct($name){
$this->name = $name;
self::$count = self::$count + 1;
array_push(self::$carList, $name);
}
function message(){
echo "<p> {$this->name}가 생성되었습니다.</p>";
echo "<p>생산번호 :". self::$count. "</p>";
}
static function getCarList(){
return self::$carList;
}
}
$p1 = new Car(name: 'volvo');
$p1->message();
$p2 = new Car(name: 'audi');
$p2->message();
$p3 = new Car(name: 'ferrari');
$p3->message();
$a = implode(',', Car::getCarList());
echo "<p>".$a."</p>";
?> |
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const ColorHash = require('color-hash');
require('dotenv').config();
const webSocket = require('./socket');
const indexRouter = require('./routes');
const connect = require('./schemas');
const app = express();
connect();
const sessionMiddleware = session({
resave: false,
saveUninitialized: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true,
secure: false,
},
})
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.set('port', process.env.PORT || 8005);
app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/gif', express.static(path.join(__dirname, 'uploads')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(sessionMiddleware);
app.use(flash());
app.use((req, res, next) => { // 익명의 접속자들에게 컬러값을 준다.
if (!req.session.color) {
const colorHash = new ColorHash();
req.session.color = colorHash.hex(req.sessionID);
}
next();
});
app.use('/', indexRouter);
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res) => {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'develpopment' ? err : {};
res.status(err.status || 500);
res.render('error');
});
const server = app.listen(app.get('port'), () => {
console.log(app.get('port'), '번 포트에서 대기중');
});
webSocket(server, app, sessionMiddleware);
// express 서버와 웹소켓을 연결
// HTTP와 WS는 포트를 공유하기 때문에 따로 포트를 연결할 필요는 없다. |
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Bonus;
use App\Entity\Bonus\BonusFactory;
use App\Repository\Bonus\BonusRepository;
use App\Tests\Controller\Traits\ProcessResponseTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DeleteBonusControllerTest extends WebTestCase
{
use ProcessResponseTrait;
public function testSuccessDelete(): void
{
$client = static::createClient();
$bonusId = static::getContainer()
->get(BonusRepository::class)
->findOneByName(BonusFactory::TEST_BONUS_FOR_DELETE_NAME)
?->getId();
$client->request(
'DELETE',
'/api/bonus/'.$bonusId,
);
$content = $this->processSuccessResponse($client->getResponse()->getContent());
$this->assertSame("Bonus $bonusId was deleted successfully", $content);
}
public function testInvalidDelete(): void
{
$client = static::createClient();
$clientId = 9999999;
$client->request(
'DELETE',
'/api/bonus/'.$clientId,
);
$content = $this->processErrorResponse($client->getResponse()->getContent());
$this->assertSame("Bonus $clientId not found", $content);
}
} |
import React, { useState } from "react";
import { View, Text, StyleSheet, TextInput, FlatList, Image, TouchableOpacity } from 'react-native'
import { useNavigation } from "@react-navigation/native";
import { Foundation } from '@expo/vector-icons';
import ShowScreen from "../Screen/ShowScreen";
const Resultlist = ({ title, result }) => {
const navigation = useNavigation();
if(!result.length){
return null;
}
return (
<View>
<Text style={style.title}>{title}</Text>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={result}
keyExtractor={(item) => item.id}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={()=>navigation.navigate("Show",{id:item.id})}>
<View>
<Image style={style.img} source={{ uri: item.image_url }} />
<Text style={style.name}>{item.name}</Text>
<Text>
<Foundation name="star" size={20} color="green" />
{item.rating} ({item.review_count}reviews)
</Text>
</View>
</TouchableOpacity>
);
}}
/>
</View>
);
};
const style = StyleSheet.create({
title: {
fontSize: 18,
fontWeight: "bold"
},
img: {
width: 230,
height: 120,
borderRadius: 5,
marginRight: 10,
},
name: {
fontWeight: "bold"
}
});
export default Resultlist; |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('menu_items', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->float('price')->default(0);
$table->boolean('is_available')->default(true);
$table->foreignId('restaurant_id')
->constrained('restaurants','id')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('menu_items');
}
}; |
<template>
<div
class="h-screen w-screen flex items-center justify-center text-center overflow-hidden"
>
<div>
<div class="loader">
<div v-for="n in 5" :key="n" class="circle" />
</div>
<h1 class="mt-32 text-2xl font-medium letter tracking-wide">
Restarting
</h1>
</div>
</div>
</template>
<script lang="ts">
export default {
name: "PageRestarting",
};
</script>
<script lang="ts" setup>
import { definePageMeta } from "#imports";
import { promiseTimeout } from "@vueuse/core";
definePageMeta({
layout: false,
});
const router = useRouter();
onMounted(async () => {
await promiseTimeout(5000);
await router.push("/");
});
</script>
<style lang="scss" scoped>
.loader {
@apply absolute top-[50%] left-[50%] w-[75px] h-[75px] m-auto;
transform: translateX(-50%) translateY(-50%);
.circle {
@apply absolute w-[75px] h-[75px] opacity-0;
transform: rotate(225deg);
animation-iteration-count: infinite;
animation-name: orbit;
animation-duration: 5.5s;
@apply duration-[5.5s];
&:after {
content: "";
@apply absolute w-[6px] h-[6px] rounded-[5px] bg-white;
}
&:nth-child(2) {
animation-delay: 240ms;
}
&:nth-child(3) {
animation-delay: 480ms;
}
&:nth-child(4) {
animation-delay: 720ms;
}
&:nth-child(5) {
animation-delay: 960ms;
}
}
}
@keyframes orbit {
0% {
@apply opacity-100;
transform: rotate(225deg);
animation-timing-function: ease-out;
}
7% {
transform: rotate(345deg);
animation-timing-function: linear;
}
30% {
transform: rotate(455deg);
animation-timing-function: ease-in-out;
}
39% {
transform: rotate(690deg);
animation-timing-function: linear;
}
70% {
@apply opacity-100;
transform: rotate(815deg);
animation-timing-function: ease-out;
}
75% {
transform: rotate(945deg);
animation-timing-function: ease-out;
}
76% {
@apply opacity-0;
transform: rotate(945deg);
}
100% {
@apply opacity-0;
transform: rotate(945deg);
}
}
</style> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.