text
stringlengths 184
4.48M
|
---|
import pygame as pg
from pygame import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
import random
from rectangle import RectangleMesh
from handle_json import write, clear_json
class App:
def __init__(self):
# initialize pygame for GUI
pg.init()
self.display = (512,512)
self.screen = pg.display.set_mode(self.display, pg.OPENGL|pg.DOUBLEBUF) # tell pygame we run OPENGL & DOUBLEBUFFERING, one frame vis & one drawing
pg.display.set_caption("Wireframe generator")
# activation variables
self.axes = 0
self.screenshot = 1
clear_json()
# initialize OpenGL
glClearColor(0,0,0,1)
glMatrixMode(GL_PROJECTION) # activate projection matrix
gluPerspective(45, self.display[0]/self.display[1], 0.1, 50)
self.projectionmatrix = glGetDoublev(GL_PROJECTION_MATRIX)
# draw wired rectangle
self.rectangle = RectangleMesh(random.uniform(0.1,5), random.uniform(0.1,5), random.uniform(0.1,5), [0,0,0], [0,0,-15])
self.rectangle.draw_wired_rect()
self.mainLoop()
def mainLoop(self):
rect_name = 1
img_number = 1 # counts the rectangle that is been shown
img_shot = 1 # counts how many screenshots were taken
running = True
while(running):
# Check for events
for event in pg.event.get():
if (event.type == pg.QUIT):
running = False
if (event.type == KEYDOWN) and (event.key == K_s):
# enable screenshots
self.screenshot = not self.screenshot
if (event.type == KEYDOWN) and (event.key == K_a):
# draw axes
self.axes = not self.axes
if (event.type == KEYDOWN) and (event.key == K_RIGHT):
# random position of rectangle
self.rectangle.set_rotation(random.uniform(0,360), random.uniform(0,360), random.uniform(0,360))
self.rectangle.set_translation(random.uniform(-5,5), random.uniform(-5,5), random.uniform(-10,-20))
self.rectangle.draw_wired_rect()
pg.time.wait(60)
print(f"random rotation: {self.rectangle.eulers}")
print(f"random translation: {self.rectangle.position}")
# take screenshot && write rectangle data to CSV file
if (self.screenshot):
# calculate annotation
wc, pc, center = self.get_annotations(self.rectangle.modelview, self.projectionmatrix, glGetIntegerv(GL_VIEWPORT))
# check if rectangle valid
valid = self.object_on_screen(pc)
# write to json
write(rect_name, img_shot, self.rectangle.get_norm_dim(), wc, pc, center, valid)
if (rect_name == img_number):
self.save_image(rect_name, img_shot)
img_shot += 1
else:
img_number += 1
rect_name = img_number
img_shot = 1
self.save_image(rect_name, img_shot)
img_shot += 1
if (event.type == KEYDOWN) and (event.key == K_RETURN):
print("delete rectangle...")
del self.rectangle
# new size of rectangle
self.rectangle = RectangleMesh(random.uniform(0.1,5), random.uniform(0.1,5), random.uniform(0.1,5), [0,0,0], [0,0,-15])
print("created rectangle: ", self.rectangle.width, self.rectangle.height, self.rectangle.depth)
# rectangle name count
rect_name += 1
# --- Drawing the scene --- #
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
self.rectangle.draw_wired_rect()
if (self.axes):
self.draw_axes()
pg.display.flip()
pg.time.wait(60)
self.quit()
def quit(self):
pg.quit()
def save_image(self, rect_name, img_shot):
print("taking screenshot...")
pixels = glReadPixels(0, 0, self.display[0], self.display[1], GL_RGB, GL_UNSIGNED_BYTE)
image = pg.image.frombuffer(pixels, (self.display[0], self.display[1]), 'RGB') # read pixels from the OpenGL buffer
#image = pg.transform.flip(image, False, True) # flip
name = "wireframes\\img" + str(rect_name) + "_" + str(img_shot) + ".png"
pg.image.save(image, name) # It then converts those pixels into a Pygame surface and saves it using pygame.image.save()
def draw_axes(self):
glPushMatrix()
glTranslatef(0,0,-15)
# X axis (red)
glBegin(GL_LINES)
glColor3f(1, 0, 0)
glVertex3f(0, 0, 0)
glVertex3f(5, 0, 0)
glEnd()
# Y axis (green)
glBegin(GL_LINES)
glColor3f(0, 1, 0)
glVertex3f(0, 0, 0)
glVertex3f(0, 5, 0)
glEnd()
# Z axis (blue)
glBegin(GL_LINES)
glColor3f(0, 0, 1)
glVertex3f(0, 0, 0)
glVertex3f(0, 0, 5)
glEnd()
glPopMatrix()
def get_annotations(self, model_view, projection, viewport):
# Calculate world and pixel cords of vertices rectangle
world_coordinates = []
pixel_coordinates = []
center = []
for vertex in self.rectangle.vertices:
x_screen, y_screen, z = gluProject(vertex[0], vertex[1], vertex[2], model_view, projection, viewport)
pixel_coordinates.append((int(x_screen),int(y_screen)))
x_world, y_world, z_world = gluUnProject( x_screen, y_screen, 0, model_view, projection, viewport)
world_coordinates.append((x_world, y_world, z_world))
print("pixel coordinates: ",pixel_coordinates)
print("world coordinates: ",world_coordinates)
# Calculate center
x_screen, y_screen, z = gluProject(0, 0, 0, model_view, projection, viewport)
x_world, y_world, z_world = gluUnProject( x_screen, y_screen, 0, model_view, projection, viewport)
center.append((x_world, y_world, z_world))
center.append((int(x_screen), int(y_screen)))
return world_coordinates, pixel_coordinates, center
def object_on_screen(self, projection_coordinates):
for i in projection_coordinates:
if (i[0] not in range(0,self.display[0]+1) or i[1] not in range(0,self.display[1]+1)):
return "false"
else:
continue
return "true"
if __name__ == "__main__":
myApp = App()
|
//
// NSObject+LifecycleMonitor.swift
//
//
// Created by Maxim Aliev on 01.05.2024.
//
import UIKit
extension NSObject {
private static var _lifecycleMonitorKey: UInt8 = 21
private static let _monitoringDepth = 5
var monitor: ObjectLifecycleMonitor? {
get { getAssociatedObject(self, key: &NSObject._lifecycleMonitorKey) }
set { setAssociatedObject(self, key: &NSObject._lifecycleMonitorKey, value: newValue) }
}
var isActive: Bool { getIsActive() }
@discardableResult
func activateLifecycleMonitor() -> Bool {
guard monitor == nil, isSystemClass(classForCoder) == false else {
return false
}
if let view = self as? UIView, view.superview == nil {
return false
} else if
let viewController = self as? UIViewController,
viewController.navigationController == nil && viewController.presentingViewController == nil
{
return false
}
monitor = ObjectLifecycleMonitor(object: self)
return true
}
func monitorAllRetainVariables(level: Int = .zero) {
guard level < NSObject._monitoringDepth else {
return
}
var propertyNames: [String] = []
if isSystemClass(classForCoder) == false {
propertyNames.append(contentsOf: getAllPropertyNames(for: classForCoder))
}
if let superclass, isSystemClass(superclass) {
propertyNames.append(contentsOf: getAllPropertyNames(for: superclass))
}
if let supersuperclass = superclass?.superclass(), isSystemClass(supersuperclass) {
propertyNames.append(contentsOf: getAllPropertyNames(for: supersuperclass))
}
for propertyName in propertyNames {
guard propertyName != "tabBarObservedScrollView", let object = value(forKey: propertyName) as? NSObject else {
continue
}
let isActivated = object.activateLifecycleMonitor()
if isActivated {
object.monitor?.host = self
object.monitorAllRetainVariables(level: level + 1)
}
}
}
private func getAllPropertyNames(for cls: AnyClass) -> [String] {
let count = UnsafeMutablePointer<UInt32>.allocate(capacity: .zero)
let properties = class_copyPropertyList(cls, count)
defer { free(properties) }
if Int(count[.zero]) == .zero {
return []
}
var result: [String] = []
for i in .zero..<Int(count[.zero]) {
guard let property = properties?[i] else {
continue
}
let propertyWrapper = PropertyWrapper(property: property)
guard let type = propertyWrapper.type, propertyWrapper.isStrong else {
continue
}
result.append(propertyWrapper.name)
}
return result
}
private func getIsActive() -> Bool {
if isKind(of: UIViewController.classForCoder()) {
if let viewController = self as? UIViewController {
return isActive(viewController)
}
} else if isKind(of: UIView.classForCoder()) {
if let view = self as? UIView {
return isActive(view)
}
}
return isActive(self)
}
private func isActive(_ controller: UIViewController) -> Bool {
guard
controller.view.window != nil ||
controller.navigationController != nil ||
controller.presentingViewController != nil
else {
return false
}
return true
}
private func isActive(_ view: UIView) -> Bool {
var view = view
while let superview = view.superview {
view = superview
}
if view is UIWindow {
return true
}
if view.monitor?.responder == nil {
var responder = view.next
while let nextResponder = responder?.next {
if nextResponder.isKind(of: UIViewController.classForCoder()) {
responder = nextResponder
break
}
responder = nextResponder
}
view.monitor?.responder = responder
}
return view.monitor?.responder?.isKind(of: UIViewController.classForCoder()) ?? false
}
private func isActive(_ object: NSObject) -> Bool {
return object.monitor?.host != nil
}
}
|
import React from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { signOutUserStart } from './../../redux/User/user.actions';
import './styles.scss';
import Logo from './../../assets/logo.png';
const mapState = ({ user }) => ({
currentUser: user.currentUser
});
function Header(props) {
const dispatch = useDispatch();
const { currentUser } = useSelector(mapState);
const signOut = () => {
dispatch(signOutUserStart());
};
return (
<header className="header">
<div className="wrap">
<div className="logo">
<Link to="/">
<img src={Logo} alt="Pouch Logo" />
</Link>
</div>
<h1>The General Store</h1>
<div className="callToActions">
{currentUser && (
<ul>
<li>
<Link to="/dashboard">
My Account
</Link>
</li>
<li>
<span onClick={() => signOut()}>
LogOut
</span>
</li>
</ul>
)}
{!currentUser && (
<ul>
<li>
<Link to="/registration">
Register
</Link>
</li>
<li>
<Link to="/login">
Login
</Link>
</li>
</ul>
)}
</div>
</div>
</header>
)
}
Header.defaultProps = {
currentUser: null
}
export default Header;
|
#ifndef AFORM_HPP
# define AFORM_HPP
# include <iostream>
# include <string>
#include "Bureaucrat.hpp"
// need to use forward declaration to solve the circular dependency issue.
class Bureaucrat;
class AForm
{
public:
// Constructors
AForm();
AForm(const AForm ©);
AForm(const std::string name, const int requiredGrade, const int gradeExecute);
// Destructor
virtual ~AForm();
// Operators
AForm & operator=(const AForm &assign);
// Getters / Setters
const std::string getName() const;
bool getSign() const;
int getRequiredGrade() const;
int getGradeExecute() const;
// Exceptions
class GradeTooHighException : public std::exception {
public:
virtual const char* what() const throw();
};
class GradeTooLowException : public std::exception {
public:
virtual const char* what() const throw();
};
class FormNotSigned : public std::exception {
public:
virtual const char* what() const throw();
};
// Methods
void beSigned(Bureaucrat &bureaucrat);
void checkGrade(int grade);
virtual void execute(Bureaucrat const & executor) const = 0;
void checkExecute(Bureaucrat const & executor) const;
private:
const std::string _name;
bool _sign;
const int _requiredGrade;
const int _gradeExecute;
};
// Stream operators
std::ostream & operator<<(std::ostream &stream, const AForm &object);
#endif
|
//Assignment 1
#include <stdio.h>
int main()
{
int a,b;
printf("Enter the number: ");
scanf("%d %d",&a, &b);
// Increment and Decrement operator
printf("Pre Increment of a is %d\n", ++a); //Pre Increment of a
printf("a is %d\n", a);
printf("Post Increment of a is %d\n", a++); //Post Increment of a
printf("a is %d\n", a);
printf("Pre Decrement of a is %d\n Post Decrement of a is %d\n", --a, a--); // Right to left associative
printf("A is %d\n",a);
// Arithmetic operator
printf("Additon of a and b is %d\n", a+b); //Additon
printf("Subtraction of a and b is %d\n", a-b); //Subtraction
printf("Multiplication of a and b is %d\n", a*b); // Multiplication
printf("Division of a and b is %d\n", a/b); // Division
printf("Modulo Division of a and b is %d\n", a%b); // Modulo Division
//Logical operator
printf("a && b is %d\n", a&&b); //Logical AND
printf("a || b is %d\n", a||b); // Logical OR
printf("!a is %d\n", !a); // Logical NOT
//Bitwise operator
printf(" a&b is %x\n", a&b); //Bitwise AND
printf("a|b is %x\n", a|b); //Bitwise OR
printf("a^b is %x\n", a^b); //Bitwise XOR
printf("~a is %x\n", ~a); //Bitwise Compliment
printf("a<<b is %x\n", a<<b); // Left Shift
printf("a>>b is %x\n", a>>b); // Right Shift
//Comparison operator
printf("a is greater than b: %d\n", a>b); //greater than
printf("a is greater than or equal to b: %d\n", a>=b);//greater than or equal
printf("a is less than b: %d\n", a<b);// less than
printf("a is less than or equal to b: %d\n", a<=b);// less than or equal
printf("a is equal to b: %d\n", a==b);// equal
printf("a is not equal to b: %d\n", a!=b);// not equal
//ternary operator
int x;
x=a>b?a:b;
printf("%d\n",x);
return 0;
}
|
<?php
namespace App\Policies;
use App\Models\Clinic;
use App\Models\Admin;
use App\Models\Role;
use Illuminate\Auth\Access\HandlesAuthorization;
class ClinicPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*
* @param \App\Models\Admin $admin
* @return \Illuminate\Auth\Access\Response|bool
*/
public function viewAny(Admin $admin)
{
$array = Role::where('id', auth()->user()->role_id)->first()->modules;
if(in_array(9, $array) || in_array(2, $array)){
return true;
}
return false;
}
/**
* Determine whether the user can view the model.
*
* @param \App\Models\Admin $admin
* @param \App\Models\Clinic $clinic
* @return \Illuminate\Auth\Access\Response|bool
*/
public function view(Admin $admin, Clinic $clinic)
{
$array = Role::where('id', auth()->user()->role_id)->first()->modules;
if(in_array(9, $array) || in_array(2, $array)){
return true;
}
return false;
}
/**
* Determine whether the user can create models.
*
* @param \App\Models\Admin $admin
* @return \Illuminate\Auth\Access\Response|bool
*/
public function create(Admin $admin)
{
$array = Role::where('id', auth()->user()->role_id)->first()->modules;
if(in_array(9, $array) || in_array(2, $array)){
return true;
}
return false;
}
/**
* Determine whether the user can update the model.
*
* @param \App\Models\Admin $admin
* @param \App\Models\Clinic $clinic
* @return \Illuminate\Auth\Access\Response|bool
*/
public function update(Admin $admin, Clinic $clinic)
{
$array = Role::where('id', auth()->user()->role_id)->first()->modules;
if(in_array(9, $array) || in_array(2, $array)){
return true;
}
return false;
}
/**
* Determine whether the user can delete the model.
*
* @param \App\Models\Admin $admin
* @param \App\Models\Clinic $clinic
* @return \Illuminate\Auth\Access\Response|bool
*/
public function delete(Admin $admin, Clinic $clinic)
{
$array = Role::where('id', auth()->user()->role_id)->first()->modules;
if(in_array(9, $array) || in_array(2, $array)){
return true;
}
return false;
}
/**
* Determine whether the user can restore the model.
*
* @param \App\Models\Admin $admin
* @param \App\Models\Clinic $clinic
* @return \Illuminate\Auth\Access\Response|bool
*/
public function restore(Admin $admin, Clinic $clinic)
{
$array = Role::where('id', auth()->user()->role_id)->first()->modules;
if(in_array(9, $array) || in_array(2, $array)){
return true;
}
return false;
}
/**
* Determine whether the user can permanently delete the model.
*
* @param \App\Models\Admin $admin
* @param \App\Models\Clinic $clinic
* @return \Illuminate\Auth\Access\Response|bool
*/
public function forceDelete(Admin $admin, Clinic $clinic)
{
$array = Role::where('id', auth()->user()->role_id)->first()->modules;
if(in_array(9, $array) || in_array(2, $array)){
return true;
}
return false;
}
}
|
import 'package:flutter/material.dart';
import 'package:todoapp_practice/util/my_button.dart';
class DialogBox extends StatelessWidget {
final controller;
final bool isEdit;
VoidCallback onSaved;
VoidCallback onCancel;
DialogBox(
{super.key,
required this.controller,
required this.onSaved,
required this.onCancel,
required this.isEdit});
@override
Widget build(BuildContext context) {
return AlertDialog(
backgroundColor: Colors.deepPurple[200],
content: Container(
height: 170,
width: double.maxFinite,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextField(
controller: controller,
decoration:
const InputDecoration(hintText: "Type your task name"),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// save button
MyButton(
text: isEdit ? "Edit" : "Save",
onPressed: onSaved,
color: isEdit ? Colors.orange : Colors.green),
// cancel button
MyButton(text: "Cancel", onPressed: onCancel, color: Colors.red)
],
)
],
),
),
);
}
}
|
<template>
<div>
<app-loading></app-loading>
<div v-if="!loading">
<v-container grid-list-lg>
<v-layout row wrap>
<v-flex
xs12
sm6
md4
v-for="product in products"
:key="product.id"
>
<v-card
class="mx-auto"
max-width="344"
>
<v-img
src="https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80"
height="200px"
></v-img>
<v-card-title>
{{ product.title }}
</v-card-title>
<v-card-text>
Price: <strong>{{ product.price }}</strong>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<app-add-to-cart-button :productId="product.id"></app-add-to-cart-button>
<v-btn
text
:to="{name: 'productShow', params: {'productId': product.id}}"
>
Open
</v-btn>
</v-card-actions>
</v-card>
</v-flex>
</v-layout>
<app-pagination :fetchMethod="'fetchProducts'"></app-pagination>
</v-container>
</div>
</div>
</template>
<script>
export default {
name: 'ProductList',
computed: {
products () {
return this.$store.getters.products
},
loading () {
return this.$store.getters.loading
}
},
created () {
this.$store.dispatch('fetchProducts')
.catch(() => {})
}
}
</script>
<style scoped>
</style>
|
#+ setup, echo=FALSE
library(tidytext)
library(tidyverse)
library(stringr)
library(knitr)
library(wordcloud)
library(ngram)
#' English Repository Files
blogs_file <- "../data/en_US/en_US.blogs.txt"
news_file <- "../data/en_US/en_US.news.txt"
twitter_file <- "../data/en_US/en_US.twitter.txt"
#' Read the data files
blogs <- readLines(blogs_file, skipNul = TRUE)
news <- readLines(news_file, skipNul = TRUE)
twitter <- readLines(twitter_file, skipNul = TRUE)
set.seed(1001)
sample_pct <- 0.05
blogs_sample <- blogs %>%
sample_n(., nrow(blogs)*sample_pct)
news_sample <- news %>%
sample_n(., nrow(news)*sample_pct)
twitter_sample <- twitter %>%
sample_n(., nrow(twitter)*sample_pct)
# combine text vectors together, create corpus ----
single_vector <- c(blogs_sample, news_sample, twitter_sample)
corpus <- VCorpus(VectorSource(single_vector))
data("stop_words")
swear_words <- read_delim("../data/en_US/en_US.swearWords.csv", delim = "\n", col_names = FALSE)
swear_words <- unnest_tokens(swear_words, word, X1)
# clean corpus function ----
clean.corpus <- function(corpus) {
require(tm)
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, removeNumbers)
# corpus <- tm_map(corpus, content_transformer(gsub),
# pattern = "shit|piss|fuck|cunt|cocksucker|motherfucker|tits",
# replacement = "")
corpus <- tm_map(corpus, content_transformer(gsub),
pattern = swear_words,
replacement = "")
corpus <- tm_map(corpus, PlainTextDocument)
}
# process corpus ----
corpus <- clean.corpus(corpus)
# create a data frame from the corpus ----
text_df <- tidy(corpus)
# tokenize and get unigrams ----
text_unigrams <- text_df %>%
select(text) %>%
unnest_tokens(unigram, text) %>%
count(unigram, sort = TRUE)
# plot unigrams ----
ggplot(text_unigrams[1:10,], aes(x = reorder(unigram,-n), y = n)) + geom_col(fill = "purple") + labs(x = "unigram", y = "frequency", title = "top 10 unigrams")
##-----
# tokenize by bigram ----
text_bigrams <- text_df %>%
select(text) %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
count(bigram, sort = TRUE)
# plot bigrams ----
ggplot(text_bigrams[1:10, ], aes(x = reorder(bigram, -n), y = n)) + geom_col(fill = "blue") + labs(x = "bigram", y = "frequency", title = "top 10 bigrams")
# tokenize by trigram ----
text_trigrams <- text_df %>%
select(text) %>%
unnest_tokens(trigram, text, token = "ngrams", n = 3) %>%
count(trigram, sort = TRUE)
# plot trigram ----
ggplot(text_trigrams[1:10, ], aes(x = reorder(trigram, -n), y = n)) + geom_col(fill = "orange") + labs(x = "trigram", y = "frequency", title = "top 10 trigrams")
# tokenize by trigram ----
text_quadgrams <- text_df %>%
select(text) %>%
unnest_tokens(quadgram, text, token = "ngrams", n = 4) %>%
count(quadgram, sort = TRUE)
# plot trigram ----
ggplot(text_quadgrams[1:10, ], aes(x = reorder(quadgram, -n), y = n)) + geom_col(fill = "red") + labs(x = "trigram", y = "frequency", title = "top 10 quadgrams") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
|
use utf8_slice;
fn slice_str_test() {
let s = "The 🚀 goes to the 🌑!";
let rocket = utf8_slice::slice(s, 4, 5);
// Will equal "🚀"
}
fn main() {
let my_name = "Pascal";
greet(my_name);
let s = String::from("hello world");
let word = first_word(&s); // 切片操作
// s.clear(); // let mut s 然后操作可变,就会报错! error!
println!("the first word is: {}", word); //
// 通过 \ + 字符的十六进制表示,转义输出一个字符
let byte_escape = "I'm writing \x52\x75\x73\x74!";
println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);
// \u 可以输出一个 unicode 字符
let unicode_codepoint = "\u{211D}";
let character_name = "\"DOUBLE-STRUCK CAPITAL R\"";
println!(
"Unicode character {} (U+211D) is called {}",
unicode_codepoint, character_name
);
// 换行了也会保持之前的字符串格式
// 使用\忽略换行符
let long_string = "String literals
can span multiple lines.
The linebreak and indentation here ->\
<- can be escaped too!";
println!("{}", long_string);
println!("{}", "hello \\x52\\x75\\x73\\x74");
slice_str_test();
}
fn greet(name: &str) {
println!("Hello, {}!", name);
/* 遍历 Unicode 的方式使用 chars方法 */
for c in "中国人".chars() {
println!("{}", c);
}
/* 遍历子节 */
for b in "中国人".bytes() {
println!("{}", b);
}
}
fn first_word(s: &String) -> &str {
&s[..1]
}
|
import 'package:channel_sender_client/src/retry_timer.dart';
import 'package:logging/logging.dart';
import 'package:test/test.dart';
void main() {
group('Retry Timer tests', () {
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((record) {
print('${record.level.name}: ${record.time}: ${record.message}');
});
test('Should retry with exponential delay', () async {
var doSomething = () async {
Logger.root.info('Dummy function called');
throw ArgumentError('Some error');
};
var retyTimer = RetryTimer(doSomething);
retyTimer.schedule();
await Future.delayed(const Duration(milliseconds: 2000));
retyTimer.schedule();
await Future.delayed(const Duration(milliseconds: 3000));
retyTimer.schedule();
await Future.delayed(const Duration(milliseconds: 4000));
});
test('Should retry with exponential delay, custom params', () async {
var doSomething = () async {
Logger.root.info('Dummy function called');
throw ArgumentError('Some error');
};
var customJitter = (int num) {
return 1;
};
var retyTimer = RetryTimer(doSomething,
initialWait: 100, maxWait: 300, jitterFn: customJitter);
retyTimer.schedule();
await Future.delayed(const Duration(milliseconds: 500));
retyTimer.schedule();
await Future.delayed(const Duration(milliseconds: 500));
retyTimer.schedule();
await Future.delayed(const Duration(milliseconds: 500));
});
test('Should cancel retry timer', () async {
var doSomething = () async {
Logger.root.info('Dummy function called');
throw ArgumentError('Some error');
};
var retyTimer = RetryTimer(doSomething);
retyTimer.schedule();
await Future.delayed(const Duration(milliseconds: 500));
retyTimer.reset();
});
});
}
|
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
import Foundation
#endif
public typealias ReconValue = Value
public enum Value: ArrayLiteralConvertible, StringLiteralConvertible, FloatLiteralConvertible, IntegerLiteralConvertible, BooleanLiteralConvertible, CustomStringConvertible, Comparable, Hashable {
case Record(ReconRecord)
case Text(String)
case Data(ReconData)
case Number(Double)
case Extant
case Absent
public init(arrayLiteral items: Item...) {
self = Record(ReconRecord(items))
}
public init(stringLiteral value: String) {
self = Text(value)
}
public init(extendedGraphemeClusterLiteral value: Character) {
self = Text(String(value))
}
public init(unicodeScalarLiteral value: UnicodeScalar) {
self = Text(String(value))
}
public init(floatLiteral value: Double) {
self = Number(value)
}
public init(integerLiteral value: Int) {
self = Number(Double(value))
}
public init(booleanLiteral value: Bool) {
self = value ? Value.True : Value.False
}
public init(_ items: [Item]) {
self = Record(ReconRecord(items))
}
public init(_ items: Item...) {
self = Record(ReconRecord(items))
}
public init(_ value: ReconRecord) {
self = Record(value)
}
public init(_ value: String) {
self = Text(value)
}
public init(_ value: ReconData) {
self = Data(value)
}
public init(base64 string: String) {
self = Data(ReconData(base64: string)!)
}
private init(extant: Bool) {
self = (extant ? .Extant : .Absent)
}
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
public init(data: NSData) {
self = Data(ReconData(data: data))
}
#endif
public init(_ value: Double) {
self = Number(value)
}
public init(_ value: Int) {
self = Number(Double(value))
}
public init(_ value: Uri) {
self = Text(value.uri)
}
/**
Convert JSON-ish objects to ReconValue instances.
This has similar restrictions to NSJSONSerialization, but expanded to
allow for Swift native types:
- Top level object is an `[AnyObject]` or `[String: AnyObject]`.
- All objects are `Bool`, `Int`, `Double`, `String`, `NSNumber`,
`[AnyObject]`, `[String: AnyObject]`, or `NSNull`.
Keys in dictionaries are sorted before being added to the corresponding
ReconRecord, so that the results are reproducible.
*/
public init(json: AnyObject) {
// Note that because json is AnyObject, the Swift native Bool, Int,
// and Double types have been boxed. This means that if we use
// "json is Bool" and similar, we get the wrong answer because
// all three native types when boxed will return true to the "is Bool"
// query. For this reason, we check the dynamicType.
//
// This is obviously relying on an internal detail of the Swift runtime,
// but it's working around what is arguably a bug in Swift.
if String(json.dynamicType) == "__NSCFBoolean" {
let bool = json as! Bool
self.init(booleanLiteral: bool)
}
else if String(json.dynamicType) == "__NSCFNumber" {
let val = json as! Double
self.init(val)
}
else if let str = json as? String {
self.init(str)
}
else if let num = json as? NSNumber {
self.init(num.doubleValue)
}
else if json is NSNull {
self.init(extant: false)
}
else {
self.init(ReconRecord(json: json))
}
}
public var isDefined: Bool {
return self != Absent
}
public var isRecord: Bool {
if case Record = self {
return true
} else {
return false
}
}
public var isText: Bool {
if case Text = self {
return true
} else {
return false
}
}
public var isData: Bool {
if case Data = self {
return true
} else {
return false
}
}
public var isNumber: Bool {
if case Number = self {
return true
} else {
return false
}
}
public var isExtant: Bool {
return self == Extant
}
public var isAbsent: Bool {
return self == Absent
}
public var record: ReconRecord? {
if case Record(let value) = self {
return value
} else {
return nil
}
}
public var json: AnyObject {
switch self {
case .Absent, .Extant:
return NSNull()
case .Number(let val):
return val
case .Record(let record):
return record.json
case .Text(let str):
return str
default:
preconditionFailure("Cannot convert ReconValue to JSON object: \(self)")
}
}
public var text: String? {
if case Text(let value) = self {
return value
} else {
return nil
}
}
public var data: ReconData? {
if case Data(let value) = self {
return value
} else {
return nil
}
}
public var number: Double? {
if case Number(let value) = self {
return value
} else {
return nil
}
}
public var integer: Int? {
if case Number(let value) = self {
return Int(value)
} else {
return nil
}
}
public var uri: Uri? {
if let string = text {
return Uri(string)
} else {
return nil
}
}
public var tag: String? {
if let head = record?.first, case .Field(.Attr(let key, _)) = head {
return key
} else {
return nil
}
}
public var first: Item {
switch self {
case Record(let value):
return value.first ?? Item.Absent
default:
return Item.Absent
}
}
public var last: Item {
switch self {
case Record(let value):
return value.last ?? Item.Absent
default:
return Item.Absent
}
}
public subscript(index: Int) -> Item {
get {
switch self {
case Record(let value) where 0 <= index && index < value.count:
return value[index] ?? Item.Absent
default:
return Item.Absent
}
}
}
public subscript(key: Value) -> Value {
switch self {
case Record(let value):
return value[key] ?? Value.Absent
default:
return Value.Absent
}
}
public mutating func popFirst() -> Item? {
switch self {
case Record(let value):
let first = value.popFirst()
self = Record(value)
return first
default:
return Item.Absent
}
}
public mutating func popLast() -> Item? {
switch self {
case Record(let value):
let last = value.popLast()
self = Record(value)
return last
default:
return Item.Absent
}
}
public func dropFirst() -> Value {
switch self {
case Record(let value) where !value.isEmpty:
return Record(value.dropFirst())
default:
return Value.Absent
}
}
public func dropLast() -> Value {
switch self {
case Record(let value) where !value.isEmpty:
return Record(value.dropLast())
default:
return Value.Absent
}
}
public subscript(key: String) -> Value {
switch self {
case Record(let value):
return value[key] ?? Value.Absent
default:
return Value.Absent
}
}
public func writeRecon(inout string: String) {
switch self {
case Record(let value):
value.writeRecon(&string)
case Text(let value):
value.writeRecon(&string)
case Data(let value):
value.writeRecon(&string)
case Number(let value):
value.writeRecon(&string)
default:
break
}
}
public func writeReconBlock(inout string: String) {
switch self {
case Record(let value):
value.writeReconBlock(&string)
default:
writeRecon(&string)
}
}
public var recon: String {
switch self {
case Record(let value):
return value.recon
case Text(let value):
return value.recon
case Data(let value):
return value.recon
case Number(let value):
return value.recon
default:
return ""
}
}
public var reconBlock: String {
switch self {
case Record(let value):
return value.reconBlock
default:
return recon
}
}
public var description: String {
return recon
}
public var hashValue: Int {
switch self {
case Record(let value):
return value.hashValue
case Text(let value):
return value.hashValue
case Data(let value):
return value.hashValue
case Number(let value):
return value.hashValue
case Extant:
return Int(bitPattern: 0x8e02616a)
case Absent:
return Int(bitPattern: 0xd35f02e5)
}
}
public static var True: Value {
return Text("true")
}
public static var False: Value {
return Text("false")
}
}
public func == (lhs: Value, rhs: Value) -> Bool {
switch (lhs, rhs) {
case (.Record(let x), .Record(let y)):
return x == y
case (.Text(let x), .Text(let y)):
return x == y
case (.Data(let x), .Data(let y)):
return x == y
case (.Number(let x), .Number(let y)):
return x == y
case (.Extant, .Extant):
return true
case (.Absent, .Absent):
return true
default:
return false
}
}
public func < (lhs: Value, rhs: Value) -> Bool {
switch lhs {
case .Record(let x):
switch rhs {
case .Record(let y):
return x < y
case .Data, .Text, .Number, .Extant, .Absent:
return true
}
case .Data(let x):
switch rhs {
case .Data(let y):
return x < y
case .Text, .Number, .Extant, .Absent:
return true
default:
return false
}
case .Text(let x):
switch rhs {
case .Text(let y):
return x < y
case .Number, .Extant, .Absent:
return true
default:
return false
}
case .Number(let x):
switch rhs {
case .Number(let y):
return x < y
case .Extant, .Absent:
return true
default:
return false
}
case .Extant:
switch rhs {
case .Absent:
return true
default:
return false
}
case .Absent:
return false
}
}
|
import { ReactNode, createContext, useEffect, useState } from "react"
import { api } from "../api/axios";
type Project = {
id: number;
name: string;
imageUrl: string;
description?: string;
githubUrl?: string;
projectUrl?: string;
}
interface ProjectsContextType {
projects: Project[]
}
interface ProjectsProviderProps {
children: ReactNode
}
export const ProjectContext = createContext({} as ProjectsContextType)
export const ProjectsProvider = ({children}:ProjectsProviderProps) => {
const [ projects, setProjects ] = useState<Project[]>([])
const getProjects = async() => {
await api.get('/project')
.then(resp => setProjects(resp.data.projects))
.catch( erro => console.warn(erro.response.data))
}
useEffect(() => {
getProjects()
}, [])
return(
<ProjectContext.Provider value={ { projects }}>
{children}
</ProjectContext.Provider>
)
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateScrewsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('screws', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('screw_config_id')->nullable();
$table->boolean('visible')->default(true);
$table->timestamps();
$table->foreign('screw_config_id')
->references('id')
->on('screw_configs');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('screws');
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Vineyard Simulator</title>
<!--
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/redux.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-redux.min.js"></script>
<script src="https://unpkg.com/[email protected]/fetch.js"></script>
-->
<script src="./vineyard.vendor.js"></script>
<style type="text/css">
#sidebar {
position: fixed;
right: 0;
margin-right: 2em;
width: 384px;
}
#vineyardInput .invalid {
border-color: red;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const initialState = {
grape: '',
vineyardStates: [],
cultivation: [{
vineyardState: 'Stems look especially fat',
tendAction: null,
acid: 0,
color: 0,
grapes: 10,
quality: 0,
skin: 0,
sugar: 0,
vigor: 100,
step: 0
}]
};
const mapVerboseToAbbrev = {
tend: {
'Aerate the soil': 'as',
'Mist the grapes': 'mg',
'Pinch off the weakest stems': 'po',
'Shade the leaves': 'sl',
'Spread out the vines': 'sv',
'Tie the vines to the trellis': 'tv',
'Trim the lower leaves': 'tl'
},
vineyard: {
'The vines are sagging a bit': 'sagging',
'Leaves are wilting': 'wilting',
'A musty smell can be detected': 'musty',
'Stems look especially fat': 'fat',
'Leaves rustle in the breeze': 'rustle',
'The grapes are starting to shrivel': 'shrivel',
'Leaves shimmer with moisture': 'shimmer'
}
}
const tendTable = {"fat":{"as":{"a":2,"c":6,"g":7,"q":1,"k":-9,"s":-2,"v":-2},"mg":{"a":1,"c":4,"g":3,"q":3,"k":11,"s":-2,"v":-4},"po":{"a":2,"c":3,"g":4,"q":1,"k":15,"s":-3,"v":-6},"sl":{"a":-5,"c":8,"g":3,"q":-2,"k":16,"s":0,"v":-12},"sv":{"a":1,"c":-4,"g":-6,"q":-2,"k":12,"s":4,"v":-14},"tv":{"a":4,"c":2,"g":0,"q":1,"k":-6,"s":0,"v":-3},"tl":{"a":5,"c":-1,"g":-2,"q":3,"k":9,"s":-2,"v":-12}},"musty":{"as":{"a":1,"c":2,"g":2,"q":-3,"k":15,"s":1,"v":-5},"mg":{"a":6,"c":2,"g":3,"q":3,"k":7,"s":3,"v":-14},"po":{"a":5,"c":6,"g":5,"q":1,"k":-1,"s":2,"v":-12},"sl":{"a":7,"c":8,"g":-5,"q":1,"k":15,"s":1,"v":-9},"sv":{"a":8,"c":4,"g":6,"q":0,"k":8,"s":4,"v":-6},"tv":{"a":0,"c":4,"g":-6,"q":-1,"k":-11,"s":2,"v":-8},"tl":{"a":8,"c":-2,"g":-3,"q":0,"k":-11,"s":-2,"v":-3}},"rustle":{"as":{"a":4,"c":4,"g":-5,"q":0,"k":6,"s":2,"v":-9},"mg":{"a":7,"c":-3,"g":6,"q":3,"k":5,"s":1,"v":-6},"po":{"a":5,"c":-6,"g":2,"q":3,"k":16,"s":-2,"v":-1},"sl":{"a":0,"c":8,"g":1,"q":1,"k":13,"s":2,"v":-11},"sv":{"a":6,"c":-4,"g":-5,"q":-3,"k":-11,"s":-1,"v":-4},"tv":{"a":-5,"c":0,"g":-6,"q":-2,"k":8,"s":-2,"v":-4},"tl":{"a":7,"c":1,"g":-5,"q":-3,"k":14,"s":0,"v":-5}},"sagging":{"as":{"a":4,"c":-2,"g":1,"q":0,"k":-8,"s":2,"v":-10},"mg":{"a":2,"c":-3,"g":2,"q":-3,"k":14,"s":0,"v":-5},"po":{"a":3,"c":-6,"g":-4,"q":1,"k":1,"s":3,"v":-9},"sl":{"a":-6,"c":2,"g":7,"q":4,"k":-6,"s":4,"v":-10},"sv":{"a":-6,"c":-1,"g":-4,"q":1,"k":5,"s":-3,"v":-10},"tv":{"a":-2,"c":6,"g":3,"q":2,"k":6,"s":3,"v":-10},"tl":{"a":-6,"c":4,"g":0,"q":1,"k":6,"s":-2,"v":-7}},"shimmer":{"as":{"a":-6,"c":0,"g":-2,"q":1,"k":4,"s":3,"v":-1},"mg":{"a":-4,"c":-3,"g":2,"q":-1,"k":5,"s":-1,"v":-9},"po":{"a":2,"c":8,"g":-1,"q":4,"k":-3,"s":-3,"v":-1},"sl":{"a":-5,"c":-1,"g":-2,"q":2,"k":-11,"s":-2,"v":-2},"sv":{"a":-3,"c":6,"g":8,"q":0,"k":11,"s":-3,"v":-10},"tv":{"a":0,"c":1,"g":4,"q":2,"k":-9,"s":0,"v":-14},"tl":{"a":3,"c":-4,"g":-4,"q":0,"k":4,"s":-2,"v":-10}},"shrivel":{"as":{"a":6,"c":-5,"g":2,"q":4,"k":9,"s":3,"v":-7},"mg":{"a":-2,"c":1,"g":-4,"q":-3,"k":-12,"s":-3,"v":-13},"po":{"a":-2,"c":4,"g":-3,"q":-1,"k":3,"s":4,"v":-6},"sl":{"a":8,"c":-3,"g":4,"q":3,"k":14,"s":1,"v":-6},"sv":{"a":5,"c":-2,"g":7,"q":4,"k":16,"s":2,"v":-9},"tv":{"a":-2,"c":4,"g":-6,"q":2,"k":1,"s":2,"v":-12},"tl":{"a":-4,"c":-1,"g":2,"q":4,"k":-1,"s":-1,"v":-2}},"wilting":{"as":{"a":-2,"c":5,"g":-2,"q":1,"k":4,"s":4,"v":-9},"mg":{"a":3,"c":5,"g":6,"q":2,"k":-2,"s":2,"v":-8},"po":{"a":2,"c":2,"g":-1,"q":4,"k":-7,"s":-3,"v":-11},"sl":{"a":-3,"c":3,"g":3,"q":-3,"k":-11,"s":0,"v":-12},"sv":{"a":8,"c":8,"g":0,"q":0,"k":10,"s":-1,"v":-14},"tv":{"a":5,"c":8,"g":2,"q":4,"k":8,"s":4,"v":-6},"tl":{"a":4,"c":5,"g":-1,"q":0,"k":13,"s":4,"v":-5}}};
function setCultivationStep(state, property, value, index) {
return _.assign({}, state, {
cultivation: _.tap(state.cultivation.map((step) => {
if (step.step === index) {
return _.assign({}, step, { [property]: value });
}
return step;
}), (cultivation) => {
const lastStep = _.last(cultivation);
if (!_.isEmpty(lastStep.tendAction)) {
const tend = tendTable[
mapVerboseToAbbrev.vineyard[lastStep.vineyardState]
][
mapVerboseToAbbrev.tend[lastStep.tendAction]
];
if (lastStep.vigor + tend.v > 0) {
cultivation.push({
vineyardState: state.vineyardStates[lastStep.step + 1] ||
_.keys(mapVerboseToAbbrev.vineyard)[0],
tendAction: null,
acid: Math.max(0, lastStep.acid + tend.a),
color: Math.max(0, lastStep.color + tend.c),
grapes: Math.max(0, lastStep.grapes + tend.g),
quality: Math.max(0, lastStep.quality + tend.q),
skin: Math.max(0, lastStep.skin + tend.k),
sugar: Math.max(0, lastStep.sugar + tend.s),
vigor: Math.max(0, lastStep.vigor + tend.v),
step: lastStep.step + 1
});
}
}
})
});
};
function vineyardApp(state = initialState, action) {
console.log(action.type, action);
switch(action.type) {
case 'CHANGE_GRAPES':
return setCultivationStep(state, 'grapes', action.grapes, 0);
case 'CHANGE_VINEYARD_STATE':
return setCultivationStep(state, 'vineyardState', action.state, action.step);
case 'CHANGE_TEND_ACTION':
return setCultivationStep(state, 'tendAction', action.tend, action.step);
case 'CHANGE_VINEYARD_STATES':
return _.assign({}, state, { vineyardStates: action.states });
default: return state;
}
};
let store = Redux.createStore(vineyardApp);
class Cultivate extends React.Component {
constructor(props) {
super(props);
_.bindAll(this, [
'vineyardStates', 'onChangeVineyardState',
'tendActions', 'onChangeTendAction',
'showGrapes', 'onChangeStartingGrapes'
]);
}
onChangeVineyardState(evt) {
this.props.changeVineyardState(evt.target.value, this.props.step);
}
vineyardStates() {
return [
'The vines are sagging a bit',
'Leaves are wilting',
'A musty smell can be detected',
'Stems look especially fat',
'Leaves rustle in the breeze',
'The grapes are starting to shrivel',
'Leaves shimmer with moisture'
].map((state) => {
return <option key={state}>{state}</option>;
});
}
onChangeTendAction(evt) {
this.props.changeTendAction(evt.target.value, this.props.step);
}
tendActions() {
return [
'',
'Aerate the soil',
'Mist the grapes',
'Pinch off the weakest stems',
'Shade the leaves',
'Spread out the vines',
'Tie the vines to the trellis',
'Trim the lower leaves'
].map((state) => { return <option key={state}>{state}</option>; });
}
onChangeStartingGrapes(evt) {
this.props.changeStartingGrapes(evt.target.valueAsNumber);
}
showGrapes() {
if (this.props.step === 0) {
return <input
type="number"
min="0" max="20" step="1"
defaultValue={this.props.grapes}
onChange={this.onChangeStartingGrapes} />;
} else {
return this.props.grapes;
}
}
render() {
return <tr className="cultivate">
<td><select className="vineyardState"
value={this.props.vineyardState}
onChange={this.onChangeVineyardState}>
{this.vineyardStates()}
</select></td>
<td><select className="tendAction"
onChange={this.onChangeTendAction}>
{this.tendActions()}
</select></td>
<td>{this.props.acid}</td>
<td>{this.props.color}</td>
<td>{this.showGrapes()}</td>
<td>{this.props.quality}</td>
<td>{this.props.skin}</td>
<td>{this.props.sugar}</td>
<td>{this.props.vigor}</td>
</tr>;
}
}
const CultivationStep = ReactRedux.connect(
null,
(dispatch) => { return {
changeStartingGrapes: (grapes) => {
store.dispatch({ type: 'CHANGE_GRAPES', grapes });
},
changeVineyardState: (state, step) => {
store.dispatch({ type: 'CHANGE_VINEYARD_STATE', state, step });
},
changeTendAction: (tend, step) => {
store.dispatch({ type: 'CHANGE_TEND_ACTION', tend, step });
}
}}
)(Cultivate);
class Cultivation extends React.Component {
render() {
const cultivation = _.map(this.props.cultivation, (step, index) => {
return <CultivationStep key={index} {...step} />;
});
return <table id="cultivation">
<thead><tr>
<th>Vineyard</th>
<th>Tend</th>
<th>Acid</th>
<th>Color</th>
<th>Grapes</th>
<th>Quality</th>
<th>Skin</th>
<th>Sugar</th>
<th>Vigor</th>
</tr></thead>
<tbody>
{cultivation}
</tbody>
</table>;
}
}
const CultivationRun = ReactRedux.connect(
(state) => state,
(dispatch) => { return {
}}
)(Cultivation);
class Vineyard extends React.Component {
constructor(props) {
super(props)
this.state = { valid: true };
_.bindAll(this, [
'onChangeVineyardStates'
]);
}
onChangeVineyardStates(evt) {
const codes = {
G: 'The vines are sagging a bit',
W: 'Leaves are wilting',
M: 'A musty smell can be detected',
F: 'Stems look especially fat',
R: 'Leaves rustle in the breeze',
V: 'The grapes are starting to shrivel',
H: 'Leaves shimmer with moisture'
}
let valid = true;
const states = evt.target.value.split('').map((code) => {
if (codes[code]) {
return codes[code];
} else {
valid = false;
}
})
if (valid) {
this.setState({ valid: true });
this.props.changeVineyardStates(states);
} else {
this.setState({ valid: false });
}
}
render() {
const help = `
G: The vines are sagging a bit
W: Leaves are wilting
M: A musty smell can be detected
F: Stems look especially fat
R: Leaves rustle in the breeze
V: The grapes are starting to shrivel
H: Leaves shimmer with moisture
`;
return <div id="vineyardInput" title={help}>
Vineyard: <input
className={this.state.valid || "invalid"}
type="text" onChange={this.onChangeVineyardStates} />
</div>;
}
}
const VineyardInput = ReactRedux.connect(
(state) => state,
(dispatch) => { return {
changeVineyardStates: (states) => {
store.dispatch({ type: 'CHANGE_VINEYARD_STATE', state: states[0], step: 0 });
store.dispatch({ type: 'CHANGE_VINEYARD_STATES', states });
}
}}
)(Vineyard);
class Translator extends React.Component {
constructor(props) {
super(props);
_.bindAll(this, [ 'translate' ]);
}
translate(evt) {
let translation = _.compact(evt.target.value.split("\n").map((line) => {
if (/sag/i.test(line)) {
return 'G';
} else if (/wilt/i.test(line)) {
return 'W';
} else if (/musty/i.test(line)) {
return 'M';
} else if (/fat/i.test(line)) {
return 'F';
} else if (/rustl/i.test(line)) {
return 'R';
} else if (/shrivel/i.test(line)) {
return 'V';
} else if (/shimmer/i.test(line)) {
return 'H';
} else {
// TODO: Invalid
}
})).join('');
document.querySelector('#translation').value = translation;
}
render() {
return <div id="translator">
Translator:<br />
<textarea onChange={this.translate} rows="25" cols="30" /><br />
<input id="translation" type="text" />
</div>;
}
}
const TranslatorApp = ReactRedux.connect(
(state) => state,
(dispatch) => { return {
}}
)(Translator);
class VineyardApp extends React.Component {
render() {
return <div id="app">
<div id="sidebar">
<Translator />
</div>
Current Grape: <a href="http://www.atitd.org/wiki/tale7/Wine/Pascalito356">
Pascalito#356
</a>
<VineyardInput />
<CultivationRun />
</div>;
}
}
ReactRedux.connect()(VineyardApp);
ReactDOM.render(
<ReactRedux.Provider store={store}>
<VineyardApp />
</ReactRedux.Provider> ,
document.getElementById('root')
);
</script>
</body>
</html>
|
# S-Plus script developed by Professor Alexander McNeil, [email protected]
# R-version adapted by Scott Ulman ([email protected])
# QRMlib 1.4.4
# This free script using QRMLib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
######Load the QRMlib and ftse100 data set##################
#QRMlib.pdf is a help file for the functions used by QRMlib. It is available at
#...\Program Files\R\R-2.6.0\library\QRMlib\Docs
#If you have created the QRMBook workspace and .Rprofile as described in QRMlib.pdf
#topics 'QRMBook-workspace' and 'profileLoadLibrary', then you may comment out the
#following line:
library(QRMlib);
#if you have previously opened the ftse100, smi,and FXGBP.RAW timeSeries AND saved
#the workspace, you may comment out the following lines:
data(ftse100);
data(smi);
data(FXGBP.RAW);
#Alternatively, if you want to load the dataframes instead of timeSeries,
#activate the following lines:
#data(ftse100.df);
#data(smi.df);
#data(FXGBP.RAW.df);
#################################################
#### COPULA FITTING
# Fitting copulas to data the R-way
#requires(fSeries) #version 260.72
#In R (unlike S-Plus), two time series being merged must have the same number of rows.
#The smi timeSeries starts on 11/09/1990 and the ftse100 starts on 01/02/1990. Both end 03/25/2004.
#Hence create a partial ftse100 time series by cutting all values between 1/2/1990-11/8/1990. so we
#will use the remaining (cut) data from 1990-11-08 to 2004-03-25. Note the first date 1990-11-08 is
#excluded
#Through R-2.5.1, timeSeries class originally belong in package fCalendar.
#Version 221.10065 used cutSeries()method to select data only between the 'to' and 'from' dates.
#Version 240.10068 used cut(). Both required the day PRIOR to desired start in "from".
#R-2.6.0. RMetrics 260.72 moved timeSeries to fSeries from fCalendar. Used window() in place of cut().
#No longer need prior date:
TS1 <- window(ftse100, "1990-11-09", "2004-03-25"); # TS1 is ftse100 truncated.
#If we try to merge the two series which have the same dates, we would hope to get two series of
#equal length. However, if we try to merge the series (use only the @Data slot from the 2nd series)
#we get an error message that series are NOT of same length.
#INDEXES.RAW <- mergeSeries(TS3, smi@Data)
# Investigation shows that TS3 has 3379 entries while TS2 has 3331 entries. TS2 is missing,
#for example, dates 1990-12-31 and 1991-01-02.
#dim(TS1@Data)[1]; #shows 3379
#dim(smi@Data)[1]; #shows 3331
#When S-Plus finds data mismatches, its ts.union() function uses the 'before' method to copy data
#from the prior date to any missing date. This is not done in R. Hence we have to run a 2nd
#set of functions to align the data using all days available. If a date has missing data, the
#"before" argument says to copy the data from the day before to the date with missing data.
TS1Augment <- alignDailySeries(TS1, method="before"); #gives 3490 observations
TS2Augment <- alignDailySeries(smi, method="before"); #gives 3490 observations
#Merge the two time series with ftse100 first. In fCalendar versions prior to 240.10068, we used
#mergeSeries(). In fCalendar 240.10068, mergeSeries() has been deprecated and we must use merge();
#INDEXES.RAW <- mergeSeries(TS1Augment, TS2Augment@Data);
INDEXES.RAW <- merge(TS1Augment,TS2Augment);
#clean up:
rm(TS1, TS1Augment, TS2Augment);
#Prior to R-2.5.0 we called plot.timeSeriesIts()from utilityFunction.R. However in R-2.5.0 both
#'its' and 'base' have a method called "names" and R-2.5.0 cannot distinguish them properly.
#"names" when both 'base' and 'its' are always loaded.
#Hence we now call a new utility function from functionsUtility.R replacing plot.timeSeriesIts():
#Plot both columns on same graph (no need to use colvec parameter):
plotMultiTS(INDEXES.RAW, reference.grid=TRUE);
#Create a time series of returns from the prices. mk.returns is in functionsUtility.R.
#By not passing a type="relative" argument, we are implicitly using a type="log" argument
# and generating logarithmic returns.
INDEXES <- mk.returns(INDEXES.RAW);
#As above call new utilityFunction.R plotMultiTS():
plotMultiTS(INDEXES);
#R-2.6.0. RMetrics 260.72 moved timeSeries to fSeries from fCalendar. Used window() in place of cut().
#No longer need prior date:
PARTIALINDEXES <- window(INDEXES, "1994-01-01", "2003-12-31");
#Now create a data matrix from the just-created timeSeries
data <- seriesData(PARTIALINDEXES);
#Keep only the data items which are non-zero for both smi and ftse100
data <- data[data[,1]!=0 & data[,2] !=0,];
plot(data);
# Construct pseudo copula data. The 2nd parameter is MARGIN=2
#when applying to columns and 1 applied to rows. Hence this says to
#apply the 'edf()' empirical distribtion function() to the columns
#of the data.
Udata <- apply(data,2,edf,adjust=1)
plot(Udata)
# Compare various bivariate models. Fit gauss copula first
mod.gauss <- fit.gausscopula(Udata)
mod.gauss
#Calculate Spearman rank correlation for pseudo-copula data:
Spearman(Udata)
#Fit 2-dimensional Archimedian copula: choices are gumbel or clayton
#using pseudo data generated via edf() from observed data:
mod.gumbel <- fit.Archcopula2d(Udata,"gumbel")
mod.clayton <- fit.Archcopula2d(Udata,"clayton")
#Fit a t-copula to the pseudo-copula data generated via edf() from real data:
mod.t <- fit.tcopula(Udata)
mod.t
sin(pi*Kendall(Udata)/2)
c(mod.gauss$ll.max, mod.t$ll.max, mod.gumbel$ll.max, mod.clayton$ll.max)
# Multivariate Fitting with Gauss and t: Simulation
# Create an equicorrelation matrix:
P <- equicorr(3,0.6)
#Simulate data for a Gaussian copula with Sigma=P
set.seed(117);
#The data will have 1000 rows and 3 columns since P is 3x3:
Udatasim <- rcopula.gauss(1000,Sigma=P);
#ALTERNTATIVELY, copy data simulated from S-Plus for usage
#Try to fit a copula to the simulated data. It should match.
mod.gauss <- fit.gausscopula(Udatasim);
mod.gauss;
#Calculate a matrix of Spearman Rank Correlations
Pstar <- Spearman(Udatasim);
#Evalutate the density of the Gauss copula using dcopula.gauss() and the matrix
# of Spearman Rank Correlations. This returns a vector.
# Sum the vector elements. See pp. 197 and 234 in QRM
sum(dcopula.gauss(Udatasim,Pstar,logvalue=TRUE));
#Reset the seed to a new value:
set.seed(113);
#Generate a new set of random data from a t-copula (10df) with the same Sigma matrix:
Udatasim2 <- rcopula.t(1000,df=10,Sigma=P)
#Fit the copula to the simulated data
mod.t <- fit.tcopula(Udatasim2);
mod.t;
#Now refit the copula to the same simulated data using (Kendall) rank correlations
#and the fit.tcopula.rank() method:
mod.t2 <- fit.tcopula.rank(Udatasim2);
mod.t2;
#Now fit the gauss copula to the same simulated data
mod.gauss <- fit.gausscopula(Udatasim2);
mod.gauss;
# ******Now use real FX data with Great Britain's Pound.
#Once again, use the new utility function for R-2.5.0:
plotMultiTS(FXGBP.RAW, reference.grid=TRUE);
#Create a return time series; it will be logarithmic unless we pass argument type="relative"
tsretFXGBP <- mk.returns(FXGBP.RAW);
#In version 240.10068, fCalendar uses cut() rather than cutSeries() to select a subset from timeseries:
#R-2.6.0. RMetrics 260.72 moved timeSeries to fSeries from fCalendar. Used window() in place of cut().
#No longer need prior date:
tsretFXGBP <- window(tsretFXGBP,from= "01/01/1997", to= "12/31/2003");
#Extract just the data, removing the date; effectively creates a data matrix
data <- seriesData(tsretFXGBP);
#Use the sum() function across rows (indicated by MARGIN=1)of the matrix. If any row
#has missing values, an NA will be returned. Hence this reports on which rows have
#missing values since there are 4 different exchange rates per row. Missing data
#will be a row value of TRUE in 'missing'; otherwise row values will be FALSE.
missing <- is.na(apply(data,1,sum));
#REMOVE any rows with missing values, i.e. keep only data which is not missing values
data <- data[!missing,];
#print scatter plots of all data pairs (e.g GBP/USD, GBP/EUR, GBP/JPY, GBP/CHF)
#remember-this is the real data
pairs(data);
# Construct pseudo copula data
#Apply the edf() function to the columns. This will calculate the empirical cumulative
#probability for each observation in the time series.
#The edf() is the empirical distribution function. edf() takes an argument 'adjust'
#which says whether the denominator should be 'n+1'(adjust=1) or not (adjust=0). The
#default is 0 (F). Hence the resulting Udata will represent the value of the ecdf
#(empirical cdf) represented by each return.
#The 2nd argument of apply is the MARGIN: 1 = rows, 2=columns, c(1,2) for both rows
#and columns)
UdataFX <- apply(data,2,edf,adjust=TRUE);
#print scatter plots of all data pairs (e.g GBP/USD, GBP/EUR, GBP/JPY, GBP/CHF)
#generated from Empirical Distribution Function edf
pairs(UdataFX);
# Fit copulas using rank correlations to the ECDF data.
mod.t <- fit.tcopula.rank(UdataFX);
mod.t;
#Get Spearman rank correlations
Pstar <- Spearman(UdataFX);
Pstar;
sum(dcopula.gauss(UdataFX,Pstar,logvalue=TRUE));
Pstar;
|
import { useContext, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { MdDeleteOutline } from "react-icons/md";
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { useApi } from "../Context/Context";
import { TableContext } from "../Context/TableContextProvider";
export default function Order() {
const [orderType, setOrderType] = useState("dine");
const { tempOrderArray, orderArray, setOrderArray, setTempOrderArray } =
useApi();
const {setRefresh} = useContext(TableContext);
const [total, setTotal] = useState(0);
const [disc, setdisc] = useState(5);
const { id } = useParams();
//buggy use effect
// useEffect(() => {
// console.log("ran");
// fetch(`http://localhost:3000/api/getOrder/${id}`)
// .then((res) => res.json())
// .then((data) => {
// setTempOrderArray({
// items: data.data.items,
// quantity: data.data.quantity,
// notes: data.data.notes,
// });
// })
// .catch((err) => console.log(err));
// }, []);
useEffect(() => {
const ttl = tempOrderArray.items
? tempOrderArray.items
.map((item, i) => {
const x = item.price * tempOrderArray.quantity[i];
return x;
})
.reduce((sum, item) => sum + item, 0)
: 0;
setTotal(ttl);
setdisc(tempOrderArray.discount);
setOrderType(tempOrderArray.orderType);
}, [tempOrderArray]);
const handlePlaceOrder = () => {
fetch(`http://localhost:3000/api/editOrder/${id}`, {
method: "PUT",
body: JSON.stringify({
...tempOrderArray,
totalamount: total,
orderType: orderType,
discount: disc,
}),
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.then((data) => {
if (data.status) {
toast.success("Order placed");
setRefresh({});
console.log(data);
}
})
.catch((err) => {
toast.error(
err.message === "Failed to fetch"
? "Check Connection and try again!"
: ""
);
console.error(err);
});
// toast.success("Order Placed");
};
return (
<div className="w-1/3 h-[100vh] bg-gray-900 space-y-2 text-white p-5 float-right">
<ToastContainer />
<div className="text-lg font-bold ">Order #{id}</div>
<div className="btn-container w-full ">
<button
onClick={() => setOrderType("dine")}
className={`${
orderType === "dine" ? "bg-red-500" : "bg-gray-500"
} p-1 w-auto mx-auto outline-neutral-200 rounded-lg my-2 me-2`}
>
Dine in
</button>
<button
onClick={() => setOrderType("to go")}
className={` ${
orderType === "to go" ? "bg-red-500" : "bg-gray-500"
} p-1 w-auto mx-auto outline-neutral-200 rounded-lg my-2 me-2`}
>
To Go
</button>
<button
disabled
onClick={() => setOrderType("delivery")}
className={` ${
orderType === "delivery" ? "bg-red-500" : "bg-gray-500"
} p-1 w-auto mx-auto outline-neutral-200 rounded-lg my-2 me-2`}
>
Delivery
</button>
</div>
{/* heading */}
<div className="flex w-full pb-2 ">
<div className="flex justify-between w-4/5 ">
<h2>Item</h2>
<h2>Qnty</h2>
</div>
<div className="w-1/5 flex justify-end">Price</div>
</div>
{/* food item container */}
<div className="h-3/5 border-t-2 border-gray-600 border-b-2 overflow-y-scroll ">
{tempOrderArray?.items &&
tempOrderArray.items.map((item, i) => (
<FoodItem
key={item._id}
itr={i}
orderArray={orderArray}
setTempOrderArray={setTempOrderArray}
tempOrderArray={tempOrderArray}
item={item}
/>
))}
</div>
<div className="space-y-2">
<div className="flex justify-between pb-2">
<h3 className="text-sm text-gray-300">Discount</h3>
<input
type="text"
value={disc}
placeholder="discount"
onFocus={(e) => e.target.select()}
onChange={(e) => setdisc(e.target.value)}
className="w-1/6 text-end text-sm bg-transparent text-gray-200 focus:outline-none"
/>
</div>
<div className="flex justify-between">
<h3 className="text-sm text-gray-300">Sub Total</h3>
<h3 className="text-sm text-gray-300">{total}</h3>
</div>
{tempOrderArray.readystatus == "ready" ? (
<button disabled className="w-full bg-gray-500 rounded-lg p-2">
Order Ready
</button>
) : (
<button
onClick={handlePlaceOrder}
className="w-full bg-red-500 rounded-lg p-2"
>
Place Order
</button>
)}
</div>
</div>
);
}
function FoodItem({ item, setTempOrderArray, itr, tempOrderArray }) {
const { _id, name, price } = item;
const [qnty, setQnty] = useState(tempOrderArray.quantity[itr]);
const [inpNot, setinpNote] = useState(tempOrderArray.notes[itr]);
const handleChange = (e, setFunc) => {
if (!isNaN(Number(e.target.value))) {
setFunc(Number(e.target.value));
}
};
useEffect(() => {
// if (qnty) {
// handleDelete(_id);
// }
const updatedQ = tempOrderArray.quantity;
updatedQ[itr] = qnty;
const updateN = tempOrderArray.notes;
updateN[itr] = inpNot;
setTempOrderArray({
...tempOrderArray,
quantity: updatedQ,
notes: updateN,
});
}, [inpNot, qnty]);
// useEffect(() => {
// if (qnty == 0) {
// handleDelete(_id);
// }
// if (qnty >= 1 || notes.length > 0 || qnty === "") {
// const newArray = tempOrderArray.map((obj) =>
// obj._id === id ? { ...obj, qty: Number(qnty), notes: inpNot } : obj
// );
// setTempOrderArray((arr) => (arr = newArray));
// }
// }, [qnty, inpNot]);
const handleDelete = (id) => {
const updatedArr = tempOrderArray.items.filter((o) => o._id !== id);
tempOrderArray.quantity.splice(itr, 1);
tempOrderArray.notes.splice(itr, 1);
setTempOrderArray({ ...tempOrderArray, items: updatedArr });
toast("Item removed");
};
return (
<>
{/* order card */}
<div className="order-card p-2 rounded-lg shadow-lg space-y-3">
<div className="flex w-full">
<div className="w-4/5 flex justify-between">
<h2 className="text-base">{name}</h2>
<input
type="text"
value={qnty}
placeholder="quantity"
onFocus={(e) => e.target.select()}
onChange={(e) => handleChange(e, setQnty)}
className="w-1/6 text-end text-sm bg-transparent text-gray-200 focus:outline-none"
/>
</div>
<div className="w-1/5 flex justify-end text-sm text-gray-200">
{price * tempOrderArray.quantity[itr]}
</div>
</div>
<div className="w-full flex">
<input
type="text"
value={inpNot}
onChange={(e) => setinpNote(e.target.value)}
className="bg-gray-800 w-4/5 p-1 text-xs rounded-lg focus:outline-none"
placeholder="Enter Note if any"
/>
<button
onClick={() => handleDelete(_id)}
className="w-1/5 flex justify-end"
>
<MdDeleteOutline size={32} className="text-red-500" />
</button>
</div>
</div>
</>
);
}
|
# Create neural network class
import torch
import torch.nn as nn
class MyNet(nn.Module):
# define constructor
def __init__(self, input_size, hidden_size, output_size):
# call nn.Module constructor
super(MyNet, self).__init__()
# define input layer for getting inputs
self.input_layer = nn.Linear(input_size, hidden_size)
# define output layer for producing output
self.output_layer = nn.Linear(hidden_size, output_size)
# define forward function
def forward(self, x):
# pass data x to input layer
out = self.input_layer(x)
# pass transformed data to next layer
out = self.output_layer(out)
return out
|
import ReactDOM from 'react-dom/client'
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import ErrorPage from './pages/ErrorPage.jsx';
import HomePageEng from './pages/English/HomePage.jsx';
import Fractions from './pages/English/Fractions/index.jsx'
import Divide from './pages/English/Fractions/Divide/DivideFract.jsx';
import Decimals from './pages/English/Decimals/index.jsx';
import Exponents from './pages/English/Exponents/index.jsx';
import Multiply from './pages/English/Fractions/Multiply/index.jsx';
import Regroup from './pages/English/Fractions/Regrouping/index.jsx';
import Home from './pages/Language.jsx';
import Creole from './pages/Creole/index.jsx';
import CreoleDecimal from './pages/Creole/Decimals/index.jsx';
import CreoleExponents from './pages/Creole/Exponents/index.jsx';
import CreoleFractions from './pages/Creole/Fractions/index.jsx';
import CreoleDivide from './pages/Creole/Fractions/Divide/DivideFract.jsx';
import CreoleMultiply from './pages/Creole/Fractions/Multiply/index.jsx';
import CreoleRegroup from './pages/Creole/Fractions/Regrouping/index.jsx';
import SpanishDecimals from './pages/Spanish/Decimals/index.jsx';
import SpanishHome from './pages/Spanish/index.jsx';
import SpanishExponents from './pages/Spanish/Exponents/index.jsx';
import SpanishFractions from './pages/Spanish/Fractions/index.jsx';
import SpanishDivide from './pages/Spanish/Fractions/Divide/DivideFract.jsx';
import SpanishMultiply from './pages/Spanish/Fractions/Multiply/index.jsx';
import SpanishRegroup from './pages/Spanish/Fractions/Regrouping/index.jsx';
import { ChakraProvider } from '@chakra-ui/react'
// Define the accessible routes, and which components respond to which URL
const router = createBrowserRouter([
{
path: '/',
element: <App />,
errorElement: <ErrorPage />,
children: [
{
index: true,
element: <Home />
},
{
path: 'english',
element: <HomePageEng />,
},
{
path: 'english/decimals',
element: <Decimals />,
},
{
path: 'english/fractions',
element: <Fractions />,
},
{
path: 'english/fractions/divide',
element: <Divide />,
},
{
path: 'english/fractions/multiply',
element: <Multiply />,
},
{
path: 'english/fractions/regrouping',
element: <Regroup />,
},
{
path: 'english/exponents',
element: <Exponents />,
},
{
path:'creole',
element: <Creole />
},
{
path:'creole/fraksyon',
element: <CreoleFractions />
},
{
path:'creole/ekspozan',
element: <CreoleExponents />
},
{
path:'creole/desimal',
element: <CreoleDecimal />
},
{
path:'creole/fraksyon/divizefraksyon',
element: <CreoleDivide />
},
{
path:'creole/fraksyon/miltipliyefraksyon',
element: <CreoleMultiply />
},
{
path:'creole/fraksyon/regroupementfraksyon',
element: <CreoleRegroup />
},
{
path:'espanol',
element: <SpanishHome />
},
{
path:'espanol/decimales',
element: <SpanishDecimals />
},
{
path:'espanol/exponentes',
element: <SpanishExponents />
},
{
path:'espanol/fracciones',
element: <SpanishFractions />
},
{
path:'espanol/fracciones/dividirfracciones',
element: <SpanishDivide />
},
{
path:'espanol/fracciones/multiplicarfracciones',
element: <SpanishMultiply />
},
{
path:'espanol/fracciones/reaguparfracciones',
element: <SpanishRegroup />
},
],
},
]);
// Render the RouterProvider component
ReactDOM.createRoot(document.getElementById('root')).render(
<ChakraProvider>
<RouterProvider router={router} />
</ChakraProvider>
);
|
import typer
import requests
from rich import print
from typing import Any, List
from typing_extensions import Annotated
from decorators import retry
from utils import get_data, format_response
app = typer.Typer(
pretty_exceptions_enable=False,
pretty_exceptions_show_locals=False
)
@app.command()
@retry(requests.exceptions.HTTPError, attemtps=3, delay=8)
def get_obj_by_bin(
biniin: Annotated[str, typer.Argument(
help="BIN or IIN of the company",
)],
field_names: Annotated[List[str], typer.Argument(
help="List of field names to return",
)] = None
) -> Any:
"""
Get information about company by BIN or IIN
"""
obj = get_data(biniin)
formatted_object = format_response(obj, field_names)
print(formatted_object)
if __name__ == "__main__":
app()
|
# Simulate the thermal behaviour of the lecture theatre during normal occupied periods.
# The inside temperature will be always maintained within the given lower and upper setpoints.
library(reticulate)
use_virtualenv("./anaconda3/envs/python_venv")
OUTPUT_DIR = "./datasets/text_data/moving_window/without_stl_decomposition/optimization/lecture_theatre"
file <- read.csv(file = "./datasets/text_data/winter_lt_data.csv")
max_forecast_horizon <- 1
input_size <- 1
mean <- 20
outside_mean <- 20
finalForecasts <- c()
times <- c()
OUTPUT_PATH <- paste(OUTPUT_DIR, "/heating_cooling_optimization_test_", max_forecast_horizon, "i", input_size, ".txt", sep = '')
#These variables need to be set before running the script if need
lower_setpoint <- 19
upper_setpoint <- 20
start_inside_temperature <- 20
start_status <- 0 # 0 if the AC is switched off and 1 if the AC is switched on
total_minutes <- 300 # total simulation time
isCoolingStarted <- TRUE #FALSE when starting from morning
time_required_to_add <- 420 # if the simulation is started during the middle of a day, what is the total time it should add to get the current time (in minutes)
outside_temperature_start_index <- 6711 # start index of the outside temperatures corresponding with our data
outside_temperature_finish_index <- 6731 # finish index of the outside temperatures corresponding with our data
output_file_name <- "sep5_1pm_to_6pm_optimized_20"
getPredictions <- function(insideTemperature, outsideTemperature, status){
sav_df <- data.frame(id=paste(1,'|i',sep=''))
sav_df[,paste('r',1,sep='')] <- insideTemperature/mean
sav_df[,paste('a',1,sep='')] <- outsideTemperature/outside_mean
sav_df[,'nyb'] <- '|#'
sav_df[,'level'] <- mean
write.table(sav_df, file=OUTPUT_PATH, row.names = F, col.names=F, sep=" ", quote=F, append = TRUE)
if(status==1){
py_run_file("./optimized_heater.py")
}
else{
py_run_file("./optimized_cooler.py")
}
forecasts <- py$forecasts[[1]]
final_temperature <- as.numeric(forecasts[length(forecasts)])
final_temperature
}
simulate <- function(){
close( file( OUTPUT_PATH, open="w" ) )
currentForecast <- start_inside_temperature
currentStatus <- start_status
outsideTemperatures <- file$outside_temp
outsideTemperatures <- outsideTemperatures[outside_temperature_start_index:outside_temperature_finish_index]
time <- 0
prevForecast <- currentForecast
while(time<total_minutes){
index <- (floor(time/15))+1
currentForecast <- getPredictions(currentForecast, outsideTemperatures[index],currentStatus)
currentForecast <- currentForecast*mean
prevStatus <- currentStatus
if((currentForecast < lower_setpoint) & isCoolingStarted){
rate <- (prevForecast-currentForecast)/15
requiredTime <- (prevForecast-lower_setpoint)/rate
time <- time + requiredTime
currentForecast <- lower_setpoint
}
else if(currentForecast > upper_setpoint){
rate <- (currentForecast-prevForecast)/15
requiredTime <- (currentForecast-upper_setpoint)/rate
time <- time + requiredTime
currentForecast <- upper_setpoint
}
else{
time <- time + 15
}
finalForecasts <<- c(finalForecasts,currentForecast)
times <<- c(times,(time+time_required_to_add))
if(currentForecast >= upper_setpoint){
isCoolingStarted <- TRUE
currentStatus <- 0
}
else if(currentForecast <= lower_setpoint){
currentStatus <- 1
}
else{
currentStatus <- prevStatus
}
if(currentStatus != prevStatus){
close( file( OUTPUT_PATH, open="w" ) )
}
prevForecast <- currentForecast
}
output <- data.frame(forecast=finalForecasts, time=times)
forecasts_file_path <- paste('./results/monash_simulation/',output_file_name,'.txt')
write.csv(output, file=forecasts_file_path)
}
simulate()
|
package main
import (
"fmt"
"math"
)
// Одне яблуко коштує 5.99 грн. Ціна однієї груші - 7 грн.
// Ми маємо 23 грн.
// 1. Скільки грошей треба витратити, щоб купити 9 яблук та 8 груш?
// 2. Скільки груш ми можемо купити?
// 3. Скільки яблук ми можемо купити?
// 4. Чи ми можемо купити 2 груші та 2 яблука?
//
// Задача:
// Опишіть вирішення всіх пунктів задачі використовуючи необхідні змінні чи/та константи.
// Під опишіть, я маю на увазі наступне:
// Я маю збілдити ваш код і запустити програму. В результаті цього, я маю побачити роздруковані // відповіді на поставлені вище запитання. Перед відповідю треба роздрукувати саме питання.
// Правильно обирайте типи даних та назви змінних чи констант.
// Публікація:
// Створити папку в своєму репозиторії в github та завантажити туди 1main.go файл, в котрому буде зроблено дане завдання.
func main() {
const (
priceApple = 5.99
pricePear = 7.00
ourWallet = 23.00
)
print("----------------------/1/----------------------\n\n")
print("\n1. Скільки грошей треба витратити, щоб купити 9 яблук та 8 груш?\n")
amountApple := 9.00
amountPear := 8.00
result := amountApple*priceApple + amountPear*pricePear
resultInString := fmt.Sprintf("%.2f", result)
println("-->Відповідь: Щоб купити 9 яблук і 8 груш нам потрібно", resultInString, " грн. \n")
print("----------------------/2/----------------------\n\n")
print(" 2. Скільки груш ми можемо купити?\n")
howMachPearsCanWeBuy := ourWallet / pricePear
resultInString = fmt.Sprintf("%.f", math.Floor(howMachPearsCanWeBuy))
println("-->Відповідь: Ми можемо купити", resultInString, " груші!\n")
print("----------------------/3/----------------------\n\n")
print(" 3. Скільки яблук ми можемо купити?\n")
howMachAppleCanWeBuy := ourWallet / priceApple
resultInString = fmt.Sprintf("%.f", math.Floor(howMachAppleCanWeBuy))
println("-->Відповідь: Ми можемо купити", resultInString, " яблук!\n")
print("----------------------/4/----------------------\n\n")
print(" 4. Чи ми можемо купити 2 груші та 2 яблука?\n")
priceTwoApplesAndTowPears := 2*priceApple + 2*pricePear
if ourWallet <= priceTwoApplesAndTowPears {
resultInString = "не"
} else {
resultInString = ""
}
println("-->Відповідь: Ми", resultInString, "можемо купити 2 груші та 2 яблука !\n")
fmt.Printf("-->Відповідь: Ми %v можемо купити 2 груші та 2 яблука !\n", resultInString)
print("----------------------//----------------------\n\n")
}
|
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<pre>
combineAll
</pre>
<script src="/lib/Rx5.js"></script>
<script>
//emit every 1s, take 2
//map each emitted value from source to interval observable that takes 5 values
const source = Rx.Observable
.interval(1000)
.do((x)=>log(x, 'pink'))
.take(2);
const example = source.map(val =>
Rx.Observable
.interval(1000)
.map(i => `val=${val}: i=${i}`)
.do((x)=>log(x, 'blue'))
.take(5));
/*
2 values from source will map to 2 (inner) interval observables that emit every 1s
combineAll uses combineLatest strategy, emitting the last value from each
whenever either observable emits a value
*/
const combined = example.combineAll();
/*
output:
["Result (0): 0", "Result (1): 0"]
["Result (0): 1", "Result (1): 0"]
["Result (0): 1", "Result (1): 1"]
["Result (0): 2", "Result (1): 1"]
["Result (0): 2", "Result (1): 2"]
["Result (0): 3", "Result (1): 2"]
["Result (0): 3", "Result (1): 3"]
["Result (0): 4", "Result (1): 3"]
["Result (0): 4", "Result (1): 4"]
*/
const subscribe = combined.subscribe(val => console.log(val));
</script>
</body>
</html>
|
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.List,br.com.alura.gerenciador.modelo.Empresa"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE hmtl>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Java Standard Taglib</title>
</head>
<body>
<c:import url="logout-parcial.jsp"/>
Usuario Logado: ${usuarioLogado.login }
<br>
<br>
<br>
<c:if test="${not empty empresas}">
Empresa ${ empresa } cadastrada com sucesso! <fmt:formatDate value="${data}" pattern="dd/MM/yyyy" />
</c:if>
<c:if test="${empty empresas}">
Nenhuma empresa cadastrada!
</c:if>
<br/>
<br/>
<a href="/gerenciador/entrada?acao=NovaEmpresaForm"><button style="background: #069cc2;
border-radius: 4px; padding: 6px; cursor: pointer;
color: #fff; border: none; font-size: 16px;">Cadastro Nova Empresa</button></a>
<br/>
<br/>
Lista de empresas:<br/>
<ul>
<c:forEach items="${empresas}" var="empresa">
<li>
${empresa.id} - ${empresa.nome} - <fmt:formatDate value="${empresa.dataAbertura}" pattern="dd/MM/yyyy"/>
<a href="/gerenciador/entrada?acao=MostraEmpresa&id=${empresa.id}">Editar</a>
<a href="/gerenciador/entrada?acao=RemovaEmpresa&id=${empresa.id}">Remove</a>
</li>
</c:forEach>
<%-- <c:forEach var="i" begin="1" end="10" step="2"> --%>
<%-- ${i} <br /> --%>
<%-- </c:forEach> --%>
</ul>
</body>
</html>
|
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdbool.h>
// A HELPFUL PREPROCESSOR MACRO TO CHECK IF ALLOCATIONS WERE SUCCESSFUL
#define CHECK_ALLOC(p) if(p == NULL) { perror(__func__); exit(EXIT_FAILURE); }
// OUR SIMPLE LIST DATATYPE - A DATA ITEM, AND A POINTER TO ANOTHER LIST
typedef struct _list {
char *fname;
char *fhash;
int size;
struct _list *next;
} LIST;
// DECLARE GLOBAL FUNCTIONS
extern char *strSHA2(char *filename);
// THESE FUNCTIONS ARE DECLARED HERE, AND DEFINED IN list.c :
// 'CREATE' A NEW, EMPTY LIST
extern LIST *list_new(void);
// ADD A NEW (STRING) ITEM TO AN EXISTING LIST
extern LIST *list_add(LIST *, char *, char *);
// DETERMINE IF A REQUIRED ITEM (A STRING) IS STORED IN A GIVEN LIST
extern bool list_find (LIST *, char *, char *);
// PRINT EACH ITEM (A STRING) IN A GIVEN LIST TO stdout
extern void list_print(LIST *);
// WE DEFINE A HASHTABLE AS A (WILL BE, DYNAMICALLY ALLOCATED) ARRAY OF LISTs
typedef LIST * HASHTABLE;
// THESE FUNCTIONS ARE DECLARED HERE, AND DEFINED IN hashtable.c :
// ALLOCATE SPACE FOR A NEW HASHTABLE (AND ARRAY OF LISTS)
extern HASHTABLE *hashtable_new(void);
// ADD A NEW STRING TO A GIVEN HASHTABLE
extern void hashtable_add( HASHTABLE *, char *);
// DETERMINE IF A REQUIRED STRING ALREADY EXISTS IN A GIVEN HASHTABLE
extern bool hashtable_find(HASHTABLE *, char *);
|
/* eslint-disable react/prop-types */
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { toggleStoryBookmark, toggleStoryLike } from "../../../api/story.js";
import { AuthContext } from "../../../contexts/AuthContexts.jsx";
import { ModalContext } from "../../../contexts/ModalContexts.jsx";
import { StoryContext } from "../../../contexts/StoryContexts.jsx";
import SignInForm from "../../forms/signin/SignInForm.jsx";
import styles from "./StorySlider.module.css";
const StorySlider = ({ story }) => {
const location = useLocation();
const navigate = useNavigate();
const { setStories } = React.useContext(StoryContext);
const { toggleModal, changeModalContent } = React.useContext(ModalContext);
const { isAuthenticated, user } = React.useContext(AuthContext);
const [currentSlide, setCurrentSlide] = React.useState(0);
const [isBookmarked, setIsBookmarked] = React.useState(story?.isBookmarked);
const [isLiked, setIsLiked] = React.useState(story?.isLiked);
const [likeCount, setLikeCount] = React.useState(story?.likes?.length);
const handlePrevious = () => {
setCurrentSlide((prev) => (prev === 0 ? prev : prev - 1));
};
const handleNext = () => {
setCurrentSlide((prev) =>
prev === story.slides?.length - 1 ? prev : prev + 1
);
};
const handleModalClose = () => {
if (location.pathname === `/${story._id}`) {
navigate("/");
} else {
toggleModal();
}
};
const handleShare = () => {
navigator.clipboard
.writeText(window.location.href + story._id)
.then(() => {
toast.success("URL copied to clipboard");
})
.catch(() => {
toast.error("Failed to copy URL");
});
};
const handleBookmark = async () => {
if (isAuthenticated) {
const response = await toggleStoryBookmark(story._id);
if (response?.success) {
setIsBookmarked((prev) => !prev);
toast.success("Successfully toggled bookmark");
setStories((prev) => {
const updataedStories = prev.map((prevStory) => {
if (prevStory?._id === story?._id) {
return {
...prevStory,
isBookmarked: !prevStory.isBookmarked,
};
}
});
return updataedStories;
});
} else {
toast.error(response?.message);
}
} else {
changeModalContent(<SignInForm />);
}
};
const handleLike = async () => {
if (isAuthenticated) {
const response = await toggleStoryLike(story._id);
if (response?.success) {
setIsLiked((prev) => !prev);
setLikeCount((prev) => (isLiked ? prev - 1 : prev + 1));
setStories((prev) => {
const updatedStories = prev.map((prevStory) => {
if (prevStory?._id === story?._id) {
return {
...prevStory,
isLiked: !prevStory.isLiked,
likes: isLiked
? prevStory.likes.filter((like) => like !== user._id)
: [...prevStory.likes, user._id],
};
} else {
return prevStory;
}
});
return updatedStories;
});
toast.success("Successfully toggled like");
} else {
toast.error(response?.message);
}
} else {
changeModalContent(<SignInForm />);
}
};
React.useEffect(() => {
const interval = setInterval(() => {
setCurrentSlide((prev) =>
prev === story?.slides?.length - 1 ? prev : prev + 1
);
}, 1500);
return () => clearInterval(interval);
}, [currentSlide, story?.slides?.length]);
React.useEffect(() => {
setIsBookmarked(story?.isBookmarked);
setIsLiked(story?.isLiked);
setLikeCount(story?.likes?.length);
}, [story]);
return (
<div className={styles.storySliderWrapper}>
<div className={styles.storySlider}>
{story?.slides?.map((slide, index) => (
<div
key={index}
style={{
width: "100%",
height: "100%",
position: "absolute",
top: "0",
left: `${index * 100}%`,
transition: "left 0.5s",
transform: `translateX(-${currentSlide * 100}%)`,
}}
>
<img
src={slide.imageUrl}
alt={slide.heading}
className={styles.slideImage}
/>
<div className={styles.slideContentWrapper}>
<h2>{slide.heading}</h2>
<p>{slide.description}</p>
</div>
</div>
))}
<button
className={`${styles.closeBtn} ${styles.btn}`}
onClick={handleModalClose}
>
<img src='/assets/icons/cross.svg' alt='close icon' />
</button>
<button
className={`${styles.shareBtn} ${styles.btn}`}
onClick={handleShare}
>
<img src='/assets/icons/share.svg' alt='share icon' />
</button>
<button
className={`${styles.bookmarkBtn} ${styles.btn}`}
onClick={handleBookmark}
>
<img
src={`/assets/icons/${
isBookmarked ? "bookmark-filled" : "bookmark"
}.svg`}
alt='bookmark icon'
/>
</button>
<button
className={`${styles.likeBtn} ${styles.btn}`}
onClick={handleLike}
>
<img
src={`assets/icons/${isLiked ? "like-filled" : "like"}.svg`}
alt='like icon'
/>
<span>{likeCount}</span>
</button>
</div>
<div className={styles.slideIndicatorWrapper}>
{story?.slides?.map((slide, index) => (
<div
key={slide._id}
style={{
width: `${100 / story.slides.length}%`,
height: "0.2rem",
background: index === currentSlide ? "#fff" : "#aaa",
animation: `${styles.progress} 5s infinite`,
animationDelay: `${index * 0.5}s`,
}}
></div>
))}
</div>
<div className={styles.storySliderControls}>
<button onClick={handlePrevious} className={styles.previousBtn}>
<img src='/assets/icons/left-chevron.svg' alt='previous' />
</button>
<button onClick={handleNext} className={styles.nextBtn}>
<img src='/assets/icons/right-chevron.svg' alt='next' />
</button>
</div>
</div>
);
};
export default StorySlider;
|
import {
Divider,
Drawer,
IconButton,
List,
ListItem,
ListItemIcon,
ListItemText,
Box,
Typography,
Tooltip,
Menu,
MenuItem,
Badge,
} from "@mui/material";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import Link from "next/link";
import { useRouter } from "next/router";
import { useState, useContext, useEffect } from "react";
import { MENU_LIST_ITEMS } from "../../constants/menu-items";
import { drawerWidth } from "../../styles/theme";
import { ProfileContext } from "../../context/ProfileContext";
import { AuthContext } from "../../context/AuthContext";
import ThemeToggler from "../../components/ThemeToggler";
import MenuIcon from "@mui/icons-material/Menu";
import { AvatarIcon } from "../../components/AvatarIcon";
import { ErrorDialogContext } from "../../context/ErrorDialogContext";
import { LoadingContext } from "../../context/LoadingContext";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import AccountBoxIcon from "@mui/icons-material/AccountBox";
import ReplayIcon from "@mui/icons-material/Replay";
import NotificationsIcon from "@mui/icons-material/Notifications";
import { NoticeCountContext } from "../../context/NoticeCountContext";
import AppsIcon from "@mui/icons-material/Apps";
interface SideBarProps {
open: boolean;
handleDrawerToggle: () => void;
}
const Sidebar = ({ open, handleDrawerToggle }: SideBarProps): JSX.Element => {
const { profile, dispatchProfile } = useContext(ProfileContext);
const { account, dispatchAccount } = useContext(AuthContext);
const { loading, dispatchLoading } = useContext(LoadingContext);
const { errorDialog, dispatchErrorDialog } = useContext(ErrorDialogContext);
const [accounts, setAccounts] = useState([]);
const [avatarMenuAnchor, setAvatarMenuAnchor] = useState(null);
const avatarOpen = Boolean(avatarMenuAnchor);
const { noticeCount, dispatchNoticeCount } = useContext(NoticeCountContext);
const handleAvatarIconButton = (event) => {
setAvatarMenuAnchor(event.currentTarget);
};
const handleAvatarMenuClose = () => {
setAvatarMenuAnchor(null);
};
const router = useRouter();
const [selectedIndex, setSelectedIndex] = useState(0);
const initialSelection = () => {
let index = MENU_LIST_ITEMS.findIndex((el) => el.route === router.pathname);
if (index !== -1) {
setSelectedIndex(index + 2);
return;
}
switch (router.pathname) {
case "/notices":
index = 1;
break;
case "/profile":
index = 2;
break;
case "/users/[did]":
index = 2;
break;
default:
index = 0;
}
setSelectedIndex(index);
};
const openMixin = (theme) => ({
width: drawerWidth,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
});
const closeMixin = (theme) => ({
width: `calc(${theme.spacing(7)} + 1px)`,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
});
useEffect(() => {
let arrAccount = JSON.parse(localStorage.getItem("accounts"));
setAccounts(arrAccount ?? []);
initialSelection();
}, []);
const storeWalletConnect = () => {
const wcJson = localStorage.getItem("walletconnect");
if (!Boolean(wcJson) || !Boolean(account?.selfId?.id)) return;
localStorage.setItem(`walletconnect-${account.selfId.id}`, wcJson);
};
const handleChangeAccount = async (item) => {
const loadingMsg = "アカウント切替中...";
dispatchLoading({ type: "add", payload: loadingMsg });
try {
storeWalletConnect();
let arrAccount = JSON.parse(localStorage.getItem("accounts"));
if (!Boolean(arrAccount)) arrAccount = [];
arrAccount = arrAccount.filter(
(storedItem) => storedItem.did !== item.did
);
arrAccount.push({
name: profile?.name,
did: account.selfId.id,
avatar: profile?.avatar,
});
localStorage.setItem("accounts", JSON.stringify(arrAccount));
setAccounts(arrAccount ?? []);
const targetWcJson = localStorage.getItem(`walletconnect-${item.did}`);
if (!Boolean(targetWcJson)) {
throw "指定されたアカウント接続情報がありません";
}
localStorage.setItem("walletconnect", targetWcJson);
await account.authenticate(false);
} catch (e) {
dispatchErrorDialog({
type: "open",
payload: e,
});
} finally {
dispatchLoading({ type: "remove", payload: loadingMsg });
location.reload();
}
};
const handleAddAccount = async () => {
storeWalletConnect();
let arrAccount = JSON.parse(localStorage.getItem("accounts"));
if (!Boolean(arrAccount)) arrAccount = [];
arrAccount.push({
name: profile?.name,
did: account.selfId.id,
avatar: profile?.avatar,
});
localStorage.setItem("accounts", JSON.stringify(arrAccount));
setAccounts(arrAccount ?? []);
await account.authenticate(true);
location.reload();
};
const handleReload = () => {
location.reload();
};
return (
<Drawer
variant="permanent"
sx={(theme) => ({
position: "relative",
whiteSpace: "nowrap",
overflowX: "hidden",
...(open && {
...openMixin(theme),
}),
...(!open && {
...closeMixin(theme),
}),
})}
PaperProps={{
sx: {
overflowY: "unset",
position: "static",
backgroundColor: (theme) => theme.palette.primary.main,
},
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "flex-start",
marginLeft: (theme) => theme.spacing(1),
}}
>
<IconButton
sx={{ color: (theme) => theme.palette.primary.contrastText }}
onClick={handleDrawerToggle}
>
{!open ? (
<MenuIcon />
) : (
<ChevronLeftIcon
sx={{ color: (theme) => theme.palette.primary.light }}
/>
)}
</IconButton>
</Box>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "5px",
marginBottom: "5px",
}}
>
<Tooltip title="アカウント切り替え">
<IconButton
onClick={handleAvatarIconButton}
aria-controls={open ? "account-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
>
<AvatarIcon src={profile?.avatar} />
</IconButton>
</Tooltip>
<Typography
variant="h6"
component="span"
sx={{
margin: "0 5px",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
color: (theme) => theme.palette.primary.contrastText,
}}
>
{profile?.name}
</Typography>
</Box>
<Menu
anchorEl={avatarMenuAnchor}
id="account-menu"
open={avatarOpen}
onClose={handleAvatarMenuClose}
onClick={handleAvatarMenuClose}
PaperProps={{
elevation: 0,
sx: {
overflow: "visible",
filter: "drop-shadow(0px 2px 8px rgba(0,0,0,0.32))",
mt: 1.5,
"&:before": {
content: '""',
display: "block",
position: "absolute",
top: 0,
right: 14,
width: 10,
height: 10,
bgcolor: "background.paper",
transform: "translateY(-50%) rotate(45deg)",
zIndex: 0,
},
},
}}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
>
{accounts.map((item) => (
<MenuItem key={item.did} onClick={(e) => handleChangeAccount(item)}>
<AvatarIcon src={item.avatar} />
<Typography
variant="h6"
component="span"
sx={{
textOverflow: "ellipsis",
whiteSpace: "nowrap",
color: (theme) => theme.palette.primary.main,
}}
>
{item.name}
</Typography>
</MenuItem>
))}
<MenuItem>
<IconButton onClick={handleAddAccount}>
<AddCircleOutlineIcon
sx={{
color: (theme) => theme.palette.primary.light,
}}
/>
</IconButton>
</MenuItem>
</Menu>
</Box>
<Divider />
<List sx={{ padding: 0 }}>
<Link href="/">
<ListItem
button
selected={selectedIndex === 0}
onClick={() => setSelectedIndex(0)}
sx={{
backgroundColor: (theme) => theme.palette.primary.main,
"&.Mui-selected": {
backgroundColor: (theme) => theme.palette.primary.light,
},
}}
>
<ListItemIcon
sx={{
color: (theme) =>
selectedIndex == 0
? theme.palette.primary.contrastText
: theme.palette.primary.light,
}}
>
<AppsIcon />
</ListItemIcon>
<ListItemText
primary="HOME"
primaryTypographyProps={{ variant: "subtitle1" }}
sx={{
color: (theme) =>
selectedIndex === 0
? theme.palette.primary.contrastText
: theme.palette.primary.light,
primary: (theme) => ({ ...theme.typography.h6 }),
}}
/>
</ListItem>
</Link>
<Link href="/notices">
<ListItem
button
selected={selectedIndex === 1}
onClick={() => setSelectedIndex(1)}
sx={{
backgroundColor: (theme) => theme.palette.primary.main,
"&.Mui-selected": {
backgroundColor: (theme) => theme.palette.primary.light,
},
}}
>
<ListItemIcon
sx={{
color: (theme) =>
selectedIndex === 1
? theme.palette.primary.contrastText
: theme.palette.primary.light,
}}
>
<Badge badgeContent={noticeCount} color="error">
<NotificationsIcon />
</Badge>
</ListItemIcon>
<ListItemText
primary="NOTICE"
primaryTypographyProps={{ variant: "subtitle1" }}
sx={{
color: (theme) =>
selectedIndex === 1
? theme.palette.primary.contrastText
: theme.palette.primary.light,
primary: (theme) => ({ ...theme.typography.h6 }),
}}
/>
</ListItem>
</Link>
<Link href={`/users/${account?.selfId?.id}`}>
<ListItem
button
selected={selectedIndex === 2}
onClick={() => setSelectedIndex(2)}
sx={{
backgroundColor: (theme) => theme.palette.primary.main,
"&.Mui-selected": {
backgroundColor: (theme) => theme.palette.primary.light,
},
}}
>
<ListItemIcon
sx={{
color: (theme) =>
selectedIndex === 2
? theme.palette.primary.contrastText
: theme.palette.primary.light,
}}
>
<AccountBoxIcon />
</ListItemIcon>
<ListItemText
primary="PROFILE"
primaryTypographyProps={{ variant: "subtitle1" }}
sx={{
color: (theme) =>
selectedIndex === 2
? theme.palette.primary.contrastText
: theme.palette.primary.light,
primary: (theme) => ({ ...theme.typography.h6 }),
}}
/>
</ListItem>
</Link>
{MENU_LIST_ITEMS.map(({ route, Icon, name }, id) => (
// eslint-disable-next-line @next/next/link-passhref
<Link href={route} key={id + 3}>
<ListItem
button
selected={id + 3 === selectedIndex}
onClick={() => setSelectedIndex(id + 3)}
sx={{
backgroundColor: (theme) => theme.palette.primary.main,
"&.Mui-selected": {
backgroundColor: (theme) => theme.palette.primary.light,
},
}}
>
<ListItemIcon
sx={{
color: (theme) =>
id + 3 === selectedIndex
? theme.palette.primary.contrastText
: theme.palette.primary.light,
}}
>
<Icon />
</ListItemIcon>
<ListItemText
primary={name}
primaryTypographyProps={{ variant: "subtitle1" }}
sx={{
color: (theme) =>
id + 3 === selectedIndex
? theme.palette.primary.contrastText
: theme.palette.primary.light,
primary: (theme) => ({ ...theme.typography.h6 }),
}}
/>
</ListItem>
</Link>
))}
</List>
<Divider />
{router.pathname !== "/" && (
<Box
sx={{
position: "absolute",
bottom: (theme) => theme.spacing(13),
left: "3px",
}}
>
<IconButton
onClick={() => router.back()}
size="large"
sx={{
color: (theme) => theme.palette.primary.contrastText,
}}
>
<ArrowBackIcon />
</IconButton>
</Box>
)}
<Box
sx={{
position: "absolute",
bottom: (theme) => theme.spacing(8),
left: "3px",
}}
>
<IconButton
onClick={() => handleReload()}
size="large"
sx={{
color: (theme) => theme.palette.primary.contrastText,
}}
>
<ReplayIcon />
</IconButton>
</Box>
<Box
sx={{
position: "absolute",
bottom: (theme) => theme.spacing(2),
}}
>
<ThemeToggler />
</Box>
</Drawer>
);
};
export default Sidebar;
|
import React from 'react'
import { formatTime, transformDecimals } from '#helpers/transform'
import { useCity } from '#city/hook'
import { IconPlastic } from '#ui/icon/plastic'
import { IconMushroom } from '#ui/icon/mushroom'
import { ResourceItem } from '#ui/resource-item'
import { IconDuration } from '#ui/icon/duration'
interface Props {
plastic: number
mushroom: number
duration: number
action?: React.ReactNode
}
export const Cost: React.FC<Props> = ({ plastic, mushroom, duration, action }) => {
const { city } = useCity()
const plasticClassName = plastic > (city?.plastic ?? 0) ? 'danger' : 'success'
const mushroomClassName = mushroom > (city?.mushroom ?? 0) ? 'danger' : 'success'
return <div>
<h3>Coût</h3>
<ul>
<li>
<ResourceItem
className={plasticClassName}
icon={<IconPlastic /> }
value={transformDecimals(plastic)}
/>
</li>
<li>
<ResourceItem className={mushroomClassName}
icon={<IconMushroom />}
value={transformDecimals(mushroom)}
/>
</li>
<li>
<ResourceItem
icon={<IconDuration />}
value={formatTime(duration)}
/>
</li>
</ul>
{action}
</div>
}
|
'''
Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares ' '.
The first player always places 'X' characters, while the second player always places 'O' characters.
'X' and 'O' characters are always placed into empty squares, never filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
Input: board = ["O "," "," "]
Output: false
Explanation: The first player always plays "X".
Example 2:
Input: board = ["XOX"," X "," "]
Output: false
Explanation: Players take turns making moves.
Example 3:
Input: board = ["XOX","O O","XOX"]
Output: true
Constraints:
board.length == 3
board[i].length == 3
board[i][j] is either 'X', 'O', or ' '.
'''
from typing import *
import unittest
class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
count_x = 0
count_y = 0
for s in board:
count_x += s.count('X')
count_y += s.count('O')
def game_over(symbol):
for s in board:
if s[0] == symbol and s[1] == symbol and s[2] == symbol:
return True
for i in range(len(board[0])):
if board[0][i] == symbol and board[1][i] == symbol and board[2][i] == symbol:
return True
if (board[0][0] == symbol and board[1][1] == symbol and board[2][2] == symbol) or \
(board[0][2] == symbol and board[1][1] == symbol and board[2][0] == symbol):
return True
return False
if count_x == count_y:
if game_over('X'):
return False
return True
elif count_x == count_y + 1:
if game_over('O'):
return False
return True
else:
return False
class TestSolution(unittest.TestCase):
def test_case(self):
examples = (
((["XOX"," X "," "],),False),
)
for first, second in examples:
self.assert_function(first, second)
def assert_function(self, first, second):
self.assertEqual(Solution().validTicTacToe(*first), second,
msg="first: {}; second: {}".format(first, second))
unittest.main()
|
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {TeamModelForm} from "../../../core/forms/team/team-model-form";
import {FileInterface} from "../../../core/interfaces/file/file.interface";
import {FileService} from "../../../core/services/image/file.service";
import {Observable, of, switchMap} from "rxjs";
import {TeamsService} from "../../../core/services/teams/teams.service";
import {ICreateTeam, IUpdateTeam, TeamDto} from "../../../core/interfaces/teams/team-interface";
import {ActivatedRoute, Router} from "@angular/router";
import {error} from "@angular/compiler-cli/src/transformers/util";
import {NotificationService} from "../../../core/services/notification/notification.service";
@Component({
selector: 'app-team-new',
templateUrl: './team-new.component.html',
styleUrls: ['./team-new.component.scss']
})
export class TeamNewComponent implements OnInit {
@ViewChild('fileInput') fileInput!: ElementRef;
teamForm: FormGroup<TeamModelForm> = this._fb.group<TeamModelForm>({
name: new FormControl('', Validators.required),
division: new FormControl('', Validators.required),
conference: new FormControl('', Validators.required),
foundationYear: new FormControl(null, [Validators.required, Validators.minLength(4), Validators.maxLength(4), Validators.min(1900), Validators.max(new Date().getFullYear())]),
imageToSend: new FormControl('', Validators.required),
imageToView: new FormControl(''),
});
maxSize = 1 * 1024 * 1024;
viewFiles: Array<FileInterface> = [];
team: TeamDto;
id: number;
breadcrumb: string = '';
isSubmitted: boolean = false;
imageValidationError: boolean = false;
constructor(private _fb: FormBuilder,
public fileService: FileService,
private teamsService: TeamsService,
private router: ActivatedRoute,
private route: Router,
private notify: NotificationService) {
}
ngOnInit() {
if (this.router.snapshot.routeConfig?.path !== 'new') {
this.id = this.router.snapshot.params['id'];
this.getTeamById(this.id);
}
}
updateForm(): void {
this.teamForm.setValue({
name: this.team.name,
division: this.team.division,
conference: this.team.conference,
foundationYear: this.team.foundationYear,
imageToSend: this.team.imageUrl,
imageToView: this.team.imageUrl
});
}
getTeamById(id: number) {
this.teamsService.getTeamById(id).then(x => {
this.team = x;
this.updateForm();
})
}
openChooseFile(): void {
this.fileInput.nativeElement.click();
}
onFileSelected(event: any) {
const input = event.target as HTMLInputElement;
const files: Array<File> = [];
for (let i = 0; i < input.files?.length!; i++) {
files.push(input.files?.item(i)!);
}
if (files.some(file => file.size > this.maxSize)) {
this.validateImage();
this.notify.showError('The image file size is over 1MB.');
} else if (files.some(file => file.type !== 'image/png' && file.type !== 'image/jpeg' && file.type !== 'image/jpg' && file.type !== 'image/svg' && file.type !== 'image/ico')) {
this.validateImage();
this.notify.showError('Invalid file format.');
} else if (files && files.length > 0 && files.every(x => x.size <= this.maxSize)) {
this.imageValidationError = false;
this.handleFiles(files);
}
}
handleFiles(files: Array<File>) {
files.forEach((file: File) => {
const reader = new FileReader();
reader.onload = (e: ProgressEvent<FileReader>) => {
if (e.target && e.target.result) {
const image = e.target.result as string;
const sizeInMB = this.bytesToMB(file.size);
if (!this.viewFiles.find(x => x.name == file.name)) {
this.viewFiles = [];
this.viewFiles.push(
{
fileToSend: file,
name: file.name.replace(/\s/g, ''),
size: sizeInMB,
urlToShow: image,
type: file.type,
});
this.imageValidationError = false;
this.teamForm.controls.imageToView.patchValue(image);
} else {
this.imageValidationError = true;
}
}
};
reader.readAsDataURL(file);
})
this.fileInput.nativeElement.value = null;
}
bytesToMB(bytes: number): string {
const mb = bytes / (1024 * 1024);
return mb.toFixed(2) + ' MB';
}
saveImage(): Observable<string> {
return this.fileService.saveImage(this.viewFiles[0].fileToSend!)
}
saveChanges(): void {
this.isSubmitted = true;
if (this.teamForm.controls.imageToView.value && this.teamForm.controls.imageToView.value?.length > 0 && !this.imageValidationError)
this.buildRequest().subscribe({
next: response => {
if (response) {
this.notify.showSuccess(this.id ? 'Team successfully edited' : 'Team successfully created')
this.teamsService.refreshTeamsList();
this.route.navigate(['/teams']);
}
},
error: error => {
this.notify.showError(error.error)
}
})
}
buildRequest(): Observable<TeamDto> {
if (this.viewFiles.length > 0) {
return this.saveImage()
.pipe(
switchMap((imageUrl: string) => {
this.teamForm.controls.imageToSend.patchValue(imageUrl);
if (this.teamForm.valid)
return this.id ? this.teamsService.updateTeam(this.createModel()) : this.teamsService.createTeam(this.createModel());
else return of();
})
);
} else
return this.id ? this.teamsService.updateTeam(this.createModel()) : this.teamsService.createTeam(this.createModel());
}
createModel(): ICreateTeam | IUpdateTeam {
return {
name: this.teamForm.value.name,
division: this.teamForm.value.division,
conference: this.teamForm.value.conference,
foundationYear: this.teamForm.value.foundationYear,
imageUrl: this.teamForm.value.imageToSend,
[this.id ? 'id' : '']: this.id
}
}
validateImage(): void {
this.viewFiles = [];
this.teamForm.controls.imageToView.patchValue(null);
this.teamForm.controls.imageToSend.patchValue(null);
this.imageValidationError = true;
}
}
|
<?php
namespace core\lib\cloud;
use app\service\sys\ConfigService;
use app\service\core\niucloud\ConfigCloudService;
use Closure;
use core\exception\NiucloudException;
use core\lib\cloud\http\AccessToken;
use core\lib\cloud\http\HasHttpRequests;
use core\lib\cloud\http\Token;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* 云请求基类
* Class BaseCloudClient
* @package core\lib\cloud
*/
class BaseCloudClient
{
use HasHttpRequests;
use AccessToken;
use Token;
/**
* 授权码
* @var mixed|string
*/
protected $code;
/**
* 授权秘钥
* @var mixed|string
*/
protected $secret;
/**
* 开发者令牌
* @var
*/
protected $developer_token;
protected $config;
const PRODUCT = 'saas';
/**
*官网服务主域名
* @var string
*/
protected string $baseUri = 'https://api.cloud.com/openapi/';
/**
*
* @var \think\facade\Request|\think\Request
*/
protected $request;
/**
* @param string $code
* @param string $secret
*/
public function __construct(string $code = '', string $secret = '')
{
if($code || $secret){
$this->code = $code;
$this->secret = $secret;
}else{
$auth_config = (new ConfigCloudService())->getNiucloudConfig();
if($auth_config['auth_code'] || $auth_config['auth_secret']){
$this->code = $auth_config['auth_code'];
$this->secret = $auth_config['auth_secret'];
}else{
$this->code = config('cloud.auth.code');
$this->secret = config('cloud.auth.secret');
}
}
$this->access_token = $this->getAccessToken();
$this->request = request();
$this->developer_token = (new ConfigCloudService())->getDeveloperToken()['token'] ?? '';
}
/**
* @param string $url
* @param array $data
* @return array|Response|object|ResponseInterface
* @throws GuzzleException
*/
public function httpPost(string $url, array $data = [])
{
return $this->request($url, 'POST', [
'form_params' => $data,
]);
}
/**
* @param string $url
* @param string $method
* @param array $options
* @param bool $returnRaw
*
* @return ResponseInterface
* @throws GuzzleException
*/
public function request(string $url, string $method = 'GET', array $options = [], bool $returnRaw = false)
{
if (empty($this->middlewares)) {
$this->registerHttpMiddlewares();
}
$response = $this->toRequest($url, $method, $options);
return $response;
}
/**
* Register Guzzle middlewares.
*/
protected function registerHttpMiddlewares()
{
// retry
$this->pushMiddleware($this->retryMiddleware(), 'retry');
//header
$this->pushMiddleware($this->headerMiddleware(), 'header');
// access token
$this->pushMiddleware($this->accessTokenMiddleware(), 'access_token');
}
/**
* @return callable
*/
protected function retryMiddleware()
{
return Middleware::retry(
function (
$retries,
RequestInterface $request,
ResponseInterface $response = null
) {
// Limit the number of retries to 2 重试次数,默认 1,指定当 http 请求失败时重试的次数。
if ($retries < config('cloud.http.max_retries', 1) && $response && $body = $response->getBody()) {
// Retry on server errors
$response = json_decode($body, true);
if (isset($response['code'])) {
if ($response['code'] != 1) {
if (in_array(abs($response['code']), [401], true)) {
$this->clearAccessToken();
$this->refreshAccessToken();
} else {
throw new NiucloudException($response['msg']);
}
}
return true;
}
}
return false;
},
function () {
//重试延迟间隔(单位:ms),默认 500
return abs(config('cloud.http.retry_delay', 500));
}
);
}
/**
* 表头属性
* @return Closure
*/
public function headerMiddleware(){
$developer_token = $this->developer_token;
return function (callable $handler) use ($developer_token) {
return function (RequestInterface $request, array $options) use ($handler, $developer_token) {
$domain = request()->domain(true);
$domain = str_replace('http://', '', $domain);
$domain = str_replace('https://', '', $domain);
$request = $request->withHeader('Referer', $domain);
$request = $request->withHeader('developer-token', $developer_token);
$options['verify'] = config('cloud.http.verify', true);
return $handler($request, $options);
};
};
}
/**
* @param string $url
* @param array $query
* @return array|object|Response|ResponseInterface
* @throws GuzzleException
*/
public function httpGet(string $url, array $query = [])
{
return $this->request($url, 'GET', [
'query' => $query,
]);
}
/**
* @return Closure
*/
protected function accessTokenMiddleware()
{
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
if ($this->access_token) {
$request = $this->applyToRequest($request, $options);
}
return $handler($request, $options);
};
};
}
/**
* @param RequestInterface $request
* @param array $requestOptions
* @return RequestInterface
*/
public function applyToRequest(RequestInterface $request, array $requestOptions = []): RequestInterface
{
return $request->withHeader($this->access_token_key, $this->access_token);
}
/**
* @param string $url
* @param array $data
* @param array $query
* @return array|Response|object|ResponseInterface
* @throws GuzzleException
*/
public function httpPostJson(string $url, array $data = [], array $query = [])
{
return $this->request($url, 'POST', ['query' => $query, 'json' => $data]);
}
/**
* @param string $url
* @param array $files
* @param array $form
* @param array $query
* @return array|Response|object|ResponseInterface
* @throws GuzzleException
*/
public function httpUpload(string $url, array $files = [], array $form = [], array $query = [])
{
$multipart = [];
$headers = [];
if (isset($form['filename'])) {
$headers = [
'Content-Disposition' => 'form-data; name="media"; filename="' . $form['filename'] . '"'
];
}
foreach ($files as $name => $path) {
$multipart[] = [
'name' => $name,
'contents' => fopen($path, 'r'),
'headers' => $headers
];
}
foreach ($form as $name => $contents) {
$multipart[] = compact('name', 'contents');
}
return $this->request(
$url,
'POST',
['query' => $query, 'multipart' => $multipart, 'connect_timeout' => 30, 'timeout' => 30, 'read_timeout' => 30]
);
}
/**
* @param string $url
* @param string $method
* @param array $options
* @throws GuzzleException
*/
public function requestRaw(string $url, string $method = 'GET', array $options = [])
{
return Response::buildFromPsrResponse($this->request($url, $method, $options, true));
}
/**
* 下载文件
* @param string $url
* @param array $query
* @param string $absolute_path
* @return string
* @throws GuzzleException
*/
public function download(string $url, array $query = [], string $absolute_path = '')
{
// 打开即将下载的本地文件,在该文件上打开一个流
$resource = fopen($absolute_path, 'w');
$res = $this->request($url, 'GET', ['sink' => $absolute_path, 'query' => $query]);
// 关闭一个已打开的文件指针
fclose($resource);
return $absolute_path;
}
public function getDomain($is_filter = true){
$domain = request()->domain(true);
if($is_filter){
$domain = str_replace('http://', '', $domain);
$domain = str_replace('https://', '', $domain);
}
return $domain;
}
}
|
import { CoffeType } from "../types";
export default function Coffee ({ coffee }: { coffee: CoffeType }) {
const { image, popular, name, votes, rating, available, price } = coffee
return (
<div className="my-5 scale-90">
<div className="relative">
<img src={image} width={300} height={185} className="rounded-2xl" alt="coffe image" />
{popular ? <span className="absolute top-3 left-3 font-bold text-sm px-4 py-1 bg-[#F6C768] text-[#111315] rounded-2xl">Popular</span> : null}
</div>
<div className="flex justify-between mt-3">
<h4 className="text-lg font-bold tracking-wide">{name}</h4>
<p className="bg-[#BEE3CC] font-bold px-2 py-1 text-sm rounded-md text-[#1B1D1F]">{price}</p>
</div>
<div className="flex justify-between mt-1 items-center">
<div className="flex items-center gap-1">
<img width={30} src={rating ? '/assets/Star_fill.svg' : '/assets/Star.svg'} alt="rating image" />
<p className="">{rating}</p>
<p className="text-[#6F757C] font-bold">({votes} votes)</p>
</div>
{!available ? <p className="text-[#ED735D] font-bold">Sold out</p> : null}
</div>
</div>
)
}
|
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
// cons
Node(int data) {
this -> data = data;
this -> right = NULL;
this -> left = NULL;
}
};
Node* createNode(int d) {
Node* temp = new Node(d);
return temp;
}
void printInorder(Node* node){
if (node == NULL)
return;
printInorder(node -> left);
cout << node -> data << " ";
printInorder(node -> right);
}
void printPreorder(Node* node) {
if (node == NULL) {
return;
}
cout << node -> data << " ";
printPreorder(node -> left);
printPreorder(node -> right);
}
void printPostorder(Node* node) {
if (node == NULL) {
return;
}
printPreorder(node -> left);
printPreorder(node -> right);
cout << node -> data << " ";
}
int main()
{
Node* root = createNode(40);
root->left = createNode(30);
root->right = createNode(50);
root->left->left = createNode(25);
root->left->right = createNode(35);
root->left->left->left = createNode(15);
root->left->left->right = createNode(28);
root->right->left = createNode(45);
root->right->right = createNode(60);
root->right->right->left = createNode(55);
root->right->right->right = createNode(70);
cout << "Inorder traversal of binary tree is " << endl;
printInorder(root);
cout << endl;
cout << "PreOrder traversal of binary tree is " << endl;
printPreorder(root);
cout << endl;
cout << "PostOrder traversal of binary tree is " << endl;
printPostorder(root);
return 0;
}
|
package ru.wardrobe.service;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
/**
* Сервис для управления загрузкой и хранением файлов.
*/
@Service
public class FileStorageService {
private final Path fileStorageLocation;
/**
* Конструктор, инициализирующий местоположение хранилища файлов и создающий директорию, если она не существует.
*/
public FileStorageService() {
this.fileStorageLocation = Paths.get("src/main/resources/static/fileRepository").toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileStorageLocation);
} catch (Exception ex) {
throw new RuntimeException("Could not create the directory where the uploaded files will be stored.", ex);
}
}
/**
* Сохраняет загруженный файл в хранилище.
*
* @param file Загруженный файл в формате MultipartFile.
* @return Имя файла после сохранения.
*/
public String storeFile(MultipartFile file) {
String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
try {
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (Exception ex) {
throw new RuntimeException("Could not store file " + fileName + ". Please try again!", ex);
}
}
/**
* Загружает файл из хранилища как ресурс.
*
* @param fileName Имя файла для загрузки.
* @return Ресурс файла.
*/
public Resource loadFileAsResource(String fileName) {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
throw new RuntimeException("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new RuntimeException("File not found " + fileName, ex);
}
}
/**
* Удаляет файл из хранилища.
*
* @param fileName Имя файла для удаления.
*/
public void deleteFile(String fileName) {
try {
// Добавляем фильтр для игнорирования определенного имени файла
if (!fileName.equals("cappelledelcommiatofirenze.png")) {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
File file = filePath.toFile();
if (file.exists()) {
file.delete();
}
}
} catch (Exception ex) {
throw new RuntimeException("Could not delete file " + fileName, ex);
}
}
}
|
package com.sc.exam.sbb;
import com.sc.exam.sbb.answer.AnswerRepository;
import com.sc.exam.sbb.question.QuestionRepository;
import com.sc.exam.sbb.question.QuestionService;
import com.sc.exam.sbb.user.UserRepository;
import com.sc.exam.sbb.user.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class UserServiceTests {
@Autowired
private UserService userService;
@Autowired
private AnswerRepository answerRepository;
@Autowired
private QuestionRepository questionRepository;
@Autowired
private UserRepository userRepository;
@BeforeEach
void beforeEach() {
clearData();
createSampleData();
}
private void createSampleData() {
createSampleData(userService);
}
private void createSampleData(UserService userService) {
userService.create("admin", "[email protected]", "1234");
userService.create("user1", "[email protected]", "1234");
}
private void clearData() {
clearData(userRepository, answerRepository, questionRepository);
}
// 삭제 순서 : 답변 -> 질문 -> 회원
public static void clearData(UserRepository userRepository,
AnswerRepository answerRepository,
QuestionRepository questionRepository) {
answerRepository.deleteAll();
answerRepository.truncateTable();
questionRepository.deleteAll();
questionRepository.truncateTable();
userRepository.deleteAll();
userRepository.truncateTable();
}
@Test
@DisplayName("회원가입이 가능하다.")
public void t1() {
userService.create("user2", "[email protected]", "1234");
}
}
|
# Hotel Revenue Data Analysis with Power BI
This Project shows a visual data story and dashboard created using **Power BI** to present hotel revenue insights to stakeholders. We'll address the following questions through our analysis:
## 1. Is Our Hotel Revenue Growing by Year?
We'll explore the overall trend in hotel revenue over time. Since we have two hotel types, we'll also segment the revenue by hotel type. Here's a step-by-step approach to finding the solution:
1. **Data Preparation**:
- Gather historical revenue data for both hotel types.
- Clean and preprocess the data (handle missing values, outliers, etc.).
2. **Visualization**:
- Create line charts or bar graphs to visualize revenue trends over the years.
- Compare revenue growth between the two hotel types.
3. **Insights**:
- Identify any significant growth or decline in revenue.
- Analyze seasonality patterns (if any).
## 2. Should We Increase Our Parking Lot Size?
We want to understand if there's a trend in guests with personal cars. To investigate parking space requirements, follow these steps:
1. **Data Collection**:
- Collect data on guest arrivals and their mode of transportation (personal car, public transport, etc.).
2. **Analysis**:
- Calculate the percentage of guests arriving with personal cars.
- Compare this percentage over time (monthly or yearly).
3. **Recommendation**:
- If the trend shows an increasing number of guests with personal cars, consider expanding the parking lot.
## 3. What Trends Can We See in the Data?
Let's focus on the following aspects:
1. **Average Daily Rate (ADR)**:
- Visualize ADR trends over time.
- Identify any seasonal patterns (e.g., peak seasons, off-peak seasons).
2. **Guests**:
- Explore the number of guests over time.
- Look for any patterns related to events, holidays, or seasons.
Remember to create compelling visualizations using Power BI to communicate these insights effectively to stakeholders. Happy analyzing! 📊🏨
Also Used
> **SQL Sever** for database Connection
|
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
Request,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserDTO } from '../users/user-dto';
import { UsersService } from '../users/users.service';
import { Public } from '../utils/public-decorator';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(
private authService: AuthService,
private userService: UsersService,
private jwtService: JwtService,
) {}
@Public()
@HttpCode(HttpStatus.OK)
@Post('login')
async login(@Body() loginDto: Record<string, string>) {
return await this.authService.login(loginDto.username, loginDto.password);
}
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
@Get('refresh')
async refresh(@Request() req) {
const oldToken = req.headers['x-token'];
const user = await this.jwtService.verifyAsync(oldToken);
const payload = {
sub: user.sub,
username: user.username,
roles: user.roles,
};
return {
accessToken: await this.jwtService.signAsync(payload),
user: {
username: user.username,
roles: user.roles,
},
};
}
@Public()
@Post('signup')
async signup(@Body() userDto: UserDTO) {
await this.userService.singup(userDto);
return 'Successfully signed up with: ' + userDto.username;
}
}
|
Testing ``7-base_geometry`` module
Testing ``BaseGeometry`` class
------------------------------
Importing ``BaseGeometry`` class from ``7-base_geometry`` module:
::
>>> BaseGeometry = __import__("7-base_geometry").BaseGeometry
Instantiate class:
::
>>> base_g = BaseGeometry()
Call area method with no arguments:
::
>>> base_g.area()
Traceback (most recent call last):
...
Exception: area() is not implemented
Call area method with an argument:
::
>>> base_g.area(1)
Traceback (most recent call last):
...
TypeError: area() takes 1 positional argument but 2 were given
Call integer_validator with name string and integer value:
::
>>> base_g.integer_validator("age", 16)
Call integer_validator with no arguments:
::
>>> base_g.integer_validator()
Traceback (most recent call last):
...
TypeError: integer_validator() missing 2 required positional arguments: 'name' and 'value'
Call integer_validator with one argument:
::
>>> base_g.integer_validator("hey")
Traceback (most recent call last):
...
TypeError: integer_validator() missing 1 required positional argument: 'value'
Call integer_validator with non integer value:
::
>>> base_g.integer_validator("name", "john")
Traceback (most recent call last):
...
TypeError: name must be an integer
>>> base_g.integer_validator("bool", False)
Traceback (most recent call last):
...
TypeError: bool must be an integer
>>> base_g.integer_validator("float", 5.6)
Traceback (most recent call last):
...
TypeError: float must be an integer
>>> base_g.integer_validator("complex", complex(1, 1))
Traceback (most recent call last):
...
TypeError: complex must be an integer
>>> base_g.integer_validator("tuple", (1, ))
Traceback (most recent call last):
...
TypeError: tuple must be an integer
>>> base_g.integer_validator("list", [1, 2, 3, 4])
Traceback (most recent call last):
...
TypeError: list must be an integer
>>> base_g.integer_validator("dict", {"key": "value"})
Traceback (most recent call last):
...
TypeError: dict must be an integer
>>> base_g.integer_validator("set", {"hello", "world"})
Traceback (most recent call last):
...
TypeError: set must be an integer
>>> base_g.integer_validator("frozenset", frozenset(["hello", "world"]))
Traceback (most recent call last):
...
TypeError: frozenset must be an integer
>>> base_g.integer_validator("bytes", b"bytes")
Traceback (most recent call last):
...
TypeError: bytes must be an integer
>>> base_g.integer_validator("bytearrays", bytearray(b"bytes"))
Traceback (most recent call last):
...
TypeError: bytearrays must be an integer
Call integer_validator with an integer equal to 0
::
>>> base_g.integer_validator("amount", 0)
Traceback (most recent call last):
...
ValueError: amount must be greater than 0
Call integer_validator with an integer less than 0:
::
>>> base_g.integer_validator("amount", -2)
Traceback (most recent call last):
...
ValueError: amount must be greater than 0
Call integer_validator with more arguments:
::
>>> base_g.integer_validator("amount", 2, 199)
Traceback (most recent call last):
...
TypeError: integer_validator() takes 3 positional arguments but 4 were given
|
use crate::common::day::{Day, Question};
pub struct Day1;
impl Day for Day1 {
fn question(&self, input: &str, question: Question) {
let result = match question {
Question::First => q1(input),
Question::Second => q2(input),
};
println!("{}", result);
}
fn test_data(&self) -> String {
return "1000
2000
3000
4000
5000
6000
7000
8000
9000
10000"
.to_string();
}
}
fn q1(input: &str) -> i32 {
let elf_calories = get_elves(input);
let max_elf: Option<i32> = elf_calories.max();
max_elf.unwrap_or(-1)
}
fn q2(input: &str) -> i32 {
let mut elf_calories = get_elves(input).collect::<Vec<_>>();
elf_calories.sort_unstable();
elf_calories.into_iter().rev().take(3).sum()
}
fn q2_alt(input: &str) -> i32 {
let elf_calories = get_elves(input);
struct Top3 {
fst: i32,
sec: i32,
thr: i32,
}
impl Top3 {
fn sum(self) -> i32 {
self.fst + self.sec + self.thr
}
}
elf_calories
.fold(
Top3 {
fst: 0,
sec: 0,
thr: 0,
},
|top3, elf| match (elf > top3.fst, elf > top3.sec, elf > top3.thr) {
(true, _, _) => Top3 {
fst: elf,
sec: top3.fst,
thr: top3.sec,
},
(false, true, _) => Top3 {
fst: top3.fst,
sec: elf,
thr: top3.sec,
},
(false, false, true) => Top3 {
fst: top3.fst,
sec: top3.sec,
thr: elf,
},
(false, false, false) => top3,
},
)
.sum()
}
fn get_elves<'a>(input: &'a str) -> impl Iterator<Item = i32> + 'a {
let elves = input.split("\n\n");
let foods = elves.map(|elf| elf.split("\n").filter(|s| !s.is_empty()));
let elf_calories = foods.map(|lines| {
lines
.map(|line| {
line.parse::<i32>()
.map_err(|e| {
println!("Yo what {} {}", line, e);
})
.unwrap()
})
.sum()
});
elf_calories
}
|
---
title: Binary Search Tree 以及一道 LeetCode 题目
date: 2018-03-08 11:08:11
tag:
category: 开发
keywords: leetcode, leetcod 刷题
description: Binary Search Tree 以及一道 LeetCode 题目
---
### 一道LeetCode题目
今天刷一道LeetCode的题目,要求是这样的:
> Given a binary search tree and the lowest and highest boundaries as```L```and```R```, trim the tree so that all its elements lies in [```L```,```R```] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
由于对于 Binary search tree 不理解,所以绕了点弯路,要解这道题,必须理解什么是 binary search tree。我们来看一下定义:
> A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the binary search property, which states that the key in each node must be greater than or equal to any key stored in the left sub-tree, and less than or equal to any key stored in the right sub-tree.[1]:287 (The leaves (final nodes) of the tree contain no key and have no structure to distinguish them from one another.
看一下下面这个图一下子就能理解,就是说每个节点左边的值一定小于右边。

了解到这个约束,这个题目解起来就比较简单了:
```python
class Solution:
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
if(root.val < L):
if(root.right != None):
root = self.trimBST(root.right, L, R)
else:
return None
elif(root.val > R):
if(root.left != None):
root = self.trimBST(root.left, L, R)
else:
return None
else:
if(root.left != None):
root.left = self.trimBST(root.left, L, R)
else:
root.left = None
if(root.right != None):
root.right = self.trimBST(root.right, L, R)
else:
root.right = None
return root
```
### 参考资料:
1、[Leetcode](https://leetcode.com/problems/trim-a-binary-search-tree/)
2、[Wiki Binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree)
|
const router = require('express').Router();
const User = require('../Models/User');
// register new user
router.post('/users/register', async (req, res) => {
console.log(req.body);
const username = req.body.username ? req.body.username : '',
email = req.body.email ? req.body.email : '',
password = req.body.password,
message = {};
if(!username){
message.err_username = 'Username is required';
message.status = 'error';
}
if(!email){
message.err_email = 'Email is required';
message.status = 'error';
}
if(!password){
message.err_password = 'Password is required';
message.status = 'error';
}
// if(message.status === 'error'){
// req.session.messages = message;
// return res.redirect(303, '/register');
// }
User.getUserByUsername(username)
.then(user => {
if(user){
message.err_username = 'Username already exists';
message.status = 'error';
req.session.messages = message;
// return res.redirect(303, '/register');
}
User.getUserByMail(email)
.then(user => {
if(user){
message.err_email = 'Email already exists';
message.status = 'error';
req.session.messages = message;
return res.redirect(303, '/register');
}
if(message.status === 'error'){
req.session.messages = message;
return res.redirect(303, '/register');
}
User.addNewUser(username, email, password)
.then(user => {
console.log('User ' + user.username + ' has been registered');
message.success = "You have been registered successfully";
message.status = 'success';
req.session.messages = message;
return res.redirect(303, '/login');
})
})
})
.catch(err => {
console.log(err);
});
});
// login user
router.post('/users/login', (req, res) => {
const username = req.body.username ? req.body.username : '',
password = req.body.password ? req.body.password : '';
const message = {};
if(!username){
message.err_username = 'Username is required';
message.status = 'error';
}
if(!password){
message.err_password = 'Password is required';
message.status = 'error';
}
if(message.status === 'error'){
req.session.messages = message;
return res.redirect(303, '/login');
}
User.getUserByUsername(username)
.then(user => {
if(!user){
message.err_username = 'Username does not exist';
message.status = 'error';
req.session.messages = message;
return res.redirect(303, '/login');
}
const isCorrectPassword = User.comparePassword(password, user.password);
if(isCorrectPassword){
req.session.user = user.username;
message.success = 'You have been logged in successfully';
message.status = 'success';
req.session.messages = message;
return res.redirect(303, '/');
}else{
message.err_password = 'Password is incorrect';
message.status = 'error';
req.session.messages = message;
return res.redirect(303, '/login');
}
})
.catch(err => {
console.log(err);
})
});
// get user by id
router.get('/users/:userid', (req, res) => {
const userid = req.params.userid;
User.getUserById(userid)
.then(user => {
res.status(200).json(user);
})
.catch(err => {
res.status(500).json({
message: 'Error',
error: err
});
});
});
// update user password by id
router.put('/users/:userid', (req, res) => {
const userid = req.params.userid;
const password = req.body.password;
console.log(userid, password);
User.updateUserPasswordById(userid, password)
.then(() => {
return res.status(200).json({
message: 'Password has been updated'
});
})
.catch(() => {
return res.status(500).json({
message: 'Error'
});
});
});
// delete user by id
router.delete('/users/:userid', (req, res) => {
const userid = req.params.userid;
User.deleteUserById(userid)
.then(() => {
return res.status(200).json({
message: 'User has been deleted'
});
})
.catch(() => {
return res.status(500).json({
message: 'Error'
});
});
});
module.exports = router;
|
<?php
namespace Database\Seeders;
use App\Models\Category;
use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// $categories = [
// ['name'=>'Arredamento',
// 'icon'=>'fa-couch',
// 'colour'=>'#D2691E'],
// ['name'=>'Elettronica',
// 'icon'=>'fa-plug',
// 'colour'=>'#808080'],
// ['name'=>'Musica',
// 'icon'=>'fa-headphones',
// 'colour'=>'#001F3F'],
// ['name'=>'Elettrodomestici',
// 'icon'=>'fa-blender',
// 'colour'=>'#D3D3D3'],
// ['name'=>'Automobili',
// 'icon'=>'fa-car',
// 'colour'=>'#FF4500'],
// ['name'=>'Abbigliamento',
// 'icon'=>'fa-shirt',
// 'colour'=>'#191970'],
// ['name'=>'Casa',
// 'icon'=>'fa-house',
// 'colour'=>'#556B2F'],
// ['name'=>'Giardino',
// 'icon'=>'fa-leaf',
// 'colour'=>'#2E8B57'],
// ['name'=>'Sport',
// 'icon'=>'fa-dumbbell',
// 'colour'=>'#4169E1'],
// ['name'=>'Motociclette',
// 'icon'=>'fa-motorcycle',
// 'colour'=>'#2F4F4F'],
// ];
$categories = [
['name' => 'Arredamento', 'icon' => 'fa-couch', 'colour' => '#FFA07A'], // Light Salmon
['name' => 'Elettronica', 'icon' => 'fa-plug', 'colour' => '#A9A9A9'], // Dark Gray
['name' => 'Musica', 'icon' => 'fa-headphones', 'colour' => '#6495ED'], // Cornflower Blue
['name' => 'Elettrodomestici', 'icon' => 'fa-blender', 'colour' => '#D3D3D3'], // Light Gray
['name' => 'Automobili', 'icon' => 'fa-car', 'colour' => '#FF6347'], // Tomato
['name' => 'Abbigliamento', 'icon' => 'fa-shirt', 'colour' => '#1E90FF'], // Dodger Blue
['name' => 'Casa', 'icon' => 'fa-house', 'colour' => '#556B2F'], // Dark Olive Green
['name' => 'Giardino', 'icon' => 'fa-leaf', 'colour' => '#2E8B57'], // Sea Green
['name' => 'Sport', 'icon' => 'fa-dumbbell', 'colour' => '#4169E1'], // Royal Blue
['name' => 'Motociclette', 'icon' => 'fa-motorcycle', 'colour' => '#2F4F4F'], // Dark Slate Gray
];
foreach ($categories as $category){
Category::create([
'name'=>$category['name'],
'icon'=>$category['icon'],
'colour'=>$category['colour'],
]);
};
/* foreach ($icons as $icon){
Category::create([
'icon'=>$icon
]);
}; */
}
}
|
# frozen_string_literal: true
describe Inventory::Entry::Electronic do
let(:entry) do
create(
:electronic_entry,
mms_id: '9977047322103681',
portfolio_pid: '53496697910003681',
collection_id: '61496697940003681',
activation_status: Inventory::Constants::ELEC_AVAILABLE,
library_code: 'VanPeltLib',
collection: 'Nature Publishing Journals',
coverage_statement: 'Available from 1869 volume: 1 issue: 1.',
interface_name: 'Nature',
inventory_type: Inventory::Entry::ELECTRONIC
)
end
describe '#status' do
it 'returns expected status' do
expect(entry.status).to eq Inventory::Constants::ELEC_AVAILABLE
end
end
describe '#human_readable_status' do
it 'returns expected human_readable_status' do
expect(entry.human_readable_status).to eq I18n.t('alma.availability.available.electronic.status')
end
end
describe '#id' do
it 'returns expected id' do
expect(entry.id).to eq '53496697910003681'
end
end
describe '#description' do
it 'returns expected description' do
expect(entry.description).to eql 'Nature Publishing Journals'
end
end
describe '#coverage_statement' do
it 'returns expected coverage_statement' do
expect(entry.coverage_statement).to eql 'Available from 1869 volume: 1 issue: 1.'
end
end
describe '#href' do
it 'returns the expected URI' do
expect(entry.href).to eq(
"https://#{Inventory::Constants::ERESOURCE_LINK_HOST}#{Inventory::Constants::ERESOURCE_LINK_PATH}?" \
"Force_direct=true&portfolio_pid=#{entry.id}&" \
"rfr_id=#{CGI.escape(Inventory::Constants::ERESOURCE_LINK_RFR_ID)}&u.ignore_date_coverage=true"
)
end
end
describe '#location' do
it 'returns nil' do
expect(entry.location).to be_nil
end
end
describe '#policy' do
it 'returns nil' do
expect(entry.policy).to be_nil
end
end
describe '#format' do
it 'returns nil' do
expect(entry.format).to be_nil
end
end
describe '#collection_id' do
it 'returns expected value' do
expect(entry.collection_id).to eql '61496697940003681'
end
end
describe '#electronic?' do
it 'returns true' do
expect(entry.electronic?).to be true
end
end
describe '#physical?' do
it 'returns false' do
expect(entry.physical?).to be false
end
end
describe '#resource_link?' do
it 'returns false' do
expect(entry.resource_link?).to be false
end
end
end
|
import React from "react";
class UserClassApiCall extends React.Component{
constructor(props){
super(props);
this.state = {
userInfo: {
name: "Dummy",
location: "Default",
},
};
}
async componentDidMount(){
//API call
const data = await fetch("https://api.github.com/users/shubh193");
const json = await data.json();
//now we have data so we will update data with api data
this.setState({
userInfo:json,
});
console.log(json);
}
componentDidUpdate(){
console.log("componentDidUpdate");
}
componentWillUnmount(){
console.log("Component will unmount");
}
render(){
const {name, location, avatar_url} = this.state.userInfo;
//debugger;
return (
<div className="user-card">
<h2>Name: {name}</h2>
<img src={avatar_url}/>
<h3>Location: {location}</h3>
<h4>Contact: dyzh-shubh</h4>
</div>
);
}
}
export default UserClassApiCall;
|
package service
import (
"genesis-currency-api/internal/model"
"genesis-currency-api/pkg/dto"
"genesis-currency-api/pkg/errors"
"gorm.io/gorm"
)
type UserService struct {
DB *gorm.DB
}
// NewUserService is a factory function for UserService
func NewUserService(db *gorm.DB) *UserService {
return &UserService{
DB: db,
}
}
// Save saves user's information into the database. Only users with unique emails are saved.
// Returns UserResponseDTO with additional information or error.
func (s *UserService) Save(user dto.UserSaveRequestDTO) (dto.UserResponseDTO, error) {
entity := dto.SaveRequestToModel(user)
// Check email uniqueness.
if s.existsByEmail(entity.Email) {
return dto.UserResponseDTO{}, errors.NewUserWithEmailExistsError()
}
if result := s.DB.Create(&entity); result.Error != nil {
return dto.UserResponseDTO{}, errors.NewDbError("", result.Error)
}
return dto.ToDTO(entity), nil
}
// GetAll is used to get all available in database users' information.
// Returns all available UserResponseDTO.
func (s *UserService) GetAll() ([]dto.UserResponseDTO, error) {
var users []model.User
if result := s.DB.Find(&users); result.Error != nil {
return nil, errors.NewDbError("", result.Error)
}
var result []dto.UserResponseDTO
for _, u := range users {
result = append(result, dto.ToDTO(u))
}
return result, nil
}
// existsByEmail is used to check if user with such email already exists in database.
// Returns false if database responded with error, otherwise true.
func (s *UserService) existsByEmail(email string) bool {
var user model.User
if result := s.DB.Where("email = ?", email).First(&user); result.Error != nil {
// result.Error - there is no user with such email
return false
}
return true
}
|
import React, { Component } from 'react';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
class ModalNewCategoria extends Component {
render() {
const {
item,
estadoModal,
title,
handleClose,
valorTexto,
handleSetValorTexto,
handleNuevoItem,
handleActualizarItem,
handleEliminarItem
} = this.props
return (
<div>
<DialogTitle id="form-dialog-title">
{
estadoModal === 'nuevo' &&
`Nueva ${title}`
}
{
estadoModal === 'editar' &&
`Editar ${item.nombre}`
}
{
estadoModal === 'eliminar' &&
`Esta seguro de eliminar "${item.nombre}"?`
}
</DialogTitle>
<DialogContent>
{/* <DialogContentText>
To subscribe to this website, please enter your email address here. We will send
updates occasionally.
</DialogContentText> */}
{
estadoModal === 'nuevo' || estadoModal === 'editar' ?
<TextField
autoFocus
margin="dense"
id="new-category"
label={title}
type="text"
fullWidth
value={valorTexto}
onChange={event => handleSetValorTexto(event.target.value)}
/>
:
<div></div>
}
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Cancelar
</Button>
{
estadoModal === 'nuevo' &&
<Button onClick={()=>{
handleNuevoItem(valorTexto)
handleClose()
}} color="primary">
Guardar
</Button>
}
{
estadoModal === 'editar' &&
<Button onClick={()=>{
handleActualizarItem(valorTexto,item.id)
handleClose()
}} color="primary">
Actualizar
</Button>
}
{
estadoModal === 'eliminar' &&
<Button onClick={()=>{
handleEliminarItem(item.id)
handleClose()
}} color="primary">
Eliminar
</Button>
}
</DialogActions>
</div>
);
}
}
export default ModalNewCategoria;
|
package ru.stqa.geometry.figures;
public record Triangle(
double side1,
double side2,
double side3) {
public Triangle {
if (side1 < 0 || side2 < 0 || side3 < 0) {
throw new IllegalArgumentException("Triangle side should be non-negative");
}
if ((side1 + side2 < side3)
|| (side1 + side3 < side2)
|| (side2 + side3 < side1)) {
throw new IllegalArgumentException("Triangle with these sides cannot be created");
}
}
public double area() {
double p = this.perimeter() / 2;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
public double perimeter() {
return side1 + side2 + side3;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Triangle triangle = (Triangle) o;
return (Double.compare(side1, triangle.side1) == 0 && Double.compare(side2, triangle.side2) == 0 && Double.compare(side3, triangle.side3) == 0)
|| (Double.compare(side1, triangle.side1) == 0 && Double.compare(side2, triangle.side3) == 0 && Double.compare(side3, triangle.side2) == 0)
|| (Double.compare(side1, triangle.side3) == 0 && Double.compare(side2, triangle.side1) == 0 && Double.compare(side3, triangle.side2) == 0)
|| (Double.compare(side1, triangle.side3) == 0 && Double.compare(side2, triangle.side2) == 0 && Double.compare(side3, triangle.side1) == 0)
|| (Double.compare(side1, triangle.side2) == 0 && Double.compare(side2, triangle.side1) == 0 && Double.compare(side3, triangle.side3) == 0)
|| (Double.compare(side1, triangle.side2) == 0 && Double.compare(side2, triangle.side3) == 0 && Double.compare(side3, triangle.side1) == 0);
}
@Override
public int hashCode() {
return 1;
}
}
|
/* Copyright 2019-2020 Centrality Investments Limited
*
* Licensed under the LGPL, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
* You may obtain a copy of the License at the root of this project source code,
* or at:
* https://centrality.ai/licenses/gplv3.txt
* https://centrality.ai/licenses/lgplv3.txt
*/
import React from 'react';
import { shallow } from 'enzyme';
import { Profile } from '../Profile';
import { List } from 'react-native-paper';
import { defaultTheme } from '../../../common/themes/default';
describe('Profile - layout test', () => {
let localizeCallCount = 0;
beforeEach(async () => {
localizeCallCount = 0;
(String.prototype as any).localized = () => {
localizeCallCount++;
return 'localized text';
};
});
it('will localize all text', () => {
const props = {
publicAddress: 'fake public key',
logout: () => ({}),
theme: defaultTheme,
navigateToSeedPhrase: () => ({}),
};
expect(localizeCallCount).toBe(0);
const wrapper = shallow(<Profile {...props} />);
expect(wrapper.contains('localized text')).toBe(true);
expect(localizeCallCount).toBeGreaterThan(0);
});
it('should contain a icon in the layout', () => {
const props = {
publicAddress: 'fake public key',
logout: () => ({}),
theme: defaultTheme,
navigateToSeedPhrase: () => ({}),
};
const wrapper = shallow(<Profile {...props} />);
expect(wrapper.find(List.Item).length).toBe(3);
});
});
|
<template>
<div>
<b-form-group>
<b-form-input id="filter-input" v-model="filter" type="search" placeholder="Search Alerts" />
</b-form-group>
<b-table
id="alerts-table"
sticky-header="600px"
hover
head-variant="light"
foot-clone
:filter="filter"
:items="getAlertsFromAlertData()"
:fields="alert_fields"
@row-clicked="showRowDetails"
>
<template #cell(selected)="data">
<div v-if="data.item.targets && data.item.targets.length > 0">
<b-form-checkbox @change="$emit('selected-alert', data, $event)" />
</div>
</template>
<template #cell(show_details)="data">
<b-link v-if="data.detailsShowing" @click="data.toggleDetails">
<b-icon-caret-down />
</b-link>
<b-link v-else @click="data.toggleDetails">
<b-icon-caret-right />
</b-link>
</template>
<template #row-details="data">
<span v-if="data.item.topic.toLowerCase().includes('circular')" style="white-space: pre-wrap;">{{ data.item.message_text }}</span>
<div v-else-if="data.item.topic.toUpperCase().includes('LVC_COUNTERPART')">
<dl class="row" v-for="[key, value] in Object.entries(data.item.data)" :key="[key, value]">
<dt class="col-md-3">{{ key }}: </dt>
<dd class="col-md-9">{{ value }}</dd>
</dl>
</div>
</template>
<template #cell(identifier)="data">
<span v-if="data.item.targets && data.item.targets.length > 0">
<b-link :href="getAlertUrl(data.item)">{{ data.item.targets[0].name }}</b-link>
</span>
<span v-else>
<b-link :href="getAlertUrl(data.item)">{{ data.item.id }}</b-link>
</span>
</template>
<template #cell(timestamp)="data">
{{ getAlertDate(data.item) }}
</template>
<template #cell(from)="data">
<span>
{{ getSimplifiedFromField(data.item.submitter) }}
</span>
</template>
<template #cell(subject)="data">
<span v-if="data.item.title">{{ data.item.title }}</span>
<span v-else-if="data.item.targets && data.item.targets.length > 0">
Right Ascension: {{ data.item.targets[0].right_ascension_sexagesimal }}<br>
Declination: {{ data.item.targets[0].declination_sexagesimal }}
</span>
</template>
</b-table>
</div>
</template>
<script>
import moment from 'moment';
export default {
name: 'AlertsTable',
components: {},
data: function() {
return {
alert_data: [],
alert_fields: [
{ 'key': 'selected', 'label': '' },
{ 'key': 'show_details', 'label': '' },
{ 'key': 'identifier' },
{ 'key': 'timestamp', 'sortable': true },
{ 'key': 'from' },
{ 'key': 'subject' }
],
filter: null,
}
},
props: {
alerts: {
type: Array,
required: true
},
},
mounted() {
},
methods: {
getAlertUrl(alert) {
return `${this.$store.state.hermesApiBaseUrl}/api/v0/messages/${alert.uuid}`;
},
getAlertsFromAlertData() {
return this.alerts.filter(alert => alert.title !== "GCN/LVC NOTICE");
},
getAlertDate(alert) {
return moment(alert.published).format('YYYY-MM-DD hh:mm:ss');
},
getSimplifiedFromField(from) {
// remove <[email protected]> part of from field; leave name at Institution
// split on the '<', take the first part, and trim the whitespace
return from.split('<')[0].trim();
},
showRowDetails(item, _index, _event) {
item._showDetails = !item._showDetails;
}
}
}
</script>
<style scoped>
#alerts-table {
height: 400px;
}
</style>
|
import React, { useCallback, useEffect, useState } from 'react';
import * as S from './styles';
import close from 'assets/close.png';
import { useNavigation } from '@react-navigation/native';
import Input from 'components/Auth/Input';
import Button from 'components/Auth/Button';
import Toast from 'react-native-toast-message';
import { authSignInRequest } from 'store/ducks/auth/actions';
import { useDispatch } from 'react-redux';
import * as Yup from 'yup';
const SignIn: React.FC = () => {
const [active, setActive] = useState(false);
const [userData, setUserData] = useState({
email: '',
password: '',
});
const dispatch = useDispatch();
const { goBack } = useNavigation();
function validateEmail(email: string) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
const schema = Yup.object().shape({
email: Yup.string().email('Invalid mail').required('E-mail is required'),
password: Yup.string()
.min(8, 'Password needed to be at least 8 caracters')
.required('Password is required'),
});
useEffect(() => {
if (validateEmail(userData.email) && userData.password.length >= 8) {
schema
.validate(userData, { abortEarly: false })
.then(() => {
setActive(true);
})
.catch((e) => {
Toast.show({
text1: e.message,
type: 'error',
});
setActive(false);
});
} else return;
return () => {
setActive(false);
};
}, [userData.email, userData.password]);
const onSubmit = useCallback(() => {
dispatch(authSignInRequest(userData.email, userData.password));
}, [userData.email, userData.password]);
return (
<S.Container>
<S.LeftAlignmentContainer>
<S.Circle onPress={() => goBack()}>
<S.Close source={close} />
</S.Circle>
<S.Title>Welcome</S.Title>
<S.SignUp>Fill the form to continue</S.SignUp>
</S.LeftAlignmentContainer>
<S.KeyBoardView behavior="position">
<S.Separator />
<S.InputContainer>
<Input
type="email"
value={userData.email}
onChangeText={(text) => setUserData({ ...userData, email: text })}
/>
<Input
type="password"
value={userData.password}
onChangeText={(text) =>
setUserData({ ...userData, password: text })
}
style={{
letterSpacing: userData.password.length !== 0 ? 4 : 0.4,
}}
/>
</S.InputContainer>
</S.KeyBoardView>
<S.LargeMargin />
<Button
onPress={() => onSubmit()}
disabled={!active}
active={active}
label="Sign In"
/>
</S.Container>
);
};
export default SignIn;
|
package com.example.newsappforandroid.product.di
import android.content.Context
import androidx.room.Room
import com.example.newsappforandroid.product.init.database.dao.FavoritesDao
import com.example.newsappforandroid.product.constants.database.DatabaseConstants.NEWS_DATABASE
import com.example.newsappforandroid.product.init.database.AppDatabase
import com.example.newsappforandroid.product.init.database.converters.DateConverter
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class DatabaseModule {
@Provides
@Singleton
fun provideRoomInstance(@ApplicationContext context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabase::class.java, NEWS_DATABASE).build()
}
@Provides
@Singleton
fun provideArticlesDao(newsDatabase: AppDatabase): FavoritesDao {
return newsDatabase.favoritesDao()
}
@Provides
@Singleton
fun provideDateConverter(): DateConverter {
return DateConverter()
}
}
|
package com.github.marcustalbots.haven.dock;
import com.github.marcustalbots.haven.impl.vehicles.dock_vehicles.offloading_vehicles.Crane;
import com.github.marcustalbots.haven.impl.vehicles.dock_vehicles.offloading_vehicles.Pump;
import com.github.marcustalbots.haven.impl.vehicles.dock_vehicles.transport_vehicles.ContainerTruck;
import com.github.marcustalbots.haven.impl.vehicles.dock_vehicles.transport_vehicles.OilTruck;
import com.github.marcustalbots.haven.models.containers.AbstractFreightContainer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Dock serves as the shared resource between all the producers and consumers in this program.
*
* @author Marcus Talbot (1041464)
*/
public final class Dock {
/**
* Serves as the space where {@link AbstractFreightContainer}-objects can be placed by {@link Crane}-objects, to
* be collected by {@link ContainerTruck}-objects. Due to the nature of the {@link BlockingQueue}-interface,
* access to this object is thread-safe.
*/
private final BlockingQueue<AbstractFreightContainer> backlog;
/**
* Serves as a space where {@link OilTruck}-objects wait to be called on by {@link Pump}-objects. Due to the nature
* of the {@link BlockingQueue}-interface, access to this object is thread-safe.
*/
private final BlockingQueue<OilTruck> oilTrucks;
/**
* Used to provide an Object-Oriented approach to wait/notify. Specifically, this lock is used by the
* {@link #placeContainer(AbstractFreightContainer)}-method, to safely wait while the {@link #backlog}-field holds
* five {@link AbstractFreightContainer}-objects, using the {@link #notFull}-{@link Condition}. Furthermore, it is
* used by the {@link #getContainer()}-method, to safely notify objects monitoring the {@link #notFull}-field.
*/
private final ReentrantLock containerLock;
/**
* Used to offer an Object-Oriented wait/notify-interface.
*/
private final Condition notFull;
/**
* Maximum capacity of the {@link #backlog}.
*/
private final int containerCapacity;
/**
* Creates a new Dock with the given configuration.
*
* @param capacity Maximum capacity of the {@link #backlog}.
* @author Marcus Talbot (1041464)
*/
public Dock(final int capacity) {
this.backlog = new PriorityBlockingQueue<>(capacity);
this.oilTrucks = new ArrayBlockingQueue<>(3, true);
this.containerCapacity = capacity;
this.containerLock = new ReentrantLock(true);
this.containerLock.lock();
try {
this.notFull = this.containerLock.newCondition();
} finally {
this.containerLock.unlock();
}
}
/**
* Places a container into the {@link #backlog}. This method is thread-safe, due to the use of
* {@link #containerLock}.
*
* @param container {@link AbstractFreightContainer}-subclass, that will be placed in the {@link #backlog}.
* @author Marcus Talbot (1041464)
*/
public boolean placeContainer(@NotNull final AbstractFreightContainer container) {
this.containerLock.lock();
try {
while (this.backlog.size() == this.containerCapacity) {
if (!this.notFull.await(30, TimeUnit.SECONDS))
return false;
}
this.backlog.put(container);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
return false;
} finally {
// The lock should be released in a finally-block, to make sure it is released even
// if an Exception is raised.
this.containerLock.unlock();
}
return true;
}
/**
* Gets the next container in the {@link #backlog}. This method is thread-safe, due to the use of
* {@link PriorityBlockingQueue}. If the {@link #backlog} is empty, this method will block for, at most, fifteen
* seconds, after which it must return either a valid container, or null.
*
* @return {@link AbstractFreightContainer}-subclass, or null if the {@link #backlog} remains empty for more than
* fifteen seconds.
* @author Marcus Talbot (1041464)
*/
public @Nullable AbstractFreightContainer getContainer() {
try {
return this.backlog.poll(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
return null;
} finally {
this.containerLock.lock();
this.notFull.signal();
this.containerLock.unlock();
}
}
/**
* Registers that an {@link OilTruck} is currently idling.
*
* @param oilTruck {@link OilTruck}-object that needs to be registered to the {@link #oilTrucks}-field.
* @author Marcus Talbot (1041464)
*/
public boolean registerOilTruck(@NotNull final OilTruck oilTruck) {
try {
this.oilTrucks.put(oilTruck);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
return false;
}
return true;
}
/**
* Gets an idling {@link OilTruck}. This method is thread-safe, due to the use of {@link ArrayBlockingQueue}.
*
* @return An {@link OilTruck} registered to the {@link #oilTrucks}-field.
* @author Marcus Talbot (1041464)
*/
public @Nullable OilTruck getOilTruck() {
try {
return this.oilTrucks.take();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
return null;
}
}
}
|
import { Box, IconButton, Paper, Slider, Stack, Typography } from "@mui/material";
import ShuffleIcon from '@mui/icons-material/Shuffle';
import SkipPreviousIcon from '@mui/icons-material/SkipPrevious';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import SkipNextIcon from '@mui/icons-material/SkipNext';
import RepeatIcon from '@mui/icons-material/Repeat';
import VolumeUpIcon from '@mui/icons-material/VolumeUp';
import PauseCircleIcon from '@mui/icons-material/PauseCircle';
import RepeatOneIcon from '@mui/icons-material/RepeatOne';
import VolumeMuteIcon from '@mui/icons-material/VolumeMute';
import { SyntheticEvent, useRef, useState } from "react";
import { useAppDispatch, useAppSelector } from "../app/hooks";
import { Link } from "react-router-dom";
import { selectCurrentSong, selectPlaying, selectRandom, selectRepeat, selectSongList, setCurrentSong, setRepeat, togglePlaying, toggleRandom } from "../features/player/playerSlice";
import { convertToMinuteAndSecond } from "../utils/convert";
import LikeButton from "./LikeButton";
import { selectUser } from "../features/auth/authSlice";
const MusicPlayer = () => {
const dispatch = useAppDispatch();
const playing = useAppSelector(selectPlaying);
const currentSong = useAppSelector(selectCurrentSong);
const songList = useAppSelector(selectSongList);
const random = useAppSelector(selectRandom);
const repeat = useAppSelector(selectRepeat);
const user = useAppSelector(selectUser);
const [stateVolume, setStateVolume] = useState<number>(100);
const [dur, setDur] = useState(0);
const [currentTime, setCurrentTime] = useState<number>(0);
const [mute, setMute] = useState(false);
let audio = useRef<HTMLAudioElement>(new Audio());
const handleTimeChange = (event: Event, newValue: number | number[]) => {
setCurrentTime(newValue as number);
if (currentSong !== -1) {
audio.current.currentTime = (newValue as number) / 100 * dur;
}
}
const handleVolumeChange = (event: Event, newValue: number | number[]) => {
if ((newValue as number) === 0)
setMute(true);
else
setMute(false);
setStateVolume(newValue as number);
audio.current.volume = (newValue as number) / 100;
}
const handleMuteChange = (mute: boolean) => {
if (mute === true) {
setStateVolume(100);
audio.current.volume = 1;
} else {
setStateVolume(0);
audio.current.volume = 0;
}
setMute(!mute);
}
const handleRandomChange = () => {
dispatch(toggleRandom(random));
}
const handleRepeatChange = () => {
dispatch(setRepeat(repeat));
}
const handleSkipRandom = () => {
const nextIndex = Math.floor((Math.random() * songList.length));
audio.current.src = songList[nextIndex].url;
audio.current.currentTime = 0;
dispatch(setCurrentSong(nextIndex));
setDur(songList[nextIndex].length);
}
const handleEndOfSong = () => {
if (random) {
handleSkipRandom();
return;
}
if (repeat === 2) {
audio.current.currentTime = 0;
return;
}
handleSkipNext();
}
const handleSkipPrevious = () => {
if (currentSong !== -1) {
if (random) {
handleSkipRandom();
return;
}
if (repeat === 0 || repeat === 2) {
if (currentSong === 0) {
audio.current.pause();
audio.current.src = "";
audio.current.currentTime = 0;
dispatch(setCurrentSong(-1));
dispatch(togglePlaying(true));
setDur(0);
return;
}
setDur(songList[currentSong - 1].length);
dispatch(setCurrentSong(currentSong - 1));
return;
}
if (currentSong === 0) {
audio.current.src = songList[songList.length - 1].url;
audio.current.currentTime = 0;
setDur(songList[songList.length - 1].length);
dispatch(setCurrentSong(songList.length - 1));
return;
}
setDur(songList[currentSong - 1].length);
dispatch(setCurrentSong(currentSong - 1));
return;
}
}
const handleSkipNext = () => {
const songListLength = songList.length;
if (currentSong !== -1) {
if (random) {
handleSkipRandom();
return;
}
if (repeat === 0 || repeat === 2) {
if (currentSong === songListLength - 1) {
audio.current.pause();
audio.current.src = "";
audio.current.currentTime = 0;
dispatch(setCurrentSong(-1));
dispatch(togglePlaying(true));
setDur(0);
return;
}
setDur(songList[currentSong + 1].length);
dispatch(setCurrentSong(currentSong + 1));
return;
}
if (currentSong === songListLength - 1) {
audio.current.src = songList[0].url;
audio.current.currentTime = 0;
setDur(songList[0].length);
dispatch(setCurrentSong(0));
return;
}
setDur(songList[currentSong + 1].length);
dispatch(setCurrentSong(currentSong + 1));
return;
}
}
const toggleAudio = () => {
if (audio.current.paused) {
audio.current.play();
dispatch(togglePlaying(false));
} else {
audio.current.pause();
dispatch(togglePlaying(true));
}
}
if (currentSong !== -1) {
if (audio.current.src === "" || audio.current.src !== songList[currentSong].url) {
audio.current.src = songList[currentSong].url;
audio.current.volume = stateVolume / 100;
audio.current.currentTime = 0;
if (dur === 0 || dur !== songList[currentSong].length) {
setDur(songList[currentSong].length);
}
}
if (playing) {
if (user.username.length === 0) {
audio.current.pause();
} else {
audio.current.play();
}
} else {
audio.current.pause();
}
} else {
audio.current.pause();
audio.current.currentTime = 0;
audio.current.src = "";
audio.current.volume = 1;
}
const contentRendered = (
<>
<Stack direction="row" alignItems="center" justifyContent="flex-start" minWidth="180px" width="30%" height={{ height: "56px" }}>
{currentSong !== -1 &&
<>
<Box marginX={2} lineHeight="1.6" maxHeight="100%">
<Stack direction="column">
<Link to={`/album/${songList[currentSong].album_id}`} style={{ textDecoration: "none", color: "white", fontWeight: "bold" }}>{songList[currentSong].name}</Link>
<Link to={`/artist/${songList[currentSong].artist_id}`} style={{ textDecoration: "none", color: "white", fontSize: "0.6875rem" }}>{songList[currentSong].artist_name}</Link>
</Stack>
</Box>
<LikeButton song_id={songList[currentSong].song_id} />
</>
}
</Stack>
<Stack direction="column" alignItems="center" justifyContent="center" maxWidth="722px" width="40%">
<Stack direction="row" marginBottom="8px">
<Stack direction="row" justifyContent="flex-end">
<IconButton onClick={handleRandomChange}><ShuffleIcon color={random ? "success" : "inherit"} /></IconButton>
<IconButton onClick={handleSkipPrevious}><SkipPreviousIcon /></IconButton>
</Stack>
<IconButton onClick={toggleAudio}>
{playing ? <PauseCircleIcon /> : <PlayCircleIcon />}
</IconButton>
<Stack direction="row" justifyContent="flex-start">
<IconButton onClick={handleSkipNext}><SkipNextIcon /></IconButton>
<IconButton onClick={handleRepeatChange}>
{repeat === 0 ? <RepeatIcon /> : (repeat === 1 ? <RepeatIcon color="success" /> : <RepeatOneIcon color="success" />)}
</IconButton>
</Stack>
</Stack>
<Stack direction="row" width="100%" alignItems="center" gap={2}>
<Typography textAlign="right" minWidth="40px" fontWeight="bold" fontSize="0.6785rem">{currentSong === -1 ? "0:00" : convertToMinuteAndSecond(currentTime)}</Typography>
<Slider value={currentTime} onChange={handleTimeChange} />
<Typography textAlign="left" minWidth="40px" fontWeight="bold" fontSize="0.6785rem">{currentSong === -1 ? "0:00": convertToMinuteAndSecond(songList[currentSong].length)}</Typography>
</Stack>
</Stack>
<Stack direction="row" alignItems="center" justifyContent="flex-end" minWidth="180px" width="30%">
<Stack direction="row" width="100%" alignItems="center">
<IconButton onClick={() => handleMuteChange(mute)}>
{mute ? <VolumeMuteIcon /> : <VolumeUpIcon />}
</IconButton>
<Slider size="small" value={stateVolume} onChange={handleVolumeChange} />
</Stack>
</Stack>
</>
);
return (
<Paper sx={{ position: "fixed", zIndex: "4", bottom: 0, left: 0, right: 0, height: "90px" }}>
<audio ref={audio} onTimeUpdate={
(e: SyntheticEvent<HTMLAudioElement>) => {
setCurrentTime((e.currentTarget.currentTime) / dur * 100);
}
}
onEnded={handleEndOfSong}
/>
<Box height="90px">
<Stack direction="row" paddingX={2} height="100%" alignItems="center">
{contentRendered}
</Stack>
</Box>
</Paper>
);
}
export default MusicPlayer;
|
//
// PillView.swift
// Crit
//
// Created by Ike Mattice on 3/19/22.
//
import SwiftUI
struct PillView: View {
@State var currentState: PillState
let text: String
var viewModel: PillViewModel {
currentState.viewModel
}
var body: some View {
BorderedText(
text,
textColor: currentState.viewModel.textColor,
backgroundColor: currentState.viewModel.backgroundColor,
frameModel: currentState.viewModel.frameViewModel)
.animation(.easeInOut, value: currentState)
.transition(.opacity)
}
init(_ text: String, state: PillState) {
self.text = text
self._currentState = State(initialValue: state)
}
}
// MARK: Previews
struct PillView_Previews: PreviewProvider {
static let standardState: PillState = .standard
static let selectableState: PillState = .selectable
static let selectedState: PillState = .selected
static let activeState: PillState = .active
static let inactiveState: PillState = .inactive
@State static var mutableState: PillState = .selectable
static var previews: some View {
Group {
PillView(String(describing: standardState.self).capitalized,
state: standardState)
.previewDisplayName("\(String(describing: standardState.self).capitalized) State")
PillView(String(describing: selectableState.self).capitalized,
state: selectableState)
.previewDisplayName("\(String(describing: selectableState.self).capitalized) State")
PillView(String(describing: selectedState.self).capitalized,
state: selectedState)
.previewDisplayName("\(String(describing: selectedState.self).capitalized) State")
PillView(String(describing: activeState.self).capitalized,
state: activeState)
.previewDisplayName("\(String(describing: activeState.self).capitalized) State")
PillView(String(describing: inactiveState.self).capitalized,
state: inactiveState)
.previewDisplayName("\(String(describing: inactiveState.self).capitalized) State")
PillView("Tap to Toggle",
state: mutableState)
.onTapGesture(perform: toggleState)
.previewDisplayName("Toggle-able Pill")
}
.previewLayout(.sizeThatFits)
}
static func toggleState() {
if mutableState == .selectable {
mutableState = .selected
} else {
mutableState = .selectable
}
}
}
|
// Copyright 2022 Redpanda Data, Inc.
//
// Use of this software is governed by the Business Source License
// included in the file https://github.com/redpanda-data/redpanda/blob/dev/licenses/bsl.md
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0
package console
import (
"fmt"
"go.uber.org/zap"
"github.com/redpanda-data/console/backend/pkg/config"
"github.com/redpanda-data/console/backend/pkg/connect"
"github.com/redpanda-data/console/backend/pkg/git"
"github.com/redpanda-data/console/backend/pkg/kafka"
"github.com/redpanda-data/console/backend/pkg/redpanda"
)
// Service offers all methods to serve the responses for the REST API. This usually only involves fetching
// several responses from Kafka concurrently and constructing them so, that they are
type Service struct {
kafkaSvc *kafka.Service
redpandaSvc *redpanda.Service
gitSvc *git.Service // Git service can be nil if not configured
connectSvc *connect.Service
logger *zap.Logger
// configExtensionsByName contains additional metadata about Topic or BrokerWithLogDirs configs.
// The additional information is used by the frontend to provide a good UX when
// editing configs or creating new topics.
configExtensionsByName map[string]ConfigEntryExtension
}
// NewService for the Console package
func NewService(
cfg config.Console,
logger *zap.Logger,
kafkaSvc *kafka.Service,
redpandaSvc *redpanda.Service,
connectSvc *connect.Service,
) (*Service, error) {
var gitSvc *git.Service
cfg.TopicDocumentation.Git.AllowedFileExtensions = []string{"md"}
if cfg.TopicDocumentation.Enabled && cfg.TopicDocumentation.Git.Enabled {
svc, err := git.NewService(cfg.TopicDocumentation.Git, logger, nil)
if err != nil {
return nil, fmt.Errorf("failed to create git service: %w", err)
}
gitSvc = svc
}
configExtensionsByName, err := loadConfigExtensions()
if err != nil {
return nil, fmt.Errorf("failed to load config extensions: %w", err)
}
return &Service{
kafkaSvc: kafkaSvc,
redpandaSvc: redpandaSvc,
gitSvc: gitSvc,
connectSvc: connectSvc,
logger: logger,
configExtensionsByName: configExtensionsByName,
}, nil
}
// Start starts all the (background) tasks which are required for this service to work properly. If any of these
// tasks can not be setup an error will be returned which will cause the application to exit.
func (s *Service) Start() error {
if s.gitSvc == nil {
return nil
}
return s.gitSvc.Start()
}
|
//
// MockAstronautService.swift
// SpaceLaunchTests
//
// Created by Sheethal Karkera on 19/1/22.
//
import Foundation
@testable import SpaceLaunch
class MockAstronautService: AstronautService {
var isSuccess = true
override func getAstronautList(completion: @escaping ([Astronaut]?, Error?) -> Void) {
let mockResponse = isSuccess ? "mock-astronaut-list" : "mock-astronaut-error"
do {
let response = try JSONDecoder().decode(AstronautsResponse.self, from: MockResponseService().fetchData(from: mockResponse))
completion(response.astronauts, nil)
}
catch let error {
completion(nil, error)
}
}
override func getAstronautDetails(for id: Int, completion: @escaping (Astronaut?, Error?) -> Void) {
let mockResponse = isSuccess ? "mock-astronaut-detail" : "mock-astronaut-detail-error"
do {
let response = try JSONDecoder().decode(Astronaut.self, from: MockResponseService().fetchData(from: mockResponse))
completion(response, nil)
}
catch let error {
completion(nil, error)
}
}
}
|
import {
ROLLS_RESULTS_FONTS,
NO_DICE_FOUND_ERROR,
USE_FATE_INSTEAD_ERROR,
DICE_TYPES_MAX,
SPECIAL_MAX_DICE_VALUE,
} from '../../defaults';
import { mapMaxValueToDice, mapRollToDice } from '../../services/dices.service';
import { DiceTypes } from '../../types';
describe('mapRollToDice', () => {
test('Should throw NO_DICE_FOUND, when the roll number is not supported', () => {
const callback = () => {
mapRollToDice(DiceTypes.D_20, 126);
};
expect(callback).toThrow(NO_DICE_FOUND_ERROR);
});
test('Should throw USE_FATE_INSTEAD_ERROR, when dice type is Fate', () => {
const callback = () => {
mapRollToDice(DiceTypes.FATE, 2);
};
expect(callback).toThrow(USE_FATE_INSTEAD_ERROR);
});
describe('Should select a right sign', () => {
const diceType = DiceTypes.D_20;
const testShouldSelectRightSign = (roll: number) => {
const expectedResult = ROLLS_RESULTS_FONTS[diceType][roll - 1];
const result = mapRollToDice(diceType, roll);
expect(result).toEqual(expectedResult);
};
test('- for min value', () => {
const roll = 1;
testShouldSelectRightSign(roll);
});
test('- for ok value', () => {
const roll = 6;
testShouldSelectRightSign(roll);
});
test('- for max value', () => {
const roll = DICE_TYPES_MAX.get(diceType)!;
testShouldSelectRightSign(roll);
});
});
});
describe('mapMaxValueToDice', () => {
test('Should get max by dice type', () => {
const diceType = DiceTypes.D_20;
const roll = DICE_TYPES_MAX.get(diceType)!;
const expectedResult = ROLLS_RESULTS_FONTS[diceType][roll - 1];
const result = mapMaxValueToDice(diceType);
expect(result).toEqual(expectedResult);
});
test('Should get max by dice type when dice is special', () => {
const diceType = DiceTypes.D_10;
const expectedSign = SPECIAL_MAX_DICE_VALUE.get(diceType)!;
const result = mapMaxValueToDice(diceType);
expect(result).toEqual(expectedSign);
});
});
export {};
|
//
// LoginView.swift
// EdvoraTaskMHamdino95
//
// Created by A One Way To Allah on 1/11/22.
//
import SwiftUI
struct LoginView: View {
//MARK: - Properities
@State var username: String = ""
@State var password: String = ""
@State var email: String = ""
@State var isAnimated: Bool = true
//MARK: - View
var body: some View {
VStack {
//Logo
AuthLogo()
.scaleEffect(isAnimated ? 0.5 : 1)
.animation(Animation.easeInOutSlow.repeatForever(autoreverses: true))
Spacer()
//Inputs
CustomTextField(placeHolder: "Username", text: $username,leadingIconName: "username")
CustomTextField(placeHolder: "password", text: $password,leadingIconName: "key",trainlingIconName:"seen",keyboardType: .asciiCapableNumberPad)
CustomTextField(placeHolder: "email address", text: $email,leadingIconName: "email",trainlingIconName: nil,keyboardType:.emailAddress)
"Forgotten password?"
.subheadlineText
.foregroundColor(DesignSystem.Colors.text.color)
.frame(maxWidth: .infinity, alignment: .trailing)
Spacer()
//Actions
VStack (spacing:14){
ButtonAnimationView()
.animation(Animation.frameSpring)
.frame(width: isAnimated ? 80 : nil)
HStack{
"Don’t have an account?".subheadlineText
.foregroundColor(DesignSystem.Colors.text.color)
"Sign up".subheadlineText
.foregroundColor(DesignSystem.Colors.text.color)
.fontWeight(.bold)
}
}
}.padding(Khorizontalpadding)
.onAppear{
isAnimated=false
}
}
}
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView()
}
}
|
// useFileList.ts
import { useState } from 'react';
export const useFileList = () => {
const [listOfFiles, setListOfFiles] = useState<File[]>([]);
const addFile = (file: File) => {
if (listOfFiles.some(f => f.name === file.name)) {
return;
}
setListOfFiles([...listOfFiles, file]);
};
const removeFile = (file: File) => {
setListOfFiles(listOfFiles.filter(f => f.name !== file.name));
};
const replaceFile = (oldFile: File, newFile: File) => {
const newList = listOfFiles.map(f => {
if (f.name === oldFile.name) {
return newFile;
}
return f;
});
setListOfFiles(newList);
}
const clearFiles = () => {
setListOfFiles([]);
}
return { listOfFiles, addFile, removeFile, clearFiles, replaceFile };
};
|
/* eslint-disable react/jsx-no-useless-fragment */
import { en, format } from "date-fns";
import MarkdownIt from "markdown-it";
import Image from "next/image";
import Link from "next/link";
import React, { useState } from "react";
import { SearchInput } from "@/widgets";
import styles from "./MainPost.module.scss";
export const MainPost = ({
title,
description,
image,
alt,
id,
date,
data1,
}) => {
const [results, setResults] = useState([]);
const latest = data1.sort(
(a, b) =>
new Date(b.attributes?.createdAt) - new Date(a.attributes?.createdAt)
);
const md = new MarkdownIt({
html: true,
});
const htmlContentDescription = md.render(description);
const htmlContentTitle = md.render(title);
const inputDate = new Date(date);
const formattedDate = format(inputDate, "d MMMM yyyy", {
locale: en,
});
return (
<div className={styles.post}>
<div className={styles.left}>
<Image
width={700}
height={400}
src={image}
alt={alt}
className={styles.image}
/>
<div
className={styles.title}
dangerouslySetInnerHTML={{ __html: htmlContentTitle }}
/>
<div
className={styles.description}
dangerouslySetInnerHTML={{ __html: htmlContentDescription }}
/>
<div className={styles.bottom}>
<div className={styles.date}>{formattedDate}</div>
</div>
</div>
<div className={styles.right}>
<div className={styles.search}>
<div className={styles.block}>
<SearchInput results={results} setResults={setResults} />
</div>
<div className={styles.latest_posts}>
<h6 className={styles.latest_post_title}>Latest Post</h6>
{results.length !== 0 ? (
results?.data?.map((result) => {
const resDate = new Date(result?.attributes?.createdAt);
const resFormDate = format(resDate, "d MMMM yyyy", {
locale: en,
});
return (
<Link
key={result?.id}
href={result?.attributes?.slug}
// chnage
className={styles.latest_post}
>
<div>
<div className={styles.latest_title}>
{result?.attributes?.latest_title}
</div>
<div className={styles.latest_date}>{resFormDate}</div>
</div>
</Link>
);
})
) : (
<>
{latest?.slice(0, 3).map((post) => {
const resDate = new Date(post?.attributes?.createdAt);
const resFormDate = format(resDate, "d MMMM yyyy", {
locale: en,
});
return (
<Link
key={post?.id}
href={post?.attributes?.slug}
className={styles.latest_post}
>
<div>
<div className={styles.latest_title}>
{post?.attributes?.latest_title}
</div>
<div className={styles.latest_date}>{resFormDate}</div>
</div>
</Link>
);
})}
</>
)}
</div>
</div>
</div>
</div>
);
};
|
from django.db import models
from django.contrib.auth.models import User
class Testimonial(models.Model):
RATING_CHOICES = (
(1, '1 star'),
(2, '2 stars'),
(3, '3 stars'),
(4, '4 stars'),
(5, '5 stars'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=False, null=False)
rating = models.IntegerField(choices=RATING_CHOICES, default=5)
testimonial = models.TextField(blank=False, null=False)
publish_testimonial = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Testimonial from {self.user.username} - Rating: {self.rating}"
|
// Modules
import React, { FC, useEffect, useState } from 'react'
import { Image, StyleSheet, Text, View } from 'react-native'
import { ScrollView, TextInput } from 'react-native-gesture-handler'
import { ObjectId } from 'bson'
import Realm from 'realm'
// Components
import LowBar from '../components/containers/LowBarCont'
import ImageButton from '../components/buttons/borderlessButton/imageButton'
import plus_icon from '../assets/plus.png'
import close_icon from '../assets/close.png'
import capitalize from './utils/capitalize'
import TextTitle from '../components/textComponents/textTitle'
import GreyInputField from '../components/inputFields/greyInputField'
import OvalButton from '../components/buttons/roundedButton/OvalButton'
// Mongo
import ingredientInterface from '../mongo/realmObjects/ingrediantInterface'
import ingredientSchema from '../mongo/schemas/ingrediantSchema'
import recipeSchema from '../mongo/schemas/recipeSchema'
import { useAuth } from '../mongo/AuthProvider'
import { useNavigation } from '@react-navigation/native'
interface Props {
}
const CreateRecipe: FC<Props> = ({}) => {
const { user, createRecipe } = useAuth()
const [name, setName] = useState<string>('')
const navigation = useNavigation()
const [state, setState] = useState<ingredientInterface[]>([
{
igName: '',
amount: 0,
unit: '',
},
])
const createPartition = () => {
const newPartition: ingredientInterface = {
igName: '',
amount: 0,
unit: '',
}
setState([...state, newPartition])
}
const onChangeNameAtIndex = (text: string, index: number)=> {
let newState: ingredientInterface[] = [...state]
let newElement = newState[index]
newElement.igName = capitalize(text)
newState[index] = newElement
setState(newState)
}
const onChangeQtyAtIndex = (text: string, index: number)=> {
let newState: ingredientInterface[] = [...state]
let newElement = newState[index]
newElement.amount = parseInt(text)
newState[index] = newElement
setState(newState)
}
const onChangeUnitAtIndex = (text: string, index: number)=> {
let newState: ingredientInterface[] = [...state]
let newElement = newState[index]
newElement.unit = text
newState[index] = newElement
setState(newState)
}
const onDeleteAtIndex = (targetIndex: number) => {
const filteredArray = state.filter((_, index) => index != targetIndex)
setState([...filteredArray])
}
const onSubmit = async () => {
await createRecipe(name, state)
navigation.navigate("DashBoard")
}
console.log(state)
return (
<LowBar>
<ScrollView style = {{flex: 1, padding: '5%'}}>
<TextTitle>
Add Recipe
</TextTitle>
<GreyInputField
value = {name}
style = {{ marginVertical: 16,}}
placeholder = 'Recipe Name'
onChangeText={(text)=> setName(capitalize(text))}
/>
<View style = {{
borderRadius: 25,
backgroundColor: 'white',
padding: '5%'
}}>
{
state?.map((item,i)=> (
<View
key={i}
style = {styles.partitionContainer}
>
<TextInput
style = {{flex:2}}
placeholder='name'
value={item.igName}
onChangeText={(text)=> onChangeNameAtIndex(text,i)}
/>
<TextInput
style = {{flex:1}}
placeholder='Qty'
value={item.amount? `${item.amount}`: undefined }
onChangeText={(text)=> onChangeQtyAtIndex(text,i)}
/>
<TextInput
style = {{flex:1}}
placeholder='Unit'
value={item.unit}
onChangeText={(text)=> onChangeUnitAtIndex(text,i)}
/>
<ImageButton
source={close_icon}
onPress={()=> onDeleteAtIndex(i)}
/>
</View>
))
}
<View
style = {[styles.partitionContainer, {borderBottomWidth: 0, marginVertical: 10}]}
>
<View style = {{ flex: 1 }}>
</View>
<ImageButton
source={plus_icon}
onPress={createPartition}
/>
</View>
</View>
<OvalButton
onPress={onSubmit}
style={{backgroundColor: 'white', alignSelf: 'center', width: '50%', marginTop: 10,}}
>
Confirm
</OvalButton>
</ScrollView>
</LowBar>
)
}
export default CreateRecipe
const styles = StyleSheet.create({
partitionContainer: {
paddingHorizontal: 16,
borderBottomWidth: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}
})
|
import React, { useState, useEffect } from "react";
import { AiFillInstagram, AiOutlineTwitter } from "react-icons/ai";
const Footer = ({ pageContent }) => {
const [loading, setLoading] = useState(true);
const [footerContent, setFooterContent] = useState({});
useEffect(() => {
setFooterContent(pageContent);
}, []);
useEffect(() => {
pageContent === undefined ? setLoading(true) : setLoading(false);
}, [footerContent]);
console.log("FOOTER BUILD PAGE CONTENT = ", pageContent);
return (
<div className="footer-container">
{loading === false ? (
<>
<p>
{pageContent.footer1 === undefined
? `2022 Oracle Deck All rights reserved `
: pageContent.footer1}
</p>
<p className="icons">
{/*<AiFillInstagram>
<a href="http://youtube.com"></a>
</AiFillInstagram>
<AiOutlineTwitter />*/}
</p>
<p>
Follow me on Facebook at
{pageContent.facebook === undefined ? (
<a href="https://www.facebook.com">
{" "}
<u>facebook.com </u>
</a>
) : (
<a href={pageContent.facebook}>
<u> {pageContent.facebook}</u>
</a>
)}
</p>
<p>
Follow me on Instagram at
{pageContent.instagram === undefined ? (
<a href="https://www.instagram.com">
<u>instagram.com </u>
</a>
) : (
<a href={pageContent.instagram}>
<u> {pageContent.instagram}</u>
</a>
)}
</p>
<p>
Follow my website
{pageContent.website === undefined ? (
<a href="https://hannahyork.info/">
<u> https://hannahyork.info/ </u>
</a>
) : (
<a href={pageContent.website}>
<u> {pageContent.website} </u>
</a>
)}
for more information
</p>
<p>{pageContent.footer2}</p>
<p>
{pageContent.footer3 === undefined
? `For more information on how to work with me privately you can visit
holistichealingbyhannah.com Free discovery calls are available, if you
have questions before booking an appointment.`
: pageContent.footer3}
</p>
</>
) : (
<h1>LOADING</h1>
)}
</div>
);
};
export default Footer;
|
package sh.java.exception;
import java.util.InputMismatchException;
import java.util.Scanner;
public class NumberGame {
public static void main(String[] args) {
new NumberGame().start();
}
/**
* 점수에 따라 실행할 게임을 분기처리하는 앱
* - 점수가 60점 이상이면 프리미엄 게임 시작
* - 점수가 60점 미만이면 그냥 그런 게임 시작
*/
private void start() {
try {
inputScore();
premiumGame();
} catch (NoGoodScoreException e) {
normalGame();
}
}
/**
* 사용자에게 점수를 입력받고, 60점 미만이면 NoGoodScoreException을 던지는 메소드
*/ // checked 예외로 만들고 싶으면 메소드 안에서
// try-catch문으로 잡거나 throws로 던져야함
private void inputScore() /* throws NoGoodScoreException */ {
while(true) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("점수 입력 : ");
int score = sc.nextInt();
if(score<60) {
throw new NoGoodScoreException("점수: " + score);
}
break;
} catch (InputMismatchException e) {
System.out.println("정수만 입력하세요");
}
}
}
private void premiumGame() {
System.out.println("프리미엄 게임을 시작합니다~~");
}
private void normalGame() {
System.out.println("그냥 그런 게임을 시작합니다~~");
}
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PEP8:OK, LINT:OK, PY3:OK
# metadata
'''SyncthinGUI.'''
import os
import sys
import signal
import psutil
import time
from threading import Timer, Event, Lock
# imports
# from datetime import datetime
from ctypes import byref, cdll, create_string_buffer
from getopt import getopt
from subprocess import call, getoutput
from urllib import request
from webbrowser import open_new_tab
# require python3-pyqt5
try:
from PyQt5.QtCore import (QProcess, Qt, QTextStream, QUrl, pyqtSlot, QSize)
from PyQt5.QtGui import QIcon, QPixmap, QTransform, QTextOption, QTextCursor
from PyQt5.QtNetwork import QNetworkRequest
from PyQt5.QtWidgets import (QApplication, QCheckBox, QInputDialog,
QMainWindow, QMenu, QMessageBox,
QPlainTextEdit, QTextEdit,
QVBoxLayout, QHBoxLayout,
QShortcut, QSystemTrayIcon, QProgressBar,
QSplitter, QWidget)
except ImportError:
print("sudo apt install python3-pyqt5")
exit(-1)
try:
# ubuntu require: python3-pyqt5.qtwebkit
# WebKit1 based (deprecate)
#from PyQt5.QtWebKitWidgets import QWebView as QWebEngineView
# new in python3
#QT 5.12
from PyQt5.QtWebEngineWidgets import QWebEngineView
except ImportError:
print("sudo apt install python3-pyqt5.qtwebengine")
exit(-1)
import syncthingui_rc
'''
require: pyqt5 (5.6), psutil
pip3 install pyqt5
cp /usr/local/lib/python3.5/dist-packages/PyQt5/Qt/resources/* /usr/local/lib/python3.5/dist-packages/PyQt5/Qt/libexec/
cp -R /usr/local/lib/python3.5/dist-packages/PyQt5/Qt/resources/ /usr/local/lib/python3.5/dist-packages/PyQt5/Qt/libexec/qtwebengine_locales/
'''
# metadata
__package__ = "syncthingui"
__version__ = ' 0.0.3'
__license__ = ' GPLv3+ LGPLv3+ '
__author__ = 'coolshou'
__author_org__ = ' juancarlos '
__email__ = ' [email protected] '
__url__ = 'https://github.com/coolshou/syncthingui#syncthingui'
__source__ = ('https://github.com/coolshou/syncthingui/releases/latest')
URL, SYNCTHING = "http://127.0.0.1:8384", "syncthing"
HELP_URL_0 = "http://forum.syncthing.net"
HELP_URL_1 = "https://github.com/syncthing/syncthing/releases"
HELP_URL_2 = "http://docs.syncthing.net"
HELP_URL_3 = "https://github.com/syncthing/syncthing/issues"
HELP_URL_4 = "https://github.com/syncthing/syncthing"
SHORTCUTS = """<b>Quit = CTRL + Q<br>Zoom Up = CTRL + +<br>
Zoom Down = CTRL + -<br>Zoom Reset = CTRL + 0"""
HELPMSG = """<h3>SyncthinGUI</h3>Python3 Qt5 GUI for Syncthing,GPLv3+LGPLv3<hr>
<i>KISS DRY SingleFile Async CrossDesktop CrossDistro SelfUpdating</i><br><br>
DEV: <a href=https://github.com/coolshou/syncthingui>Coolshou</a><br>
Original DEV: <a href=https://github.com/juancarlospaco>JuanCarlos</a><br>
<br>
""" + getoutput(SYNCTHING + ' --version')
BASE_JS = """var custom_css = document.createElement("style");
custom_css.textContent = '*{font-family:Oxygen}';
custom_css.textContent += 'body{background-color:lightgray}';
custom_css.textContent += '.navbar-fixed-bottom{display:none}';
document.querySelector("head").appendChild(custom_css);"""
###############################################################################
class AnimatedSysTrayIcon(QSystemTrayIcon):
"""Animated SystemTrayIcon"""
def __init__(self, icon, period=1.0, parent=None, *args, **kwargs):
""" construct """
super(AnimatedSysTrayIcon, self).__init__(parent)
self.args = args
self.kwargs = kwargs
# Thread timer
self._interval = period # after this time, the timer will run
self.ani_timer = None
self.ani_stop = False
self.schedule_lock = Lock()
self.ani_icons = []
self.ani_idx = 0
self.mainicon = QIcon(icon)
self.setIcon(self.mainicon)
def add_ani_icon(self, QIcon):
"""add QIcon for animate use"""
self.ani_icons.append(QIcon)
def restore_icon(self):
"""restore to original icon"""
self.ani_idx = 0
self.setIcon(self.mainicon)
def _run(self):
"""
Run desired callback and then reschedule Timer
(if thread is not stopped)
"""
try:
self.update_trayicon()
except Exception as e:
# logging.exception("Exception in running periodic thread")
raise("Exception in running periodic thread")
finally:
with self.schedule_lock:
if not self.ani_stop:
self.schedule_timer()
def update_trayicon(self):
"""use ani_icons to loop update trayicon """
total = len(self.ani_icons)
self.ani_idx = self.ani_idx + 1
# print("ani_idx: %s" % self.ani_idx)
if self.ani_idx > (total - 1):
self.ani_idx = 0
icon = self.ani_icons[self.ani_idx]
self.setIcon(icon)
def animate_start(self):
"""
Mimics Thread standard start method
"""
total = len(self.ani_icons)
# print("total: %s" % total)
if total < 2:
try:
raise NameError("Too few icons to do animate!!")
finally:
raise
self.schedule_timer()
def schedule_timer(self):
"""
Schedules next Timer run
"""
self.ani_timer = Timer(self._interval, self._run,
*self.args, **self.kwargs)
self.ani_timer.start()
def animate_stop(self):
"""stop animate tray icon"""
with self.schedule_lock:
self.ani_stop = True
if self.ani_timer is not None:
self.ani_timer.cancel()
self.restore_icon()
class MainWindow(QMainWindow):
"""Main window class."""
def __init__(self):
"""Init class."""
super(MainWindow, self).__init__()
self.pixmap_syncthingui = QPixmap(":/images/syncthingui.svg")
tf = QTransform()
self.pixmap_syncthingui0 = QPixmap(":/images/syncthingui.svg")
tf.rotate(90.0)
self.pixmap_syncthingui1 = self.pixmap_syncthingui0.transformed(tf)
tf.rotate(180.0)
self.pixmap_syncthingui2 = self.pixmap_syncthingui0.transformed(tf)
tf.rotate(270.0)
self.pixmap_syncthingui3 = self.pixmap_syncthingui0.transformed(tf)
self.init_gui()
self.init_menu()
self.init_systray()
self.run()
self.view.show()
def init_gui(self):
"""init gui setup"""
self.setWindowIcon(QIcon(self.pixmap_syncthingui))
self.progressbar = QProgressBar()
self.statusBar().showMessage(getoutput(SYNCTHING + ' --version'))
self.statusBar().addPermanentWidget(self.progressbar)
self.setWindowTitle("%s (%s)" % (__doc__.strip().capitalize(), __version__))
self.setMinimumSize(900, 600)
self.setMaximumSize(1280, 1024)
self.resize(self.minimumSize())
self.center()
# QWebView
# self.view = QWebView(self)
self.view = QWebEngineView(self)
self.view.loadStarted.connect(self.start_loading)
self.view.loadFinished.connect(self.finish_loading)
self.view.loadProgress.connect(self.loading)
self.view.titleChanged.connect(self.set_title)
self.view.page().linkHovered.connect(
lambda link_txt: self.statusBar().showMessage(link_txt[:99], 3000))
QShortcut("Ctrl++", self, activated=lambda:
self.view.setZoomFactor(self.view.zoomFactor() + 0.2))
QShortcut("Ctrl+-", self, activated=lambda:
self.view.setZoomFactor(self.view.zoomFactor() - 0.2))
QShortcut("Ctrl+0", self, activated=lambda: self.view.setZoomFactor(1))
QShortcut("Ctrl+q", self, activated=lambda: self.close())
# syncthing console
self.consolewidget = QWidget(self)
# TODO: start at specify (w,h)
self.consolewidget.setMinimumSize(QSize(200, 100))
# TODO: setStyleSheet
# self.consolewidget.setStyleSheet("margin:0px; padding: 0px; \
# border:1px solid rgb(0, 0, 0);")
# border-radius: 40px;")
# TODO read syncthing console visible from setting
# self.consolewidget.setVisible(False)
# self.consolewidget.showEvent
# self.consoletextedit = QPlainTextEdit(parent=self.consolewidget)
self.consoletoolbar = QWidget(self)
hlayout = QHBoxLayout()
self.consoletoolbar.setLayout(hlayout)
self.consoletextedit = QTextEdit(parent=self.consolewidget)
self.consoletextedit.setWordWrapMode(QTextOption.NoWrap)
# self.consoletextedit.setStyleSheet(" border:1px solid rgb(0, 0, 0);")
# self.consoletextedit.setStyleSheet("margin:0px; padding: 0px;")
layout = QVBoxLayout()
layout.addWidget(self.consoletoolbar)
layout.addWidget(self.consoletextedit)
self.consolewidget.setLayout(layout)
self.splitter = QSplitter(Qt.Vertical)
self.splitter.addWidget(self.view)
self.splitter.addWidget(self.consolewidget)
# process
self.process = QProcess()
self.process.error.connect(self._process_failed)
# QProcess emits `readyRead` when there is data to be read
self.process.readyRead.connect(self._process_dataReady)
self.process.stateChanged.connect(self._process_stateChanged)
# Just to prevent accidentally running multiple times
# Disable the button when process starts, and enable it when it finishes
# self.process.started.connect(lambda: self.runButton.setEnabled(False))
# self.process.finished.connect(lambda: self.runButton.setEnabled(True))
# backend options
self.chrt = QCheckBox("Smooth CPU ", checked=True)
self.ionice = QCheckBox("Smooth HDD ", checked=True)
self.chrt.setToolTip("Use Smooth CPUs priority (recommended)")
self.ionice.setToolTip("Use Smooth HDDs priority (recommended)")
self.chrt.setStatusTip(self.chrt.toolTip())
self.ionice.setStatusTip(self.ionice.toolTip())
# main toolbar
self.toolbar = self.addToolBar("SyncthinGUI Toolbar")
# self.toolbar.addAction(QIcon.fromTheme("media-playback-stop"),
self.toolbar.addAction(QIcon(":/images/stop.svg"),
"Stop Sync", lambda: self.syncthing_stop())
# self.toolbar.addAction(QIcon.fromTheme("media-playback-start"),
self.toolbar.addAction(QIcon(":/images/start.svg"),
"Restart Sync", lambda: self.run())
self.toolbar.addSeparator()
self.toolbar.addWidget(self.chrt)
self.toolbar.addWidget(self.ionice)
self.toolbar.addSeparator()
# TODO: test event API
self.toolbar.addAction(QIcon(":/images/start.svg"),
"test ", lambda: self.test())
# final gui setup
self.setCentralWidget(self.splitter)
def test(self):
""" test some function """
print("test")
def init_menu(self):
"""init menu setup"""
# file menu
file_menu = self.menuBar().addMenu("File")
# TODO: setting menu item
file_menu.addAction("Exit", lambda: self.close())
# Syncthing menu
sync_menu = self.menuBar().addMenu("Syncthing")
sync_menu.addAction("Start Syncronization", lambda: self.run())
sync_menu.addAction("Stop Syncronization",
lambda: self.syncthing_stop())
# TODO: restart
# TODO: reflash F5
sync_menu.addAction("Open in external browser",
lambda: open_new_tab(URL))
# view menu
view_menu = self.menuBar().addMenu("View")
# TODO: syncthing console menu
view_menu.addAction("syncthing console", lambda: self.show_console)
#
zoom_menu = view_menu.addMenu("Zoom browser")
zoom_menu.addAction(
"Zoom In",
lambda: self.view.setZoomFactor(self.view.zoomFactor() + .2))
zoom_menu.addAction(
"Zoom Out",
lambda: self.view.setZoomFactor(self.view.zoomFactor() - .2))
zoom_menu.addAction(
"Zoom To...",
lambda: self.view.setZoomFactor(QInputDialog.getInt(
self, __doc__, "<b>Zoom factor ?:", 1, 1, 9)[0]))
zoom_menu.addAction("Zoom Reset", lambda: self.view.setZoomFactor(1))
view_menu.addSeparator()
act = view_menu.addAction("View Page Source",
lambda: self.view_syncthing_source)
act.setDisabled(True)
# window menu
window_menu = self.menuBar().addMenu("&Window")
window_menu.addAction("Minimize", lambda: self.showMinimized())
window_menu.addAction("Maximize", lambda: self.showMaximized())
window_menu.addAction("Restore", lambda: self.showNormal())
window_menu.addAction("Center", lambda: self.center())
window_menu.addAction("Top-Left", lambda: self.move(0, 0))
window_menu.addAction("To Mouse",
lambda: self.move_to_mouse_position())
window_menu.addAction("Fullscreen", lambda: self.showFullScreen())
window_menu.addSeparator()
window_menu.addAction("Increase size", lambda: self.resize(
self.size().width() * 1.2, self.size().height() * 1.2))
window_menu.addAction("Decrease size", lambda: self.resize(
self.size().width() // 1.2, self.size().height() // 1.2))
window_menu.addAction("Minimum size", lambda:
self.resize(self.minimumSize()))
window_menu.addAction("Maximum size", lambda:
self.resize(self.maximumSize()))
window_menu.addAction("Horizontal Wide", lambda: self.resize(
self.maximumSize().width(), self.minimumSize().height()))
window_menu.addAction("Vertical Tall", lambda: self.resize(
self.minimumSize().width(), self.maximumSize().height()))
window_menu.addSeparator()
window_menu.addAction("Disable Resize",
lambda: self.setFixedSize(self.size()))
# help menu
help_menu = self.menuBar().addMenu("&Help")
help_menu.addAction("Support Forum", lambda: open_new_tab(HELP_URL_0))
help_menu.addAction("Lastest Release",
lambda: open_new_tab(HELP_URL_1))
help_menu.addAction("Documentation", lambda: open_new_tab(HELP_URL_2))
help_menu.addAction("Bugs", lambda: open_new_tab(HELP_URL_3))
help_menu.addAction("Source Code", lambda: open_new_tab(HELP_URL_4))
help_menu.addSeparator()
help_menu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self))
help_menu.addAction("About Python 3",
lambda: open_new_tab('https://www.python.org'))
help_menu.addAction("About " + __doc__,
lambda: QMessageBox.about(self, __doc__, HELPMSG))
help_menu.addSeparator()
help_menu.addAction("Keyboard Shortcuts", lambda:
QMessageBox.information(self, __doc__, SHORTCUTS))
help_menu.addAction("View GitHub Repo", lambda: open_new_tab(__url__))
if not sys.platform.startswith("win"):
help_menu.addAction("Show Source Code", lambda: self.view_source())
help_menu.addSeparator()
help_menu.addAction("Check Updates", lambda: self.check_for_updates())
def init_systray(self):
"""init system tray icon"""
# self.tray = QSystemTrayIcon(QIcon(self.pixmap_syncthingui), self)
self.tray = AnimatedSysTrayIcon(QIcon(self.pixmap_syncthingui), self)
self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui0))
self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui1))
self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui2))
self.tray.add_ani_icon(QIcon(self.pixmap_syncthingui3))
self.tray.setToolTip(__doc__.strip().capitalize())
traymenu = QMenu(self)
traymenu.addAction(__doc__).setDisabled(True)
traymenu.addSeparator()
# to test animate
# traymenu.addAction("start", lambda: self.tray.animate_start())
# traymenu.addAction("stop", lambda: self.tray.animate_stop())
# traymenu.addSeparator()
traymenu.addAction("Stop Sync", lambda: self.syncthing_stop())
traymenu.addAction("Restart Sync", lambda: self.run())
traymenu.addSeparator()
traymenu.addAction("Show", lambda: self.show_gui())
traymenu.addAction("Hide", lambda: self.hide())
traymenu.addSeparator()
# traymenu.addAction("Open Web", lambda: open_new_tab(URL))
# traymenu.addAction("Quit All", lambda: self.close())
traymenu.addAction("Quit All", lambda: self.app_exit())
self.tray.setContextMenu(traymenu)
self.tray.show()
def show_gui(self):
"""
Helper method to show UI, this should not be needed, but I discovered.
"""
self.showNormal()
# webview require 70Mb to show webpage
self.view.load(QUrl(URL))
def syncthing_start(self):
"""syncthing start"""
self.run()
def syncthing_stop(self):
"""syncthing stop"""
print("try to stop syncthing")
self.process.kill()
# check there is no other syncthing is running!
for proc in psutil.process_iter():
# check whether the process name matches
# print("procress: %s " % proc.name())
if proc.name() == SYNCTHING:
proc.kill()
def run(self):
"""Run bitch run!."""
# Stop first!
self.syncthing_stop()
command_to_run_syncthing = " ".join((
"ionice --ignore --class 3" if self.ionice.isChecked() else "",
"chrt --verbose --idle 0" if self.chrt.isChecked() else "",
SYNCTHING, "-no-browser"))
print(command_to_run_syncthing)
self.process.start(command_to_run_syncthing)
if not self.process.waitForStarted():
self._process_failed()
@pyqtSlot()
def _process_failed(self):
"""Read and return errors."""
self.statusBar().showMessage("ERROR:Fail:Syncthing blow up in pieces!")
print("ERROR:Fail:Syncthing blow up in pieces! Wheres your God now?")
return str(self.process.readAllStandardError()).strip().lower()
@pyqtSlot()
def _process_dataReady(self):
"""get process stdout/strerr when data ready"""
# TODO: format the msg to remove extra b and \n
msg = str(self.process.readAll())
lines = msg.split("'")
tmp = lines[1]
tmp = tmp.splitlines(0)
lines = tmp[0].split("\\n")
for line in lines:
if line != "":
# print("1: %s" % line)
self.consoletextedit.append(line)
self.consoletextedit.ensureCursorVisible()
# autoscroll to last line's first character
self.consoletextedit.moveCursor(QTextCursor.End)
self.consoletextedit.moveCursor(QTextCursor.StartOfLine)
@pyqtSlot(QProcess.ProcessState)
def _process_stateChanged(self, state):
""" procress_stateChanged """
# TODO handle procress_stateChanged
print("procress_stateChanged: %s" % state)
def center(self):
"""Center Window on the Current Screen,with Multi-Monitor support."""
window_geometry = self.frameGeometry()
mousepointer_position = QApplication.desktop().cursor().pos()
screen = QApplication.desktop().screenNumber(mousepointer_position)
centerpoint = QApplication.desktop().screenGeometry(screen).center()
window_geometry.moveCenter(centerpoint)
self.move(window_geometry.topLeft())
def move_to_mouse_position(self):
"""Center the Window on the Current Mouse position."""
window_geometry = self.frameGeometry()
window_geometry.moveCenter(QApplication.desktop().cursor().pos())
self.move(window_geometry.topLeft())
def show_console(self):
"""Show syncthing console"""
visible = not self.consolewidget.isVisible
print("bVisible: %s" % visible)
self.consolewidget.setVisible(True)
self.consolewidget.resize(QSize(200, 100))
def view_source(self):
""" TODO: Call methods to load and display source code."""
# call(('xdg-open ' if sys.platform.startswith("linux") else 'open ')
# + __file__, shell=True)
pass
def view_syncthing_source(self):
"""Call methods to load and display web page source code."""
print("view_syncthing_source start")
# access_manager = self.view.page().networkAccessManager()
# reply = access_manager.get(QNetworkRequest(self.view.url()))
# reply.finished.connect(self.slot_source_downloaded)
def slot_source_downloaded(self):
"""Show actual page source code."""
reply = self.sender()
# TODO: highlight html source editor/viewer
self.textedit = QPlainTextEdit()
self.textedit.setAttribute(Qt.WA_DeleteOnClose)
self.textedit.setReadOnly(True)
self.textedit.setPlainText(QTextStream(reply).readAll())
self.textedit.show()
reply.deleteLater()
@pyqtSlot()
def start_loading(self):
"""show progressbar when downloading data"""
self.progressbar.show()
@pyqtSlot(bool)
def finish_loading(self, finished):
"""Finished loading content."""
if not finished:
# TODO: When loading fail, what should we do?
print("load fail")
if self.process.state() == QProcess.NotRunning:
self.run()
self.view.reload()
# if self.process.state != QProcess.Running:
# print("syncthing is not running: %s" % self.process.state())
# pass
print("finish_loading: %s" % finished)
# TODO: WebEngineView does not have following function?
# self.view.settings().clearMemoryCaches()
# self.view.settings().clearIconDatabase()
# print("finish_loading %s" % datetime.strftime(datetime.now(),
# '%Y-%m-%d %H:%M:%S'))
# TODO: following line need 6 sec to finish!!
# TODO: (" INFO: Loading Web UI increases >250Mb RAM!.")
# self.view.page().mainFrame().evaluateJavaScript(BASE_JS)
# print("finish_loading %s" % datetime.strftime(datetime.now(),
# '%Y-%m-%d %H:%M:%S'))
self.progressbar.hide()
@pyqtSlot(int)
def loading(self, idx):
"""loading content"""
#print("loading %s" % idx)
self.progressbar.setValue(idx)
@pyqtSlot(str)
def set_title(self, title):
"""set title when webview's title change"""
# print("title: %s" % title)
if len(title.strip()) > 0:
self.setWindowTitle(self.view.title()[:99])
def check_for_updates(self):
"""Method to check for updates from Git repo versus this version."""
# print("TODO: https://github.com/coolshou/syncthingui/releases/latest")
print("__version__: %s" % __version__)
'''
this_version = str(open(__file__).read())
print("this_version: %s" % this_version)
last_version = str(request.urlopen(__source__).read().decode("utf8"))
print("last_version: %s" % last_version)
TODO: previous use file compare, when diff then there is new file!!
if this_version != last_version:
m = "Theres new Version available!<br>Download update from the web"
else:
m = "No new updates!<br>You have the lastest version of" + __doc__
return QMessageBox.information(self, __doc__.title(), "<b>" + m)
'''
def closeEvent(self, event):
"""Ask to Quit."""
if self.tray.isVisible():
if self.tray.supportsMessages():
self.tray.showMessage("Info",
"The program will keep running in the "
"system tray. To terminate the program,"
" choose <b>Quit</b> in the context "
"menu of the system tray entry.")
else:
print(" System tray not supports balloon messages ")
self.hide()
event.ignore()
def app_exit(self):
"""exit app"""
# TODO: do we need to show UI when doing close?
# self.show_gui()
# TODO: show QMessageBox on all virtual desktop
the_conditional_is_true = QMessageBox.question(
self, __doc__.title(), 'Quit %s?' % __doc__,
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No) == QMessageBox.Yes
if the_conditional_is_true:
self.syncthing_stop()
self.ani_stop = True
QApplication.instance().quit
quit()
###############################################################################
class Application(QApplication):
"""wrapper QApplication to handle event"""
def event(self, event_):
"""application event overwrite"""
return QApplication.event(self, event_)
def signal_handler(signal_, frame):
"""signal handler"""
print('You pressed Ctrl+C!')
sys.exit(0)
def main():
"""Main Loop."""
appname = str(__package__ or __doc__)[:99].lower().strip().replace(" ", "")
try:
os.nice(19) # smooth cpu priority
libc = cdll.LoadLibrary('libc.so.6') # set process name
buff = create_string_buffer(len(appname) + 1)
buff.value = bytes(appname.encode("utf-8"))
libc.prctl(15, byref(buff), 0, 0, 0)
except Exception as reason:
print(reason)
# app = QApplication(sys.argv)
app = Application(sys.argv)
# Connect your cleanup function to signal.SIGINT
signal.signal(signal.SIGINT, signal_handler)
# And start a timer to call Application.event repeatedly.
# You can change the timer parameter as you like.
app.startTimer(200)
app.setApplicationName(__doc__.strip().lower())
app.setOrganizationName(__doc__.strip().lower())
app.setOrganizationDomain(__doc__.strip())
web = MainWindow()
app.aboutToQuit.connect(web.syncthing_stop)
try:
opts, args = getopt(sys.argv[1:], 'hv', ('version', 'help'))
except:
pass
for opt, val in opts:
if opt in ('-h', '--help'):
print(''' Usage:
-h, --help Show help informations and exit.
-v, --version Show version information and exit.''')
return sys.exit(1)
elif opt in ('-v', '--version'):
print(__version__)
return sys.exit(1)
# web.show() # comment out to hide/show main window, normally don't needed
sys.exit(app.exec_())
if __name__ in '__main__':
main()
|
import React, { useEffect, useRef, useState } from 'react';
import styles from './StopWatch.module.css';
export default function StopWatch() {
const [time, setTime] = useState(650);
const interval = useRef(null);
useEffect(() => {
startClick();
}, []);
function changeSecondstoTime(sec) {
let result = '00:00';
let minute = 0;
while (sec >= 60 && minute < 60) {
sec -= 60;
minute++;
}
if (minute === 60) {
return result;
}
let secResult = sec < 10 ? `0${sec}` : sec;
let minuteResult = minute < 10 ? `0${minute}` : minute;
result = `${minuteResult}:${secResult}`;
return result;
}
function startClick() {
if (interval.current) return;
interval.current = setInterval(() => {
setTime((time) => time + 1);
}, 1000);
}
function stopClick() {
clearInterval(interval.current);
interval.current = null;
}
function resetClick() {
stopClick();
setTime(0);
}
return (
<>
<div className={styles.timerShowContainer}>
<span className={styles.timerShow}>{changeSecondstoTime(time)}</span>
</div>
<button onClick={startClick}>start</button>
<button onClick={stopClick}>stop</button>
<button onClick={resetClick}>reset</button>
</>
);
}
|
package com.sakura.user.controller;
import com.sakura.user.param.AdminUserRoleParam;
import com.sakura.user.service.AdminUserRoleService;
import lombok.extern.slf4j.Slf4j;
import com.sakura.common.base.BaseController;
import com.sakura.common.api.ApiResult;
import com.sakura.common.log.Module;
import com.sakura.common.log.OperationLog;
import com.sakura.common.enums.OperationLogType;
import com.sakura.common.api.Add;
import org.springframework.validation.annotation.Validated;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* admin用户角色表 控制器
*
* @author Sakura
* @since 2023-09-26
*/
@Slf4j
@RestController
@RequestMapping("/adminUserRole")
@Module("user")
@Api(value = "admin用户角色API", tags = {"admin用户角色管理"})
public class AdminUserRoleController extends BaseController {
@Autowired
private AdminUserRoleService adminUserRoleService;
/**
* 添加用户角色表
*/
@PostMapping("/add")
@OperationLog(name = "添加用户角色", type = OperationLogType.ADD)
@ApiOperation(value = "添加用户角色", response = ApiResult.class)
public ApiResult<Boolean> addAdminUserRole(@Validated(Add.class) @RequestBody AdminUserRoleParam adminUserRoleParam) throws Exception {
boolean flag = adminUserRoleService.saveAdminUserRole(adminUserRoleParam);
return ApiResult.result(flag);
}
/**
* 删除用户角色表
*/
@PostMapping("/delete")
@OperationLog(name = "删除用户角色", type = OperationLogType.DELETE)
@ApiOperation(value = "删除用户角色", response = ApiResult.class)
public ApiResult<Boolean> deleteAdminUserRole(@Validated @RequestBody AdminUserRoleParam adminUserRoleParam) throws Exception {
boolean flag = adminUserRoleService.deleteAdminUserRole(adminUserRoleParam);
return ApiResult.result(flag);
}
}
|
const { Model, DataTypes } = require("sequelize");
const sequelize = require("../utils/sequelize");
class Card extends Model {}
Card.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
primaryKey: true,
autoIncrement: true,
},
user_id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
},
card_number: {
type: DataTypes.STRING(255),
allowNull: false,
},
issue_date: {
type: DataTypes.DATE,
allowNull: false,
},
expire_date: {
type: DataTypes.DATE,
allowNull: false,
},
balance: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false,
defaultValue: 0.0,
},
currency: {
type: DataTypes.STRING(10),
allowNull: false,
defaultValue: "CAD",
},
status: {
type: DataTypes.TINYINT,
allowNull: false,
comment: "0: expired, 1: active, 2: lost, 3: in review",
},
card_pin: {
type: DataTypes.STRING(255),
allowNull: false,
},
card_cvv: {
type: DataTypes.STRING(255),
allowNull: false,
},
card_form: {
type: DataTypes.TINYINT,
allowNull: false,
comment: "0: virtual, 1: physical",
},
card_type: {
type: DataTypes.TINYINT,
allowNull: false,
comment: "0: debit, 1: credit, 2: prepaid",
},
active_time: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
},
{
sequelize,
modelName: "Card",
tableName: "card",
timestamps: false,
}
);
module.exports = Card;
|
import { useContext } from "react";
import { useNavigate } from "react-router-dom";
import { CourseContext } from "../../contexts/course-context";
const Leftbar = () => {
const navigate = useNavigate();
const [, setCourseDetail] = useContext(CourseContext);
return (
<>
<div className="md:flex flex-col w-[100px] items-center px-3 py-5 left-0 sticky hidden ">
<div className="add w-11 h-11 text-white bg-[#1473e6] flex justify-center items-center rounded-full hover:text-[20px] transition-all cursor-pointer ">
<i className="fa-solid fa-plus"></i>
</div>
<div className="home mt-3">
<button
onClick={() => {
navigate("/");
}}
className="active:bg-[#e8ebed] hover:bg-slate-100 rounded-2xl focus:bg-[#e8ebed] border-[2px] border-[#fff] "
>
<div className="home w-[72px] h-[72px] flex flex-col text-center justify-center transition-all rounded-2xl">
<i className="fa-solid fa-house text-[20px] "></i>
<p className="text-[10px] mt-1 font-bold text-gray-500 ">Home</p>
</div>
</button>
<button
onClick={() => {
navigate("/roadmap");
}}
className="active:bg-[#e8ebed] hover:bg-slate-100 rounded-2xl focus:bg-[#e8ebed] border-[2px] border-[#fff] "
>
<div className="home w-[72px] h-[72px] flex flex-col text-center justify-center transition-all rounded-2xl">
<i className="fa-solid fa-road text-[20px]"></i>
<p className="text-[10px] mt-1 font-bold text-gray-500 ">
Lộ trình
</p>
</div>
</button>
<button
onClick={() => {
setCourseDetail({
id : ""
});
navigate("/courses")
}}
className="active:bg-[#e8ebed] hover:bg-slate-100 rounded-2xl focus:bg-[#e8ebed] border-[2px] border-[#fff] "
>
<div className="home w-[72px] h-[72px] flex flex-col text-center justify-center transition-all rounded-2xl">
<i className="fa-solid fa-lightbulb text-[23px]"></i>
<p className="text-[10px] mt-1 font-bold text-gray-500 ">Học</p>
</div>
</button>
<button
onClick={() => {
navigate("/blog");
}}
className="active:bg-[#e8ebed] hover:bg-slate-100 rounded-2xl focus:bg-[#e8ebed] border-[2px] border-[#fff] "
>
<div className="home w-[72px] h-[72px] flex flex-col text-center justify-center transition-all rounded-2xl">
<i className="fa-solid fa-newspaper text-[20px] "></i>
<p className="text-[10px] mt-1 font-bold text-gray-500 ">Blog</p>
</div>
</button>
</div>
</div>
</>
);
};
export default Leftbar;
|
import clr
import os
import math
# Import Revit API
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import FamilyLoadSettings, Color, FilteredElementCollector, BuiltInCategory, Transaction, ElementId, FamilySymbol, View, TextNoteType, BuiltInParameter, Family, IFamilyLoadOptions, XYZ, Line
# get the current document
doc = __revit__.ActiveUIDocument.Document
# Set up the color
blue = Color(44,128,255)
# Function to convert the color
def CreateINTColor(color):
return int(color.Red) + int(color.Green) * int(math.pow(2,8)) + int(color.Blue) * int(math.pow(2,16))
intblue = CreateINTColor(blue)
class FamilyOption(IFamilyLoadOptions):
def OnFamilyFound(self, familyInUse, overwriteParameterValues):
overwriteParameterValues = True
return True
def OnSharedFamilyFound(self, sharedFamily, familyInUse, source, overwriteParameterValues):
overwriteParameterValues = True
return True
# Define the base directory
base_dir = r"C:\Temp"
# Find the door tag family symbol
door_tags = FilteredElementCollector(doc).OfClass(FamilySymbol).OfCategory(BuiltInCategory.OST_DoorTags).ToElements()
# For each door tag family
for door_tag in door_tags:
# Get the family name
family_name = door_tag.Family.Name
# Open the family document
family_doc = doc.EditFamily(door_tag.Family)
# Collect all TextNoteTypes in the family document
text_note_types = FilteredElementCollector(family_doc).OfClass(clr.GetClrType(TextNoteType)).ToElements()
# Start a transaction
t = Transaction(family_doc, "Change color of text note type and create a line")
t.Start()
try:
# Change the color of each TextNoteType
for text_note_type in text_note_types:
print(text_note_type.get_Parameter(BuiltInParameter.LINE_COLOR).Set(intblue))
# Access the TEXT_FONT parameter and set it to a new value
print("Before:", text_note_type.get_Parameter(BuiltInParameter.TEXT_FONT).AsString())
text_note_type.get_Parameter(BuiltInParameter.TEXT_FONT).Set("Arial")
print("After:", text_note_type.get_Parameter(BuiltInParameter.TEXT_FONT).AsString())
# Get the first available view
view = FilteredElementCollector(family_doc).OfClass(View).FirstElement()
# Define start and end points
start = XYZ(0, 0, 0)
end = XYZ(10, 10, 0)
# Create a new Line
line = Line.CreateBound(start, end)
# Create a new DetailCurve
detailCurve = family_doc.FamilyCreate.NewDetailCurve(view, line)
# Commit the transaction if successful
t.Commit()
except Exception as ex:
# Roll back the transaction in case of error
print("Error: ", ex)
if t.HasStarted(): # Check if the transaction has started before rolling back
t.RollBack()
# Proceed with the rest of the code after the try-except block
# Create a unique file path for the family
temp_file_path = os.path.join(base_dir, "{}.rfa".format(family_name))
# Before saving the family document
if os.path.exists(temp_file_path):
os.remove(temp_file_path) # This will delete the existing file
# After saving the family document
family_doc.SaveAs(temp_file_path)
# Close the family document
family_doc.Close(False)
# And when you load the family:
loadOpts = FamilyOption()
loadSuccess, familyOut = doc.LoadFamily(temp_file_path, loadOpts)
family = familyOut
# Get the FamilySymbol for the loaded family
familySymbol = family.FamilySymbols.GetEnumerator()
familySymbol.MoveNext()
familySymbol = familySymbol.Current
# Start a transaction to update the instances
t3 = Transaction(doc, "Update instances")
t3.Start()
# Find the instances of the door tag in the document
instances = FilteredElementCollector(doc).OfClass(FamilyInstance).OfCategory(BuiltInCategory.OST_DoorTags).ToElements()
# For each instance, set the symbol to the loaded family symbol
for instance in instances:
instance.Symbol = familySymbol
t3.Commit()
# Regenerate the document
t2 = Transaction(doc, "Regenerate document")
t2.Start()
doc.Regenerate()
t2.Commit()
|
import React, { useContext, useState } from 'react';
import { Main, Scroll, Column, Label, Title, Row, Button, SubLabel } from '@theme/global';
import { ThemeContext } from 'styled-components/native';
import { MotiImage } from 'moti';
import { Dimensions, FlatList, TextInput } from 'react-native';
import { Search } from 'lucide-react-native'
import { useNavigation } from '@react-navigation/native';
const { width , height } = Dimensions.get('window');
export default function SearchScreen({ navigation, }) {
const { color, font, margin} = useContext(ThemeContext);
const [type, settype] = useState('Pastor');
return (
<Main >
<MotiImage source={require('@imgs/search.png')} style={{ width: width, height: height, position: 'absolute', top: 1, }} />
<Button onPress={() => navigation.goBack()} style={{ position: 'absolute', top: 10, zIndex: 999, alignSelf: 'center', width: 82, height: 10, borderRadius: 100, backgroundColor: '#ffffff50', }}>
<Column/>
</Button>
<Scroll>
<Column style={{ marginHorizontal: margin.h, marginVertical: margin.v,}}>
<Title style={{ fontSize: 32, }}>Buscador</Title>
<Row>
<TextInput placeholderTextColor="#70707090" style={{ backgroundColor:"#fff", flexGrow: 1, borderRadius: 12, padding: 16, fontFamily: font.bold, fontSize: 24, marginVertical: 16, }} placeholder='Buscar...'/>
<Search size={24} color="#000" style={{ position: 'absolute', top: 36, right: 20, }}/>
</Row>
<Row style={{ alignItems: 'center', marginVertical: 4, }}>
<Button style={{ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 6,}} onPress={() => {settype('Ministracao')}} >
<Label style={{ fontFamily: 22, color: type === 'Ministracao' ? '#fff' : color.label, fontFamily:'Font_Medium', textDecorationLine: type === 'Ministracao' ? 'underline' : 'none', textDecorationStyle: type === 'Ministracao' ? 'solid' : 'none', }}>Ministração</Label>
</Button>
<Button style={{ paddingHorizontal: 12, marginHorizontal: 10, paddingVertical: 6, borderRadius: 6, }} onPress={() => {settype('Pastor')}} >
<Label style={{ fontFamily: 22, color: type === 'Pastor' ? '#fff' : color.label, fontFamily:'Font_Medium', textDecorationLine: type === 'Pastor' ? 'underline' : 'none', textDecorationStyle: type === 'Pastor' ? 'solid' : 'none', }}>Pastor</Label>
</Button>
<Button style={{ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 6, }} onPress={() => {settype('Capitulo')}} >
<Label style={{ fontFamily: 22, color: type === 'Capitulo' ? '#fff' : color.label, fontFamily:'Font_Medium', textDecorationLine: type === 'Capitulo' ? 'underline' : 'none', textDecorationStyle: type === 'Capitulo' ? 'solid' : 'none', }}>Capítulo</Label>
</Button>
</Row>
<Button onPress={() => {}} style={{ justifyContent: 'center', alignItems: 'center', paddingVertical: 12, marginVertical: 12, borderWidth: 1, borderColor: '#ffffff50', backgroundColor: '#ffffff25', borderRadius: 100, }}>
<SubLabel style={{ }}>Pesquisar</SubLabel>
</Button>
<Column style={{flexGrow: 1, height: 1, backgroundColor: '#ffffff20', marginVertical: 12, }} />
<Title>Resultados</Title>
<FlatList
data={data}
keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => <Result item={item} />}
ListEmptyComponent={<Empty />}
/>
</Column>
</Scroll>
</Main>
)
}
const data = [{
id: 1,
name: 'Avivamento',
desc: 'Conjunto de ministrações.',
img: require('@imgs/avivamento.png'),
chapters: 12,
duration: '26min',
}]
const Result = ({item}) => {
const navigation = useNavigation();
return(
<Button style={{ marginTop: 12, borderRadius: 12,}} onPress={() => {navigation.navigate('SerieSingle', {item: item,})}} >
<Row >
<MotiImage from={{opacity: 0, translateY: 20,}} animate={{opacity: 1, translateY: 0,}} source={item.img} style={{ width: 110, height: 180, borderRadius: 12, }} />
<Column style={{ marginLeft: 30, }}>
<Label style={{ textDecorationLine: 'underline', textDecorationStyle:'solid', fontSize: 16, }}>Disponível me Libras</Label>
<Title style={{ fontSize: 24, marginVertical: 4, }}>{item?.name}</Title>
<Label>{item?.desc}</Label>
<Label style={{ fontSize: 16, }}>{item?.chapters} capítulos - {item?.duration}</Label>
<Row style={{ marginTop: 16, }}>
<Button style={{ paddingVertical: 6, paddingHorizontal: 18, borderRadius: 100, backgroundColor: '#fff', }}>
<SubLabel style={{ color: "#000", }}>Assistir</SubLabel>
</Button>
<Button style={{ backgroundColor: '#30303090', borderWidth:1, borderColor: '#505050', borderRadius:100, paddingVertical: 6, paddingHorizontal: 18, marginLeft: 12,}}>
<SubLabel>Sobre</SubLabel>
</Button>
</Row>
</Column>
</Row>
</Button>
)
}
const Empty = () => {
return(
<Column style={{ marginVertical: 20, }}>
<MotiImage from={{opacity: 0, translateY: 20,}} animate={{opacity: 1, translateY: 0,}} source={require('@imgs/empty.png')} style={{ width: 120, height: 120, alignSelf: 'center' }} />
<Title style={{ textAlign: 'center' }}>Não conseguimos encontrar...</Title>
<Label style={{ textAlign: 'center' }}>Que tal tentar utilizar outro termo?</Label>
<Button style={{ paddingHorizontal: 24, paddingVertical: 10, backgroundColor: '#fff', borderRadius: 100, justifyContent: 'center', alignItems: 'center', alignSelf: 'center', marginTop: 20, }}>
<SubLabel style={{ color: '#000', textAlign:'center',}}>Limpar</SubLabel>
</Button>
</Column>
)}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="index.css">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
LimeGreen: "hsl(163, 72%, 41%)",
BrightRed:" hsl(356, 69%, 56%)",
Facebook: "hsl(208, 92%, 53%)",
Twitter: "hsl(203, 89%, 53%)",
InstagramFirst: "hsl(37, 97%, 70%)",
InstagramFirst: "hsl(329, 70%, 58%)",
YouTube: "hsl(348, 97%, 39%)",
ToggleFirst: "hsl(210, 78%, 56%)",
ToggleSecond: " hsl(146, 68%, 55%)",
// Light Theme
ToggleLight: "hsl(230, 22%, 74%)",
// Dark Theme
VeryDarkBlue: "hsl(230, 17%, 14%)",
VeryDarkBlue: "hsl(232, 19%, 15%)",
DarkDesaturatedBlue: "hsl(228, 28%, 20%)",
DesaturatedBlueText: "hsl(228, 34%, 66%)",
WhiteText:"hsl(0, 0%, 100%)",
// Light Theme
WhiteBg :" hsl(0, 0%, 100%)",
VeryPaleBlue: "hsl(225, 100%, 98%)",
LightGrayishBlue: "hsl(227, 47%, 96%)",
DarkGrayishBlue: "hsl(228, 12%, 44%)",
VeryDarkBlue: "hsl(230, 17%, 14%)",
}
}
}
}
</script>
<link rel="icon" type="image/png" sizes="32x32" href="./social-media-dashboard-with-theme-switcher-master/images/favicon-32x32.png">
<title>Frontend Mentor | Social-Media Dashboard</title>
</head>
<body class="min-h-screen">
<div class="px-[100px] py-[50px] max-[1100px]:px-[20px]">
<div class="flex justify-between max-[850px]:block">
<div>
<h1 class="text-WhiteText text-[35px] font-[600] dark-text title max-[500px]:text-[25px]">Social Media Dashboard</h1>
<p class="text-DesaturatedBlueText font-[500]">Total Followers: 23,004</p>
</div>
<div class="flex gap-[20px] mt-[20px] max-[850px]:justify-between max-[850px]:bg-VeryDarkBlue max-[850px]:p-[10px]">
<p class="text-DesaturatedBlueText font-[500] pt-[5px]">Dark Mode</p>
<div class="toggle-switch">
<input type="checkbox" id="toggle" class="checkbox">
<label for="toggle" class="label"></label>
</div>
</div>
</div>
<div class="py-[50px] flex justify-between max-[1100px]:flex-col">
<div class="px-[60px] py-[40px] text-center justify-center items-center flex flex-col bg-DarkDesaturatedBlue rounded-[10px]
border-t-8 border-Facebook w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px] ">
<div class="flex gap-[10px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-facebook.svg" alt="" class="w-[30px]">
<p class="text-DesaturatedBlueText font-[600] pt-[3px]">@nathanf</p>
</div>
<h1 class="text-[60px] text-WhiteText font-[600] pt-[10px] dark-text">1987</h1>
<p class="tracking-[5px] uppercase text-DesaturatedBlueText">followers</p>
<div class="block pt-[20px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="" class="inline-block">
<p class="inline-block text-LimeGreen font-[600]">12 Today</p>
</div>
</div>
<div class="px-[60px] py-[40px] text-center justify-center items-center flex flex-col bg-DarkDesaturatedBlue rounded-[10px]
border-t-8 border-Twitter w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="flex gap-[10px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-twitter.svg" alt="" class="w-[30px]">
<p class="text-DesaturatedBlueText font-[600] pt-[3px]">@nathanf</p>
</div>
<h1 class="text-[60px] text-WhiteText font-[600] pt-[10px] dark-text">1044</h1>
<p class="tracking-[5px] uppercase text-DesaturatedBlueText">followers</p>
<div class="block pt-[20px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="" class="inline-block">
<p class="inline-block text-LimeGreen font-[600]">99 Today</p>
</div>
</div>
<div class="px-[60px] py-[40px] text-center justify-center items-center flex flex-col bg-DarkDesaturatedBlue rounded-[10px]
gradient-border-top w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="flex gap-[10px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-instagram.svg" alt="" class="w-[30px]">
<p class="text-DesaturatedBlueText font-[600] pt-[3px]">@realnathanf</p>
</div>
<h1 class="text-[60px] text-WhiteText font-[600] pt-[10px] dark-text">11k</h1>
<p class="tracking-[5px] uppercase text-DesaturatedBlueText">followers</p>
<div class="block pt-[20px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="" class="inline-block">
<p class="inline-block text-LimeGreen font-[600]">99 Today</p>
</div>
</div>
<div class="px-[60px] py-[40px] text-center justify-center items-center flex flex-col bg-DarkDesaturatedBlue rounded-[10px]
border-t-8 border-YouTube w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="flex gap-[10px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-youtube.svg" alt="" class="w-[30px]">
<p class="text-DesaturatedBlueText font-[600] pt-[3px]">Nathan F.</p>
</div>
<h1 class="text-[60px] text-WhiteText font-[600] pt-[10px] dark-text">8239</h1>
<p class="tracking-[5px] uppercase text-DesaturatedBlueText">Subscribers</p>
<div class="block pt-[20px]">
<img src="./social-media-dashboard-with-theme-switcher-master/images/icon-down.svg" alt="" class="inline-block">
<p class="inline-block text-BrightRed font-[600]">144 Today</p>
</div>
</div>
</div>
<h1 class="text-WhiteText font-[600] text-[30px] dark-text title max-[500px]:text-[25px]"> Overview - Today</h1>
<div class="flex flex-col">
<div class="flex justify-between py-[20px] max-[1100px]:flex-col">
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Page Views</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-facebook.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">87</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="">
<p class="inline-block text-LimeGreen">3%</p>
</div>
</div>
</div>
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Likes</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-facebook.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">52</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-down.svg" alt="">
<p class="inline-block text-BrightRed">2%</p>
</div>
</div>
</div>
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Likes</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-instagram.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">5462</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="">
<p class="inline-block text-LimeGreen">2257%</p>
</div>
</div>
</div>
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:mt-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Profile Views</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-instagram.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">52k</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="">
<p class="inline-block text-LimeGreen">1375%</p>
</div>
</div>
</div>
</div>
<div class="flex justify-between py-[20px] max-[1100px]:flex-col">
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:mb-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Retweets</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-twitter.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">117</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="">
<p class="inline-block text-LimeGreen">303%</p>
</div>
</div>
</div>
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Likes</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-twitter.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">507</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-up.svg" alt="">
<p class="inline-block text-LimeGreen">553%</p>
</div>
</div>
</div>
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Likes</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-youtube.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">107</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-down.svg" alt="">
<p class="inline-block text-BrightRed">19%</p>
</div>
</div>
</div>
<div class="p-[20px] bg-DarkDesaturatedBlue rounded-[10px] w-[24%] light-bg max-[1100px]:w-[100%] max-[1100px]:my-[20px]">
<div class="justify-between flex pb-[10px]">
<p class="text-DesaturatedBlueText ">Total Views</p>
<img class="h-[20px]" src="./social-media-dashboard-with-theme-switcher-master/images/icon-youtube.svg" alt="">
</div>
<div class="flex justify-between">
<h2 class="text-WhiteText text-[30px] font-[600] dark-text">1407</h2>
<div class="block mt-[15px]">
<img class="inline-block" src="./social-media-dashboard-with-theme-switcher-master/images/icon-down.svg" alt="">
<p class="inline-block text-BrightRed">12%</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
|
import threading
import time
import random
from queue import Queue
TAMANO_BUFFER = 5
buffer = Queue(maxsize=TAMANO_BUFFER)
def productor():
while True:
item = random.randint(1, 100)
buffer.put(item)
print(f"Productor produjo: {item}")
time.sleep(random.uniform(0.1, 0.5))
def consumidor():
while True:
item = buffer.get()
print(f"Consumidor consumió: {item}")
buffer.task_done()
time.sleep(random.uniform(0.1, 0.5))
# Crear hilos de productores y consumidores
hilos = [threading.Thread(target=productor) for _ in range(3)] + [threading.Thread(target=consumidor) for _ in range(2)]
# Iniciar hilos
for hilo in hilos:
hilo.start()
# Esperar a que todos los hilos terminen (esto se ejecuta en un ciclo infinito)
for hilo in hilos:
hilo.join()
|
package ma.youcode.gathergrid.repositories;
import jakarta.enterprise.context.RequestScoped;
import jakarta.enterprise.inject.Model;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceUnit;
import jakarta.transaction.Transactional;
import ma.youcode.gathergrid.config.UserDatabase;
import ma.youcode.gathergrid.domain.Role;
import ma.youcode.gathergrid.domain.User;
import java.util.List;
import java.util.Optional;
@RequestScoped
public class UserRepositoryImpl implements UserRepository {
private EntityManager em;
@Inject
public UserRepositoryImpl(@UserDatabase EntityManager em) {
this.em = em;
}
@Override
@Transactional
public Optional<User> findByUsername(String username) {
System.out.println("Getting user by username: " + username);
return em.createQuery("select u from User u where u.username = :username", User.class)
.setParameter("username", username)
.getResultStream().findAny();
}
@Override
public void save(User user) {
System.out.println("saving user... " + user);
Role userRole = em.createQuery("select r from Role r where r.name = :name", Role.class)
.setParameter("name", "USER")
.getResultStream().findAny().orElse(null);
if (userRole == null) {
userRole = new Role("USER");
em.persist(userRole);
}
user.setRole(userRole);
em.merge(user);
}
@Override
@Transactional
public void update(User user) {
em.merge(user);
em.flush();
em.clear();
}
@Override
@Transactional
public void delete(User user) {
em.remove(user);
}
@Override
@Transactional
public List<User> findAll() {
return em.createQuery("select u from User u", User.class).getResultList();
}
@Override
public Optional<User> findByName(String userName) {
return em.createQuery("select u from User u where u.name = :name", User.class)
.setParameter("name", userName)
.getResultStream().findAny();
}
}
|
package com.example.MyBoxYoonho;
import com.example.MyBoxYoonho.dao.UserDAO;
import com.example.MyBoxYoonho.domain.User;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import java.util.List;
import java.util.Scanner;
@SpringBootApplication
@EnableJpaAuditing
public class MyBoxYoonhoApplication {
public static void main(String[] args) {
SpringApplication.run(MyBoxYoonhoApplication.class, args);
}
// createMultipleStudent(userDAO);
// readStudent(userDAO);
// queryForStudentsByLastName(userDAO);
// updateStudent(userDAO);
// deleteStudent(userDAO);
// deleteAllStudent(userDAO);
@Bean
public CommandLineRunner commandLineRunner(UserDAO userDAO, String[] args){
return runner -> {
// createStudent(userDAO);
// queryForUsers(userDAO);
// createUserByCommand(userDAO);
System.out.println("If you enter 1, we will create a new User instance for you.");
System.out.println("If you enter 2, we will create a new User query for you.");
System.out.println("If you enter 3, we will delete a User with your given Id.");
System.out.println("If you enter 4, we will delete all the users.");
System.out.println("If you enter 5, we will get your usedStorage and remainingStorage values.");
Scanner scanner = new Scanner(System.in);
int command = scanner.nextInt();
System.out.println(command);
while(true){
if(command == 1){
createUserByCommand(userDAO);
}else if (command == 2){
queryForUsers(userDAO);
}else if (command == 3){
String deleteId = scanner.next();
deleteStudent(userDAO, Integer.parseInt(deleteId));
}else if (command == 4){
deleteAllStudent(userDAO);
}else if (command == 5){
System.out.println("not implemented yet");
}else{
break;
}
System.out.println("Please write the next command.");
command = scanner.nextInt();
}
};
}
private void deleteAllStudent(UserDAO userDAO) {
System.out.println("delete all");
userDAO.deleteAll();
}
private void deleteStudent(UserDAO userDAO, Integer deleteId) {
System.out.println("deleting id: " + deleteId);
userDAO.delete(deleteId);
}
private void updateStudent(UserDAO userDAO) {
// retrieve student based on the id: primary key
int studentId = 1;
System.out.println("Getting student with id: " + studentId);
User myUser = userDAO.findById(studentId);
// change first name to scooby
System.out.println("Updating");
myUser.setUsedStorage(3.3);
// update the student
userDAO.update(myUser);
// display the updated student
System.out.println("updated: " + myUser);
}
private void queryForUsers(UserDAO userDAO) {
// get a list of students
List<User> theUsers = userDAO.findAll();
// display list of students
for(User tempStudent: theUsers){
System.out.println(tempStudent);
}
}
private void readStudent(UserDAO userDAO) {
// create a student object
System.out.println("creating new student..");
User tempStudent = new User(2.2 , 4.4);
// save the student
System.out.println("saving the student..");
userDAO.save(tempStudent);
// display id of the saved student
System.out.println("student: " + tempStudent.getId());
// retrieve student based on the id: primary key
System.out.println("Retrieving ... ");
User myStudent = userDAO.findById(tempStudent.getId());
}
/*
private void createMultipleStudent(UserDAO userDAO) {
// create multiple student object
System.out.println("creating 3 student object");
User tempStudent1 = new Student("Um", "Junsik", "junsik.com");
User tempStudent2 = new Student("Yoonho", "Kim", "yoonho.com");
User tempStudent3 = new Student("Hyunji", "Lee", "hyongding.com");
// save multiple student object
System.out.println("saving the student");
studentDAO.save(tempStudent1);
studentDAO.save(tempStudent2);
studentDAO.save(tempStudent3);
// display id of the saved student
System.out.println("Saved. : " +tempStudent1.getId());
System.out.println("Saved. : " +tempStudent2.getId());
System.out.println("Saved. : " +tempStudent3.getId());
}
*/
private void createStudent(UserDAO userDAO) {
// create the student object
System.out.println("creating new student object");
User tempStudent = new User(4.1, 2.2);
// save the student object
System.out.println("saving the student");
userDAO.save(tempStudent);
// display id of the saved student
System.out.println("Saved. : " +tempStudent.getId());
}
void createUserByCommand(UserDAO userDAO){
System.out.println("Create new User object.");
System.out.println("Your total storage is 30GB.");
User newUser = new User(0, 30);
userDAO.save(newUser);
System.out.println("New user saved, your id is : " + newUser.getId());
}
}
|
import { Controller, Get, Request, BadRequestException, Post, Param, UseGuards, Delete, Body, } from '@nestjs/common';
import { ShoppingCartService } from './shopping-cart.service';
import { ShoppingCart } from './interfaces/shopping-cart.interface';
import { JwtService } from '@nestjs/jwt';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
import { RolesGuard } from 'src/auth/roles.guard';
import { Roles } from 'src/auth/roles.decorator';
import { AddToCartDto } from './dto/add-to-cart.dto';
import { ModifyCartQtyDto } from './dto/modify-cart-qty.dto';
import { Product } from 'src/products/interfaces/product.interface';
@Controller('api/shopping-cart')
export class ShoppingCartController {
constructor(
private readonly shoppingCartService: ShoppingCartService,
private readonly jwtService: JwtService,
) {}
@Get()
findMyCart(@Request() req): Promise<ShoppingCart> {
let cartId: string;
if(req.cartid) {
cartId = req.cartid;
} else {
throw new BadRequestException("Unable to determine valid cart.")
}
return this.shoppingCartService.getCart(cartId);
}
@UseGuards(JwtAuthGuard)
@Post('assign-user-to-cart')
async assignUserToCart(@Request() req): Promise<ShoppingCart> {
let username = await this.jwtService.decode(req.cookies['jwt'])['username'];
return this.shoppingCartService.assignUserToCart(req.cartid, username);
}
@Roles('superuser', 'admin')
@UseGuards(JwtAuthGuard, RolesGuard)
@Delete('delete/:id')
async deleteOneById(@Param() params): Promise<ShoppingCart> {
return this.shoppingCartService.destroyCart(params.id);
}
@Post('add-to-cart')
async addToCart(@Request() req, @Body() addToCartDto: AddToCartDto): Promise<ShoppingCart> {
return this.shoppingCartService.addItemToCart(
req.cartid,
addToCartDto.product,
addToCartDto.qty
);
}
@Post('modify-cart-qty')
async modifyCart(@Request() req, @Body() modifyCartQtyDto: ModifyCartQtyDto): Promise<ShoppingCart> {
return this.shoppingCartService.modifyItemInCart(
req.cartid,
modifyCartQtyDto.product,
modifyCartQtyDto.qty
);
}
@Get('secret')
async createIntentAndRetrieveSecret(@Request() req): Promise<Object> {
const cart = await this.shoppingCartService.getCart(req.cartid);
const paymentIntent = await this.shoppingCartService.createPaymentIntent(cart.total, "aud", {"orderid": req.cookies["mm-orderid"]});
this.shoppingCartService.assignPaymentIntentToCart(req.cartid, paymentIntent.id);
let secretObj = {};
secretObj["secret"] = paymentIntent.client_secret
return secretObj;
}
@Post('remove-item')
async removeItemFromCart(@Request() req, @Body() product: Product): Promise<ShoppingCart> {
return this.shoppingCartService.removeItemFromCart(req.cartid, product);
}
}
|
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const env = require('dotenv');
const authRoutes = require('./src/routes/auth');
const userRoutes = require('./src/routes/user');
const categoryRoutes = require('./src/routes/category');
const productRoutes = require('./src/routes/product');
const cors = require('cors');
// Cors
app.use(cors());
env.config();
// DB Connection
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection
.on('open', () => {
console.log('Mongoose connection open');
})
.on('error', (err) => {
console.log(`Connection error: ${err.message}`);
});
// Middleware
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
// Routes Middleware
app.use('/api', authRoutes);
app.use('/api', userRoutes);
app.use('/api', categoryRoutes);
app.use('/api', productRoutes);
// Port
const port = process.env.PORT || 8000;
// Server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
|
#!/usr/bin/env python3
"""Typing more generalized inputs and output"""
from typing import Sequence, Any, Union
def safe_first_element(lst: Sequence[Any]) -> Union[Any, None]:
"""Returns the first element of a sequence.
Args:
lst: The list.
Returns:
The first element of the list. Otherwise None.
"""
if lst:
return lst[0]
else:
return None
|
<div *ngIf="noHay" class="alert alert-danger" role="alert">
<div class="alert-items">
<div class="alert-item static">
<div class="alert-icon-wrapper">
<clr-icon class="alert-icon" shape="exclamation-circle"></clr-icon>
</div>
<span class="alert-text">
Esta liga no tiene equipos, debera crear alguno.
</span>
</div>
</div>
</div>
<div class="clr-row">
<div class="clr-col-2" *ngFor="let liga of ligas">
<div class="card clickable" (click)="hola(liga._id)">
<div class="card-header">
Nombre de la liga
</div>
<div class="card-block">
<p class="card-text">
{{ liga.nombreLiga }}
</p>
</div>
<div class="card-footer">
<a class="btn btn-sm btn-link">Seleccionar</a>
</div>
</div>
</div>
<button
type="button"
(click)="agregarLiga()"
class="btn btn-icon btn-success"
>
<clr-icon shape="plus"></clr-icon>Agregar Liga
</button>
</div>
<div *ngIf="mostrar">
<!-- <table class="table">
<thead>
<tr>
<th>Nombre</th>
<th>Goles a Favor</th>
<th>Goles en Contra</th>
<th>Diferencia de Goles</th>
<th>Partidos Jugados</th>
<th>Puntos</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let equipo of equiposLiga">
<td>{{ equipo.nombreEquipo }}</td>
<td>{{ equipo.golesAFavor }}</td>
<td>{{ equipo.golesEnContra }}</td>
<td>{{ equipo.diferenciaDeGoles }}</td>
<td>{{ equipo.partidosJugados }}</td>
<td>{{ equipo.puntos }}</td>
</tr>
</tbody>
</table> -->
<div *ngIf="equiposLiga != 'undefined'">
<clr-datagrid>
<clr-dg-column>Nombre</clr-dg-column>
<clr-dg-column>Goles a Favor</clr-dg-column>
<clr-dg-column>Goles en Contra</clr-dg-column>
<clr-dg-column>Diferencia de Goles</clr-dg-column>
<clr-dg-column>Partidos Jugados</clr-dg-column>
<clr-dg-column>Puntos</clr-dg-column>
<clr-dg-column></clr-dg-column>
<clr-dg-row *ngFor="let equipo of equiposLiga">
<clr-dg-cell>{{ equipo.nombreEquipo }}</clr-dg-cell>
<clr-dg-cell>{{ equipo.golesAFavor }}</clr-dg-cell>
<clr-dg-cell>{{ equipo.golesEnContra }}</clr-dg-cell>
<clr-dg-cell>{{ equipo.diferenciaDeGoles }}</clr-dg-cell>
<clr-dg-cell>{{ equipo.partidosJugados }}</clr-dg-cell>
<clr-dg-cell>{{ equipo.puntos }}</clr-dg-cell>
<clr-dg-cell><img src="{{ url + 'obtener-imagen/' + equipo.imagen }}" width="50" height="50" alt="Imagen"></clr-dg-cell>
</clr-dg-row>
</clr-datagrid>
</div>
<button type="button" class="btn btn-primary" (click)="mostrarModalEquipo = !mostrarModalEquipo">Agregar Equipo</button>
<button type="button" class="btn btn-primary" (click)="mostrarModalMarcador = !mostrarModalMarcador">Agregar Marcador</button>
<div *ngIf="radarChartData.length != 0">
<div>
<div style="display: block">
<canvas
baseChart
[datasets]="radarChartData"
[options]="radarChartOptions"
[labels]="radarChartLabels"
[chartType]="radarChartType"
>
</canvas>
</div>
</div>
</div>
</div>
<!-- Seccion para modals -->
<clr-modal [(clrModalOpen)]="mostrarModalLiga">
<h3 class="modal-title">Agregar nueva liga</h3>
<div class="modal-body">
<form clrForm>
<clr-input-container>
<label>Nombre de la liga</label>
<input
placeholder="Full name"
clrInput
[(ngModel)]="nombreNuevaLiga"
name="name"
required
/>
<clr-control-helper>No uses caracteres extraños</clr-control-helper>
<clr-control-error>Este campo es obligatorio!</clr-control-error>
</clr-input-container>
</form>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-outline"
(click)="mostrarModalLiga = !mostrarModalLiga"
>
Cancel
</button>
<button type="button" class="btn btn-primary" (click)="agregarLiga()">
Ok
</button>
</div>
</clr-modal>
<clr-modal [(clrModalOpen)]="mostrarModalEquipo">
<h3 class="modal-title">Agregar nuevo equipo</h3>
<div class="modal-body">
<form clrForm>
<clr-input-container>
<label>Nombre del equipo</label>
<input
placeholder="nombre"
clrInput
[(ngModel)]="nombreEquipo"
name="name"
required
/>
<clr-control-helper>No uses caracteres extraños</clr-control-helper>
<clr-control-error>Este campo es obligatorio!</clr-control-error>
</clr-input-container>
</form>
<form clrForm>
<clr-input-container>
<label>Nombre goles a favor</label>
<input
placeholder="No. goles"
clrInput
[(ngModel)]="golesAFavor"
name="name"
required
/>
<clr-control-helper>No uses caracteres extraños</clr-control-helper>
<clr-control-error>Este campo es obligatorio!</clr-control-error>
</clr-input-container>
</form>
<form clrForm>
<clr-input-container>
<label>Goles en contra</label>
<input
placeholder="No. goles"
clrInput
[(ngModel)]="golesEnContra"
name="name"
required
/>
<clr-control-helper>No uses caracteres extraños</clr-control-helper>
<clr-control-error>Este campo es obligatorio!</clr-control-error>
</clr-input-container>
</form>
<form clrForm>
<clr-input-container>
<label>Partidos jugados</label>
<input
placeholder="No. partidos"
clrInput
[(ngModel)]="partidosJugados"
name="name"
required
/>
<clr-control-helper>No uses caracteres extraños</clr-control-helper>
<clr-control-error>Este campo es obligatorio!</clr-control-error>
</clr-input-container>
</form>
<form clrForm>
<clr-input-container>
<label>Puntos</label>
<input
placeholder="No. puntos"
clrInput
[(ngModel)]="puntos"
name="name"
required
/>
<clr-control-helper>No uses caracteres extraños</clr-control-helper>
<clr-control-error>Este campo es obligatorio!</clr-control-error>
</clr-input-container>
</form>
<button (click)="fileInput.click()" type="button" class="btn btn-icon">
<clr-icon shape="home"></clr-icon>Agregar imagen
</button>
<input hidden type="file" #fileInput id="file" (change)="fileChangeEvent($event)"/>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-outline"
(click)="mostrarModalEquipo = !mostrarModalEquipo"
>
Cancel
</button>
<button type="button" class="btn btn-primary" (click)="agregarEquipo()">
Ok
</button>
</div>
</clr-modal>
|
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
export const fetchOrders = createAsyncThunk(
'orders/fetchOrders',
async () => {
try {
const response = await axios.get(
'https://secondhandbookstoreapi.azurewebsites.net/api/Orders'
);
const data = response.data;
console.log(response.data);
return data;
} catch (error) {
console.error('Failed to retrieve orders:', error);
throw error;
}
}
);
export const fetchOrdersDetail = createAsyncThunk(
'orders/fetchOrdersDetail',
async () => {
try {
const response = await axios.get(
'https://secondhandbookstoreapi.azurewebsites.net/api/OrdersDetails'
);
const data = response.data;
console.log(response.data);
return data;
} catch (error) {
console.error('Failed to retrieve ordersDetail:', error);
throw error;
}
}
);
const orderSlice = createSlice({
name: 'order',
initialState: {
orders: [],
status: '',
ordersDetails: [], // Thêm thuộc tính ordersDetails vào state
},
reducers: {
setorders: (state, action) => {
state.orders = action.payload;
},
},
extraReducers: (builder) => {
builder
.addCase(fetchOrders.fulfilled, (state, action) => {
state.orders = action.payload;
})
.addCase(fetchOrders.pending, (state, action) => {
state.status = 'loading';
})
.addCase(fetchOrdersDetail.fulfilled, (state, action) => {
state.ordersDetails = action.payload; // Lưu trữ dữ liệu ordersDetails vào state
})
.addCase(fetchOrdersDetail.pending, (state, action) => {
state.status = 'loading';
})
}
});
export const { setorders, } = orderSlice.actions;
export default orderSlice.reducer;
export const { reducer } = orderSlice;
// Thêm fetchOrdersDetail vào danh sách các actions
|
// SQL "RDBMS"
// RDBMS -> 상용 S/W 활용
// RDS 서비스를 통해 RDBMS
// code level 에서 어떻게 SQL을 RDBMS
// RDBMS - SQLite, Postgresql, Oracle, MySQL
// code SQL 만들어 -> RDBMS
// code -> SQL " -> " RDBMS
// sqlite3
import sqlite3 from "sqlite3";
const { verbose } = sqlite3;
// DBMS - System -> S/W -> server -> 연결해야댐
const db = new (verbose().Database)("./prisma/mydb.sqlite3", (err) => {
if (err) {
console.error(err.message);
} else {
console.log("Connected to the SQLite database.");
}
});
const query = `
SELECT *
FROM post
INNER JOIn comment
ON post.post_id = comment.post_id
WHERE post.post_id = 1;
`;
db.all(query, [], (err, rows) => {
if (err) {
console.error("Query execution error: ", err.message);
return;
}
// 조회된 데이터 출력
console.log(rows);
// 또는 rows.forEach((row) => console.log(row)); 로 각 행을 반복 출력
});
// // CommonJS
// // const sqlite3 = require("sqlite3").verbose();
// // verbose() 메소드를 호출하면, 내부적으로 로깅 메커니즘이 활성화되며,
// // SQL 실행 과정에서 발생하는 세부 정보, 경고, 오류 메시지 등이 더 자세히 표시됌
// // ESM 형식으로 sqlite3 모듈 import
// import sqlite3 from "sqlite3";
// const { verbose } = sqlite3;
// const db = new (verbose().Database)("./mydb.sqlite3", (err) => {
// if (err) {
// console.error(err.message);
// } else {
// console.log("Connected to the SQLite database.");
// }
// });
// // SELECT 쿼리 실행
// const query1 = `SELECT * FROM user`;
// const query2 = `SELECT * FROM post`;
// const query3 = `SELECT * FROM comment`;
// const queryFun = (query) => {
// if (!query) new Error("query 값은 빈 값이 될 수 없습니다.");
// db.all(query, [], (err, rows) => {
// if (err) {
// console.error("Query execution error: ", err.message);
// return;
// }
// // 조회된 데이터 출력
// console.log(rows);
// // 또는 rows.forEach((row) => console.log(row)); 로 각 행을 반복 출력
// });
// };
// queryFun(query3);
// // 데이터베이스 연결 종료
// db.close((err) => {
// if (err) {
// console.error(err.message);
// } else {
// console.log("Close the database connection.");
// }
// });
|
@page "/product"
@inject IDialogService DialogService
@inject IProductService Service
@inject ISnackbar Snackbar;
@using RestClient.Components.Products
<PageTitle>Prodoct Management</PageTitle>
<h3>Product Management</h3>
<MudButtonGroup Class="mb-2">
<MudIconButton Icon="@Icons.Material.Rounded.Add" Color="Color.Primary" Title="Add New Product" OnClick="Add" />
<MudIconButton Icon="@Icons.Material.Rounded.Edit" Disabled="disableEdite" Color="Color.Warning" Title="Edit Product" OnClick="Edit" />
<MudIconButton Icon="@Icons.Material.Rounded.Delete" Disabled="disableDelete" Color="Color.Error" Title="Delete Products" OnClick="Delete" />
</MudButtonGroup>
<List OnSelectedProductsChanged="OnSelectedProductsChangedHandler" @ref="_list"/>
@code {
public bool disableEdite = true;
private bool disableDelete = true;
private int[] selectedIds = new int[0];
private RestClient.Components.Products.List? _list;
private DialogOptions dialogOptions = new DialogOptions
{
CloseButton = true,
CloseOnEscapeKey = true,
Position = DialogPosition.TopCenter,
MaxWidth = MaxWidth.ExtraSmall,
FullWidth = true
};
private void OnSelectedProductsChangedHandler(SelectedProductEventArgs args)
{
selectedIds = args.SelectedItemIds;
if (selectedIds.Length == 0)
{
disableEdite = true;
disableDelete = true;
}
else if (selectedIds.Length == 1)
{
disableEdite = false;
disableDelete = false;
}
else
{
disableEdite = true;
disableDelete = false;
}
}
private async Task Add()
{
var result = await DialogService.Show<Create>("Add New Product", dialogOptions).Result;
if (!result.Cancelled)
{
await _list!.ReloadAsync();
}
}
private async Task Edit()
{
disableEdite = true;
disableDelete = true;
var productId = selectedIds[0];
var parameters = new DialogParameters();
parameters.Add("productId", productId);
var result = await DialogService.Show<Edit>("Edite Product", parameters, dialogOptions).Result;
if (!result.Cancelled)
{
await _list!.ReloadAsync();
}
_list!.CleareSelectedItems();
//OnSelectedProductsChangedHandler(new SelectedProductEventArgs(new int[0]));
}
private async Task Delete()
{
int[] ids = selectedIds;
_list!.CleareSelectedItems();
disableEdite = true;
disableDelete = true;
var s = selectedIds.Length == 1 ? "" : "s";
bool? confirm = await DialogService.ShowMessageBox("Delete",
$"Are you sure to delet {ids.Length} product{s}?",
yesText: "Delete!",
cancelText: "Cancle");
if (!confirm.Value) return;
var listIds = ids.ToList();
foreach (var item in listIds)
{
await Service.DeleteProduct(item);
}
await _list!.ReloadAsync();
//ids.ToList().ForEach(async id => await Service.DeleteProduct(id));
//await _list!.ReloadAsync();
Snackbar!.Add($"{ids.Length} Product{s} deleted successfull", Severity.Success);
await _list!.ReloadAsync();
}
}
|
//
// HomeRepository.swift
// nextStep
//
// Created by 도학태 on 2023/09/23.
//
import Foundation
import RxSwift
import RxCocoa
final class HomeRepository: CommonRepositoryProtocol {
func getLayouts() -> Observable<[HomeLayoutStatus]> {
let willdInformationBetweenAttribute = HomeBetweenBannerAttribute.getMockupData()
return Observable.just([
.small(lolChampionTagCategory: .assassin),
.betweenBanner(betweenBannerAttribute: willdInformationBetweenAttribute),
.small(lolChampionTagCategory: .fighter),
.small(lolChampionTagCategory: .tank),
.large(lolChampionTagCategory: .mage),
.large(lolChampionTagCategory: .support),
])
}
func getBannerList() -> Observable<[HomeBannerItemAttribute]> {
let sequence = HomeBannerItemAttribute.getMocupData().shuffled()
return Observable.just(sequence)
}
func getCategory() -> Observable<[HomeChampionCategoryAttribute]> {
riotAPI.getChampionList()
.map {
var result: [HomeChampionCategoryAttribute] = []
$0.forEach { champion in
champion.tagCategoys.forEach { tagCategory in
let value = HomeChampionCategoryAttribute(
id: champion.id ?? "",
category: tagCategory,
thumbnailImageURL: RiotAPIRequestContext.getChampionImageURL(
championImageSizeStatus: .full,
championID: champion.id
),
championName: champion.name ?? "",
title: champion.title ?? ""
)
result.append(value)
}
}
return result.shuffled()
}
.catch { error in
Observable<[HomeChampionCategoryAttribute]>.empty()
}
}
}
|
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { useState,useEffect } from 'react';
import Axios from 'axios';
import LogoutModal from '../../modals/LogoutModal';
import BikePagination from '../paginations/BikePagination';
const Bicycles = ({ logoutMssg }) => {
const [bikes,setBikes] = useState('');
const imageLocation = 'http://localhost:5000/products/';
// paginations
const [currentPage,setCurrentPage] = useState(1);
const [bikesPerPage] = useState(9);
const indexOfLastBike = currentPage * bikesPerPage;
const indexOfFirstBike = indexOfLastBike - bikesPerPage;
const currentPages = bikes.slice(indexOfFirstBike, indexOfLastBike);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
useEffect(() => {
Axios.get('/api/bicycles')
.then((res) => {
setBikes(res.data);
})
},[])
return (
<motion.div
initial={{ opacity:0 }}
animate={{ opacity:1 }}
transition={{ delay:0.5 }}
className="col-span-4 w-full py-7"> {/* items side */}
<Helmet><title>Bicycle System | Bikes</title></Helmet>
<div className="px-5 border-b-2 p-4">
<h1 className="font-semibold text-5xl select-none">Bicycles</h1>
</div>
<div className="px-10 py-3">
<div className="flex justify-between"> {/* nav for page and search */}
<div className="flex w-1/2">
<span className="text-gray-700 font-semibold text-md self-center">Sort by</span>
<select className="p-1 outline-none rounded-md border border-gray-700 w-1/2 ml-2 cursor-pointer" name="filter" id="cars">
<option hidden value="relevance">Relevance</option>
<option value="brake">Brake</option>
</select>
</div>
{/* <div className="p-2 cursor-pointer">
<span>View: </span>
<span className="text-gray-700">30 | 60</span>
</div> */}
</div>
<div className="flex gap-5 flex-wrap">
{ bikes.length <= 0 ?
<div className="w-full h-96 flex items-center justify-center">
<h1 className="text-3xl font-bold text-gray-400 animate-pulse">Nothing to display...</h1>
</div> : currentPages.map((bike) => (
<div className="flex py-5" key={bike.id}> { /* items goes here */ }
<Link to={`/bike/details/${bike.item_name}`}>
<div className="border border-gray-300 shadow-xl overflow-hidden rounded">
<img className="w-60 h-36 object-cover transform hover:scale-105 transition duration-300" src={`${imageLocation}${bike.product_image}`} alt={bike.item_name} />
<div className="grid grid-rows-3 justify-items-center m-2">
<span className="font-semibold text-gray-800">{bike.brand_name}</span>
<span className="font-normal text-sm text-gray-600">{bike.item_name}</span>
<span className="font-semibold text-gray-900 text-xl">₱{bike.product_price}</span>
</div>
</div>
</Link>
</div>
)) }
</div>
</div>
<BikePagination bikesPerPage={bikesPerPage} totalBikes={bikes.length} paginate={paginate} />
{ logoutMssg && <LogoutModal /> }
</motion.div>
)
}
export default Bicycles
|
"""
URL configuration for reez project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from django.views.generic import RedirectView
from staff.views import login_user, logout_view
urlpatterns = [
path('admin/', admin.site.urls),
path('rujukan/', include('wad.urls')),
path('staff/', include('staff.urls')),
path("__debug__/", include("debug_toolbar.urls")),
path("login/",login_user),
path("logout/",logout_view),
path('', include("exam.urls"))
]
if settings.DEBUG:
import os
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns() # tell gunicorn where static files are in dev mode
urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images'))
urlpatterns += [
path('favicon.ico', RedirectView.as_view(url=settings.STATIC_URL + 'favicon.ico'))
]
|
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:forus/model/identification_system.dart';
class CreateChat extends StatefulWidget {
final String groupName;
final String groupId;
const CreateChat({Key? key, required this.groupName, required this.groupId})
: super(key: key);
@override
State<CreateChat> createState() => _CreateChatState();
}
class _CreateChatState extends State<CreateChat> {
final titleController = TextEditingController();
final aboutController = TextEditingController();
List<String> selectedValues = [];
List<String> items = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromRGBO(40, 40, 45, 0.612),
appBar: AppBar(
iconTheme: const IconThemeData(color: Colors.white),
title: const Text(
"Group Chat",
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
),
backgroundColor: const Color.fromRGBO(22, 23, 31, 1),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(14.0),
child: Column(
children: [
SizedBox(
width: 1200,
child: TextField(
controller: titleController,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(6.0),
),
filled: true,
fillColor: Colors.grey[200],
hintText: "Thread Title",
),
),
),
Form(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Text('Choose Tags:'),
Theme(
data: ThemeData(
highlightColor:
Colors.transparent, // Remove the highlight color
focusColor:
Colors.transparent, // Remove the focus color
),
child: TypeAheadFormField<String>(
textFieldConfiguration: TextFieldConfiguration(
decoration: InputDecoration(
labelText: 'Enter tag', // Add this line
filled: true,
fillColor: Colors.grey[200],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(6.0),
),
suffixIcon: const Icon(Icons.arrow_drop_down),
),
),
suggestionsCallback: (pattern) {
return items.where((item) => item
.toLowerCase()
.contains(pattern.toLowerCase()));
},
itemBuilder: (context, suggestion) {
return ListTile(
title: Text(suggestion),
);
},
transitionBuilder:
(context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (suggestion) {
setState(() {
selectedValues.add(suggestion);
});
},
noItemsFoundBuilder: (context) =>
const SizedBox.shrink(),
),
),
const SizedBox(height: 20),
Wrap(
spacing: 8.0,
runSpacing: 4.0,
children: selectedValues
.map((value) => Chip(
label: Text(
value,
style: const TextStyle(fontSize: 11.0),
),
padding: const EdgeInsets.symmetric(
horizontal: 7.0, vertical: 1.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100.0),
),
labelPadding: const EdgeInsets.all(1.0),
visualDensity: const VisualDensity(
horizontal: 0.0, vertical: -4.0),
deleteIcon: Transform.scale(
scale: 0.7,
child: const Icon(
Icons.close,
color: Colors.white,
),
),
onDeleted: () {
setState(() {
selectedValues.remove(value);
});
},
))
.toList(),
),
],
),
),
SizedBox(
width: 1200,
child: TextField(
minLines: 6,
maxLines: 6,
controller: aboutController,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(6.0),
),
filled: true,
fillColor: Colors.grey[200],
hintText: "Tell us your thoughts!",
),
),
),
const SizedBox(height: 20),
SizedBox(
width: 1200,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(6.0), // Set the border radius
),
),
onPressed: () async {
// Implement the logic to create the thread
// This is just a placeholder, replace it with your logic
print("Create Thread Button Pressed");
String firebasePath = 'public_data/group_chats';
String threadId =
(await IdSystem.getUniqueId(firebasePath, "id"))
.toString();
DatabaseReference userGroupsRef =
FirebaseDatabase.instance.ref(firebasePath);
userGroupsRef.push().set({
'name': titleController.text,
'about': aboutController.text,
'id': threadId,
'groupBelongs': widget.groupId
});
},
child: const Text("Create Thread",
style: TextStyle(color: Color.fromRGBO(40, 40, 45, 1))),
),
),
],
),
),
),
);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Transactions;
using Qtc.Branch.BusinessEntities;
using Qtc.Branch.Dal;
using Qtc.Branch.Validation;
using Qtc.Branch.Audit;
namespace Qtc.Branch.Bll
{
[DataObjectAttribute()]
public static class RepairDetailManager
{
#region Public Methods
[DataObjectMethod(DataObjectMethodType.Select, true)]
public static RepairDetailCollection GetList()
{
RepairDetailCriteria repairdetail = new RepairDetailCriteria();
return GetList(repairdetail, string.Empty, -1, -1);
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public static RepairDetailCollection GetList(string sortExpression)
{
RepairDetailCriteria repairdetail = new RepairDetailCriteria();
return GetList(repairdetail, sortExpression, -1, -1);
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public static RepairDetailCollection GetList(int startRowIndex, int maximumRows)
{
RepairDetailCriteria repairdetail = new RepairDetailCriteria();
return GetList(repairdetail, string.Empty, startRowIndex, maximumRows);
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public static RepairDetailCollection GetList(RepairDetailCriteria repairdetailCriteria)
{
return GetList(repairdetailCriteria, string.Empty, -1, -1);
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public static RepairDetailCollection GetList(RepairDetailCriteria repairdetailCriteria, string sortExpression, int startRowIndex, int maximumRows)
{
RepairDetailCollection myCollection = RepairDetailDB.GetList(repairdetailCriteria);
if (!string.IsNullOrEmpty(sortExpression))
{
myCollection.Sort(new RepairDetailComparer(sortExpression));
}
if (startRowIndex >= 0 && maximumRows > 0)
{
return new RepairDetailCollection(myCollection.Skip(startRowIndex).Take(maximumRows).ToList());
}
return myCollection;
}
public static int SelectCountForGetList(RepairDetailCriteria repairdetailCriteria)
{
return RepairDetailDB.SelectCountForGetList(repairdetailCriteria);
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public static RepairDetail GetItem(int id)
{
RepairDetail repairdetail = RepairDetailDB.GetItem(id);
return repairdetail;
}
[DataObjectMethod(DataObjectMethodType.Update, true)]
public static int Save(RepairDetail myRepairDetail)
{
if (!myRepairDetail.Validate())
{
throw new InvalidSaveOperationException("Can't save an invalid repairdetail. Please make sure Validate() returns true before you call Save.");
}
using (TransactionScope myTransactionScope = new TransactionScope())
{
if(myRepairDetail.mId != 0)
AuditUpdate(myRepairDetail);
int id = RepairDetailDB.Save(myRepairDetail);
if(myRepairDetail.mId == 0)
AuditInsert(myRepairDetail, id);
myRepairDetail.mId = id;
myTransactionScope.Complete();
return id;
}
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public static int Delete(RepairDetail myRepairDetail)
{
if (RepairDetailDB.Delete(myRepairDetail.mId))
{
AuditDelete(myRepairDetail);
return myRepairDetail.mId;
}
else
return 0;
}
#endregion
#region Audit
private static void AuditInsert(RepairDetail myRepairDetail, int id)
{
AuditManager.AuditInsert(false, myRepairDetail.mUserFullName,(int)(Tables.ptApi_RepairDetail),id,"Insert");
}
private static void AuditDelete( RepairDetail myRepairDetail)
{
AuditManager.AuditDelete(false, myRepairDetail.mUserFullName,(int)(Tables.ptApi_RepairDetail),myRepairDetail.mId,"Delete");
}
private static void AuditUpdate( RepairDetail myRepairDetail)
{
RepairDetail old_repairdetail = GetItem(myRepairDetail.mId);
AuditCollection audit_collection = RepairDetailAudit.Audit(myRepairDetail, old_repairdetail);
if (audit_collection != null)
{
foreach (BusinessEntities.Audit audit in audit_collection)
{
AuditManager.Save(audit);
}
}
}
#endregion
#region IComparable
private class RepairDetailComparer : IComparer < RepairDetail >
{
private string _sortColumn;
private bool _reverse;
public RepairDetailComparer(string sortExpression)
{
if (string.IsNullOrEmpty(sortExpression))
{
sortExpression = "field_name desc";
}
_reverse = sortExpression.ToUpperInvariant().EndsWith(" desc", StringComparison.OrdinalIgnoreCase);
if (_reverse)
{
_sortColumn = sortExpression.Substring(0, sortExpression.Length - 5);
}
else
{
_sortColumn = sortExpression;
}
}
public int Compare(RepairDetail x, RepairDetail y)
{
int retVal = 0;
switch (_sortColumn.ToUpperInvariant())
{
case "FIELD":
retVal = string.Compare(x.mRemarks, y.mRemarks, StringComparison.OrdinalIgnoreCase);
break;
}
int _reverseInt = 1;
if ((_reverse))
{
_reverseInt = -1;
}
return (retVal * _reverseInt);
}
}
#endregion
}
}
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Furniture } from '../models/furniture.model';
const URL = 'http://localhost:8080/api/furnitures';
@Injectable({
providedIn: 'root'
})
export class FurnitureService {
constructor(private http: HttpClient) { }
all_furnitures(): Observable<Furniture[]> {
return this.http.get<Furniture[]>(URL);
}
get_furniture(id: String): Observable<Furniture> {
return this.http.get<Furniture>(`${URL}/${id}`);
}
create_furniture(furniture: Furniture): Observable<Furniture[]> {
return this.http.post<Furniture[]>(URL, furniture);
}
update_furniture(furniture: Furniture, id: String): Observable<Furniture[]> {
return this.http.put<Furniture[]>(`${URL}/${id}`, furniture);
}
delete_furniture(id: String): Observable<Furniture[]> {
return this.http.delete<Furniture[]>(`${URL}/${id}`);
}
delete_all_furnitures(): Observable<Furniture[]> {
return this.http.delete<Furniture[]>(`${URL}`);
}
}
|
import { createReducer, Action, AnyAction, combineReducers } from "@rbxts/rodux";
import { assign, copy as shallowCopy } from "@rbxts/object-utils";
import { intialPlacementSettings } from "template/client/intialState";
import * as Functionalities from "template/shared/Functionalities";
import { PlacementSettings } from "template/shared/Types";
export enum ActionTypes {
UPDATE_PROPERTY = "UPDATE_PROPERTY",
UPDATE_FUNCTIONALITY = "UPDATE_FUNCTIONALITY",
UPDATE_FUNCTIONALITY_PROPERTY = "UPDATE_FUNCTIONALITY_PROPERTY",
UPDATE_BASE_PART = "UPDATE_BASE_PART",
UPDATE_BUILD_MODE = "UPDATE_BUILD_MODE",
ADD_FUNCTIONALITY = "ADD_FUNCTIONALITY",
REMOVE_FUNCTIONALITY = "REMOVE_FUNCTIONALITY",
}
export type PlacementSettingsActions =
| ActionRecievedUpdateProperty
| ActionRecievedAddFunctionality
| ActionRecievedUpdateFunctionality
| ActionRecievedUpdateFunctionalityProperty
| ActionRecievedRemoveFunctionality
| UpdateBasePart
| UpdateBuildMode;
//UPDATE PROPERTY
type ValueOfRawProperties = ValueOf<RawProperties>;
export interface UpdatePropertyDataType {
readonly propertyName: keyof RawProperties;
readonly value: ValueOfRawProperties;
}
interface ActionRecievedUpdateProperty extends Action<ActionTypes.UPDATE_PROPERTY> {
readonly data: UpdatePropertyDataType[];
}
export function updateProperty(data: UpdatePropertyDataType[]): ActionRecievedUpdateProperty & AnyAction {
return {
type: ActionTypes.UPDATE_PROPERTY,
data,
};
}
//UPDATE FUNCTIONALITY
interface ActionRecievedUpdateFunctionality extends Action<ActionTypes.UPDATE_FUNCTIONALITY> {
guid: string;
value: Functionalities.FunctionalitiesInstancesValues;
}
export function updateFunctionality(
guid: string,
value: Functionalities.FunctionalitiesInstancesValues,
): ActionRecievedUpdateFunctionality & AnyAction {
return {
type: ActionTypes.UPDATE_FUNCTIONALITY,
guid,
value,
};
}
//UPDATE FUNCTIONALITY PROPERTY
interface ActionRecievedUpdateFunctionalityProperty extends Action<ActionTypes.UPDATE_FUNCTIONALITY_PROPERTY> {
guid: string;
property: Functionalities.FunctionalitiesPropertiesNames;
value: Functionalities.FunctionalitiesPropertiesValueTypes;
}
export function updateFunctionalityProperty(
guid: string,
property: Functionalities.FunctionalitiesPropertiesNames,
value: Functionalities.FunctionalitiesPropertiesValueTypes,
): ActionRecievedUpdateFunctionalityProperty & AnyAction {
return {
type: ActionTypes.UPDATE_FUNCTIONALITY_PROPERTY,
guid,
property,
value,
};
}
interface ActionRecievedAddFunctionality extends Action<ActionTypes.ADD_FUNCTIONALITY> {
functionality: Functionalities.FunctionalitiesInstancesValues;
}
export function addFunctionality(
functionality: Functionalities.FunctionalitiesInstancesValues,
): ActionRecievedAddFunctionality & AnyAction {
return {
type: ActionTypes.ADD_FUNCTIONALITY,
functionality,
};
}
interface ActionRecievedRemoveFunctionality extends Action<ActionTypes.REMOVE_FUNCTIONALITY> {
guid: string;
}
export function removeFunctionality(guid: string): ActionRecievedRemoveFunctionality & AnyAction {
return {
type: ActionTypes.REMOVE_FUNCTIONALITY,
guid,
};
}
//----
interface UpdateBasePart extends Action<ActionTypes.UPDATE_BASE_PART> {
value: BasePart;
}
export function UpdateBasePart(value: BasePart): UpdateBasePart & AnyAction {
return {
type: ActionTypes.UPDATE_BASE_PART,
value,
};
}
interface UpdateBuildMode extends Action<ActionTypes.UPDATE_BUILD_MODE> {
value: BuildMode;
}
export function UpdateBuildMode(value: BuildMode): UpdateBuildMode & AnyAction {
return {
type: ActionTypes.UPDATE_BUILD_MODE,
value,
};
}
type FunctionalitiesActions =
| ActionRecievedUpdateFunctionality
| ActionRecievedUpdateFunctionalityProperty
| ActionRecievedAddFunctionality
| ActionRecievedRemoveFunctionality;
export const placementSettingsReducer = combineReducers<
PlacementSettings,
UpdateBasePart | UpdateBuildMode | FunctionalitiesActions | ActionRecievedUpdateProperty
>({
Shape: createReducer<BasePart, UpdateBasePart>(intialPlacementSettings.Shape, {
[ActionTypes.UPDATE_BASE_PART]: (_, action) => action.value,
}),
BuildMode: createReducer<BuildMode, UpdateBuildMode>(intialPlacementSettings.BuildMode, {
[ActionTypes.UPDATE_BUILD_MODE]: (_, action) => action.value,
}),
Functionalities: createReducer<Functionalities.FunctionalitiesInstancesValues[], FunctionalitiesActions>([], {
[ActionTypes.UPDATE_FUNCTIONALITY]: (state, action) =>
state.map((functionality) => (functionality.GUID === action.guid ? action.value : functionality)),
[ActionTypes.UPDATE_FUNCTIONALITY_PROPERTY]: (state, action) =>
state.map((functionality) => {
if (functionality.GUID === action.guid)
assign((functionality.Properties as Functionalities.IntersectionProperties)[action.property], {
Current: action.value,
});
return functionality;
}),
[ActionTypes.ADD_FUNCTIONALITY]: (state, action) => {
const newState = shallowCopy(state);
newState.push(action.functionality);
return newState;
},
[ActionTypes.REMOVE_FUNCTIONALITY]: (state, action) => {
const newState = shallowCopy(state);
const functionalityIndex = newState.findIndex((functionality) => functionality.GUID === action.guid);
newState.unorderedRemove(functionalityIndex);
return newState;
},
}),
RawProperties: createReducer<RawProperties, ActionRecievedUpdateProperty>(intialPlacementSettings.RawProperties, {
[ActionTypes.UPDATE_PROPERTY]: (state, action) => {
const newState = shallowCopy(state);
for (const data of action.data) newState[data.propertyName] = data.value as never;
return newState;
},
}),
});
|
/*
* @author Haoze Wu <[email protected]>
*
* The Legolas Project
*
* Copyright (c) 2024, University of Michigan, EECS, OrderLab.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.umich.order.legolas.orchestrator.workload;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public abstract class Workload {
private static final Logger LOG = LoggerFactory.getLogger(Workload.class);
protected final Map<Integer, ClientWorkload> clients = new TreeMap<>();
public final void proceed(final int clientId) {
clients.get(clientId).proceed();
}
public final String[] registerClient(final int clientId, final long pid) {
final ClientWorkload client = clients.get(clientId);
client.notifyPid(pid);
return client.command;
}
public final void run(final long endTime) throws Exception {
// LOG.info("A workload started");
final Collection<ClientWorkload> clientSet = clients.values();
for (final ClientWorkload client : clientSet) {
client.start();
}
long timeoutMS = 10 + endTime - System.currentTimeMillis();
for (final ClientWorkload client : clientSet) {
client.waitForStartup(timeoutMS);
}
final CountDownLatch signal = new CountDownLatch(1);
final Thread merge = new Thread(() -> {
// LOG.info("Merge started");
for (final ClientWorkload client : clientSet) {
try {
// LOG.info("Client {} joining", client.clientId);
client.join();
} catch (InterruptedException e) {
LOG.error("Client thread fails to join due to", e);
}
}
// LOG.info("All clients ended");
signal.countDown();
});
merge.start();
long d = endTime - System.currentTimeMillis();
if (d > 0) {
signal.await(d, TimeUnit.MILLISECONDS);
}
for (final ClientWorkload client : clientSet) {
client.shutdown();
}
merge.join();
}
public abstract void reportResult(final int phase);
public final boolean isFinished() {
for (final ClientWorkload client : clients.values()) {
if (!client.isFinished()) {
return false;
}
}
return true;
}
}
|
import styled from 'styled-components';
const Container = styled.div`
position: relative;
`;
const Label = styled.label`
display: block;
font-size: 1.28rem;
color: ${({ theme }) => theme.colors.light};
font-weight: 600;
margin-bottom: ${({ theme }) => theme.spacing.sm};
`;
const StyledTextArea = styled.textarea`
width: 100%;
font-family: inherit;
padding: ${({ theme }) => theme.padding.md};
background-color: rgb(244, 246, 248);
resize: none;
border-radius: ${({ theme }) => theme.radius.md};
border: 2px solid transparent;
height: 12rem;
outline: none;
transition: ${({ theme }) => theme.transitions.easeInOut};
font-size: 1.4rem;
&::placeholder {
color: ${({ theme }) => theme.colors.light};
}
&:focus {
background-color: rgb(255, 255, 255);
border: 2px solid rgb(244, 246, 248);
}
`;
export function TextArea({ label, ...rest }) {
return (
<Container>
<Label>{label}</Label>
<StyledTextArea {...rest} />
</Container>
);
}
|
// const persona = {
// nombre: 'emanuel',
// edad: 20,
// }
// let texto = 'hola mundo';
// texto = 2
// texto.concat('hla')
// console.log(texto)
// ignora el typado en javascript
// let str:any = 'hola mundo'
// que nosabes cuales es el tipo
// let str2:unknown = 'hola mundo'
// inferencia
// comoa a y b infiere que son numeros sin decir nada
// let a = 10;
// let b = 20;
// let c = a + b;
// c tambien sera number
// // funcion
// function saludar(nombre:string) {
// console.log(`hola ${nombre}`);
// }
// saludar('emanuel')
// function saludar2({name,age} : {name: string, age: number}){
// console.log(`hola ${name} y tienes ${age}`)
// }
// function saludar2(persona: {name:string,age:number}){
// let {name,age} = persona;
// console.log(`hola ${name} y tienes ${age}`)
// }
// function saludar2({name,age} : {name: string, age: number}): number{
// console.log(`hola ${name} y tienes ${age}`)
// return age
// }
// saludar2({name:'emanuel',age:20});
// const saludarRow = (fn: (name:string) => void) =>{
// return fn('miguel');
// }
// saludarRow((name:string)=>{
// console.log(`buenas tardes ${name}`)
// })
// // tipar arrow function
// const sumar = ( a:number , b:number ) : number => {
// return a + b
// }
// const restar: (a:number,b:number) => number = (a,b)=>{
// return a - b;
// }
// never nunca va a devolver un valor
// void indica que la funcion puede devolver un valor pero no importa realmente
// function msk ( nombre : string ): void {
// console.log(nombre);
// }
// inferencia en funciones anonimas dependiendo el contexto
// let arr = ['hulk','loki','thor','black widow'];
// arr.forEach(element => {
// console.log(element.toLocaleLowerCase())
// });
// objectos
// let hero = {
// name: 'thor',
// edad: 1500
// }
// function createHero(nombre:string,edad:number){
// return {nombre,edad}
// }
// let loki = createHero('loki',2000);
// type alias
// type Hero = {
// name: string,
// edad: number
// }
// let hero: Hero = {
// name: 'thor',
// edad: 1500
// }
// function createHero(hero:Hero): Hero{
// let {name,edad} = hero
// return {name,edad}
// }
// let loki = createHero({name:'loki',edad:2000});
// templade union type
// type HeroId = `${string}-${string}-${string}-${string}-${string}`
// type Hero = {
// // optonial properties
// // readonly id?: number,
// // readonly id?: string,
// // id?: HeroId,
// readonlyid?: HeroId,
// name: string,
// edad: number,
// isActividi?: boolean
// }
// let hero: Hero = {
// name: 'thor',
// edad: 1500
// }
// function createHero(hero:Hero): Hero{
// let {name,edad} = hero
// return {
// id:crypto.randomUUID(),
// name,
// edad,
// isActividi:true}
// }
// let loki = Object.freeze(createHero({name:'loki',edad:2000}));
// // console.log(loki) // ---> true
// loki.id?.toString()
// type HexaDemimal = `#${string}`
// let color: HexaDemimal = '#000';
// let color_black:HexaDemimal = '000' da error
// type HeroId = `${string}-${string}-${string}-${string}-${string}`
// union types
// type HeroPower = 'local'|'planetario'|'galactico'|'universal'|'multiversal'
// let numero: string | number;
// let variable: boolean | number = 200
// numero = 10;
// intersecion types
// type HeroBasicInfo = {
// name: string,
// edad: number
// }
// type HeroProperties = {
// // optonial properties
// // readonly id?: number,
// // readonly id?: string,
// // id?: HeroId,
// id?: HeroId,
// // name: string,
// // edad: number,
// isActividi?: boolean,
// porweScale?: HeroPower
// }
// type Hero = HeroBasicInfo & HeroProperties
// let hero: Hero = {
// name: 'thor',
// edad: 1500
// }
// function createHero(input:HeroBasicInfo): Hero{
// let {name,edad} = input
// return {
// id:crypto.randomUUID(),
// name,
// edad,
// isActividi:true
// }
// }
// let loki = createHero({name:'loki',edad:2000});
// loki.porweScale = "galactico"
// type indexing
// type HeroProperties = {
// isActiviti?: boolean,
// address: {
// planet: string,
// city: string
// }
// }
// const addresHero: HeroProperties['address'] = {
// planet: 'tierra',
// city: 'mendoza'
// }
// type from value
// const addres = {
// planet:'tierra',
// city: 'mendoza'
// }
// lo que podemos hacer con typeof es poder estraer los tipos de un obj
// type Address = typeof addres
// const addressTwich: Address = {
// planet:'tiera',
// city:'mendoza'
// }
// type from function return
function createAddress(){
return {
planet: 'tierra',
city: 'mendoza'
}
}
type address = ReturnType<typeof createAddress>
// array
// const lenguajes = [] // queremos que siempre este vacio
const lenguajes: string[] = [] // queremos que siempre este vacio
const lenguajes2:Array<string> = [] // queremos que siempre este vacio
const lenguajes3:(string | number)[] = []
// lenguajes.push('java') da error
lenguajes2.push('java')
lenguajes2.push('c')
lenguajes2.push('c++')
lenguajes2.push('c#')
lenguajes3.push('python')
lenguajes3.push('javascript')
lenguajes3.push('ruby')
lenguajes3.push(1)
lenguajes3.push(2)
lenguajes3.push(3)
// intersecion types
type HeroBasicInfo = {
name: string,
edad: number
}
const heros:HeroBasicInfo[] = []
// matrix y tuplas
type cellValue = 'x'|'o'|''
// tupla limite fijado de longitud
type gameBoard = [
[cellValue,cellValue,cellValue],
[cellValue,cellValue,cellValue],
[cellValue,cellValue,cellValue]
]
const gameBoard: gameBoard = [
['x','o','o'],
['o','x','o'],
['o','o','x']
]
gameBoard[0][1] = 'x'
type RBG = [number,number,number]
const rbg: RBG = [255,255,255]
|
package week2;
public class Person {
public String name;
public int phoneNumber;
public String address;
public Person() {
this.name = null;
this.phoneNumber = 0;
this.address = null;
}
public Person(String name) {
this.name = name;
}
public Person(String name, String address) {
this.name = name;
this.address = address;
}
public Person(String name, long phone) {
this.name = name;
this.phoneNumber = (int) phone;
}
public Person(String name, long phone, String address) {
this.name = name;
this.phoneNumber = (int) phone;
this.address = address;
}
// public void main(String [] args) {
// Person p1 = new Person();
// Person p2 = new Person("john");
// Person p3 = new Person("mary","cork");
// Person p4 = new Person("claire", 871234567);
// Person p5 = new Person("Micheal",871234567,"Dublin");
//
// System.out.println(p5.address);
// }
public void printDetails() {
System.out.print("Name " + name);
System.out.print("Address " + address);
System.out.print("Phone " + phoneNumber);
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
import {BitMask, BN, getBytesCount, trim0x} from '@1inch/byte-utils'
import {Extension} from './extension'
import {Interaction} from './interaction'
import {Address} from '../address'
import {ZX} from '../constants'
export enum AmountMode {
/**
* Amount provided to fill function treated as `takingAmount` and `makingAmount` calculated based on it
*/
taker,
/**
* Amount provided to fill function treated as `makingAmount` and `takingAmount` calculated based on it
*/
maker
}
/**
* TakerTraitsLib
* This class defines TakerTraits, which are used to encode the taker's preferences for an order in a single uint256.
*
* The TakerTraits are structured as follows:
* High bits are used for flags
* 255 bit `_MAKER_AMOUNT_FLAG` - If set, the taking amount is calculated based on making amount, otherwise making amount is calculated based on taking amount.
* 254 bit `_UNWRAP_WETH_FLAG` - If set, the WETH will be unwrapped into ETH before sending to taker.
* 253 bit `_SKIP_ORDER_PERMIT_FLAG` - If set, the order skips maker's permit execution.
* 252 bit `_USE_PERMIT2_FLAG` - If set, the order uses the permit2 function for authorization.
* 251 bit `_ARGS_HAS_TARGET` - If set, then first 20 bytes of args are treated as receiver address for maker’s funds transfer.
* 224-247 bits `ARGS_EXTENSION_LENGTH` - The length of the extension calldata in the args.
* 200-223 bits `ARGS_INTERACTION_LENGTH` - The length of the interaction calldata in the args.
* 0-184 bits - The threshold amount (the maximum amount a taker agrees to give in exchange for a making amount).
*/
export class TakerTraits {
private static MAKER_AMOUNT_FLAG = 255n
private static UNWRAP_WETH_FLAG = 254n
private static SKIP_ORDER_PERMIT_FLAG = 253n
private static USE_PERMIT2_FLAG = 252n
private static ARGS_HAS_RECEIVER = 251n
private static THRESHOLD_MASK = new BitMask(0n, 185n)
private static ARGS_INTERACTION_LENGTH_MASK = new BitMask(200n, 224n)
private static ARGS_EXTENSION_LENGTH_MASK = new BitMask(224n, 248n)
private flags: BN
private receiver?: Address
private extension?: Extension
private interaction?: Interaction
constructor(
flag: bigint,
data: {
receiver?: Address
extension?: Extension
interaction?: Interaction
}
) {
this.flags = new BN(flag)
this.receiver = data.receiver
this.extension = data.extension
this.interaction = data.interaction
}
static default(): TakerTraits {
return new TakerTraits(0n, {})
}
/**
* Returns enabled amount mode, it defines how to treat passed amount in `fillContractOrderArgs` function
*
* @see AmountMode
*/
public getAmountMode(): AmountMode {
return this.flags.getBit(TakerTraits.MAKER_AMOUNT_FLAG)
}
public setAmountMode(mode: AmountMode): this {
this.flags = this.flags.setBit(TakerTraits.MAKER_AMOUNT_FLAG, mode)
return this
}
/**
* Is the Wrapped native currency will be unwrapped into Native currency before sending to taker
*/
public isNativeUnwrapEnabled(): boolean {
return this.flags.getBit(TakerTraits.UNWRAP_WETH_FLAG) === 1
}
/**
* Wrapped native currency will be unwrapped into Native currency before sending to taker
*/
public enableNativeUnwrap(): this {
this.flags = this.flags.setBit(TakerTraits.UNWRAP_WETH_FLAG, 1)
return this
}
/**
* Wrapped native currency will NOT be unwrapped into Native currency before sending to taker
*/
public disableNativeUnwrap(): this {
this.flags = this.flags.setBit(TakerTraits.UNWRAP_WETH_FLAG, 0)
return this
}
/**
* If true, then maker's permit execution is skipped
*/
public isOrderPermitSkipped(): boolean {
return Boolean(this.flags.getBit(TakerTraits.SKIP_ORDER_PERMIT_FLAG))
}
/**
* The order skips maker's permit execution
*/
public skipOrderPermit(): this {
this.flags = this.flags.setBit(TakerTraits.SKIP_ORDER_PERMIT_FLAG, 1)
return this
}
/**
* Should use permit2 function for authorization or not
*
* @see https://github.com/Uniswap/permit2
*/
public isPermit2Enabled(): boolean {
return this.flags.getBit(TakerTraits.USE_PERMIT2_FLAG) === 1
}
/**
* Use permit2 function for authorization
*
* @see https://github.com/Uniswap/permit2
*/
public enablePermit2(): this {
this.flags = this.flags.setBit(TakerTraits.USE_PERMIT2_FLAG, 1)
return this
}
/**
* NOT use permit2 function for authorization
*/
public disablePermit2(): this {
this.flags = this.flags.setBit(TakerTraits.USE_PERMIT2_FLAG, 0)
return this
}
/**
* Sets address where order filled to, `msg.sender` used if not set
*
* @param receiver
*/
public setReceiver(receiver: Address): this {
this.receiver = receiver
return this
}
/**
* Set order receiver as `msg.sender`
*/
public removeReceiver(): this {
this.receiver = undefined
return this
}
/**
* Sets extension, it is required to provide same extension as in order creation (if any)
*/
public setExtension(ext: Extension): this {
this.extension = ext
return this
}
public removeExtension(): this {
this.extension = undefined
return this
}
/**
* Set threshold amount
*
* In taker amount mode: the minimum amount a taker agrees to receive in exchange for a taking amount.
* In maker amount mode: the maximum amount a taker agrees to give in exchange for a making amount.
*
* @see AmountMode
*/
public setAmountThreshold(threshold: bigint): this {
this.flags = this.flags.setMask(TakerTraits.THRESHOLD_MASK, threshold)
return this
}
/**
* @see setAmountThreshold
*/
public removeAmountThreshold(): this {
this.flags = this.flags.setMask(TakerTraits.THRESHOLD_MASK, 0n)
return this
}
/**
* Sets taker interaction
*
* `interaction.target` should implement `ITakerInteraction` interface
*
* @see https://github.com/1inch/limit-order-protocol/blob/1a32e059f78ddcf1fe6294baed6cafb73a04b685/contracts/interfaces/ITakerInteraction.sol#L11
*/
public setInteraction(interaction: Interaction): this {
this.interaction = interaction
return this
}
public removeInteraction(): this {
this.interaction = undefined
return this
}
public encode(): {trait: bigint; args: string} {
const extensionLen = this.extension
? getBytesCount(this.extension.encode())
: 0n
const interactionLen = this.interaction
? getBytesCount(this.interaction.encode())
: 0n
const flags = this.flags
.setBit(TakerTraits.ARGS_HAS_RECEIVER, this.receiver ? 1 : 0)
.setMask(TakerTraits.ARGS_EXTENSION_LENGTH_MASK, extensionLen)
.setMask(TakerTraits.ARGS_INTERACTION_LENGTH_MASK, interactionLen)
const args =
(this.receiver?.toString() || ZX) +
trim0x(this.extension?.encode() || '') +
trim0x(this.interaction?.encode() || '')
return {
trait: flags.value,
args
}
}
}
|
import { InstrumentStatus, Share } from "invest-nodejs-grpc-sdk/dist/generated/instruments";
import logger from "./logger";
import { InvestSdk } from "./types";
class InstrumentsService {
private readonly client: InvestSdk;
constructor(client: InvestSdk) {
if (!client) throw new Error('client is required');
this.client = client;
}
/**
* Получить интрументы по списку тикеров и отфильтровать по доступности их для торговли
* @param candidates - Список тикеров для получения информации о них
* @returns Картеж из доступных и недоступных для торговли инструментов
*/
public async filterByAvailable(candidates: string[]): Promise<[Share[], Share[]]> {
try {
const allShares = await this.client.instruments.shares({
instrumentStatus: InstrumentStatus.INSTRUMENT_STATUS_BASE,
});
const available = allShares.instruments
.filter((share) => candidates.includes(share.ticker));
const notAvailable = candidates
.filter((ticker) => !available.some((c) => c.ticker === ticker))
.map((ticker) => ({ ticker })) as Share[];
return [available, notAvailable];
} catch (e) {
logger.error(`Ошибка при фильтрации инструментов: ${e.message}`);
return [[], candidates.map((ticker) => ({ ticker })) as Share[]];
}
}
}
export default InstrumentsService;
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>绑定Value</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
<div id="bangdingValue">
<!-- 当选中时,`picked` 为字符串 "a" -->
<input type="radio" v-model="picked" value="a">
<p>{{ picked }}</p>
<!-- `toggle` 为 true 或 false -->
<input type="checkbox" v-model="toggle">
<p>{{ toggle }}</p>
<!-- 当选中时,`selected` 为字符串 "abc" -->
<select v-model="selected">
<option value="abc">ABC</option>
</select>
<p>{{ selected }}</p>
<!-- a、b是属性变量,必须声明,否则报错 -->
<input
type="checkbox"
v-model="toggleC"
v-bind:true-value="a"
v-bind:false-value="b"
>
<p>{{ toggleC }}</p>
<select v-model="selectedObj">
<!-- 内联对象字面量==>放对象 -->
<option v-bind:value="selectedObj">123</option>
</select>
<p>{{ selectedObj.number }}</p>
<!-- 在 "change" 而不是 "input" 事件中更新 -->
<input v-model="inputMsg" >
<p>"input" 事件中更新: {{ inputMsg }}</p>
<input v-model.lazy="changeMsg" >
<p>"change" 事件中更新(失去焦点后): {{ changeMsg }}</p>
<input v-model.number="age" type="number">
<p>输入值转为 Number 类型(如果原值的转换结果为 NaN 则返回原值): {{ age }}</p>
<p>注意:输入数字和e的时候转化为科学计数法</p>
<input v-model.trim="trimMsg">
<p>如果要自动过滤用户输入的首尾空格,可以添加 trim 修饰符到 v-model 上过滤输入:</p>
</div>
</body>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
var vm1 = new Vue({
el: '#bangdingValue',
data: {
picked: '',
toggle: false,
selected: '',
a: 'aa',
b: 'bb',
toggleC: '',
selectedObj: { number: 123 },
inputMsg: '',
changeMsg: '',
age: '',
trimMsg: ''
}
})
</script>
</html>
|
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import domain.Dept;
//sql을 실행할수있게 기능들을 만들어 놓은 클래스가 DAO이다.
public class DeptDao {
// DAO: sql을 실행하는 메소드만 가지는 클래스
// => 여러개의 인스턴스가 생성될 필요가 없다!
// => 싱글톤처리를 통해 하나의 인스턴스만 사용!
// 싱글톤처리 방법
// 1. 인스턴스 생성 금지 : private 생성자
private DeptDao () {
}
// 2. 클래스 내부에서 인스턴스 생성 : 인스턴스 생성할때 private static이 붙어야함
private static DeptDao dao = new DeptDao();
// 3. 다른클래스에서 인스턴스를 얻을 수 있도록 메소드가 필요함 : 메소드도 public static이어야함
public static DeptDao getInstance() {
return dao;
}
// 1.dept테이블에 list를 구해주는 메소드 = dept list : List<Dept>
public List<Dept> selectByAll(Connection conn) { // conn : 참조변수
// Connection
// 1.메소드 내부에서 Connection을 구하는 방법 (X-비추천)
/*
* 2.Dao 클래스 내부의 인스턴스 변수로 Connection을 구하는 방법 (X-비추천) -Dao클래스는 싱글톤처리 불가,
* Connection 구하기 위해서 인스턴스 계속 생성
*/
// 3.매개변수로 Connection을 구하는 방법(O)
// -방법: Service클래스의 메소드에서 Connection을 생성해서 전달
// 메소든 내부에서 Connection을 구하면 close()를 해줘야함
// close()
// <순서>
// 1.Connection
// 2.PreparedStatement
PreparedStatement pstmt = null;
ResultSet rs = null;
// 반환하고자 하는 결과 데이터
// Collection 클래스중 List => List의 특징은 입력순서를 가진다, index도 가짐,반복문을 통해서 결과 출력
List<Dept> result = new ArrayList<Dept>();
// SQL생성
String sql = "select * from dept";
try {
pstmt = conn.prepareStatement(sql);
// 3.executeQuery
// 4.ResultSet
rs = pstmt.executeQuery(); // select 일때 executeQuery
// 5.while문
while (rs.next()) {
int deptno = rs.getInt("deptno");
String dname = rs.getString("dname");
String loc = rs.getString("loc");
Dept dept = new Dept(deptno, dname, loc); // 여기 부분에서는 객체 생성
// List<Dept>에 Dept 객체를 추가해주면됨
result.add(dept);
// System.out.println(deptno + dname + loc);
}
// result : 4개의 객체를 가지고 있다.
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
// 2. 부서번호로 검색하는 기능을하는 메소드 (Connection conn ,int num) -> Connection conn을 매개변수로
// 받아야함
public Dept selectByDeptno(Connection conn, int deptno) {
PreparedStatement pstmt = null;
ResultSet rs = null;
Dept result = null;
// sql
String sql = "select * from dept where deptno=?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, deptno);
rs = pstmt.executeQuery();
if (rs.next()) { // 여기서는 행이 한개 나올꺼같아서 while문을 쓰지않음
result = new Dept(rs.getInt(1), rs.getString(2), rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
// 3. 부서정보를 입력해주는 기능을하는 메소드 : deptno,dname,loc를 받아야함 +conn도 받아야함
public int insertDept(Connection conn, Dept dept) { // 파라미터 3개(deptno,dname,loc)를 더 쓰는것보다 dept객체로 받는게 더 효율적임
PreparedStatement pstmt = null; // sql실행하려면 PreparedStatement이 필요함
int result = 0;
// Insert하기위한 sql
String sql = "insert into dept values (?,?,?)"; // sql작성전에 디벨로퍼로 들어가서 sql실행해서 확인하는게 좋음
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, dept.getDeptno()); // dept라는 객체를 받아서 dept.getDeptno()로 접근을 해야함
pstmt.setString(2, dept.getDname());
pstmt.setString(3, dept.getLoc()); // 여기까지 sql완성
result = pstmt.executeUpdate(); // sql이 이미 만들어져서 괄호안에 sql안넣어도됨 ,pstmt = conn.prepareStatement(sql);여기서 만들어짐
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
// 4. 부서 정보 수정 메소드 : updateDeptByDeptno 파라미터안에 deptno, dname,loc but 비효율적이여서
// 인스턴스로받음
public int updateDeptByDeptno(Connection conn, Dept dept) {
PreparedStatement pstmt = null;
int result = 0;
// update sql
String sql = "update dept set dname = ?,loc = ? where deptno = ?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dept.getDname());
pstmt.setString(2, dept.getLoc());
pstmt.setInt(3, dept.getDeptno());
result = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
// 5. 부서 정보 삭제 메소드 : deptno => 삭제할 부서 번호
public int deleteDeptByDeptno(Connection conn, int deptno) {
PreparedStatement pstmt = null;
int result = 0;
// delete 를 하기 위한 sql이 필요함
String sql = "delete from dept where deptno = ?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, deptno);
result = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
public static void main(String[] args) throws SQLException { // 테스트하려고 만든 main메소드
DeptDao dao = new DeptDao();
String dbUrl = "jdbc:oracle:thin:@localhost:1521:xe";
Connection conn = DriverManager.getConnection(dbUrl, "hr", "tiger");
List<Dept> list = dao.selectByAll(conn);
for (Dept dept : list) {
System.out.println(dept);
}
Dept dept = dao.selectByDeptno(conn, 50);
System.out.println("결과 : " + dept);
// int insertResult = dao.insertDept(conn, new Dept(50,"TEST","SEOUL")); //바로 new 객체생성
// int insertResult2 = dao.insertDept(conn,dept);
// System.out.println("저장 결과 : " + insertResult);
Dept d = new Dept(50, "TTT", "QQQ"); // 수정하고자 하는 부서 정보를 가지고있는 Dept = 50번 부서를 TTT QQQ로 바꿈
int updateResult = dao.updateDeptByDeptno(conn, d);
System.out.println(updateResult);
}
}
|
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
vector<int> adj[N];
bool visited[N];
int level[N];
int parent[N];
void bfs (int u) { // (Time complexity - O(2e)) e = Edge
queue<int> q;
q.push(u);
visited[u] = true;
level[u] = 0;
parent[u] = -1;
while (!q.empty()) {
int temp = q.front();
q.pop(); // Every node will be visited 2 times (Time complexity - O(e))
for (int v: adj[temp]) { // Time complexity - O(n)
if (visited[v] == true) continue;
q.push(v);
visited[v] = true;
level[v] = level[temp] + 1;
parent[v] = temp; // Save the parent node for every node
}
}
}
// (Time complexity - O(n+e)
int main () {
// Shortest Path using BFS
int n, e; // n = Node & e = Edge
cin >> n >> e;
for (int i = 0; i < e; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
int s, d; // s = Source & d = Destination
cin >> s >> d;
// BFS (Time complexity - O(n+e))
bfs(s);
cout << s << " to " << d << " distance - "<< level[d] << endl;
// Path Finding (Time complexity - O(n))
vector<int> path;
int curr = d;
while (curr != -1) {
path.push_back(curr);
curr = parent[curr];
}
reverse(path.begin(), path.end());
cout << s << " to " << d << " path - ";
for (int v: path) {
cout << v << " ";
}
/*
// Print parent's node of all node
for (int i = 1; i <= n; i++) {
cout << "Parent of " << i << ": "<< parent[i] << endl;
}
*/
return 0;
}
|
App = {
web3Provider: null,
contracts: {},
account: "0x0",
hasVoted: false,
init: function () {
return App.initWeb3();
},
// connect out client-side application to our local blockchain
initWeb3: function () {
console.log(window);
// web3 == window.web3
if (typeof web3 !== "undefined") {
// If a web3 instance is already provided by MetaMask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider(
"http://localhost:7545"
);
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function () {
$.getJSON("Election.json", function (election) {
// Instantiate a new truffle contract from the artifact
App.contracts.Election = TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider);
App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
// refresh the page once a vote is casted
listenForEvents: function () {
App.contracts.Election.deployed().then(function (instance) {
// Restart Chrome if you are unable to receive this event
// This is a known issue with Metamask
// https://github.com/MetaMask/metamask-extension/issues/2393
instance
.votedEvent(
// solidity allows us to pass a filter to the event,
// we won't need that so we pass an empty object
{},
// subscribe the events from the entire blockchain (from
// the first block to the most recent one)
{
fromBlock: 0,
toBlock: "latest",
}
)
// subscribe to the event
.watch(function (error, event) {
console.log("event triggered", event);
// Reload when a new vote is recorded
App.render();
});
});
},
// render out the content of the application
render: function () {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load the chosen account in metamask
web3.eth.getCoinbase(function (err, account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
// Load contract data
App.contracts.Election.deployed()
.then(function (instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
})
.then(function (candidatesCount) {
var candidatesResults = $("#candidatesResults");
candidatesResults.empty();
var candidatesSelect = $("#candidatesSelect");
candidatesSelect.empty();
for (var i = 1; i <= candidatesCount; i++) {
electionInstance.candidates(i).then(function (candidate) {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate =
"<tr><th>" +
id +
"</th><td>" +
name +
"</td><td>" +
voteCount +
"</td></tr>";
candidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption =
"<option value='" + id + "' >" + name + "</ option>";
candidatesSelect.append(candidateOption);
});
}
return electionInstance.voters(App.account);
})
.then(function (hasVoted) {
// Do not allow a user to vote
if (hasVoted) {
$("form").hide();
}
loader.hide();
content.show();
})
.catch(function (error) {
console.warn(error);
});
},
castVote: function () {
var candidateId = $("#candidatesSelect").val();
App.contracts.Election.deployed()
.then(function (instance) {
return instance.vote(candidateId, { from: App.account });
})
.then(function (result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
})
.catch(function (err) {
console.error(err);
});
},
};
// initialize the app whenever the window loads
$(function () {
$(window).load(function () {
App.init();
});
});
|
package be.intecbrussel.testy.model.dto.create;
import be.intecbrussel.testy.model.EntityMapper;
import be.intecbrussel.testy.model.entity.ExamEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.time.Instant;
import java.util.Objects;
import static java.util.Objects.hash;
import static java.util.Objects.isNull;
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreateExamRequest implements java.io.Serializable, EntityMapper<ExamEntity> {
public CreateExamRequest() {
}
public CreateExamRequest(Long id) {
this.id = id;
}
private Long id;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public CreateExamRequest withId(Long id) {
setId(id);
return this;
}
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public CreateExamRequest withCode(String code) {
setCode(code);
return this;
}
private String header;
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public CreateExamRequest withHeader(String header) {
setHeader(header);
return this;
}
private String body;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public CreateExamRequest withBody(String body) {
setBody(body);
return this;
}
private CreateQuestionRequest question;
public CreateQuestionRequest getQuestion() {
return question;
}
public void setQuestion(CreateQuestionRequest question) {
this.question = question;
}
public CreateExamRequest withQuestion(CreateQuestionRequest question) {
setQuestion(question);
return this;
}
private CreateUserRequest student;
public CreateUserRequest getStudent(){
return student;
}
public void setStudent(CreateUserRequest student) {
this.student = student;
}
public CreateExamRequest withStudent(CreateUserRequest student) {
setStudent(student);
return this;
}
private Instant started;
public Instant getStarted() {
return started;
}
public void setStarted(Instant started) {
this.started = started;
}
public CreateExamRequest withStarted(Instant started) {
setStarted(started);
return this;
}
private Instant ended;
public Instant getEnded() {
return ended;
}
public void setEnded(Instant ended) {
this.ended = ended;
}
public CreateExamRequest withEnded(Instant ended) {
setEnded(ended);
return this;
}
private Double score;
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public CreateExamRequest withScore(Double score) {
setScore(score);
return this;
}
public boolean isNew() {
return isNull(this.id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CreateExamRequest)) return false;
CreateExamRequest createExamRequest = (CreateExamRequest) o;
return Objects.equals(getCode(), createExamRequest.getCode()) && Objects.equals(getQuestion(), createExamRequest.getQuestion());
}
@Override
public int hashCode() {
return hash(getCode(), getQuestion());
}
@Override
public String toString() {
return "{" + "id=" + id +
", code='" + code + '\'' +
", header='" + header + '\'' +
", body='" + body + '\'' +
", questionId=" + question.getId() +
", started=" + started +
", ended=" + ended +
", score=" + score +
'}';
}
@Override
public ExamEntity toEntity() {
final var entity = new ExamEntity();
if (this.id != null)
entity.setId(this.getId());
if (this.code != null)
entity.setCode(this.getCode());
if (this.header != null)
entity.setHeader(this.getHeader());
if (this.body != null)
entity.setBody(this.getBody());
if (this.question != null)
entity.setQuestion(this.getQuestion().toEntity());
if (this.started != null)
entity.setStarted(this.getStarted());
if (this.ended != null)
entity.setEnded(this.getEnded());
if (this.score != null)
entity.setScore(this.getScore());
return entity;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.