text
stringlengths 184
4.48M
|
---|
const supertest = require('supertest');
const expect = require('expect');
var app = require('./server').app;
describe('server', () => {
describe('GET /', => {
it('should return hello world response', (done) => {
supertest(app)
.get('/')
.expect(200)
//.expect('Hello World!')
//.expect({
// error: 'Page not found.',
//})
.expect((res) => {
expect(res.body).toInclude({
error: 'Page not found.'
});
})
.end(done);
});
});
describe('GET /users', () => {
it('should return my user object', (done) => {
supertest(app)
.get('/user')
.expect(200)
.expect((res) => {
expect(res.body).toInclude({
name: 'Andrew',
age: 25
});
})
.end(done);
});
});
});
|
//
// KSLiveProvider.swift
// KSHLSPlayer
//
// Created by Ken Sun on 2016/1/18.
// Copyright © 2016年 KS. All rights reserved.
//
import Foundation
/**
* Provider has its own mechanism to maintain playlist and TS segments. The only thing you have
* to do is push and add segment to it. Please follow the rules:
* 1. Push a segment by `push(ts: TSSegment)`.
* 2. Fill segment data you have pushed by fill(ts: TSSegment, data: NSData). If you haven't push
* it before, data will be ignored.
* 3. If you want to cancel a segment you have pushed, drop it by drop(ts: TSSegment).
* This may happen when you know you can't provide segment data for it anymore.
* Be aware if you don't drop such segment, provider will stop providing new playlist once
* its show time is come.
* 4. If you drop a segment which is already been filled, nothing will happen. The segment still
* appears in output playlist when its show time comes.
*
* Here's how provider provides playlist:
* 1. Provider go through segment list which contains all pushed segments.
* 2. For each segment, if its data has been filled, mark it as a valid segment.
* 3. Once an invalid segment(a segment without filled data) encountered, provider stops going
* through segment list and see if new playlist is available from valid segments.
*/
public class KSLiveProvider: KSStreamProvider {
struct Config {
/**
Maximum number of cached TS segment data.
*/
static let tsDataCacheMax = 10
/**
Number of segments in output playlist.
*/
static let playlistSegmentSize = 5
}
/**
Target duration in output playlist.
*/
var targetDuration: Double?
/**
Sequence number in output playlist. Starts from 0.
*/
private var sequenceNumber = 0
private var buffering = false
private var saveFolderPath: String?
private var saving = false
public func cleanUp() {
synced(segmentFence, closure: { [unowned self] in
self.segments.removeAll()
self.outputSegments.removeAll()
self.segmentData.removeAll()
})
self.outputPlaylist = nil
sequenceNumber = 0
buffering = false
}
/**
push segment to input list.
*/
public func push(ts: TSSegment) {
synced(segmentFence, closure: { [unowned self] in
self.segments += [ts]
})
}
/**
Drop segment from input list if data doesn't exist.
*/
public func drop(ts: TSSegment) {
synced(segmentFence, closure: { [unowned self] in
if self.segmentData[ts.filename()] == nil {
if let index = self.segments.indexOf(ts) {
self.segments.removeAtIndex(index)
}
}
})
}
public func fill(ts: TSSegment, data: NSData) {
if !segments.contains(ts) { return }
segmentData[ts.filename()] = data
/**
Maintain data cache size as `Config.tsDataCacheMax` or less.
*/
synced(segmentFence, closure: { [unowned self] in
if self.segmentData.count > Config.tsDataCacheMax {
/* Remove segments from oldest */
var overSize = self.segmentData.count - Config.tsDataCacheMax
while overSize > 0 {
if self.segments.count == 0 { break }
if self.segmentData.removeValueForKey(self.segments.removeFirst().filename()) != nil {
overSize--
}
}
}
})
/* Save file */
if let folder = saveFolderPath where saving {
let filePath = (folder as NSString).stringByAppendingPathComponent(ts.filename())
data.writeToFile(filePath, atomically: true)
}
}
public func startSaving(folder: String) {
saveFolderPath = folder
if !NSFileManager.defaultManager().fileExistsAtPath(folder) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(folder, withIntermediateDirectories: true, attributes: nil)
} catch {
print("create saving folder failed");
return
}
}
saving = true
/* Save memory cached segments into disk */
synced(segmentFence, closure: { [unowned self] in
for filename in self.segmentData.keys {
let data = self.segmentData[filename]
let filePath = (folder as NSString).stringByAppendingPathComponent(filename)
data?.writeToFile(filePath, atomically: true)
}
})
}
public func stopSaving() {
saving = false
saveFolderPath = nil
}
/**
Provide latest output playlist.
*/
override public func providePlaylist() -> String? {
/* If we don't have enough segments, start buffering. */
if outputSegments.count < Config.tsPrebufferSize {
buffering = true
}
/* Before we have enough buffered segments, we don't update playlist. */
if buffering {
/* If buffer size is enough, stop buffering and update playlist. */
if bufferedSegmentCount() >= Config.tsPrebufferSize {
buffering = false
updateOutputPlaylist()
}
} else {
/* If playlist is not changed, start buffering. */
if !updateOutputPlaylist() {
buffering = true
}
}
return outputPlaylist
}
private func updateOutputPlaylist() -> Bool {
return synced(segmentFence, closure:{ [unowned self] () -> Bool in
/* Check if plyalist should change */
var changed = false
for i in 0..<self.outputSegments.count {
let ts = self.outputSegments[i]
/* If any segment in output playlist doesn't exist anymore, change playlist. */
if !self.segments.contains(ts) {
changed = true
break
}
/* If we have new segments, change playlist. */
if i == self.outputSegments.count - 1 {
if let index = self.segments.indexOf(ts) where self.segments.count > index + 1 {
let nextNewSegment = self.segments[index + 1]
changed = self.segmentData[nextNewSegment.filename()] != nil
}
}
}
if self.outputSegments.count > 0 && !changed {
return false
}
/* Update playlist */
var startIndex = 0
if self.outputSegments.count > 0 {
if let index = self.segments.indexOf(self.outputSegments.last!) {
startIndex = index
}
}
for i in startIndex..<self.segments.count {
let ts = self.segments[i]
if self.segmentData[ts.filename()] == nil { break }
if !self.outputSegments.contains(ts) {
self.outputSegments += [ts]
}
}
/* Remove old segments in playlist and increase sequence number. */
if self.outputSegments.count > Config.playlistSegmentSize {
let offset = self.outputSegments.count - Config.playlistSegmentSize
self.outputSegments.removeRange(Range(start: 0, end: offset))
self.sequenceNumber += offset
}
/* Generate playlist */
let m3u8 = HLSPlaylist(
version: Config.HLSVersion,
targetDuration: self.targetDuration,
sequence: self.sequenceNumber,
segments: self.outputSegments)
self.outputPlaylist = m3u8.generate(self.serviceUrl, end: false)
return true
})
}
}
|
//Да се напише програма, която дефинира клас Gilishte, определящ адрес, площ и цена на
//жилище, данните за всички жилища се съхраняват в масив от обекти. Дефинират се и класове Apartament
//с етаж и Kashta с размер на двор, наследници на Gilishte. Да се въведат n жилища от различен тип
//(апартамент или къща). Да се изведат всички жилища от даден тип, чиято цена е под дадена въведена
//стойност
using System;
class Jilishte
{
public string address;
public double plosht;
public float price;
public Jilishte(string x, double y, float z)
{
address = x;
plosht = y;
price = z;
}
public virtual string Type()
{
return "";
}
public virtual float Price()
{
return 0;
}
public virtual double Plosht()
{
return 0;
}
}
class Apartment : Jilishte
{
public int floor;
public Apartment(string address, double plosht, float price, int floor) :
base(address, plosht, price)
{
this.floor = floor;
}
public override string Type()
{
return "apartment";
}
public override float Price()
{
return price;
}
public override double Plosht()
{
return plosht;
}
}
class House : Jilishte
{
public float dworRazmer;
public House(string address, double plosht, float price, float dworRazmer) :
base(address, plosht, price)
{
this.dworRazmer = dworRazmer;
}
public override string Type()
{
return "house";
}
public override float Price()
{
return price;
}
public override double Plosht()
{
return plosht;
}
}
class MyClass
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
float cenaZaSrawnenie = float.Parse(Console.ReadLine());
string address, type; double plosht; float price, dworRazmer; int floor;
Jilishte[] arr = new Jilishte[n];
for (int i = 0; i < n; i++)
{
Console.Write($"Address {i}: ");
address = Console.ReadLine();
Console.Write($"Plosht {i}:");
plosht = double.Parse(Console.ReadLine());
Console.Write($"Price {i}:");
price = float.Parse(Console.ReadLine());
Console.Write($"House or apartment? {i}:");
type = Console.ReadLine();
if ("house".Equals(type.ToLower()))
{
Console.Write($"Razmer na dwor {i}:");
dworRazmer = float.Parse(Console.ReadLine());
arr[i] = new House(address, plosht, price, dworRazmer);
}
else
{
Console.Write($"Etaj {i}:");
floor = int.Parse(Console.ReadLine());
arr[i] = new Apartment(address, plosht, price, floor);
}
}
for (int i = 0; i < n; i++)
{
if (arr[i].price < cenaZaSrawnenie)
{
Console.WriteLine(arr[i].Type() + " " + arr[i].Price());
}
}
}
}
|
import React, { useEffect, useState, useCallback } from 'react';
import { Text, View, ScrollView, Image, Pressable, Alert, Keyboard, TouchableWithoutFeedback, } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import Styles from '../Styles/Styles';
import ButtonStyles from '../Styles/ButtonStyles';
import NavBar from '../components/NavBar';
import Header from '../components/Header';
import axios from 'axios';
import BASE_URL from '../json/BaseUrl';
import SearchBox from '../components/SearchBox';
// sivu joka näyttää kaikki tai filtteröidyt ilmoitukset
export default function MainPage({ navigation }) {
const [ads, setAds] = useState([]);
const [page, setPage] = useState(1);
const [total_rows, setTota_rows] = useState(0)
const [region, setRegion] = useState('');
const [type, setType] = useState('');
const [searchText, setSearchText] = useState("");
const [filter, setFilter] = useState('1')
useEffect(() => {
getData(type, region, filter, page, searchText);
}, [page]);
const getData = async (type, region, filter, page, searchText) => {
//haetaan parametrien mukaiset ilmoitukset 10kpl
console.log('getdata', region)
try {
const results = await axios.get(BASE_URL + '/ad/withparams/get?type=' + type + '®ion=' + region + '&order=' + filter + '&page=' + page + '&query=' + searchText + '')
setAds(Object.values(results.data.data))
setTota_rows(results.data.total_rows)
console.log('getData success')
} catch (error) {
console.log("getData error ", error)
Alert.alert('Ei hakutuloksia!')
}
}
const nextAds = async () => { //tässä lisätään offsettia jotta saadaan seuraava sivu
const pages = Math.ceil(total_rows / 10)
if (page < pages) {
setPage(page + 1);
getData(type, region, filter, page, searchText);
}
}
const previousAds = async () => { // tässä vähennetään offsettia nollaan asti jotta saadaan aiempi sivu
if (page > 1) {
setPage(page - 1);
getData(type, region, filter, page, searchText);
}
}
const handleButtonAdClicket = (adid, userid) => { //kun painetaan ilmoitusta, avataan seuraava sivu
navigation.navigate('ShowAd', { adid, userid })
}
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={Styles.container}>
<StatusBar style="light" translucent={true} />
<Header></Header>
<View style={Styles.container2}>
<SearchBox getData={getData} />
<ScrollView style={Styles.scrollViewStyle}>
{
Object.values(ads).map((item, index) => (
<Pressable key={index} onPress={(() => handleButtonAdClicket(item.adid, item.userid))}>
<View style={Styles.adContainer}>
<Image
style={Styles.image}
/>
<View style={Styles.descriptionContainer1}>
<View style={Styles.descriptionContainer2}>
<View style={Styles.descriptionContainer3}>
<Text style={Styles.textStyle}>{item.header} </Text>
<Text style={Styles.textStyle}>Hinta {item.price}€</Text>
<Text style={Styles.textStyle}>{item.region}</Text>
</View>
</View>
<View style={Styles.descriptionContainer3}>
<Text>{item.description}</Text>
</View>
</View>
</View>
</Pressable>
))
}
</ScrollView>
<View style={ButtonStyles.nextContainer}>
<Pressable style={ButtonStyles.buttonSearch}
onPress={() => previousAds()}
>
<Text style={ButtonStyles.buttonText}>Takaisin</Text>
</Pressable>
<View style={ButtonStyles.infoContainer}>
<Text style={ButtonStyles.infoText}>Sivu {page}/{Math.ceil(total_rows / 10)} osumia {total_rows}</Text>
</View>
<Pressable style={ButtonStyles.buttonSearch}
onPress={() => nextAds()}
>
<Text style={ButtonStyles.buttonText}>Seuraava</Text>
</Pressable>
</View>
</View>
<NavBar navigation={navigation}></NavBar>
</View>
</TouchableWithoutFeedback>
);
}
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const passport_1 = __importDefault(require("passport"));
const logger_1 = __importDefault(require("../../../middlewares/logger"));
const categories_1 = __importDefault(require("../controllers/categories"));
const categories_2 = __importDefault(require("../utils/validator/categories"));
const roles_1 = require("../../auth/controllers/roles");
const router = (0, express_1.Router)();
router.get('/', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
const categories = yield categories_1.default.listCategories(req);
res.status(200).json(categories);
}
catch (error) {
logger_1.default.error(error);
res.status(400).json({ message: 'Error getting categories' });
}
}));
router.post('/', passport_1.default.authenticate('jwt', { session: false }), categories_2.default.validateCreateCategory, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
const isAuthorized = yield (0, roles_1.authorizeUser)(req, 'create:resources');
if (!isAuthorized) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
const newCategory = yield categories_1.default.createCategory(req);
res.status(201).json(newCategory);
}
catch (error) {
logger_1.default.error(error);
res.status(400).json({ message: 'Error creating category' });
}
}));
router.get('/list/:categoryId/:cityId', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
const users = yield categories_1.default.listUsersByCategoryAndCity(req);
res.status(200).json(users);
}
catch (error) {
logger_1.default.error(error);
res.status(400).json({ message: 'Error getting users' });
}
}));
exports.default = router;
|
<?php
/**
*@copyright : ToXSL Technologies Pvt. Ltd. < www.toxsl.com >
*@author : Shiv Charan Panjeta < [email protected] >
*
* All Rights Reserved.
* Proprietary and confidential : All information contained herein is, and remains
* the property of ToXSL Technologies Pvt. Ltd. and its partners.
* Unauthorized copying of this file, via any medium is strictly prohibited.
*
*/
namespace app\modules\seo\controllers;
use Yii;
use app\modules\seo\models\Log;
use app\modules\seo\models\search\Log as LogSearch;
use app\components\TController;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\AccessRule;
use app\models\User;
use yii\web\HttpException;
use app\components\TActiveForm;
/**
* LogController implements the CRUD actions for Log model.
*/
class LogController extends TController
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'ruleConfig' => [
'class' => AccessRule::className()
],
'rules' => [
[
'actions' => [
'clear',
'delete',
'view'
],
'allow' => true,
'matchCallback' => function () {
return User::isAdmin();
}
],
[
'actions' => [
'clone'
],
'allow' => true,
'matchCallback' => function () {
return User::isManager();
}
],
[
'actions' => [
'index',
// 'add',
// 'view',
// 'update',
// 'clone',
'ajax',
'mass'
],
'allow' => true,
'matchCallback' => function () {
return User::isManager();
}
]
]
]
];
}
/**
* Lists all Log models.
*
* @return mixed
*/
public function actionIndex()
{
$searchModel = new LogSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$this->updateMenuItems();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]);
}
/**
* Displays a single Log model.
*
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$this->updateMenuItems($model);
return $this->render('view', [
'model' => $model
]);
}
/**
* Creates a new Log model.
* If creation is successful, the browser will be redirected to the 'view' page.
*
* @return mixed
*/
public function actionAdd(/* $id*/)
{
$model = new Log();
$model->loadDefaultValues();
$model->state_id = Log::STATE_ALLOWED;
/*
* if (is_numeric($id)) {
* $post = Post::findOne($id);
* if ($post == null)
* {
* throw new NotFoundHttpException('The requested post does not exist.');
* }
* $model->id = $id;
*
* }
*/
$model->checkRelatedData([]);
$post = \yii::$app->request->post();
if (\yii::$app->request->isAjax && $model->load($post)) {
\yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return TActiveForm::validate($model);
}
if ($model->load($post) && $model->save()) {
return $this->redirect($model->getUrl());
}
$this->updateMenuItems();
return $this->render('add', [
'model' => $model
]);
}
/**
* Updates an existing Log model.
* If update is successful, the browser will be redirected to the 'view' page.
*
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$post = \yii::$app->request->post();
if (\yii::$app->request->isAjax && $model->load($post)) {
\yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return TActiveForm::validate($model);
}
if ($model->load($post) && $model->save()) {
return $this->redirect($model->getUrl());
}
$this->updateMenuItems($model);
return $this->render('update', [
'model' => $model
]);
}
/**
* Clone an existing Log model.
* If update is successful, the browser will be redirected to the 'view' page.
*
* @param integer $id
* @return mixed
*/
public function actionClone($id)
{
$old = $this->findModel($id);
$model = new Log();
$model->loadDefaultValues();
$model->state_id = Log::STATE_ALLOWED;
// $model->id = $old->id;
$model->referer_link = $old->referer_link;
$model->message = $old->message;
$model->current_url = $old->current_url;
// $model->state_id = $old->state_id;
$model->type_id = $old->type_id;
$model->user_id = $old->user_id;
$model->user_ip = $old->user_ip;
$model->user_agent = $old->user_agent;
// $model->created_on = $old->created_on;
// $model->created_by_id = $old->created_by_id;
$post = \yii::$app->request->post();
if (\yii::$app->request->isAjax && $model->load($post)) {
\yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return TActiveForm::validate($model);
}
if ($model->load($post) && $model->save()) {
return $this->redirect($model->getUrl());
}
$this->updateMenuItems($model);
return $this->render('update', [
'model' => $model
]);
}
/**
* Deletes an existing Log model.
* If deletion is successful, the browser will be redirected to the 'index' page.
*
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
if (\yii::$app->request->post()) {
$model->delete();
return $this->redirect([
'index'
]);
}
return $this->render('delete', [
'model' => $model
]);
}
/**
* Truncate an existing Log model.
* If truncate is successful, the browser will be redirected to the 'index' page.
*
* @param integer $id
* @return mixed
*/
public function actionClear($truncate = true)
{
$query = Log::find();
foreach ($query->each() as $model) {
$model->delete();
}
if ($truncate) {
Log::truncate();
}
\Yii::$app->session->setFlash('success', 'Log Cleared !!!');
return $this->redirect([
'index'
]);
}
/**
* Finds the Log model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
*
* @param integer $id
* @return Log the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id, $accessCheck = true)
{
if (($model = Log::findOne($id)) !== null) {
if ($accessCheck && ! ($model->isAllowed()))
throw new HttpException(403, Yii::t('app', 'You are not allowed to access this page.'));
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
protected function updateMenuItems($model = null)
{
switch (\Yii::$app->controller->action->id) {
case 'add':
{
$this->menu['index'] = [
'label' => '<span class="glyphicon glyphicon-list"></span>',
'title' => Yii::t('app', 'Manage'),
'url' => [
'index'
]
// 'visible' => User::isAdmin ()
];
}
break;
case 'index':
{
$this->menu['add'] = [
'label' => '<span class="glyphicon glyphicon-plus"></span>',
'title' => Yii::t('app', 'Add'),
'url' => [
'add'
],
'visible' => false
];
$this->menu['clear'] = [
'label' => '<span class="glyphicon glyphicon-remove"></span>',
'title' => Yii::t('app', 'Clear'),
'url' => [
'clear'
],
'htmlOptions' => [
'data-confirm' => "Are you sure to delete these items?"
],
'visible' => User::isAdmin()
];
}
break;
case 'update':
{
$this->menu['add'] = [
'label' => '<span class="glyphicon glyphicon-plus"></span>',
'title' => Yii::t('app', 'Add'),
'url' => [
'add'
],
'visible' => false
];
$this->menu['index'] = [
'label' => '<span class="glyphicon glyphicon-list"></span>',
'title' => Yii::t('app', 'Manage'),
'url' => [
'index'
]
// 'visible' => User::isAdmin ()
];
}
break;
default:
case 'view':
{
$this->menu['index'] = [
'label' => '<span class="glyphicon glyphicon-list"></span>',
'title' => Yii::t('app', 'Manage'),
'url' => [
'index'
]
// 'visible' => User::isAdmin ()
];
$this->menu['clone'] = [
'label' => '<span class="glyphicon glyphicon-copy">Clone</span>',
'title' => Yii::t('app', 'Clone'),
'url' => $model->getUrl('clone')
// 'visible' => User::isAdmin ()
];
}
}
}
}
|
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<child>
<h1 slot ="header">Dell1</h1>
<h1 slot ="footer">Dell2</h1>
</child>
</div>
<script>
Vue.component('child', {
template:'<div><p>hello</p><slot name ="header">默认内容</slot></div>'
// 还可以设置 默认内容
})
var vm = new Vue({
el:'#app',
data: {}
})
</script>
</body>
</html>
<!-- <html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<child content ="<p>Dell Lee</p>"></child>
</div>
<script>
Vue.component('child', {
props:['content'],
template:'<div><p>hello</p><div v-html="this.content">{{content}}</div></div>'
})
var vm = new Vue({
el:'#app',
data: {}
})
</script>
</body>
</html>
子组件 除了展示子组件自己的内容
还想展示父组件传递的内容
通过绑定属性 传递DOM结构 代码难以维护
-->
<!--
使用slot 还能正确解析DOM元素
具名插槽
-->
|
# 511. Game Play Analysis I
[Question Link](https://leetcode.com/problems/game-play-analysis-i/)
## Intuition
Knowledge of this test:
- if you don't use `inplace = True` in rename, the output will not change the name of the column.
So you have 2 choices:
- No.1:
```
result = activity.rename(columns={'event_date':'first_login'})
return result
```
- N0.2:
```
activity.rename(columns={'event_date':'first_login'},inplace=True)
return activity
```
The solution below is the latter one.
## Code
```python
import pandas as pd
def game_analysis(activity: pd.DataFrame) -> pd.DataFrame:
activity=activity.loc[:,['player_id','event_date']]
activity=activity.groupby(['player_id'])['event_date'].min().reset_index()
activity.rename(columns={'event_date':'first_login'},inplace=True)
return activity
```
|
#pragma once
#include <string>
#include <fstream>
#include <iostream>
#include "tape_exceptions.hpp"
namespace tape_simulation {
template<typename T>
class tape final {
std::fstream file_;
int size_;
static constexpr int elem_sz = sizeof(T);
public:
tape(std::string path) : file_(path, std::fstream::out | std::fstream::in | std::fstream::binary) {
if (!file_.is_open())
throw tape_exceptions::cannot_open_file(path);
file_.seekg(0, file_.end);
size_ = file_.tellg();
file_.seekg(0, file_.beg);
}
tape() = default;
//------------------Rule of five------------------
~tape() = default;
tape(const tape&) = delete;
tape(tape&&) = delete;
tape& operator=(const tape&) = delete;
tape& operator=(tape&&) = delete;
//------------------------------------------------
void move_next() {
int pos = file_.tellg() + elem_sz;
if (pos > size_) throw tape_exceptions::move_next_out_of_range();
file_.seekg(elem_sz, file_.cur);
/* seekg and seekp call rdbuf()->pubseekoff() for the same buffer,
so no need to call seekp to move put pointer */
}
void move_prev() {
int pos = file_.tellg() - elem_sz;
if (pos < 0) throw tape_exceptions::move_prev_out_of_range();
file_.seekg(-elem_sz, file_.cur);
}
bool read_elem(T &elem) {
if (file_.tellg() == size_) return false;
file_.read(reinterpret_cast<char*>(&elem), elem_sz);
move_prev();
return true;
}
void write_elem(T elem) {
if (file_.tellg() == size_) size_ += elem_sz;
file_.write(reinterpret_cast<char*>(&elem), elem_sz);
move_prev();
}
#ifdef TAPE_DUMP_MODE
void dump() {
auto save_pos = file_.tellg();
file_.seekg(0, file_.beg);
std::cout << "TAPE DUMP" << std::endl;
for (int i = 0, e = size_/elem_sz, tmp{}; i < e; ++i) {
read_elem(tmp); move_next();
std::cout << "pos_" << i << "=" << tmp << std::endl;
}
file_.seekg(save_pos);
}
#endif // TAPE_DUMP_MODE
#ifndef TAPE_DUMP_MODE
void dump() { }
#endif // TAPE_DUMP_MODE
void open_tape(std::string path) {
if (file_.is_open())
throw tape_exceptions::tape_already_initialized(path);
file_.open(path, std::fstream::out | std::fstream::in | std::fstream::binary | std::fstream::trunc);
if (!file_.is_open())
throw tape_exceptions::cannot_open_file(path);
file_.seekg(0, file_.end);
size_ = file_.tellg();
file_.seekg(0, file_.beg);
}
int rewind_begin() {
int len = file_.tellg() / elem_sz;
file_.seekg(0, file_.beg);
return len;
}
template<typename TypeIt>
int read_buffer(TypeIt beg, TypeIt end) {
int len = 0;
for(int tmp{}; beg != end && read_elem(tmp); ++len, *(beg++) = tmp, move_next());
return len;
}
template<typename TypeIt>
int write_buffer(TypeIt beg, TypeIt end) {
int len = 0;
for (; beg != end; write_elem(*(beg++)), ++len, move_next());
return len;
}
int pos() { return file_.tellg() / elem_sz; }
int size() const { return size_ / elem_sz; }
bool is_valid() const { return file_.is_open() && size_ >= 0; }
};
} // <--- namespace tape_simulation
|
package model
import (
"ecommerce/database"
"html"
"log"
"strings"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type User struct {
gorm.Model
Username string `gorm:"size:255;not null;unique" json:"username" validate:"required,min=2,max=30"`
// Email string `gorm:"size:255;not null;" json:"email" validate:"email,required"`
Password string `gorm:"size:255;not null;" json:"-" validate:"required,min=6"`
// Phone *string `gorm:"size:255;not null;" json:"phone" validate:"required"`
Address []Address
}
func (user *User) Save() (*User, error) {
err := database.Database.Create(&user).Error
if err != nil {
return &User{}, err
}
return user, nil
}
func (user *User) BeforeSave(*gorm.DB) error {
passwordHash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
user.Password = string(passwordHash)
user.Username = html.EscapeString(strings.TrimSpace(user.Username))
return nil
}
func (user *User) ValidatePassword(password string) error {
log.Println(password)
log.Println(user.Password)
return bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
}
func FindUserByUsername(username string) (User, error) {
var user User
err := database.Database.Where("username=?", username).Find(&user).Error
if err != nil {
return User{}, err
}
return user, nil
}
func FindUserById(id uint) (User, error) {
var user User
err := database.Database.Preload("Address").Where("ID=?", id).Find(&user).Error
if err != nil {
return User{}, err
}
return user, nil
}
|
package com.oym.oa.dao;
import com.oym.oa.entity.Employee;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("employeeDAO")
public interface IEmployeeDAO {
/**
* 插入员工信息
* @param employee
*/
void insert(Employee employee);
/**
* 更新员工信息
* @param employee
*/
void update(Employee employee);
/**
* 删除该员工信息
* @param sn
*/
void delete(String sn);
/**
* 查询目的员工
* @param sn
* @return
*/
Employee select(String sn);
/**
* 查询各员工信息
* @return
*/
List<Employee> selectAll();
/**
* 查询待处理人
* @param dsn
* @param post
* @return
*/
List<Employee> selectByDepartmentAndPost(@Param("dsn") String dsn,@Param("post") String post);
}
|
const int switchPin = 12; // switch input
const int leftMotor1Pin1 = 3; // pin 2 on L293D
const int leftMotor1Pin2 = 4; // pin 7 on L293D
const int rightMotor1Pin1 = 5; // pin 2 on L293D
const int rightMotor1Pin2 = 6; // pin 7 on L293D
const int leftEnablePin = 8; // pin 1 on L293D
const int rightEnablePin = 9; // pin 1 on L293D
volatile unsigned long time,new_time,old_time;
volatile unsigned char ir_check=1, IR_start=0;
volatile unsigned long mask=0x00000001, IR_rx_data=0x00000000, IR_code, before_value = 0x00000001;
int motor_left = 0;
int motor_right = 0;
const int FORWARD = 1;
const int STOP = 0;
const int BACKWARD = -1;
void setup() {
Serial.begin(9600);
// set the switch as an input:
pinMode(switchPin, INPUT);
// set all the other pins you're using as outputs:
pinMode(13, OUTPUT);
pinMode(11, OUTPUT); // ir vcc
pinMode(leftMotor1Pin1, OUTPUT);
pinMode(leftMotor1Pin2, OUTPUT);
pinMode(rightMotor1Pin1, OUTPUT);
pinMode(rightMotor1Pin2, OUTPUT);
pinMode(leftEnablePin, OUTPUT);
pinMode(rightEnablePin, OUTPUT);
// set enablePin high so that motor can turn on:
digitalWrite(leftEnablePin, HIGH);
digitalWrite(rightEnablePin, HIGH);
digitalWrite(11, HIGH); // ir vcc
attachInterrupt(0, IR_remote, FALLING);
}
void loop() {
// digitalWrite(irvcc, HIGH); // ir vcc ON
while(ir_check);
ir_check=1;
digitalWrite(13, HIGH); // set the LED off
delay(100);
digitalWrite(13, LOW); // set the LED off
}
void forward(int pin1, int pin2)
{
digitalWrite(pin1, HIGH); // set pin 2 on L293D high
digitalWrite(pin2, LOW); // set pin 7 on L293D low
}
void backward(int pin1, int pin2)
{
digitalWrite(pin1, LOW); // set pin 2 on L293D high
digitalWrite(pin2, HIGH); // set pin 7 on L293D low
}
void stopMotor(int pin1, int pin2)
{
digitalWrite(pin1, LOW); // set pin 2 on L293D high
digitalWrite(pin2, LOW); // set pin 7 on L293D low
}
void IR_remote()
{
char before_value_str[256];
new_time = micros(); // 현재시간 저장
time=new_time - old_time; // 엣지 사이의 시간 계산
old_time=new_time; // 이전시간을 현재시간으로 갱신
if(time > 13000 && time <14000) IR_start=1; // lead code 13.5ms의 리드코드를 확인합니다.
else if(time > 9000 && time <12000) // repeat code 일때는 무시 입력은 1번만
{
// Serial.println("R"); // repeat code 가 들어오면 LCD에 'R' 을 출력합니다.
IR_start=0; // 변수 초기화
mask=0x00000001;
IR_rx_data=0x00000000;
}else if(IR_start==1) // 리드코드가 들어 왔다면...
{
if(time > 1025 && time < 1225) // 1.125ms 0을 받습니다.
{
IR_rx_data &= ~mask;
mask=mask<<1; // mask를 1비트씩 시프트 하면서 데이터를 쌓습니다.
}
else if(time > 2125 && time < 2325) // 2.25ms 1을 받습니다.
{
IR_rx_data |= mask;
mask=mask<<1; // mask를 1비트씩 시프트 하면서 데이터를 쌓습니다.
}
if(mask==0) // mask가 모두 시프트되어 0이되면(32bit data를 모두 받으면.. )
{
IR_code = IR_rx_data;
// snprintf(before_value_str, sizeof(before_value_str), "before %d",before_value );
// Serial.println(before_value_str);
// Serial.println(IR_code, HEX);
if(before_value == IR_code){
Serial.println("toggle");
before_value = 0x00000001;
motor_left = 0;
motor_right = 0;
}else{
if(IR_code == 0x280B87EE){
motor_left = FORWARD;
motor_right = FORWARD;
Serial.println("forward");
}else if(IR_code == 0x280887EE){
motor_left = BACKWARD;
motor_right = FORWARD;
Serial.println("left");
}else if(IR_code == 0x280787EE){
motor_left = FORWARD;
motor_right = BACKWARD;
Serial.println("right");
}else if(IR_code == 0x280D87EE){
motor_left = BACKWARD;
motor_right = BACKWARD;
Serial.println("backward");
}else if(IR_code == 0x280487EE){
motor_left = FORWARD;
motor_right = FORWARD;
Serial.println("center");
}else if(IR_code == 0x280287EE){
motor_left = 0;
motor_right = 0;
Serial.println("menu");
}else if(IR_code == 0x280487EE){
motor_left = FORWARD;
motor_right = FORWARD;
Serial.println("play");
}
before_value = IR_code;
}
switch(motor_left){
case FORWARD:
forward(leftMotor1Pin1, leftMotor1Pin2);
break;
case STOP:
stopMotor(leftMotor1Pin1, leftMotor1Pin2);
break;
case BACKWARD:
backward(leftMotor1Pin1, leftMotor1Pin2);
break;
}
switch(motor_right){
case 1:
forward(rightMotor1Pin1, rightMotor1Pin2);
break;
case 0:
stopMotor(rightMotor1Pin1, rightMotor1Pin2);
break;
case BACKWARD:
backward(rightMotor1Pin1, rightMotor1Pin2);
break;
}
// 변수 초기화
IR_start=0;
mask=0x00000001;
IR_rx_data=0x00000000;
ir_check=0;
}
}
}
|
package com.hazz.kotlinmvp.view
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.annotation.DrawableRes
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.hazz.kotlinmvp.R
/**
* Created by Terminator on 2019/2/10.
*/
class ExpandableTextView : LinearLayout, View.OnClickListener {
private var mTextView: TextView? = null
private var mButton: ImageView? = null
private var mRelayout: Boolean = false
private var mCollapsed = true
private var mExpandDrawable: Drawable? = null
private var mCollapseDrawable: Drawable? = null
private var mMaxCollapsedLines: Int = 0
private var mTextHeightWithMaxLines: Int = 0
private var mMarginBetweenTxtAndBottom: Int = 0
private var mCollapsedHeight: Int = 0
private var mAnimating: Boolean = false
private var mAnimAlphaStart: Float = 0.toFloat()
private var mAnimationDuration: Int = 0
private val mListener: OnExpandStateChangeListener? = null
var text: CharSequence?
get() = if (mTextView == null) "" else mTextView!!.text
set(text) {
mRelayout = true
mTextView!!.text = text
visibility = if (TextUtils.isEmpty(text)) View.GONE else View.VISIBLE
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initView(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initView(attrs)
}
private fun initView(attrs: AttributeSet) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView)
mMaxCollapsedLines = typedArray.getInt(R.styleable.ExpandableTextView_maxCollapsedLines, MAX_COLLAPSED_LINES)
mAnimationDuration = typedArray.getInt(R.styleable.ExpandableTextView_animDuration, DEFAULT_ANIM_DURATION)
mAnimAlphaStart = typedArray.getFloat(R.styleable.ExpandableTextView_animAlphaStart, DEFAULT_ANIM_ALPHA_START)
mExpandDrawable = typedArray.getDrawable(R.styleable.ExpandableTextView_expandDrawable)
mCollapseDrawable = typedArray.getDrawable(R.styleable.ExpandableTextView_collapseDrawable)
if (mExpandDrawable == null) {
mExpandDrawable = getDrawable(context, R.mipmap.ic_action_down_white)
}
if (mCollapseDrawable == null) {
mCollapseDrawable = getDrawable(context, R.mipmap.ic_action_up_white)
}
typedArray.recycle()
orientation = LinearLayout.VERTICAL
visibility = View.GONE
}
override fun setOrientation(orientation: Int) {
if (orientation == LinearLayout.HORIZONTAL) {
throw IllegalArgumentException("ExpandableTextView only supports Vertical Orientation")
}
super.setOrientation(orientation)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (!mRelayout || visibility == View.GONE) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
return
}
mRelayout = false
mButton!!.visibility = View.GONE
mTextView!!.maxLines = Integer.MAX_VALUE
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (mTextView!!.lineCount <= mMaxCollapsedLines) return
mTextHeightWithMaxLines = getRealTextViewHeight(mTextView!!)
if (mCollapsed) {
mTextView!!.maxLines = mMaxCollapsedLines
}
mButton!!.visibility = View.VISIBLE
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (mCollapsed) {
mTextView!!.post { mMarginBetweenTxtAndBottom = height - mTextView!!.height }
mCollapsedHeight = measuredHeight
}
}
override fun onFinishInflate() {
findViews()
super.onFinishInflate()
}
private fun findViews() {
mTextView = findViewById<View>(R.id.expandable_text) as TextView
mButton = findViewById<View>(R.id.expand_collapse) as ImageView
mTextView!!.setOnClickListener(this)
mButton!!.setOnClickListener(this)
mButton!!.setImageDrawable(if (mCollapsed) mExpandDrawable else mCollapseDrawable)
}
override fun onClick(v: View?) {
if (mButton!!.visibility != View.VISIBLE) {
return
}
mCollapsed = !mCollapsed
mButton!!.setImageDrawable(if (mCollapsed) mExpandDrawable else mCollapseDrawable)
mAnimating = true
val animation: Animation = if (mCollapsed) {
ExpandCollapseAnimation(this, height, mCollapsedHeight)
} else {
ExpandCollapseAnimation(this, height, height + mTextHeightWithMaxLines - mTextView!!.height)
}
animation.fillAfter = true
animation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
applyAlphaAnimation(mTextView, mAnimAlphaStart)
}
override fun onAnimationEnd(animation: Animation?) {
clearAnimation()
mAnimating = false
mListener?.onExpandStateChanged(mTextView, !mCollapsed)
}
override fun onAnimationRepeat(animation: Animation?) {
}
})
clearAnimation()
startAnimation(animation)
}
internal inner class ExpandCollapseAnimation(private val mTargetView: View, private val mStartHeight: Int, private val mEndHeight: Int) : Animation() {
init {
duration = mAnimationDuration.toLong()
}
override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
val newHeight = ((mEndHeight - mStartHeight) * interpolatedTime + mStartHeight).toInt()
mTextView!!.maxHeight = newHeight - mMarginBetweenTxtAndBottom
if (java.lang.Float.compare(mAnimAlphaStart, 1.0f) != 0) {
applyAlphaAnimation(mTextView, mAnimAlphaStart + interpolatedTime * (1.0f - mAnimAlphaStart))
}
mTargetView.layoutParams.height = newHeight
mTargetView.requestLayout()
}
}
interface OnExpandStateChangeListener {
fun onExpandStateChanged(textView: TextView?, isExpanded: Boolean)
}
companion object {
private val MAX_COLLAPSED_LINES = 8
private val DEFAULT_ANIM_DURATION = 300
private val DEFAULT_ANIM_ALPHA_START = 0.7f
private fun getRealTextViewHeight(textView: TextView): Int {
val textHeight = textView.layout.getLineTop(textView.lineCount)
val padding = textView.compoundPaddingTop + textView.compoundPaddingBottom
return textHeight + padding
}
private fun getDrawable(context: Context, @DrawableRes resId: Int): Drawable? {
val resources = context.resources
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
resources.getDrawable(resId, context.theme)
} else {
ContextCompat.getDrawable(context, resId)
}
}
}
private fun applyAlphaAnimation(view: View?, alpha: Float) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
view!!.alpha = alpha
} else {
val alphaAnimation = AlphaAnimation(alpha, alpha)
alphaAnimation.duration = 0
alphaAnimation.fillAfter = true
view!!.startAnimation(alphaAnimation)
}
}
}
|
public class Pawn extends ChessPiece {
public Pawn(String color) {
super(color);
}
@Override
public String getColor() {
return this.color;
}
//метод позволяющий определять может ли фигура двигаться в какую либо позицию
//в него передается шахматная доска, линия и колонка с которых начинается ход, линия и колонка куда будет сделан ход
public boolean canMoveToPosition(ChessBoard chessBoard, int line, int column, int toLine, int toColumn) {
// проверяем все ли начальные и переданные координаты существуют(все ли они есть на нашей доске)
// и есть ли по указанным координатам на доске шахматная фигура
if (isOnBoard (line,column,toLine,toColumn) && chessBoard.board[line][column] != null) {
if (column == toColumn) { // реализовываем часть метода когда пешка не ходит наискосок (не рубит)
int dir; // переменная говорит на сколько клеток пешка движется вперед (длина хода, для белых со знаком плюс)
int start; // переменная которая говорит на какой line стоит пешка
if (color.equals("White")) { // если пешка белая
dir = 1; // положительная - значит вверх по доске
start = 1; // стартовая линия на которой находится пешка
} else {
dir = -1; // отрицательная - значит вниз по доске
start = 6;
}
// проверяем можем ли сходить в конечную клетку
if (line + dir == toLine) {
// если указанная клетка (chessBoard.board[toLine][toColumn]) пуста то вернется правда, иначе ложь
return chessBoard.board[toLine][toColumn] == null;//
}
// если линия, на которой стоит пешка, является стартовой (1 или 6) и ход выполняется на 2 клетки
if (line == start && line + 2 * dir == toLine) {
// если конечная клетка свободна и на ее пути нет фигур, то функция вернет правду
return (chessBoard.board[toLine][toColumn] == null && chessBoard.board[line + dir][column] == null);
}
}
} else { // теперь пешка должна рубить
// если по колонке и линии сдвигаемся на один
if (column - toColumn == 1 || column - toColumn == -1 && line - toLine == 1 || line - toLine == -1 &&
// и на этой клетке есть фигура
chessBoard.board[toLine][toColumn] != null){
//возвращаем правду если цвет этой фигуры не совпадает с цветом нашей фигуры
return (!chessBoard.board[toLine][toColumn].getColor().equals(color));
} else return false;
} return false;
}
@Override
public String getSymbol() {
return "P";
}
}
|
import { SORT_BY_NAME, SORT_ASCENDING } from '../constants';
import { LibraryItem } from '../models/library-item.model';
export class ItemLibrary {
constructor(
private items: Map<string, LibraryItem> = new Map(),
private sortMode: string = SORT_BY_NAME,
private sortDirection: string = SORT_ASCENDING
) {}
get(id: string) {
return this.items.get(id);
}
add(id: string, item: LibraryItem) {
this.items.set(id, item);
}
remove(id: string) {
this.items.delete(id);
}
update(id: string, item: LibraryItem) {
this.items.set(id, item);
}
setItems(items: Map<string, LibraryItem>) {
this.items = items;
}
has(key: string) {
return this.items.has(key);
}
size() {
return this.items.size;
}
values() {
return this.items.values();
}
getAllItems() {
return this.items;
}
getAllTags() {
const tags = [];
this.items.forEach(item => {
if (item.tags.length > 0) {
tags.push(...item.tags);
}
});
return [...new Set(tags)];
}
getAllUnits() {
const units = [];
this.items.forEach(item => {
const unit = item.unit;
if (unit && typeof unit !== 'undefined') {
units.push(unit);
}
});
return [...new Set(units)];
}
getSortDetails() {
return { sortMode: this.sortMode, sortDirection: this.sortDirection };
}
setSortDetails(newMode: string, newDirection: string) {
this.sortMode = newMode;
this.sortDirection = newDirection;
}
}
|
package com.appn.core_common.base.delegate
import android.content.Context
import android.os.Bundle
import android.view.View
/**
* Fragment 代理类,用于框架内部在每个Fragment 的对应生命周期中插入需要的逻辑
*/
interface FragmentDelegate {
fun onAttach(context: Context)
fun onCreate(savedInstanceState: Bundle?)
fun onCreateView(view: View?, savedInstanceState: Bundle?)
fun onActivityCreate(savedInstanceState: Bundle?)
fun onStart()
fun onResume()
fun onPause()
fun onStop()
fun onSaveInstanceState(outState: Bundle)
fun onDestroyView()
fun onDestroy()
fun onDetach()
/**
* Return true if the fragment is currently added to its activity.
*/
fun isAdded(): Boolean
}
|
const assert = require('assert');
const ToolsSchema = require('./../database/mongodb/schemas/toolsSchema');
const MongoDb = require('./../database/mongodb/mongodb');
const MOCK_DEFAULT_ITEM = {
title: `Notion - ${Date.now()}`,
link: "https://notion.so",
description: "All in one tool to organize teams and ideas. Write, plan, collaborate, and get organized. ",
tags: [
"organization",
"planning",
"collaboration",
"writing",
"calendar"
]
}
let baseTool = '';
describe('MongoDb test suit', function () {
this.timeout(4000);
this.beforeAll(async () => {
const connection = MongoDb.connect();
context = new MongoDb(connection, ToolsSchema);
baseTool = await context.create(MOCK_DEFAULT_ITEM);
});
this.afterAll(async () => {
await context.delete(baseTool._id);
});
it('Verify the mongo connection', async () => {
const result = await context.isConected();
assert.ok(result === 1 || result === 2);
});
it('Create a test tool', async () => {
const { title } = await context.create(MOCK_DEFAULT_ITEM);
assert.deepStrictEqual(title, MOCK_DEFAULT_ITEM.title);
});
it('Read the tools', async () => {
const [{ title }] = await context.read({ title: MOCK_DEFAULT_ITEM.title });
assert.deepStrictEqual(title, MOCK_DEFAULT_ITEM.title);
})
it('Update any field of a tool by ID', async () => {
const result = await context.update(baseTool._id, { title: 'noitoN' });
assert.deepStrictEqual(result.nModified, 1);
});
it('Delete a tool by ID', async () => {
const result = await context.delete(baseTool._id);
assert.deepStrictEqual(result.n, 1);
});
it('Clear all tools', async () => {
const result = await context.delete();
assert.ok(result.ok === 1)
});
})
|
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</head>
<body>
<div class='container'>
<div class='row' align="center">
<div class="col">
<h1> Welcome, ${user.firstName}</h1>
<h2>User Management System</h2>
<h6> <i>Currently signed in:</i> ${email}</h6>
<p> <b>Note:</b> You will <u>not</u> be able to make <i>critical changes</i> to <u>yourself</u>.<br> Request changes through another Admin</p><br>
<p> You can view and manage <a href="category"><i>Categories</i></a></p><br><br>
<table class="table">
<thead>
<tr>
<th>E-mail</th>
<th>First Name</th>
<th>Last Name</th>
<th>Active</th>
<th>Role</th>
<th>Password</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${users}">
<tr>
<td>${user.email}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.active ? "Y" : "N"}</td>
<td>${user.role.name}</td>
<td>${user.password}</td>
<td>
<form action ="admin" method="post">
<input type="hidden" name="action" value="disable">
<input type="hidden" name="email" value="${user.email}">
<button type="submit">Disable</button>
</form>
</td>
<td>
<form action ="admin" method="post">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="email" value="${user.email}">
<button type="submit">Delete</button>
</form>
</td>
<td>
<form action ="admin" method="post">
<input type="hidden" name="action" value="enable">
<input type="hidden" name="email" value="${user.email}">
<button type="submit">Enable</button>
</form>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<div class='row' align="center">
<p> You may modify the system below.<br> <b>Note:</b> New users can <u>not</u> be created if the email used to add them already exists in our system.
If you would like to make any changes to existing users, type in their email address followed by the information you wish to change. All fields must be filled.<br> Email's are <u>non-changeable</u>.</p>
</div>
<div class='row' align="center">
<div class="col">
<h2>Add user</h2>
<p> Enter the information:</p>
<form action="admin" method="post">
<input type="hidden" name="action" value="add">
<label for="email">E-mail: </label>
<input type="text" name="email" id="email">
<br>
<label for="first">First Name: </label>
<input type="text" name="first" id="first">
<br>
<label for="last">Last Name: </label>
<input type="text" name="last" id="last">
<br>
<label for="password">Password: </label>
<input type="text" name="password" id="password">
<br>
<label for="role">Role: </label>
<select name="role" id="role">
<option value="1">System Admin</option>
<option value="2">Regular User</option>
<option value="3">Company Admin</option>
</select>
<button type="submit">Add</button>
</form>
</div>
<div class="col">
<h2> Edit user </h2>
<p> Edit accounts using account email:</p>
<form action="admin" method="post">
<input type="hidden" name="action" value="edit">
<label for="email">E-mail: </label>
<input type="text" name="email" id="email">
<br>
<label for="first">First Name: </label>
<input type="text" name="first" id="first">
<br>
<label for="last">Last Name: </label>
<input type="text" name="last" id="last">
<br>
<label for="password">Password: </label>
<input type="text" name="password" id="password">
<br>
<label for="role">Role: </label>
<select name="role" id="role">
<option value="1">System Admin</option>
<option value="2">Regular User</option>
<option value="3">Company Admin</option>
</select>
<button type="submit">Edit</button>
</form>
</div>
</div>
</div><br><br>
<div align="center">
<a href="login">Logout</a>
</div>
</body>
</html>
|
"""
This module defines a base class, Base, for managing the 'id' attribute in future classes.
"""
class Base:
"""
Base class for managing the 'id' attribute in future classes.
Attributes:
None
Methods:
__init__(self, id=None): Constructor for the Base class.
Class Attributes:
__nb_objects (int): A private class attribute to keep track of the number of objects created.
"""
# Private class attribute to keep track of the number of objects created.
__nb_objects = 0
def __init__(self, id=None):
"""
Constructor for the Base class.
Args:
id (int, optional): If provided, assign the 'id' attribute with this value.
If not provided, increment '__nb_objects' and assign the new value to 'id'.
"""
if id is not None:
# If 'id' is provided, assign it directly.
self.id = id
else:
# If 'id' is not provided, increment '__nb_objects' and assign it to 'id'.
Base.__nb_objects += 1
self.id = Base.__nb_objects
# Example usage:
if __name__ == "__main__":
b1 = Base()
print(b1.id) # Should print 1 (the first object created)
b2 = Base(10)
print(b2.id) # Should print 10 (id provided during object creation)
|
package DesensitizedUtils
import (
"fmt"
"reflect"
"strconv"
"strings"
)
type DesensitizedUtils struct {
}
func (DesensitizedUtils) ChineseName(name string) string {
if name == "" {
return ""
}
s := hide(name, 1, len(name)/3)
return s
}
func (DesensitizedUtils) Email(email string) string {
if email == "" {
return ""
}
index := strings.Index(email, "@")
emailValue := hide(email, 1, index)
return emailValue
}
func (DesensitizedUtils) MobilePhone(phone string) string {
if phone == "" {
return ""
}
return hide(phone, 3, 7)
}
func (DesensitizedUtils) IdCard(idCard string, front int, end int) string {
if idCard == "" {
return ""
}
return hide(idCard, front, len(idCard)-end)
}
func (DesensitizedUtils) Address(address string, sensitiveSize int) string {
if address == "" {
return ""
}
length := len(strings.Split(address, ""))
return hide(address, length-sensitiveSize, length)
}
func (DesensitizedUtils) PossWord(password string) string {
if password == "" {
return ""
}
return hide(password, 0, len(password))
}
//SecureStructList 结构体切片脱敏
/**
*需要在结构体的tag标签备注stt[start:end],例如stt:"1:2",表示此字段需要脱敏从第0个字符到第2个字符
*如果需要从第1个字符到最后一个都需要脱敏可以:stt:"1:a",反之,start=a表示0,end=a表示最后一个字符
*/
func (DesensitizedUtils) SecureStructList(structData []interface{}) []map[string]interface{} {
frist := reflect.ValueOf(structData[0])
b := frist.Kind() == reflect.Struct
if !b {
panic("不是一个结构体")
}
var list []map[string]interface{}
for _, data := range structData {
var m = make(map[string]interface{})
structValue := reflect.ValueOf(data)
for i := 0; i < structValue.NumField(); i++ {
name := structValue.Type().Field(i).Name
value := structValue.Field(i).Interface()
stt := structValue.Type().Field(i).Tag.Get("stt")
split := strings.Split(stt, ":")
if len(split) != 2 {
m[name] = value
} else {
fmt.Println("========", stt)
start := 0
end := 0
if split[0] == "a" {
start = 0
} else {
start, _ = strconv.Atoi(split[0])
}
if split[1] == "a" {
end = len(strings.Split(value.(string), ""))
} else {
end, _ = strconv.Atoi(split[1])
}
m[name] = hide(value.(string), start, end)
}
}
list = append(list, m)
}
return list
}
func hide(value string, start int, end int) string {
split := strings.Split(value, "")
for i := start; i < end; i++ {
split[i] = "*"
}
return strings.Join(split, "")
}
|
package qiao;
import java.util.HashSet;
import java.util.Set;
/**
* Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
* @author liqiao
*
*/
public class SurroundedRegions {
public void solve(char[][] board) {
if(board==null || board.length<3){
return;
}
Set<String> safePos = new HashSet<String>();
for(int i=0; i<board.length; i++){
if(board[i][0]=='o'){
safePos.add(String.valueOf(i)+"-"+String.valueOf(0));
int j=1;
while(j<board[i].length){
if(board[i][j]=='o'){
safePos.add(String.valueOf(i)+"-"+String.valueOf(j));
j++;
}else{
break;
}
}
}
if(board[i][board[i].length-1]=='o'){
safePos.add(String.valueOf(i)+"-"+String.valueOf(board[i].length-1));
int j = board[i].length - 2;
while(j>=0){
if(board[i][j]=='o'){
safePos.add(String.valueOf(i)+"-"+String.valueOf(j));
j--;
}else{
break;
}
}
}
}
for(int i=0; i<board[0].length; i++){
if(board[0][i]=='o'){
safePos.add(String.valueOf(0)+"-"+String.valueOf(i));
int j=1;
while(j<board.length){
if(board[j][i]=='o'){
safePos.add(String.valueOf(j)+"-"+String.valueOf(i));
j++;
}else{
break;
}
}
}
if(board[board.length-1][i]=='o'){
safePos.add(String.valueOf(board.length-1)+"-"+String.valueOf(i));
int j = board.length - 2;
while(j>=0){
if(board[j][i]=='o'){
safePos.add(String.valueOf(j)+"-"+String.valueOf(i));
j--;
}else{
break;
}
}
}
}
for(int i=0; i<board.length; i++){
for(int j=0; j<board[i].length; j++){
if(board[i][j]=='o'){
String key = String.valueOf(i)+"-"+String.valueOf(j);
if(!safePos.contains(key)){
board[i][j] = 'x';
}
}
}
}
}
}
|
$primary-color: #444;
$secondary-color: #eece1a;
$show-home-image: true;
$home-image: url(../img/background.jpg);
$background-opacity: 0.9;
@import "menu";
@mixin easeOut {
transition: all ease-out;
transition-duration: 1s;
}
* {
box-sizing: border-box;
}
@mixin background {
@if $show-home-image {
&#bg-img {
background: $home-image;
background-attachment: fixed;
background-size: cover;
.overlay {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
z-index: -1;
background: rgba($primary-color, $background-opacity);
}
}
}
}
//set text color
@function set-text-color($color){
@if(lightness($color)>30){
@return black;
}
@else{
@return white;
}
}
body {
@include background();
background: $primary-color;
color: set-text-color($primary-color);
height: 100%;
margin: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.5;
}
//headings
h1,
h2,
h3 {
margin: 0;
font-weight: 400;
&.lg-heading {
font-size: 4rem;
}
&.sm-heading {
margin-bottom: 1rem;
padding-top: 0.2rem;
padding-bottom: 0.2rem;
padding-left: 1rem;
background: rgba(lighten($primary-color, 2), 0.5);
}
}
a {
color: white;
text-decoration: none;
}
header {
position: fixed;
z-index: 2;
width: 100%;
}
.text-Secondary {
color: yellow;
}
main {
padding: 3.5rem;
min-height: calc(100vh-60px);
.icons {
margin-top: 1rem;
a {
padding: 0.2rem;
&:hover {
color: #eece1a;
@include easeOut();
}
}
}
&#home {
overflow: hidden;
h1 {
margin-top: 20vh;
}
}
}
// Media query mixins
@mixin mediaSm {
@media screen and (max-width: 500px) { @content; }
}
@mixin mediaMd {
@media screen and (min-width: 768px) { @content; }
}
@mixin mediaLg {
@media screen and (min-width: 769px) and (max-width: 1170px) { @content; }
}
@mixin mediaXl {
@media screen and (min-width: 1171px) { @content; }
}
// wide screens
@include mediaXl {
// Styles for big desktop screens
.projects{
grid-template-columns: repeat(4,1fr);
}
}
@include mediaLg {
// Styles for desktop screens
.projects{
grid-template-columns: repeat(3,1fr);
}
}
@include mediaMd {
// Styles for tablet screens
main {
align-items: center;
text-align: center;
.lg-heading {
line-height: 1;
margin-bottom: 1rem;
}
}
ul.menu-nav,
div.menu-branding{
float: none;
width: 100%;
min-height: 0%;
&.show{
transform: translate3d(0,0,0);
}
}
.menu-nav{
height: 75vh;
transform: translate3d(-100%,0,0);
font-size: 24px;
}
.menu-branding{
height: 25vh;
transform: translate3d(100%,0,0);
.portrait{
background: url(../img/portrait_small.jpg);
width: 150px;
height: 150px;
}
}
.about-info{
grid-template-areas:
'bioimg'
'bio'
'NPTEL'
'AZ-220'
'AI-900';
grid-template-columns: 1fr;
}
}
.projects{
grid-template-columns: repeat(2,1fr);
}
@include mediaSm {
// Styles for mobile screens
main {
align-items: center;
text-align: center;
.lg-heading {
line-height: 1;
margin-bottom: 1rem;
main#home{
margin-top: 10vh;
}
}
}
.projects{
grid-template-columns: 1fr;
}
}
.about-info{
display: grid;
grid-gap: 30px;
grid-template-areas:
'bioimg bio bio'
'NPTEL AZ-220 AI-900';
grid-template-columns: repeat(3, 1fr);
.bio-img{
border-radius: 50%;
border: $secondary-color 3px solid;
}
.bio{
grid-area: bio;
font-size: 1.5rem;
}
.certificate-1{
grid-area: NPTEL;
}
.certificate-2{
grid-area: AZ-220;
}
.certificate-3{
grid-area: AI-900;
}
.certificate-1{
background: lighten( $primary-color, 5);
padding: 0.5rem;
border-bottom: $secondary-color 5px solid;
}
.certificate-2{
background: lighten( $primary-color, 5);
padding: 0.5rem;
border-bottom: $secondary-color 5px solid;
}
.certificate-3{
background: lighten( $primary-color, 5);
padding: 0.5rem;
border-bottom: $secondary-color 5px solid;
}
}
//work/projects
.projects{
display: grid;
grid-gap: 0.7rem;
grid-template-columns: repeat(3,1fr);
img{
width: 100%;
border: 3px white solid;
&:hover{
opacity: 0.5;
border-color: #eece1a;
@include easeOut();
}
}
}
//button styles
.btn{
display: block;
padding: 0.5rem 1rem;
border: 0;
margin-bottom: 0.3rem;
&:hover{
background: $secondary-color;
color: set-text-color($secondary-color);
}
}
.btn-dark{
@extend.btn;
background: darken($color: $primary-color, $amount: 50);
color:white;
}
.btn-light{
@extend.btn;
background: lighten($color: $primary-color, $amount: 50);
color:black;
}
#main-footer{
text-align: center;
padding: 1rem;
background: darken($color: #444, $amount: 10);
color: set-text-color($primary-color);
height: 60px;
}
|
import { useEffect, useState } from "react";
import {
Box,
Card,
CardContent,
Container,
TextField,
Typography,
} from "@mui/material";
import { LoadingButton } from "@mui/lab";
const API_KEY = "4490f3b5fd564a37ac8143640232405";
const API_WEATHER = `https://api.weatherapi.com/v1/current.json?key=${API_KEY}&aqi=no`;
export default function App() {
const [city, setCity] = useState("");
const [error, setError] = useState({
error: false,
message: "",
});
const [loading, setLoading] = useState(false);
const [weather, setWeather] = useState({
city: "",
country: "",
temperature: 0,
condition: "",
conditionText: "",
icon: "",
});
const [searchHistory, setSearchHistory] = useState([]);
useEffect(() => {
const fetchWeather = async () => {
if (city.trim()) {
try {
const res = await fetch(`${API_WEATHER}&q=${encodeURIComponent(city)}`);
const data = await res.json();
if (data.error) {
throw new Error(data.error.message);
}
const newWeather = {
city: data.location.name,
country: data.location.country,
temperature: data.current.temp_c,
condition: data.current.condition.code,
conditionText: data.current.condition.text,
icon: data.current.condition.icon,
};
setWeather(newWeather);
setSearchHistory((prevSearches) => [...prevSearches, newWeather]);
} catch (error) {
setError({ error: true, message: error.message });
} finally {
setLoading(false);
}
}
};
fetchWeather();
}, [city]);
const handleSubmit = (e) => {
e.preventDefault();
setError({ error: false, message: "" });
setLoading(true);
};
return (
<Container maxWidth="xs" sx={{ mt: 2 }}>
<Typography variant="h3" component="h1" align="center" gutterBottom sx={{ color: "#333" }}>
Aplicacion Clima
</Typography>
<Box
sx={{ display: "grid", gap: 2 }}
component="form"
autoComplete="off"
onSubmit={handleSubmit}
>
<TextField
id="city"
label="Estado"
variant="outlined"
size="small"
required
value={city}
onChange={(e) => setCity(e.target.value)}
error={error.error}
helperText={error.message}
sx={{ backgroundColor: "#fff", borderRadius: 4 }}
/>
<LoadingButton
type="submit"
variant="contained"
loading={loading}
loadingIndicator="Buscando..."
sx={{ backgroundColor: "#008000", color: "#FFFF00" }}
>
Buscar
</LoadingButton>
</Box>
{weather.city && (
<Box sx={{ mt: 2 }}>
<Card>
<CardContent>
<Typography variant="h4" component="h2">
{weather.city}, {weather.country}
</Typography>
<Box
component="img"
alt={weather.conditionText}
src={weather.icon}
sx={{ margin: "0 auto" }}
/>
<Typography variant="h5" component="h3">
{weather.temperature} °C
</Typography>
<Typography variant="h6" component="h4">
{weather.conditionText}
</Typography>
</CardContent>
</Card>
</Box>
)}
{searchHistory.length > 0 && (
<Box sx={{ mt: 2 }}>
<Typography variant="h4" component="h2" sx={{ color: "#333" }}>
Busquedas Recientes
</Typography>
{searchHistory.map((weatherData, index) => (
<Card key={index} sx={{ backgroundColor: "#f5f5f5" }}>
<CardContent>
<Typography variant="h5" component="h3">
{weatherData.city}, {weatherData.country}
</Typography>
<Box
component="img"
alt={weatherData.conditionText}
src={weatherData.icon}
sx={{ margin: "0 auto" }}
/>
<Typography variant="body1" component="p">
{weatherData.temperature} °C
</Typography>
<Typography variant="body2" component="p">
{weatherData.conditionText}
</Typography>
</CardContent>
</Card>
))}
</Box>
)}
<Typography textAlign="center" sx={{ mt: 2, fontSize: "10px", color: "#777" }}>
Autor: [Gerardo Ismael Ruz Can]
</Typography>
</Container>
);
}
|
package Pages;
import Steps.Hooks;
import io.appium.java_client.AppiumBy;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class DeliveryInformation {
public DeliveryInformation(WebDriver driver){
PageFactory.initElements(Hooks.driver, this);
}
WebDriverWait wait = new WebDriverWait(Hooks.driver, Duration.ofSeconds(20));
By fullName = AppiumBy.accessibilityId("Full Name* input field");
By address01 = AppiumBy.accessibilityId("Address Line 1* input field");
By address02 = AppiumBy.accessibilityId("Address Line 2 input field");
By city = AppiumBy.accessibilityId("City* input field");
By state = AppiumBy.accessibilityId("State/Region input field");
By zipCode = AppiumBy.accessibilityId("Zip Code* input field");
By country = AppiumBy.accessibilityId("Country* input field");
By toPaymentButton = AppiumBy.accessibilityId("To Payment button");
public WebElement fullName(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(fullName));
}
public WebElement address01(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(address01));
}
public WebElement address02(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(address02));
}
public WebElement city(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(city));
}
public WebElement state(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(state));
}
public WebElement zipCode(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(zipCode));
}
public WebElement country(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(country));
}
public WebElement toPaymentButton(){
return wait.until(ExpectedConditions.visibilityOfElementLocated(toPaymentButton));
}
}
|
import React, { useEffect, useState } from "react";
import {
Image,
Container,
FlexWrapper,
NavbarText,
TextBase,
Button,
} from "components";
import styled from "styled-components";
import { teal, white, lightGreenBackground, black } from "styles/colors";
import { useQuery } from "styles/breakpoints";
import NavigationItems from "./NavBarNavigationItems";
const Navbar = () => {
const { isTablet, isSmMobile } = useQuery();
useEffect(() => {
if (typeof window !== "undefined") {
const navbar = document.querySelector(".navbar");
const adjustNavbar = () => {
if (!navbar) {
return;
}
if (
document.body.scrollTop > 80 ||
document.documentElement.scrollTop > 80
) {
navbar.style.cssText = `background: ${white}; box-shadow: 0 1px 1.5rem -0.813rem #000000`;
} else {
navbar.style.cssText = `background: ${lightGreenBackground}; box-shadow: none;`;
}
};
adjustNavbar();
window.onscroll = () => {
adjustNavbar();
};
}
});
const [isShown, setIsShown] = useState(false);
const showNavigationItems = () => {
setIsShown(!isShown);
};
return (
<Wrapper className="navbar">
<Container>
<FlexWrapper alignItems="center">
<Image src="np_logo" />
{isTablet ? (
<FlexWrapper margin="0 0 0 auto" alignItems="center">
<Button
display={isSmMobile ? "none" : "inline-block"}
background={teal}
>
<TextBase fontSize="0.75rem" color={white}>
Open Vault
</TextBase>
</Button>
<BarContainer onClick={showNavigationItems}>
<Bar1 />
<Bar2 />
<Bar3 />
</BarContainer>
</FlexWrapper>
) : (
<FlexWrapper margin="0 0 0 auto" alignItems="center">
<NavbarText>Features</NavbarText>
<NavbarText margin="0 1.5rem">Pricing</NavbarText>
<NavbarText>Apps</NavbarText>
<NavbarText margin="0 1.5rem">Blog</NavbarText>
<NavbarText>Help</NavbarText>
<NavbarText color={teal} margin="0 1.5rem">
My Account
</NavbarText>
<Button background={teal}>
<TextBase fontSize="0.75rem" color={white}>
Open Vault
</TextBase>
</Button>
</FlexWrapper>
)}
</FlexWrapper>
{isTablet ? <NavigationItems isShown={isShown} /> : ""}
</Container>
</Wrapper>
);
};
export default Navbar;
const Wrapper = styled.div`
position: sticky;
top: 0;
padding: 0.75rem 0;
transition: all 0.3s ease;
z-index: 100;
`;
export const BarContainer = styled.div`
display: inline-block;
cursor: pointer;
margin: 0 0 0 2rem;
`;
export const Bar1 = styled.div`
width: 1.875rem;
height: 0.188rem;
background-color: ${black};
margin: 0.375rem 0;
`;
export const Bar2 = styled(Bar1)``;
export const Bar3 = styled(Bar1)``;
|
<?php
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;
class AdminController extends Controller
{
public function index()
{
$data['error'] = session()->getFlashdata('error');
// Get the success message from the registration redirect, if any
$data['successMessage'] = session()->getFlashdata('successMessage');
return view('admin/login', $data);
}
public function auth()
{
$model = new UserModel();
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$user = $model->where('email', $email)->first();
if ($user && password_verify($password, $user['password'])) {
if ($user['is_admin']) {
// User is an admin, set user_id in session
session()->set('user_id', $user['id']);
return redirect()->to(base_url('/admin/dashboard'));
} else {
// User is not an admin, throw error
session()->setFlashdata('error', 'You are not authorized as an admin');
return redirect()->to(base_url('/admin'));
}
} else {
// Set flash data for the error
session()->setFlashdata('error', 'Invalid email or password');
return redirect()->to(base_url('/admin'));
}
}
public function AdminProfile()
{
$userId = session()->get('user_id');
if (!$userId) {
return redirect()->to('/admin');
}
$userModel = new UserModel();
$data['users'] = $userModel->where('id', $userId)->findAll();
return view("admin/manage_account", $data);
}
public function updateProfile()
{
$userId = session()->get('user_id');
if (!$userId) {
return redirect()->to('/login')->with('error', 'You are not logged in.');
}
$userModel = new UserModel();
$userData = $userModel->find($userId);
if (empty($userData)) {
return redirect()->to('/user/404page')->with('error', 'User not found.');
}
if ($this->request->getMethod() === 'post') {
$validationRules = [
'username' => 'required|min_length[3]|max_length[50]',
'email' => 'required|valid_email',
'name' => 'required|min_length[3]|max_length[50]',
'categories' => 'permit_empty|max_length[255]',
'birthdate' => 'required|valid_date[Y-m-d]',
'location' => 'permit_empty|max_length[255]',
'about' => 'permit_empty',
'gender' => 'required|in_list[male,female,other]',
'profile_photo' => 'max_size[profile_photo,10240]',
];
//$this->request->do_upload() is method to upload the file
if ($this->validate($validationRules)) {
$data = [
'username' => $this->request->getPost('username'),
'email' => $this->request->getPost('email'),
'name' => $this->request->getPost('name'),
'categories' => $this->request->getPost('categories'),
'birthdate' => $this->request->getPost('birthdate'),
'location' => $this->request->getPost('location'),
'about' => $this->request->getPost('about'),
'gender' => $this->request->getPost('gender'),
'insgtagram' => $this->request->getPost('instagram'),
'discordlink' => $this->request->getPost('discord'),
'twitter' => $this->request->getPost('twitter'),
'github' => $this->request->getPost('github'),
];
$profilePhoto = $this->request->getFile('profile_photo');
if ($profilePhoto->isValid() && !$profilePhoto->hasMoved()) {
$newName = $userData['username'] . '.' . $profilePhoto->getExtension();
$profilePhoto->move(ROOTPATH . 'public/images/userprofilephoto', $newName);
// Update the 'profile_photo' column to store the image content as blob
$data['profile_photo'] = file_get_contents(ROOTPATH . 'public/images/userprofilephoto/' . $newName);
}
$userModel->update($userId, $data);
// Remove the uploaded image file after updating the database
// this is used to remove file from userprofilephoto
// unlink(ROOTPATH . 'public/images/userprofilephoto/' . $newName);
return redirect()->to("admin/manage_accounts")->with('success', 'Profile updated successfully.');
} else {
return view('/admin/manage_accounts', ['validation' => $this->validator, 'userData' => $userData]);
}
}
return view('admin/manage_accounts', ['userData' => $userData]);
}
}
|
# -*- coding: utf-8 -*-
# This file is part of Shuup PagSeguro.
#
# Copyright (c) 2016, Rockho Team. All rights reserved.
# Author: Christian Hess
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.http.response import HttpResponse, HttpResponseBadRequest
from django.views.generic.base import TemplateView, View
import shuup_pagseguro
from shuup_pagseguro.models import PagSeguroPayment
TRANSACTION_DETAIL_TEMPLAE = 'pagseguro/admin/payment_detail.jinja'
class DashboardView(TemplateView):
template_name = "pagseguro/admin/dashboard.jinja"
title = "PagSeguro"
def get_context_data(self, **kwargs):
context_data = super(DashboardView, self).get_context_data(**kwargs)
context_data.update({
'VERSION': shuup_pagseguro.__version__,
'payment_return_url': self.request.build_absolute_uri(reverse("shuup:pagseguro_payment_return")),
'notification_url': self.request.build_absolute_uri(reverse("shuup:pagseguro_notification"))
})
return context_data
class PaymentRefreshView(View):
''' Atualiza as informações de um pagamento do PagSeguro '''
def post(self, request, *args, **kwargs):
try:
payment = PagSeguroPayment.objects.get(pk=request.POST.get("pk"))
payment.refresh()
return HttpResponse()
except Exception as exc:
return HttpResponseBadRequest("{0}".format(exc))
|
"use strict";
import * as antlr4ts from 'antlr4ts';
import { cyoaeLexer } from './cyoaeLexer';
import * as cyoaeParser from './cyoaeParser';
import { Variable_storage, Variable_storage_types } from './storage';
import { create_variable_table } from './variables_screen';
import { createHTML } from './html';
import { get_undo_update_code } from './undo';
let current_arc = "";
let current_scene = "";
let current_source = "";
class ParserErrorListener implements antlr4ts.ANTLRErrorListener<antlr4ts.Token> {
constructor(private parser: antlr4ts.Parser) { }
syntaxError(recognizer: antlr4ts.Recognizer<antlr4ts.Token, any>, offendingSymbol: antlr4ts.Token | undefined, line: number, charPositionInLine: number, msg: string, e: antlr4ts.RecognitionException | undefined) {
throw_evaluation_error(`Parser error: ${msg}${e ? `: ${e.context?.toStringTree(this.parser)}` : ""}`, { start: { line: line, charPositionInLine: charPositionInLine }, sourceInterval: { length: offendingSymbol?.text?.length || 0 } }, current_source);
}
}
class LexerErrorListener implements antlr4ts.ANTLRErrorListener<number> {
syntaxError(recognizer: antlr4ts.Recognizer<number, any>, offendingSymbol: number | undefined, line: number, charPositionInLine: number, msg: string, e: antlr4ts.RecognitionException | undefined) {
throw_evaluation_error(`Lexer error: ${msg}`, { start: { line: line, charPositionInLine: charPositionInLine }, sourceInterval: { length: 1 } }, current_source);
}
}
class Lazy_evaluated<T> {
private _value: T | undefined;
constructor(private init: () => T) { }
get value() {
if (typeof this._value === "undefined") {
this._value = this.init();
}
return this._value;
}
get is_evaluated() {
return typeof this._value !== "undefined";
}
}
class Lazy_evaluated_rich_text {
private _value: Tag_result | cyoaeParser.Rich_text_Context;
constructor(ctx: cyoaeParser.Rich_text_Context) {
this._value = ctx;
}
get is_evaluated() {
return this._value instanceof Tag_result;
}
get value() {
if (this._value instanceof cyoaeParser.Rich_text_Context) {
this._value = evaluate_richtext(this._value);
}
return this._value;
}
get maybe_unevaluated_value() {
if (this._value instanceof cyoaeParser.Rich_text_Context) {
return `(unevaluated)${this._value.text}`;
}
return this._value.current_value;
}
}
function HTMLElement_to_string(who: HTMLElement) {
let el = document.createElement("div");
el.appendChild(who.cloneNode(true));
let txt = el.innerHTML;
return txt;
}
type Tag_types = cyoaeParser.Rich_text_Context | string | HTMLElement;
class Tag_result {
get text(): string {
let this_text: string;
if (this.data instanceof Lazy_evaluated_rich_text) {
this_text = this.data.value.text;
}
else if (this.data instanceof HTMLElement) {
throw "Plaintext unavailable";
}
else {
this_text = this.data;
}
return `${this.prev?.current_value || ""}${this_text}`;
}
insert_into(element: HTMLElement): void {
if (this.prev) {
element.append(this.prev.value);
}
element.append(this.value);
}
get is_text_available(): boolean {
return typeof this.value === "string" && (this.prev?.is_text_available || true);
}
get current_value(): string {
let this_text: string;
if (this.data instanceof Lazy_evaluated_rich_text) {
this_text = this.data.maybe_unevaluated_value;
}
else if (this.data instanceof HTMLElement) {
this_text = HTMLElement_to_string(this.data);
}
else {
this_text = this.data;
}
return `${this.prev?.current_value || ""}${this_text}`;
}
append(other: Tag_types | Tag_result): Tag_result {
const debug = false;
if (other instanceof Tag_result) {
if (other.prev) {
debug && console.log(`Entering append with other tag_result with children and value ${other.value}`);
return new Tag_result(other.data, this.append(other.prev));
}
else {
debug && console.log(`Entering append with other tag_result without children and value ${other.value}`);
return new Tag_result(other.data, this);
}
}
else {
if (typeof other === "string" && other === "") {
return this;
}
debug && console.log(`Entering append with other not tag_result and value ${other}`);
if (typeof this.data === "string") {
return new Tag_result(this.data + other, this.prev);
}
return this.append(new Tag_result(other));
}
}
get range(): (string | HTMLElement)[] {
const data: (string | HTMLElement)[] = [];
for (let current: Tag_result | undefined = this; current; current = current.prev) {
data.push(current.value);
}
return data.reverse();
}
private get value(): string | HTMLElement {
return this.data instanceof Lazy_evaluated_rich_text ? this.data.value.value : this.data;
}
private readonly data: Lazy_evaluated_rich_text | string | HTMLElement;
private readonly prev?: Tag_result;
constructor(initializer: Tag_types | Lazy_evaluated_rich_text | [Tag_types | Lazy_evaluated_rich_text, ...(Tag_types | Lazy_evaluated_rich_text)[]], prev?: Tag_result) {
if (Array.isArray(initializer)) {
let result = new Tag_result(initializer.shift() || "");
for (const object of initializer) {
result = result.append(new Tag_result(object));
}
this.data = result.data;
this.prev = result.prev;
return;
}
this.prev = prev;
this.data = initializer instanceof cyoaeParser.Rich_text_Context ? new Lazy_evaluated_rich_text(initializer) : initializer;
}
}
interface Attribute_replacement {
name: string;
replacement(value: Tag_result, tag: Tag): Tag_result;
default_value?: Tag_result;
}
interface Tag_replacement {
readonly tag_name: string;
readonly required_attributes: Readonly<string[]>;
readonly optional_attributes: Readonly<string[]>;
readonly replacements: (tag: Tag) => Tag_result;
}
interface Tag {
ctx: cyoaeParser.Tag_Context;
name: string;
default_value?: Tag_result;
attributes: [string, Tag_result][];
}
function get_optional_attributes(tag: Tag, attribute: string) {
let result: Tag_result[] = [];
for (const [attribute_name, attribute_value] of tag.attributes) {
if (attribute_name === attribute) {
result.push(attribute_value);
}
}
return result;
}
function get_unique_optional_attribute(tag: Tag, attribute: string): Tag_result | undefined {
const result = get_optional_attributes(tag, attribute);
if (result.length > 1) {
throw_evaluation_error(`Duplicate attribute "${attribute}" in tag "${tag.name}" which doesn't allow duplicate attributes`, tag.ctx);
}
return result[0];
}
function get_unique_required_attribute(tag: Tag, attribute: string) {
const result = get_unique_optional_attribute(tag, attribute);
if (typeof result === "undefined") {
throw_evaluation_error(`Missing required attribute "${attribute}" in tag "${tag.name}"`, tag.ctx);
}
return result;
}
enum Page_availability {
Available, Unavailable, Unknown
}
class Page_checker {
private static debug = false;
static page_available(arc: string, scene: string): Page_availability {
Page_checker.debug && console.log(`Checking availability of ${arc}/${scene}`);
const available = Page_checker.choice_available.get(`${arc}/${scene}`);
if (typeof available === "boolean") {
Page_checker.debug && console.log(`We know that page ${arc}/${scene} is ${available ? "available" : "unavailable"}`);
return available ? Page_availability.Available : Page_availability.Unavailable;
}
else if (available === undefined) {
Page_checker.debug && console.log(`But we don't know if it's available yet, nobody has fetched it yet.`);
}
else {
Page_checker.debug && console.log(`But we don't know if it's available yet, but it's being fetched.`);
}
return Page_availability.Unknown;
}
static async fetch_page_available(arc: string, scene: string) {
const available = this.choice_available.get(`${arc}/${scene}`);
if (typeof available === "boolean") {
return available;
}
if (available === undefined) {
const promise = (async () => {
try {
await download(`${arc}/${scene}.txt`);
this.choice_available.set(`${arc}/${scene}`, true);
Page_checker.debug && console.log(`Source for page ${arc}/${scene} is available`);
return true;
}
catch (error) {
this.choice_available.set(`${arc}/${scene}`, false);
Page_checker.debug && console.log(`Source for page ${arc}/${scene} is not available because ${error}`);
return false;
}
})();
Page_checker.choice_available.set(`${arc}/${scene}`, promise);
return promise;
}
return available;
}
private static choice_available = new Map<string, boolean | Promise<boolean>>();
}
function sleep(ms: number) {
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
class Delayed_evaluation {
private static debug = false;
private static delayed_evaluation_placeholder_number = 0;
private static delay_evaluation_promise = (async () => { })();
private static active_delayed_evaluations = 0;
//returns a placeholder that will be replaced by the real thing later
static evaluate(replacement: Promise<Tag_result>, placeholder_text = new Tag_result("[loading]")): Tag_result {
const placeholder_id = `delayed_evaluation_placeholder_${this.delayed_evaluation_placeholder_number}`;
const slot = createHTML(["slot", { class: "placeholder", id: placeholder_id }]);
placeholder_text.insert_into(slot);
this.active_delayed_evaluations += 1;
const old_promise = this.delay_evaluation_promise;
this.delay_evaluation_promise = (async () => {
const result = await replacement;
let link = document.querySelector(`#${placeholder_id}`);
if (link) {
this.debug && console.log(`Replacement: "${link.outerHTML}" to "${result.current_value}"`);
link.replaceWith(...result.range);
}
else {
console.error(`Failed finding ID "${placeholder_id}" for replacement`);
}
this.active_delayed_evaluations -= 1;
return old_promise;
})();
this.delayed_evaluation_placeholder_number += 1;
return new Tag_result(slot);
}
static get has_everything_been_evaluated() {
return this.active_delayed_evaluations === 0;
}
static async wait_for_everything_to_be_evaluated() {
return this.delay_evaluation_promise;
}
}
function get_attributes(tag: Tag, tag_replacement: Tag_replacement) {
let result: { [key: string]: Tag_result } = {};
for (const attr of tag_replacement.required_attributes) {
result[attr] = get_unique_required_attribute(tag, attr);
}
for (const attr of tag_replacement.optional_attributes) {
const attribute = get_unique_optional_attribute(tag, attr);
if (attribute) {
result[attr] = attribute;
}
}
return result;
}
const replacements: Readonly<Tag_replacement[]> = [
{ //img
tag_name: "img",
required_attributes: ["url"],
optional_attributes: ["alt"],
replacements: function (tag): Tag_result {
const attributes = get_attributes(tag, this);
return new Tag_result(createHTML(["img", { src: attributes["url"].text, alt: attributes["alt"]?.text ?? "image" }]));
},
},
{ //code
tag_name: "code",
required_attributes: ["text"],
optional_attributes: [],
replacements: function (tag): Tag_result {
const attributes = get_attributes(tag, this);
return new Tag_result(createHTML(["span", { class: "code" }, ...attributes["text"].range]));
},
},
{ //choice
tag_name: "choice",
required_attributes: ["next", "text"],
optional_attributes: ["onclick"],
replacements: function (tag) {
const attributes = get_attributes(tag, this);
function get_result(page_available: boolean) {
//next
const result = createHTML(["a",
page_available
? { class: "choice", href: `#${current_arc}/${attributes["next"].text}` }
: { class: "dead_choice" }]);
//onclick
if (attributes.onclick) {
const expression_context = run_parser(
{
code: attributes["onclick"].text,
evaluator: (parser) => parser.expression_(),
}
);
result.addEventListener("click", () => {
evaluate_expression(expression_context);
return true;
});
}
//text
result.append(...attributes["text"].range);
return new Tag_result(result);
}
switch (Page_checker.page_available(current_arc, attributes["next"].text)) {
case Page_availability.Available:
return get_result(true);
case Page_availability.Unavailable:
return get_result(false);
case Page_availability.Unknown:
return Delayed_evaluation.evaluate((async () => {
return get_result(await Page_checker.fetch_page_available(current_arc, attributes["next"].text));
})(), attributes["text"]);
}
},
},
{ //test
tag_name: "test",
required_attributes: ["text"],
optional_attributes: [],
replacements: function (tag) {
const debug = false;
const attributes = get_attributes(tag, this);
if (debug) {
for (const attribute in attributes) {
console.log(`Attribute "${attribute}" with value "${attributes[attribute].current_value}" and text "${attributes[attribute].text}"`);
}
}
return new Tag_result(createHTML(["a", attributes["text"].text]));
},
},
{ //test delayed evaluation
tag_name: "test_delayed_evaluation",
required_attributes: [],
optional_attributes: [],
replacements: (tag) => {
return Delayed_evaluation.evaluate((async () => new Tag_result("test_delayed_evaluation_result"))(), new Tag_result("test_delayed_evaluation_placeholder"));
}
},
{ //source
tag_name: "source",
required_attributes: [],
optional_attributes: [],
replacements: () => {
const current_url = window.location.toString().replace(/\/[^\/]*$/, `/`).replace(/#.*/, "");
const html = new Tag_result(createHTML(["hr"]));
html.append(createHTML(["a", { href: `${current_url}story arcs/${current_arc}/${current_scene}.txt` }, "Source"]));
html.append(createHTML(["br"]));
html.append(createHTML(["p", { class: "source" }, current_source]));
return html;
},
},
{ //select
tag_name: "select",
required_attributes: [""],
optional_attributes: [],
replacements: (tag: Tag) => evaluate_select_tag(tag.ctx),
},
{ //case
tag_name: "case",
required_attributes: [],
optional_attributes: [],
replacements: (tag: Tag) => { throw `"case" tag cannot be outside of "switch" tag` }
},
] as const;
function html_comment(content: string) {
return `<!-- ${content.replace(/-->/g, "~~>")} -->\n`;
}
function reduce<Key_type, Value_type, Accumulator_type>(map: Map<Key_type, Value_type>, reducer: { (current_value: Accumulator_type, key_value: [Key_type, Value_type]): Accumulator_type }, accumulator: Accumulator_type) {
for (const key_value of map) {
accumulator = reducer(accumulator, key_value);
}
return accumulator;
}
interface Evaluation_error_context {
readonly start: { line: number, charPositionInLine: number };
readonly sourceInterval: { length: number };
}
type Extends<Class, Interface, Message = ""> = Class extends Interface ? true : Message;
function static_assert<T extends true>() { }
static_assert<Extends<antlr4ts.ParserRuleContext, Evaluation_error_context, "antlr4ts.ParserRuleContext doesn't implement Evaluation_error_context anymore, need to change Evaluation_error_context so it does again">>();
interface Case_result {
readonly applicable: boolean;
readonly score: number;
readonly priority: number;
readonly text: Tag_result;
}
interface Case_code_result {
readonly applicable: boolean;
readonly score: number;
}
function throw_evaluation_error(error: string, context: Evaluation_error_context, source = current_source): never {
const line = context.start.line;
const character = context.start.charPositionInLine;
const source_line = source.split('\n')[line - 1];
function min(x: number, y: number) {
return x < y ? x : y;
}
const length = min(context.sourceInterval.length, source_line.length - character);
throw `Error evaluating source in line ${line}:\n`
+ `${source_line}\n`
+ `${" ".repeat(character) + "^" + (length > 1 ? "~".repeat(length - 1) : "")}\n`
+ error;
}
function evaluate_expression(expression: cyoaeParser.Expression_Context): Variable_storage_types | undefined {
if (expression._operator) {
switch (expression._operator.text) {
case "+":
case "-":
case "*":
case "/":
const lhs = evaluate_expression(expression._left_expression);
const rhs = evaluate_expression(expression._right_expression);
if (typeof lhs === "number" && typeof rhs === "number") {
switch (expression._operator.text) {
case "+":
return lhs + rhs;
case "-":
return lhs - rhs;
case "*":
return lhs * rhs;
case "/":
if (rhs === 0) {
throw_evaluation_error(`Zero division error: "${expression.text}" evaluated to ${lhs} / ${rhs}`, expression);
}
return lhs / rhs;
}
}
if (typeof lhs === "string" && typeof rhs === "string" && expression._operator.text === "+") {
return lhs + rhs;
}
throw_evaluation_error(`Failed evaluating "${expression._left_expression.text}" (evaluated to value "${lhs}" of type ${typeof lhs}) ${expression._operator.text} "${expression._right_expression.text}" (evaluated to value "${rhs}" of type ${typeof rhs})`, expression);
default:
throw_evaluation_error(`TODO: Need to implement evaluating expression "${expression.text}"`, expression);
}
} else if (expression._assignment) {
const value = evaluate_expression(expression._expression);
if (typeof value === "undefined") {
throw_evaluation_error(`Cannot assign value "${expression._expression.text}" to variable "${expression._identifier.text}" because the expression does not evaluate to a value.`, expression);
}
Variable_storage.set_variable(expression._identifier.text, value);
}
else {
if (expression._identifier) {
const value = Variable_storage.get_variable(expression._identifier.text);
if (typeof value === "undefined") {
throw_evaluation_error(`Variable "${expression._identifier.text}" is undefined`, expression);
}
return value;
}
else if (expression._number) {
return parseFloat(expression._number.text);
}
else if (expression._expression) {
return evaluate_expression(expression._expression);
}
else if (expression._string) {
return expression._string.text;
}
else if (expression._comparator) {
const lhs = evaluate_expression(expression._left_expression);
const rhs = evaluate_expression(expression._right_expression);
if (typeof lhs === "undefined") {
throw_evaluation_error(`Failed evaluating expression because ${expression._left_expression.text} is undefined`, expression._left_expression);
}
if (typeof rhs === "undefined") {
throw_evaluation_error(`Failed evaluating expression because ${expression._right_expression.text} is undefined`, expression._right_expression);
}
function get_operator() {
switch (expression._comparator.text) {
case "==":
return (lhs: Variable_storage_types, rhs: Variable_storage_types) => lhs === rhs;
case "!=":
return (lhs: Variable_storage_types, rhs: Variable_storage_types) => lhs !== rhs;
case "<=":
return (lhs: Variable_storage_types, rhs: Variable_storage_types) => lhs <= rhs;
case ">=":
return (lhs: Variable_storage_types, rhs: Variable_storage_types) => lhs >= rhs;
case "<":
return (lhs: Variable_storage_types, rhs: Variable_storage_types) => lhs < rhs;
case ">":
return (lhs: Variable_storage_types, rhs: Variable_storage_types) => lhs > rhs;
default:
throw_evaluation_error(`Invalid operator ${expression._comparator.text}`, expression._comparator);
}
}
if (typeof lhs === typeof rhs) {
return get_operator()(lhs, rhs);
}
else {
throw_evaluation_error(`Cannot compare ${lhs} of type ${typeof lhs} with ${rhs} of type ${typeof rhs}`, expression);
}
}
else {
throw_evaluation_error(`Unknown expression ${expression.text}`, expression);
}
}
}
function evaluate_code(code: cyoaeParser.Code_Context) {
for (let i = 0; i < code.childCount; i++) {
const child = code.getChild(i);
if (child instanceof cyoaeParser.Statement_Context) {
evaluate_expression(child._expression);
}
else if (child instanceof cyoaeParser.Expression_Context) {
return evaluate_expression(child);
}
}
}
function evaluate_tag(tag: Tag): Tag_result {
const debug = false;
debug && console.log(`Executing tag "${tag.name}" with value "${tag.default_value?.current_value}" and attributes [${tag.attributes.length > 0
? tag.attributes.reduce((curr, [attribute_name, attribute_value]) => `${curr}\t${attribute_name}="${attribute_value.current_value}"\n`, "\n")
: ""
}]\n`);
const replacement = replacements.find((repl) => repl.tag_name === tag.name);
if (replacement === undefined) {
throw_evaluation_error(`Unknown tag "${tag.name}"`, tag.ctx);
}
//check that there are no duplicate attributes
{
let attribute_names = new Set<string>();
for (const [attribute_name,] of tag.attributes) {
if (attribute_names.has(attribute_name)) {
throw_evaluation_error(`Found duplicate attribute ${attribute_name} in tag ${tag.name} which doesn't support that`, tag.ctx);
}
attribute_names.add(attribute_name);
}
}
//TODO: Check that replacement.required_attributes are there
//handle default value
if (tag.default_value) {
if (replacement.required_attributes.length === 0) {
throw_evaluation_error(`Tag "${tag.name}" does not take arguments`, tag.ctx);
}
for (const attribute of tag.attributes) {
if (attribute[0] === replacement.required_attributes[0]) {
throw_evaluation_error(`Attribute "${attribute[0]}" of tag "${tag.name}" has been specified both as the default value and explicitly`, tag.ctx);
}
}
tag.attributes.push([replacement.required_attributes[0], tag.default_value]);
}
try {
return replacement.replacements(tag);
}
catch (error) {
throw_evaluation_error(`${error}`, tag.ctx);
}
}
function evaluate_richtext(ctx: cyoaeParser.Rich_text_Context): Tag_result {
const debug = false;
debug && console.log(`Evaluating richtext "${ctx.text}"`);
let result = new Tag_result("");
for (let i = 0; i < ctx.childCount; i++) {
const child = ctx.getChild(i);
debug && console.log(`Tag child ${i}: >>>${child.text}<<< with current text "${result.current_value}"`);
if (child instanceof cyoaeParser.Plain_text_Context) {
debug && console.log(`found plaintext "${child.text}"`);
for (let i = 0; i < child.childCount; i++) {
const grandchild = child.getChild(i);
if (grandchild instanceof cyoaeParser.Escaped_text_Context) {
if (grandchild.text.length !== 2) {
throw_evaluation_error(`Invalid escape sequence: ${grandchild.text}`, grandchild);
}
result = result.append(grandchild.text[1]); //cut off the \
}
else {
result = result.append(grandchild.text);
}
}
}
else if (child instanceof cyoaeParser.Tag_Context) {
debug && console.log(`evaluating tag ${child._tag_name.text}`);
function extract_tag(ctx: cyoaeParser.Tag_Context): Tag {
let tag: Tag = {
ctx: ctx,
name: ctx._tag_name.text,
attributes: []
};
if (ctx._default_value.text) {
debug && console.log(`Got a tag default value "${ctx._default_value.text}"`);
tag.default_value = new Tag_result(ctx._default_value);
}
for (let i = 0; i < ctx.childCount; i++) {
const child = ctx.getChild(i);
if (child instanceof cyoaeParser.Attribute_Context) {
let attribute = tag.attributes.find(attrib => attrib[0] === child._attribute_name.text);
if (attribute) {
attribute[1] = attribute[1].append(new Tag_result(child._attribute_value));
debug && console.log(`Found addition attribute child for attribute ${child._attribute_name.text} with value ${child._attribute_value.text}. Full value: ${attribute[1].current_value}`);
}
else {
debug && console.log(`Found first attribute child for attribute ${child._attribute_name.text} with value ${child._attribute_value.text}`);
tag.attributes.push([child._attribute_name.text, new Tag_result(child._attribute_value)]);
}
}
}
return tag;
}
result = result.append(evaluate_tag(extract_tag(child)));
}
else if (child instanceof cyoaeParser.Code_Context) {
debug && console.log(`Evaluating code "${child.text}"`);
const value = evaluate_code(child);
debug && console.log(`Result: "${value}"`);
if (typeof value !== "undefined") {
result = result.append(`${value}`);
}
}
else if (child instanceof cyoaeParser.Number_Context) {
debug && console.log(`Found number ${child.text}`);
result = result.append(child.text);
}
else {
throw_evaluation_error(`Internal logic error: Found child that is neither a plain text nor a tag nor a number in rich text`, ctx);
}
}
debug && console.log(`Tag execution result: "${result.current_value}" which is ${result.is_text_available ? "plaintext" : "html"}`);
return result;
}
function evaluate_select_tag(ctx: cyoaeParser.Tag_Context): Tag_result {
const debug = false;
if (ctx._tag_name.text !== "select") {
throw_evaluation_error(`Internal logic error: Evaluating "${ctx._tag_name.text}" as a "select" tag`, ctx);
}
if (ctx._attribute) {
throw_evaluation_error(`The "select" tag may not have attributes`, ctx._attribute);
}
let cases: Case_result[] = [];
for (let i = 0; i < ctx._default_value.childCount; i++) {
const child = ctx._default_value.getChild(i);
if (child instanceof cyoaeParser.Tag_Context) {
if (child._tag_name.text !== "case") {
throw_evaluation_error(`Syntax error in "switch" tag: Only "case" tags are allowed as direct children of "switch" tag`, child);
}
cases.push(evaluate_case(child));
}
else if (child instanceof cyoaeParser.Plain_text_Context) {
if (child._escapes || child._word) {
throw_evaluation_error(`Syntax error in "switch" tag: Unexpected tokens "${child.text}"`, child);
}
continue;
}
else {
if (child instanceof antlr4ts.ParserRuleContext) {
throw_evaluation_error(`Syntax error in "switch" tag: Unexpected tokens "${child.text}"`, child);
}
else {
throw `Syntax error in "switch" tag: Unexpected tokens "${child.text}"`;
}
}
}
debug && console.log(`All found cases: ${cases.reduce((curr, case_) => `${curr}\nApplicable: ${case_.applicable}, Score: ${case_.score}, Priority: ${case_.priority}, Text: ${case_.text.current_value}`, "")}`);
cases = cases.filter(case_ => case_.applicable);
debug && console.log(`Applicable cases: ${cases.reduce((curr, case_) => `${curr}\nApplicable: ${case_.applicable}, Score: ${case_.score}, Priority: ${case_.priority}, Text: ${case_.text.current_value}`, "")}`);
const max_score = cases.reduce((curr, case_) => case_.score > curr ? case_.score : curr, 0);
debug && console.log(`Max score: ${max_score}`);
cases = cases.filter(case_ => case_.score === max_score);
debug && debug && console.log(`Max score cases: ${cases.reduce((curr, case_) => `${curr}\nApplicable: ${case_.applicable}, Score: ${case_.score}, Priority: ${case_.priority}, Text: ${case_.text.current_value}`, "")}`);
const total_priority = cases.reduce((curr, case_) => curr + case_.priority, 0);
debug && console.log(`Total priority: ${total_priority}`);
if (cases.length === 0) {
return new Tag_result("");
}
if (cases.length === 1) {
return cases[0].text;
}
let choice = Math.random() * total_priority;
for (const case_ of cases) {
choice -= case_.priority;
if (choice <= 0) {
return case_.text;
}
}
//this should be unreachable
console.error(`Reached supposedly unreachable case choice`);
return cases[0].text;
}
function evaluate_case_code(ctx: cyoaeParser.Case_code_Context): Case_code_result {
const debug = false;
debug && console.log(`Entered case code evaluation with "${ctx.childCount}" expressions to evaluate`);
let result = { applicable: true, score: 0 };
for (let i = 0; i < ctx.childCount; i++) {
const child = ctx.getChild(i);
if (child instanceof cyoaeParser.Expression_Context) {
debug && console.log(`Evaluating case condition ${child.text}`);
try {
const value = evaluate_expression(child);
if (!value) {
result.applicable = false;
}
}
catch (error) {
if (`${error}`.search(/Variable "[^"]+" is undefined/) !== -1) {
result.applicable = false;
}
else {
throw error;
}
}
result.score++;
}
}
return result;
}
function evaluate_case(ctx: cyoaeParser.Tag_Context): Case_result {
const debug = false;
debug && console.log(`Evaluating case ${ctx.text}`);
if (ctx._tag_name.text !== "case") {
throw_evaluation_error(`Internal logic error: Evaluating "${ctx._tag_name.text}" as a "case" tag`, ctx);
}
let result = {
applicable: true,
score: 0,
priority: 1,
text: null as unknown as Tag_result,
};
for (let i = 0; i < ctx.childCount; i++) {
const child = ctx.getChild(i);
if (child instanceof cyoaeParser.Attribute_Context) {
debug && console.log(`Found "${child._attribute_name.text}" attribute with value "${child._attribute_value.text}"`);
switch (child._attribute_name.text) {
case "text":
result.text = new Tag_result(child._attribute_value);
break;
case "condition":
try {
const case_code_result = run_parser({
code: child._attribute_value.text,
filename: `Expression in ${child.start.line}:${child.start.charPositionInLine}`,
evaluator: parser => evaluate_case_code(parser.case_code_())
});
result.applicable = result.applicable && case_code_result.applicable;
result.score += case_code_result.score;
}
catch (err) {
throw_evaluation_error(`Failed evaluating condition: ${err}`, child._attribute_value);
}
break;
case "priority":
try {
const text = evaluate_richtext(child._attribute_value).text;
const priority = parseFloat(text);
if (Number.isNaN(priority)) {
throw "NaN";
}
if (priority < 0) {
throw "Priority cannot be negative";
}
result.priority = priority;
}
catch (err) {
throw_evaluation_error(`Attribute "${child._attribute_name}" did not evaluate to a number: ${err}`, child._attribute_name);
}
break;
default:
throw_evaluation_error(`Unknown attribute "${child._attribute_name.text}" in tag "case"`, child._attribute_name);
}
}
}
if (!result.text) {
result.text = new Tag_result(ctx._default_value);
}
debug && console.log(`Result: applicable: ${result.applicable}, priority: ${result.priority}, score: ${result.score}, text: ${result.text.current_value}`);
return result;
}
function run_parser<T>(parameters: {
readonly code: string;
readonly filename?: string;
lexer_error_listener?: antlr4ts.ANTLRErrorListener<number>;
parser_error_listener?: antlr4ts.ANTLRErrorListener<antlr4ts.Token>;
evaluator: (parser: cyoaeParser.cyoaeParser) => T;
}) {
const old_source = current_source;
current_source = parameters.code;
try {
const input = antlr4ts.CharStreams.fromString(current_source, parameters.filename || "???");
const lexer = new cyoaeLexer(input);
const tokens = new antlr4ts.CommonTokenStream(lexer);
const parser = new cyoaeParser.cyoaeParser(tokens);
parameters.parser_error_listener = parameters.parser_error_listener || new ParserErrorListener(parser);
parameters.lexer_error_listener = parameters.lexer_error_listener || new LexerErrorListener();
lexer.removeErrorListeners();
lexer.addErrorListener(parameters.lexer_error_listener);
parser.removeErrorListeners();
parser.addErrorListener(parameters.parser_error_listener);
return parameters.evaluator(parser);
}
finally {
current_source = old_source;
}
}
function parse_source_text(data: string, filename: string) {
console.log(`Starting parsing source text ${filename}`);
return run_parser({
code: data,
filename: filename,
evaluator: parser => {
const tree = parser.start_();
if (tree._rich_text) {
return evaluate_richtext(tree._rich_text);
}
//TODO: Put up a proper placeholder page for an empty source
return new Tag_result(`Empty file "${filename}"`);
}
});
}
// plays through a story arc
async function play_arc(name: string) {
window.location.hash = `#${name}/start`;
}
// display a scene based on a source .txt file and the current arc
async function update_current_scene() {
const debug = false;
debug && console.log(`updating scene to ${current_arc}/${current_scene}`);
try {
Variable_storage.set_internal("current_scene", `${current_arc}/${current_scene}`);
const story_container = createHTML(["div", { class: "main" }]);
story_container.append(...parse_source_text(await download(`${current_arc}/${current_scene}.txt`), `${current_arc}/${current_scene}.txt`).range);
const debug_container = createHTML(["div", { class: "debug" }]);
const debug_button = createHTML(["button", "🐛"]);
const lazy_variable_table = new Lazy_evaluated(() => {
const result = createHTML(["div"]);
result.append(createHTML(["hr"]), create_variable_table());
return result;
});
debug_container.append(debug_button);
debug_button.onclick = () => {
const variable_table = lazy_variable_table.value;
if (debug_container.contains(variable_table)) {
debug_container.removeChild(variable_table);
}
else {
debug_container.append(variable_table);
}
};
document.body.textContent = "";
document.body.append(story_container, debug_container);
}
catch (err) {
display_error_document(`${err}`);
}
}
async function url_hash_change() {
const debug = false;
const [, arc, scene] = window.location.hash.match(/#([^\/]*)\/(.*)/) || [];
debug && console.log(`URL changed to ${arc}/${scene}`);
if (arc && scene) {
current_arc = arc;
current_scene = scene;
await update_current_scene();
}
}
window.onhashchange = url_hash_change;
// downloads a local resource given its path/filename
async function download(url: string) {
const current_url = window.location.toString().replace(/\/[^\/]*$/, `/`).replace(/#.*/, "");
const filepath = `${current_url}story arcs/${url}`;
try {
const request = await fetch(filepath);
if (request.ok) {
return await request.text();
}
throw request.statusText;
}
catch (err) {
throw `Failed loading resource ${filepath}: ${err}`;
}
}
function display_error_document(error: string) {
document.body.append(createHTML(["span", { class: 'error' }, error]));
}
function assert(predicate: any, explanation: string = "") {
if (!predicate) {
const details = `\n>Value >>>${predicate}<<<`;
const source = ` in ${(new Error()).stack?.split("\n")[1]}`;
if (explanation) {
throw `Assertion fail${source}:${details}${explanation ? "\n" + explanation : ""}`;
}
throw `Assertion fail: ${predicate}`;
}
}
function assert_equal(actual: any, expected: any, explanation?: any) {
function throw_error() {
const details = `\n Actual: "${actual}"\nExpected: "${expected}"`;
const source = ` in ${(new Error()).stack?.split("\n")[1]}`;
if (explanation) {
throw `Assertion fail${source}:${details}${explanation ? "\n" + explanation : ""}`;
}
throw `Assertion fail${source}: ${details}`;
}
if (Array.isArray(actual) && Array.isArray(expected)) {
if (actual.length !== expected.length) {
throw_error();
}
for (const i in actual) {
try {
assert_equal(actual[i], expected[i])
}
catch (err) {
explanation = `${err}\n${explanation}`;
throw_error();
}
return;
}
}
if (actual !== expected) {
throw_error();
}
}
async function tests() {
function test_HTMLElement_to_string() {
const element = document.createElement("p");
assert_equal(HTMLElement_to_string(element), "<p></p>", `test_HTMLElement_to_string <p> tag`);
element.append("TestText");
assert_equal(HTMLElement_to_string(element), "<p>TestText</p>", `test_HTMLElement_to_string <p> tag with text "TestText"`);
const span = document.createElement("span");
element.append(span);
assert_equal(HTMLElement_to_string(element), "<p>TestText<span></span></p>", `test_HTMLElement_to_string <p> tag with text "TestText" and <span> tag`);
span.append("span text");
assert_equal(HTMLElement_to_string(element), "<p>TestText<span>span text</span></p>", `test_HTMLElement_to_string <p> tag with text "TestText" and <span> tag`);
}
test_HTMLElement_to_string();
function test_creatHTML() {
assert_equal(HTMLElement_to_string(createHTML(["p", "test", "bla", "blup"])), "<p>testblablup</p>");
assert_equal(HTMLElement_to_string(createHTML(["p", { class: "foo" }, "test", "bla", "blup"])), '<p class="foo">testblablup</p>');
assert_equal(HTMLElement_to_string(createHTML(["p", { class: "foo" }, ["a", { href: "inter.net" }, "link"]])), '<p class="foo"><a href="inter.net">link</a></p>');
}
test_creatHTML();
function test_Tag_result() {
let text = new Tag_result("111");
assert_equal(text.text, "111", "Initializing text failed");
text = text.append("222");
assert_equal(text.text, "111222", "Appending text failed");
assert_equal(text.range.join(), "111222");
}
test_Tag_result();
function test_tag_parsing() {
let result = parse_source_text("[test {text:test1}]", "test_tag_parsing");
let expected = new Tag_result(createHTML(["a", "test1"]));
assert_equal(result.current_value, expected.current_value, `Checking test tag 1.`);
result = parse_source_text("[test {text:test1}]", "test_tag_parsing");
expected = new Tag_result(createHTML(["a", "test1"]));
assert_equal(result.current_value, expected.current_value, `Checking test tag 2.`);
result = parse_source_text("[test {text:test1}][test {text:test2}]", "test_tag_parsing");
expected = new Tag_result([createHTML(["a", "test1"]), createHTML(["a", "test2"])]);
assert_equal(result.current_value, expected.current_value, `Checking test tag 3.`);
}
test_tag_parsing();
async function test_delayed_evaluation() {
const debug = false;
const result = parse_source_text("[test_delayed_evaluation]", "test_delayed_evaluation").current_value;
assert(result.includes("test_delayed_evaluation_placeholder"), `test_delayed_evaluation_placeholder not found: ${result}`);
assert(!result.includes("test_delayed_evaluation_result"), `test_delayed_evaluation_result found prematurely: ${result}`);
document.body.innerHTML = result;
debug && console.log(`Result: "${result}"`);
debug && console.log(`HTML: "${document.body.innerHTML}"`);
assert(document.body.innerHTML.includes("test_delayed_evaluation_placeholder"), `test_delayed_evaluation_placeholder not found: ${document.body.innerHTML}`);
assert(!document.body.innerHTML.includes("test_delayed_evaluation_result"), `test_delayed_evaluation_result found prematurely: ${document.body.innerHTML}`);
await Delayed_evaluation.wait_for_everything_to_be_evaluated();
assert(Delayed_evaluation.has_everything_been_evaluated, "Everything should be evaluated after waiting for it, but isn't.");
assert(!document.body.innerHTML.includes("test_delayed_evaluation_placeholder"), `test_delayed_evaluation_placeholder found after evaluation: ${document.body.innerHTML}`);
assert(document.body.innerHTML.includes("test_delayed_evaluation_result"), `test_delayed_evaluation_result not found after evaluation: ${document.body.innerHTML}`);
}
await test_delayed_evaluation();
function test_code_evaluation() {
function test_eval(code: string, expected: string | number | void) {
run_parser({
code: code,
filename: `code evaluation test "${code}"`,
evaluator: parser => {
assert_equal(evaluate_expression(parser.expression_()), expected, `for code "${code}"`);
}
});
}
test_eval("x=42");
test_eval("x", 42);
test_eval("x + 27", 69);
test_eval("1+2*3", 7);
test_eval("(1+2)*3", 9);
try {
test_eval("1/0");
assert(false, `Zero division error did not produce exception`);
} catch (e) { }
Variable_storage.delete_variable("x");
}
test_code_evaluation();
function test_game_variables() {
assert_equal(typeof Variable_storage.get_variable("internal test variable"), "undefined");
Variable_storage.set_variable("internal test variable", "yo");
assert_equal(typeof Variable_storage.get_variable("internal test variable"), "string");
assert_equal(Variable_storage.get_variable("internal test variable"), "yo");
Variable_storage.set_variable("internal test variable", 42);
assert_equal(typeof Variable_storage.get_variable("internal test variable"), "number");
assert_equal(Variable_storage.get_variable("internal test variable"), 42);
Variable_storage.set_variable("internal test variable", true);
assert_equal(typeof Variable_storage.get_variable("internal test variable"), "boolean");
assert_equal(Variable_storage.get_variable("internal test variable"), true);
Variable_storage.delete_variable("internal test variable");
assert_equal(typeof Variable_storage.get_variable("internal test variable"), "undefined");
}
test_game_variables();
function test_variable_undo() {
let old_values = new Map<string, Variable_storage_types>([["oldname", "oldvalue"]]);
let new_values = new Map<string, Variable_storage_types>();
assert_equal(get_undo_update_code(old_values, old_values), '');
assert_equal(get_undo_update_code(new_values, new_values), '');
assert_equal(get_undo_update_code(old_values, new_values), 'oldname="oldvalue";');
//assert_equal(old_values, new_values);
old_values = new Map<string, Variable_storage_types>([["name", "oldvalue"]]);
new_values = new Map<string, Variable_storage_types>([["name", "newvalue"]]);
assert_equal(get_undo_update_code(old_values, new_values), 'name="oldvalue";');
old_values = new Map<string, Variable_storage_types>();
new_values = new Map<string, Variable_storage_types>([["name", "newvalue"]]);
assert_equal(get_undo_update_code(old_values, new_values), 'delete name;');
}
test_variable_undo();
document.body.innerHTML = "";
}
// script entry point, loading the correct state and displays errors
async function main() {
Variable_storage.init();
try {
await tests();
}
catch (err) {
console.error(`Test failed: ${err}`);
return;
}
try {
const value = Variable_storage.get_internal_string("current_scene");
if (value) {
window.location.hash = `#${value}`;
}
else {
await play_arc("intro");
}
await url_hash_change();
}
catch (err) {
display_error_document(`${err}`);
}
}
main();
|
import React from "react";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { changeName } from "../store/slices/userName.slice";
import { useNavigate } from "react-router-dom";
import ash from "../assets/ashShadow.png";
const UserInput = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const [userName, setUserName] = useState("");
const dispatchUserName = () => {
if (userName === "") {
alert("Type your name");
} else {
dispatch(changeName(userName));
navigate("/pokedex");
}
};
return (
<div className="user-container">
<div className="user-info-container">
<div className="user-info">
<h1>Hello trainer!</h1>
<form onSubmit={dispatchUserName} className="input-container">
<input
type="text"
placeholder="Type your name to start"
value={userName}
onChange={(e) => setUserName(e.target.value)}
/>
<button>
<i className="fa-solid fa-paper-plane"></i>
</button>
</form>
</div>
</div>
<img className="ash" src={ash} alt="" />
</div>
);
};
export default UserInput;
|
<template lang="pug">
b-container(fluid)#list.overflow-auto
b-row
b-col(cols="12" lg="6" class="my-3")
b-form-group(label="新增事項" invalid-feedback="請至少輸入兩個字" :state="state")
b-form-input(v-model="newtodo" trim :state="state" @keydown.enter="addTodo")
b-btn(variant="danger" @click="addTodo") 新增
b-col(cols="12")
b-table(:items="todos" :fields="fields")
template(#cell(name)="data")
b-form-input(
v-if="data.item.edit"
v-model="data.item.model"
trim
:state="stateTodo(data.item.model)"
@keydown.enter="changeTodo(data.index)"
)
span(v-else) {{ data.item.name }}
template(#cell(action)="data")
span(v-if="data.item.edit")
b-btn(size="sm" variant="success" @click="changeTodo(data.index)" class="mr-2")
font-awesome-icon(:icon="['fas', 'check']")
b-btn(size="sm" variant="danger" @click="cancelTodo(data.index)")
font-awesome-icon(:icon="['fas', 'undo']")
span(v-else)
b-btn(size="sm" variant="primary" @click="editTodo(data.index)" class="mr-2")
font-awesome-icon(:icon="['fas', 'pen']")
b-btn(size="sm" variant="danger" @click="delTodo(data.index)")
font-awesome-icon(:icon="['fas', 'times']")
</template>
<script>
export default {
name: 'List',
data () {
return {
newtodo: '',
fields: [
{
key: 'name',
label: '待辦事項'
},
{
key: 'action',
label: '操作'
}
]
}
},
computed: {
state () {
if (this.newtodo.length === 0) {
return null
} else if (this.newtodo.length < 2) {
return false
} else {
return true
}
},
todos () {
return this.$store.state.todos
}
},
methods: {
addTodo () {
if (this.state) {
this.$store.commit('addTodo', this.newtodo)
this.newtodo = ''
}
},
delTodo (index) {
this.$store.commit('delTodo', index)
},
editTodo (index) {
this.$store.commit('editTodo', index)
},
stateTodo (data) {
if (data.length < 2) {
return false
} else {
return true
}
},
changeTodo (index) {
const valid = this.stateTodo(this.todos[index].model)
if (valid) {
this.$store.commit('changeTodo', index)
}
},
cancelTodo (index) {
this.$store.commit('cancelTodo', index)
}
}
}
</script>
|
class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
Map<Integer, Integer> relativePositions = new HashMap<>();
for (int i = 0; i < arr2.length; i++) {
relativePositions.put(arr2[i], i);
}
// Count the occurrences of elements in arr1
int[] counts = new int[1001];
for (int num : arr1) {
counts[num]++;
}
// Fill arr1 with elements based on their relative positions in arr2
int index = 0;
for (int num : arr2) {
while (counts[num] > 0) {
arr1[index++] = num;
counts[num]--;
}
}
// Fill arr1 with remaining elements in ascending order
for (int i = 0; i < counts.length; i++) {
while (counts[i] > 0) {
arr1[index++] = i;
counts[i]--;
}
}
return arr1;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] arr1 = {2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19};
int[] arr2 = {2, 1, 4, 3, 9, 6};
int[] sortedArr = solution.relativeSortArray(arr1, arr2);
System.out.println(Arrays.toString(sortedArr));
}
}
|
Git — это система управления версиями (система контроля версий) с распределенной архитектурой, которая позволяет
сразу нескольким разработчикам сохранять и отслеживать изменения в файлах проекта.
Репозиторий Git — это виртуальное хранилище проекта. В нём можно хранить версии кода для дальнейшего доступа к нему.
Git хранит имеющиеся данные в виде набора «снимков», называемых коммитами.
Коммиты хранят состояние файловой системы в конкретный момент времени,а также имеют указатель на предыдущие коммиты.
Каждый коммит содержит уникальный контрольный идентификатор, который используется Git, чтобы ссылаться на этот коммит.
Команды Git:
1) Инициализация нового репозитория: git init
2) Настройка имени пользователя и email:
git config --global user.name "[UserName]"
git config --global user.email "[UserEmail]"
Флаг --global задаёт имя автора, которое будет использоваться для всех коммитов, выполненных текущим пользователем.
Добавление аргумента --local или выполнение команды без параметра уровня конфигурации приведёт к установке
значения user.name для текущего локального репозитория.
3) Клонирование репозитория
git clone [Copied SSH key]
(создаётся локальный клон уже настроенного проекта в центральном репозитории).
4) Сохранение изменений
git add [FileName]
(добавляет изменения из рабочего каталога в раздел проиндексированных файлов и сообщает Git,
что изменения должны быть включены в конкретном файле в следующий коммит).
5) Добавление изменений
git commit -m "[MessageText]"
(добавляет проиндексированный снимок состояния в историю проекта).
6) Переписывание истории
git commit --amend
(позволяет внести изменения в последний коммит, например, если вы забыли
проиндексировать файл или не указали важную информацию в комментарии к коммиту).
Перезапись коммита
git commit --amend -m "[MessageText]"
7) Проверка репозитория
git status
(показывает состояние рабочего каталога и проиндексированного снимка состояния;
можно увидеть файлы, которые не отслеживаются Git).
8) Проверка репозитория
git log
(позволяет просмотреть коммиты, сделанные в репозиториях- показывает историю коммитов).
9) Синхронизация
git pull
(загружает ветку из удалённого репозитория и сразу же объединяет её с текущей веткой).
10) Синхронизация
git push
(с её помощью можно перенести локальную ветку в другой репозиторий и опубликовать поступивший код).
11) Просмотр удалённых подключений к репозиториям
git remote -v
Флаг -v включает URL-адрес каждого подключения.
12) Сброс изменений с локального файла
git checkout -- [FileName]
Можно сбросить изменения с нескольких локальных файлов при помощи команды
checkout . (есть пробел между командой и точкой).
13) Удаление неотслеживаемых файлов в рабочем каталоге репозитория- удаление новых файлов (не в индексе)
git clean -xdf
Неотслеживаемые файлы — это файлы в каталоге репозитория, которые еще не добавлены в раздел проиндексированных
файлов репозитория с помощью команды git add .
14) Отмена локальных изменений в репозитории
git reset -- [FileName]
15) Удаление коммита
git reset HEAD~[NumberOfCommits]
16) Безопасная отмена изменений (коммиты не удаляются)
git revert [SHA1]
Вместо удаления коммита из истории проекта эта команда отменяет внесенные в нём изменения и добавляет новый коммит с полученным содержимым.
В результате история в Git не теряется, что важно для обеспечения целостной истории версий и надежной совместной работы.
Целью для команды git revert можно выбрать любой отдельный коммит в истории проекта,в то время как действие команды git reset
может отменить только коммит, предшествующий текущему. Команда git revert не создает угрозу потери кода.
17) Перейти в нужную папку на компьютере
cd git/Skills
Skills- название искомой папки на текущем диске
18) Перейти на другой диск
cd d:/
|
import Foundation
import SwiftUI
struct Category {
let city: String
let items: [String]
}
class ContentViewController: UIViewController {
private let tableView: UITableView = {
let table = UITableView()
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return table
}()
private let data: [Category] = [
Category(city: "Madrid", items: ["UC3M", "El Retiro", "Parque de Andalucía", "Parque de Alcobendas"]),
Category(city: "Toledo", items: ["Zocodover", "El Alcázar", "La Catedral", "Puerta Bisagra"]),
Category(city: "Miguel Esteban", items: ["Castillo Novo", "Prado inicial"]),
Category(city: "Fuengirola", items: ["Castillo de la Luz", "Plaza de la Paz"]),
Category(city: "Viveiro", items: ["Plaza Mayor", "Puerto"]),
]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
tableView.separatorColor = UIColor(hex:0x56C271)
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.backgroundColor = .white
tableView.frame = view.bounds
}
}
extension ContentViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let category = data[indexPath.row]
let vc = ListViewController(items: category.items)
vc.title = category.city
navigationController?.pushViewController(vc, animated: true)
}
}
extension ContentViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row].city
return cell
}
}
|
# Django-API
# Book API
The Book API is a Django-based RESTful API for managing books. With this API, you can perform essential CRUD (Create, Read, Update, Delete) operations on books. It provides a straightforward way to store and manage information about your book collection.
## Table of Contents
- [Features](#features)
- [Getting Started](#getting-started)
- [API Endpoints](#api-endpoints)
- [Usage Examples](#usage-examples)
- [Authentication](#authentication)
- [Data Models](#data-models)
- [Contributing](#contributing)
- [License](#license)
## Features
- Create, view, update, and delete books in your collection.
- Simple and intuitive API endpoints.
- Secure and scalable using Django best practices.
## Getting Started
### Prerequisites
- Python 3.x
- Django
- Django REST framework
### Installation
1. Clone this repository:
```shell
git clone https://github.com/yourusername/book-api.git
Change into the project directory:
shell
Copy code
cd book-api
Install the required dependencies:
shell
Copy code
pip install -r requirements.txt
Create and apply database migrations:
shell
Copy code
python manage.py makemigrations
python manage.py migrate
Start the development server:
shell
Copy code
python manage.py runserver
The API should now be accessible at http://localhost:8000/.
API Endpoints
The following endpoints are available for managing books:
GET /books/: List all books.
POST /books/: Create a new book.
GET /books/{id}/: Retrieve details of a specific book.
PUT /books/{id}/: Update a book.
DELETE /books/{id}/: Delete a book.
Usage Examples
Here are some example requests using curl, but you can use your favorite HTTP client:
List all books:
shell
Copy code
curl http://localhost:8000/books/
Create a new book:
shell
Copy code
curl -X POST -d "title=Book Title&author=Author Name&published_date=2023-10-01" http://localhost:8000/books/
Update a book (replace {id} with the actual book ID):
shell
Copy code
curl -X PUT -d "title=New Title" http://localhost:8000/books/{id}/
Delete a book (replace {id} with the actual book ID):
shell
Copy code
curl -X DELETE http://localhost:8000/books/{id}/
Authentication
You can secure the API with authentication mechanisms like JWT, OAuth, or API keys, depending on your project's needs. Please refer to the documentation or Django REST framework's authentication documentation for more details.
Data Models
The project includes the following data model:
Book: Represents a book with attributes like title, author, and published date.
Contributing
Contributions are welcome! If you'd like to contribute to this project, please follow these guidelines:
Fork the repository.
Create a new branch for your feature or bug fix: git checkout -b feature-name.
Implement your changes.
Test your changes thoroughly.
Submit a pull request.
Please make sure your code follows PEP 8 coding standards, and include tests for new features or bug fixes.
License
This project is licensed under the MIT License.
|
<template>
<section class="cart">
<div class="cart__container">
<div class="cart__container__title">購物籃</div>
<div
class="cart__container__wrapper"
v-for="product in carts"
:key="product.id"
>
<div class="cart__container__wrapper__product-photo">
<img
:src="product.img"
:alt="'product' + product.id"
class="cart__container__wrapper__product-photo--img"
/>
</div>
<div class="cart__container__wrapper__product">
<div class="cart__container__wrapper__product__info">
<div class="cart__container__wrapper__product__info--product-name">
{{ product.name }}
</div>
<div class="cart__container__wrapper__product__info__modifier">
<div
class="cart__container__wrapper__product__info__modifier--minus minus"
@click.stop.prevent="minusQty(product.id)"
></div>
<div
class="cart__container__wrapper__product__info__modifier--qty qty"
>
{{ product.qty }}
</div>
<div
class="cart__container__wrapper__product__info__modifier--plus plus"
@click.stop.prevent="addQty(product.id)"
></div>
</div>
</div>
<div class="cart__container__wrapper__product__info--price">
{{ product.price | addComma }}
</div>
</div>
</div>
<div class="cart__container__wrapper">
<div class="cart__container__wrapper__freight">
<div class="cart__container__wrapper__freight--item">運費</div>
<div class="cart__container__wrapper__freight--amount freight">
{{ deliveryCost | filterFreightCost }}
</div>
</div>
</div>
<div class="cart__container__wrapper">
<div class="cart__container__wrapper__total">
<div class="cart__container__wrapper__total--item">小計</div>
<div class="cart__container__wrapper__total--amount total-amount">
{{ calculateTotal | addComma }}
</div>
</div>
</div>
`
</div>
</section>
</template>
<script>
import { v4 as uuidv4 } from 'uuid'
export default {
name: 'Cart',
props: {
deliveryCost: {
type: [Number, String, Object],
required: true,
default: () => ({
deliveryCost: 0,
}),
},
},
data() {
return {
carts: [
{
id: uuidv4(),
img: require('./../assets/product1.svg'),
name: '破壞補丁修身牛仔褲',
price: 3299,
qty: 1,
},
{
id: uuidv4(),
img: require('./../assets/product2.svg'),
name: '刷色直筒牛仔褲',
price: 1299,
qty: 1,
},
],
}
},
methods: {
addQty(productId) {
this.carts.map((product) => {
if (product.id === productId) {
product.qty += 1
}
})
},
minusQty(productId) {
this.carts.map((product) => {
if (product.id === productId) {
product.qty -= 1
}
if (product.qty <= 0) {
product.qty = 0
}
})
},
},
filters: {
// 把數字加上千分位逗號
addComma: function (value) {
if (!value) return '$0'
return (
'$' + value.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',')
)
},
// 依照運費金額顯示免費或是運費價錢
filterFreightCost: function (value) {
return value === 0
? '免費'
: '$' + value.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',')
},
},
computed: {
// 計算總金額
calculateTotal: function () {
const total = this.carts.reduce((accu, curr) => {
return accu.price * accu.qty + curr.price * curr.qty
})
return this.deliveryCost + total
},
},
watch: {
// 監聽總金額變化並往父組件送
calculateTotal: {
handler: function (total) {
this.$emit('handleTotal', total)
},
deep: true,
immediate: true,
},
},
}
</script>
|
<?php
namespace App\Models;
use App\Models\Categorie;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Article extends Model
{
use HasFactory;
protected $fillable = ['libelle', 'quantiteStock', 'categorie_id', 'fournisseur_id', 'photo'];
public function categorie(): BelongsTo
{
return $this->belongsTo(Categorie::class);
}
public function articlevente()
{
return $this->belongsToMany(Articlevente::class, 'article_articleventes')
->withTimestamps();
}
public function fournisseurs()
{
return $this->belongsToMany(Fournisseur::class );
}
protected static function boot()
{
parent::boot();
static::creating(function ($article) {
$article->reference = $article->generateReference();
});
static::created(function ($article) {
$fournisseurs = request()->input('fournisseur_id');
$article->fournisseurs()->attach($fournisseurs);
});
static::addGlobalScope('withRelations', function ($builder) {
$builder->with('fournisseurs', 'categorie');
});
static::updating(function ($user) {
});
static::deleting(function ($user) {
// Code pour supprimer un utilisateur
});
}
public function generateReference()
{
$categorie = $this->categorie ? $this->categorie->libelle : 'NOCAT';
return 'REF-' . substr($this->libelle, 0, 3) . '-' . strtoupper($categorie) . '-' . sprintf('%04d', static::count() + 1);
}
}
|
//
// LocationTableViewCellViewModel.swift
// Rick & Morty
//
// Created by Николай Никитин on 06.09.2023.
//
import Foundation
struct LocationTableViewCellViewModel: Hashable, Equatable {
private let location: Location
init(with location: Location) {
self.location = location
}
public var name: String {
return location.name
}
public var type: String {
return "Type: " + location.type
}
public var dimension: String {
return location.dimension == "unknown" ? "Unknown dimension" : location.dimension
}
static func == (lhs: LocationTableViewCellViewModel, rhs: LocationTableViewCellViewModel) -> Bool {
return lhs.location.id == rhs.location.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(location.id)
hasher.combine(dimension)
hasher.combine(type)
}
}
|
import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {MatDialog} from '@angular/material/dialog';
import {DeleteConfirmationComponent} from '../../module-share/delete-confirmation/delete-confirmation.component';
import {NotificationsService} from 'angular2-notifications';
import {HttpErrorResponse} from '@angular/common/http';
import {EmployeesFormComponent} from './employees-form/employees-form.component';
import {EmployeesService} from '../services/employees.service';
@Component({
selector: 'app-employees',
templateUrl: './employees.component.html',
styleUrls: ['./employees.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class EmployeesComponent implements OnInit {
@ViewChild('formComponent', {static: false}) formComponent: EmployeesFormComponent;
list: any[] = [];
itemSelected;
constructor(
private service: EmployeesService,
private router: Router,
private route: ActivatedRoute,
private matDialog: MatDialog,
private notifications: NotificationsService,
) {
}
ngOnInit(): void {
this.route.queryParams.subscribe((params: any) => {
if (params) {
this.loadAll();
}
});
}
loadAll(): void {
this.service.query().subscribe(response => {
if (response && response.length > 0) {
this.list = response;
} else {
this.list = [];
}
});
}
loadForm(item): void {
if (item) {
this.formComponent.loadAll(item);
this.itemSelected = item;
}
}
successSubmit(result: any): void {
if (result) {
this.loadAll();
}
}
download(): void {
this.service.query().subscribe(response => {
if (response && response.length > 0) {
let csv = 'No.,Nombre,Apellido,Dirección,Teléfono,DPI,Género,Fecha nacimiento,Puesto,Fecha inicio labores, Fecha ingreso\n';
response.forEach((row) => {
const tempRow = Object.values(row);
csv += tempRow.join(',');
csv += '\n';
});
const hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'Empleados.csv';
hiddenElement.click();
}
});
}
onDelete(item: any): void {
const response = this.matDialog.open(DeleteConfirmationComponent, {
disableClose: true,
data: {}
});
response.afterClosed().subscribe(
(data: boolean) => {
if (data === true) {
this.service.delete(item.idEmpleado).pipe().subscribe(
() => {
this.notifications.success('Correcto', 'La acción se realizó con éxito.');
this.loadAll();
},
(error: HttpErrorResponse) => {
this.notifications.error('Error', error);
}
);
}
}
);
}
}
|
plot_ls <- list()
for(rn in c("lm","lr")){
agg_df <- agg_df_ls[[rn]]
# # use mean and se
# plot_df <- NULL
# for(en in c("_mean","_se")){
# tmpdf <- pivot_longer(agg_df[,c("id", paste0(c("aic_diff", "bic_diff", "nic_diff"),en))],
# cols = ends_with(en),
# names_to = "ic_type",
# values_to = paste0("ic_diff",en))
# tmpdf$ic_type <- gsub(en,"", tmpdf$ic_type)
# if(is.null(plot_df)){plot_df <- tmpdf}
# else{
# plot_df <- merge(plot_df, tmpdf)
# }
# }
# plot_df$ic_diff <- plot_df$ic_diff_mean
# plot_df$ic_diff_l <- plot_df$ic_diff - plot_df$ic_diff_se
# plot_df$ic_diff_u <- plot_df$ic_diff + plot_df$ic_diff_se
# use IQR
plot_df <- NULL
for(en in c("_median","_q25", "_q75")){
tmpdf <- pivot_longer(agg_df[,c("id", paste0(c("aic_diff", "bic_diff", "nic_diff"),en))],
cols = ends_with(en),
names_to = "ic_type",
values_to = paste0("ic_diff",en))
tmpdf$ic_type <- gsub(en,"", tmpdf$ic_type)
if(is.null(plot_df)){plot_df <- tmpdf}
else{
plot_df <- merge(plot_df, tmpdf)
}
}
plot_df$ic_diff <- plot_df$ic_diff_median
plot_df$ic_diff_l <- plot_df$ic_diff_q25
plot_df$ic_diff_u <- plot_df$ic_diff_q75
plot_df <- merge(plot_df,simulation_conditions, by="id", all.x=T) %>% as.data.frame()
plot_df <- plot_df %>% filter(sigma_rdm_fix_ratio == r, na_rate == na) %>% as.data.frame()
plot_df$n_obs_per_cluster <- paste0(plot_df$n_obs_per_cluster, " obs/cluster")
plot_df$n_obs_per_cluster <- factor(plot_df$n_obs_per_cluster, levels=c("5 obs/cluster",
"10 obs/cluster",
"50 obs/cluster",
"100 obs/cluster",
"150 obs/cluster") )
plot_df$ic_type <- stringr::str_to_upper(gsub("_diff","",plot_df$ic_type))
plot_df$ic_type <- factor(plot_df$ic_type, levels=c("NIC","AIC","BIC"))
levels(plot_df$ic_type) <- c("NICc","AIC","BIC")
plot_df$ar1_phi <- paste0("AR1(",plot_df$ar1_phi,")")
plot_df$ar1_phi <- factor(plot_df$ar1_phi, levels = c("AR1(0)", "AR1(0.4)", "AR1(0.8)"))
# plot_df$na_rate_factor <- factor(plot_df$na_rate, levels = c(0, 1))
# levels(plot_df$na_rate_factor) <- c("Balanced", "Unbalanced")
plot_ls[[rn]] <- ggplot(data = plot_df, aes(x = n_ttl_betas, y = ic_diff, color = ic_type)) +
geom_point(size=2) +
geom_line() +
# geom_line(mapping = aes(linetype=na_rate_factor))+
geom_errorbar(aes(ymin = ic_diff_l, ymax = ic_diff_u),width=0.5) +
scale_linetype_manual(values = c("solid", "dashed", "dotdash", "dotted")) +
geom_hline(aes(yintercept=0)) +
scale_x_continuous(limits = c(min(plot_df$n_ttl_betas), max(plot_df$n_ttl_betas)), breaks = seq(min(plot_df$n_ttl_betas), max(plot_df$n_ttl_betas), 1)) +
coord_trans(y = "sqrt") +
facet_wrap(~ar1_phi + n_obs_per_cluster, ncol=5, nrow=3, scales="free_x") +
labs(subtitle = ifelse(rn=="lr", "Binomial", "Gaussian"),
x = "Generating Model Size",
y = "Error = |IC - looDeviance|",
color = "Criterion",
linetype="Cluster") +
theme_bw()+
scale_color_manual(values = c("NICc" = "red", "AIC" = "blue", "BIC" = "darkorange", "looDeviance" = "black", "Deviance" = "gray")) +
theme(text = element_text(face = "bold"),
plot.subtitle = element_text(size=12, face="bold"),
axis.title = element_text(size=12),
axis.text = element_text(size=10),
legend.title = element_text(size=12),
legend.text = element_text(size=10))
}
p <- ggarrange(plotlist = plot_ls, nrow=2,ncol=1, common.legend = T,legend = "right")
p <- annotate_figure(p, top = text_grob("Error in approximating out-of-cluster performance", size = 14, face = "bold"))
|
@page
@model Dissertation.Pages.Authentication.AuthenticationModel
@{
ViewData["Title"] = "Log in";
Layout = "_Layout";
}
<div class="main-container">
<div class="right-container">
<section>
<form id="account" asp-page="./Authentication" asp-page-handler="Login" method="post">
<h2>Sign In</h2>
<div asp-validation-summary="ModelOnly" role="alert"></div>
<div class="form-control">
<input asp-for="LoginInput.Email" class="inputBox" autocomplete="username" aria-required="true"
placeholder="Username" />
<span asp-validation-for="LoginInput.Email"></span>
</div>
<div class="form-control">
<input asp-for="LoginInput.Password" class="inputBox" autocomplete="current-password"
aria-required="true" placeholder="Password" />
<span asp-validation-for="LoginInput.Password"></span>
</div>
<div>
<button id="loginButton" type="submit">Log in</button>
</div>
</form>
</section>
</div>
<div class="left-container">
<form id="registerForm" asp-page="./Authentication" asp-page-handler="Register" method="post">
<h2>Sign Up</h2>
<div class="form-control">
<input asp-for="RegisterInput.FirstName" class="inputBox" aria-required="true" placeholder="First Name" />
<span asp-validation-for="RegisterInput.FirstName" class="text-danger"></span>
</div>
<div class="form-control">
<input asp-for="RegisterInput.LastName" class="inputBox" aria-required="true" placeholder="Last Name" />
<span asp-validation-for="RegisterInput.LastName" class="text-danger"></span>
</div>
<div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div>
<div class="form-control">
<input asp-for="RegisterInput.Email" class="inputBox" autocomplete="username" aria-required="true"
placeholder="[email protected]" />
<span asp-validation-for="RegisterInput.Email" class="text-danger"></span>
</div>
<div class="form-control">
<input asp-for="RegisterInput.Password" class="inputBox" autocomplete="new-password" aria-required="true"
placeholder="password" />
<span asp-validation-for="RegisterInput.Password" class="text-danger"></span>
</div>
<div class="form-control">
<input asp-for="RegisterInput.ConfirmPassword" class="inputBox" autocomplete="new-password"
aria-required="true" placeholder="password" />
<span asp-validation-for="RegisterInput.ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-control">
<select asp-for="RegisterInput.UserType" class="inputBox">
<option value="business">Business</option>
<option value="tourist">Tourist</option>
<option value="admin">Admin</option>
</select>
<span asp-validation-for="RegisterInput.UserType" class="text-danger"></span>
</div>
<button class="register" type="submit">Register</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
|
from typing import Optional, Dict, Any
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers.models.whisper import WhisperProcessor, WhisperForConditionalGeneration
from transformers.models.whisper import WhisperProcessor
from transformers.modeling_outputs import Seq2SeqLMOutput
from transformers.models.whisper.modeling_whisper import shift_tokens_right
from trainer.distillation import DistillationTrainingArgumentsBase, DistillationTrainerBase
class DistillationSeqLevelTrainingArguments(DistillationTrainingArgumentsBase):
"""
Subclass of `TrainingArguments` used for `DistillationTrainer`.
Only supports distillation for non-sequential tasks.
"""
def __init__(self,
alpha_ce: float = 0.5,
distillation_num_beams: int = 1,
beta_decay: Optional[float] = 2.0,
*args,
**kwargs):
# Drop the `method_distil` argument since it is not needed for sequence-level distillation:
method_distil = kwargs.pop("method_distil", None)
assert method_distil in ["seq_level_uniform", "seq_level_ranked"], \
"method_distil should be `seq_level_uniform` or `seq_level_ranked`"
super().__init__(method_distil=method_distil,
*args,
**kwargs)
self.alpha_ce = alpha_ce
self.distillation_num_beams = distillation_num_beams
self.use_ranking = (method_distil == "seq_level_ranked")
self.beta_decay = beta_decay
class DistillationSeqLevelTrainer(DistillationTrainerBase):
"""
Trainer class for distillation. Should be used with `args=DistillationTrainingArguments`.
"""
def __init__(self,
args: DistillationSeqLevelTrainingArguments,
student_processor: WhisperProcessor,
**kwargs):
super().__init__(args=args,
student_processor=student_processor,
**kwargs)
self.args = args
self.counter = 0
def compute_loss(self,
model: WhisperForConditionalGeneration,
inputs,
return_outputs: bool = False):
"""
Compute the loss for sequence-level distillation. Override the `compute_loss` method of `Seq2SeqTrainer`.
"""
if self.args.distillation_num_beams == 1:
loss_fn = self.compute_loss_1_best
else:
loss_fn = self.compute_loss_k_best
return loss_fn(model, inputs, return_outputs)
def compute_loss_1_best(self,
model: WhisperForConditionalGeneration,
inputs: Dict[str, Any],
return_outputs: bool = False):
"""
Compute the loss for 1-best sequence-level distillation where `k = self.args.distillation_num_beams`.
"""
inputs_ce = inputs.copy()
inputs_ce.pop("teacher_sequences")
inputs_ce.pop("attention_mask_teacher_sequences")
loss_ce, output_student_wrt_labels = super().compute_loss(model, inputs_ce, return_outputs=True)
inputs_kd = inputs.copy()
inputs_kd["labels"] = inputs["teacher_sequences"]
inputs_kd["attention_mask"] = inputs["attention_mask_teacher_sequences"]
inputs_kd.pop("teacher_sequences")
inputs_kd.pop("attention_mask_teacher_sequences")
loss_kd = super().compute_loss(model, inputs_kd, return_outputs=False)
loss = self.args.alpha_ce * loss_ce + (1 - self.args.alpha_ce) * loss_kd
return (loss, output_student_wrt_labels) if return_outputs else loss
def compute_loss_k_best(self,
model: WhisperForConditionalGeneration,
inputs: Dict[str, Any],
return_outputs: bool = False):
"""
Compute the loss for k-best sequence-level distillation where `k = self.args.distillation_num_beams`.
If k = 1, use `compute_loss_1_best` instead.
"""
language = self.student_tokenizer.language
assert language is not None, "The `language` must be specified in the tokenizer."
# Move inputs to device:
inputs = inputs.to(self.device) # inputs.keys -> ['input_features', 'labels', 'attention_mask', 'teacher_sequences',
# 'attention_mask_teacher_sequences', 'teacher_sequences_scores']
# Get all useful features from `inputs`:
input_features = inputs["input_features"] # (batch_size, 80, 3000)
labels = inputs["labels"] # (batch_size, n_tokens_labels)
attention_mask_labels = inputs["attention_mask"] # (batch_size, n_tokens_labels)
teacher_sequences = inputs["teacher_sequences"] # (batch_size, num_beams, n_tokens_teacher_seq)
attention_mask_teacher_sequences = inputs["attention_mask_teacher_sequences"] # (batch_size, num_beams, n_tokens_teacher_seq)
teacher_sequences_scores = inputs["teacher_sequences_scores"] # (batch_size, num_beams)
# Get additional useful information for K-best KD:
batch_size = input_features.shape[0]
distillation_num_beams = self.args.distillation_num_beams
n_tokens_teacher_seq = teacher_sequences.shape[-1]
# Re-normalize scores using only the K-best sequences by applying a softmax over the beam dimension:
teacher_sequences_prob = torch.nn.functional.softmax(teacher_sequences_scores, dim=-1) # (batch_size, distillation_num_beams)
# We want to take advantage of the fact that the batch dimension and the beam dimension are indifferent to process them all at once.
# Important note: Technically, the student model should be able to process the entire batch of size `batch_size * distillation_num_beams`. If
# this is not the case, we need to reduce the batch size accordingly.
teacher_sequences = teacher_sequences.reshape(batch_size * distillation_num_beams, n_tokens_teacher_seq) # (batch_size * distillation_num_beams, n_tokens_teacher_seq)
attention_mask_teacher_sequences = attention_mask_teacher_sequences.reshape(batch_size * distillation_num_beams, n_tokens_teacher_seq) # (batch_size * distillation_num_beams, n_tokens_teacher_seq)
# ---------------------------- Cross-entropy term ----------------------------
# Forward pass through student with labels as decoder input:
student_output_wrt_labels: Seq2SeqLMOutput = model.forward(input_features=input_features,
decoder_attention_mask=attention_mask_labels,
labels=labels)
# Get the cross-entropy loss:
loss_ce = student_output_wrt_labels.loss # (1,)
# ---------------------------- Distillation term ----------------------------
# Repeat input features for the number of beams. The resulting tensor will have shape (batch_size * distillation_num_beams, dim_features).
input_features = input_features.repeat_interleave(distillation_num_beams, dim=0) # (batch_size * distillation_num_beams, 80, 3000)
# `shift_tokens_right` takes a 2D tensor as input, so we need to reshape the teacher sequences to be able to use it. This is
# also necessary to align the labels with the shape of `input_features`.
teacher_sequences_right_shifted = shift_tokens_right(teacher_sequences.reshape(batch_size * distillation_num_beams, -1),
model.config.pad_token_id,
model.config.decoder_start_token_id) # (batch_size * distillation_num_beams, n_tokens_teacher_seq)
# NOTE: In order to weight the terms in the KD loss properly, we must get the per-sequence loss instead of the total loss.
# Hence, we cannot use the `forward` loss auto-compute with the `labels` argument.
# Forward pass through student with respect to teacher sequences as decoder input:
student_output_wrt_teacher: Seq2SeqLMOutput = model.forward(input_features=input_features,
decoder_input_ids=teacher_sequences_right_shifted,
decoder_attention_mask=attention_mask_teacher_sequences)
student_logits_wrt_teacher = student_output_wrt_teacher.logits # (batch_size * distillation_num_beams, n_tokens_teacher_seq, vocab_size)
loss_fct = CrossEntropyLoss(reduction="none")
loss_wrt_teacher = loss_fct(student_logits_wrt_teacher.view(-1, model.config.vocab_size),
teacher_sequences.reshape(-1)).view(batch_size * distillation_num_beams, n_tokens_teacher_seq) # (batch_size, distillation_num_beams, n_tokens_teacher_seq)
n_tokens_per_seq = attention_mask_teacher_sequences.eq(1).sum(axis=-1, keepdim=True) # (batch_size * distillation_num_beams, 1)
loss_kd_per_sentence = torch.sum(loss_wrt_teacher / n_tokens_per_seq, axis=-1) # (batch_size * distillation_num_beams,)
loss_kd_per_sentence = loss_kd_per_sentence.view(batch_size, distillation_num_beams) # (batch_size, distillation_num_beams)
# Compute the weighted mean of the sequence log-probabilities:
# Inputs:
# - weights -> (distillation_num_beams,)
# - teacher_sequences_prob -> (batch_size, distillation_num_beams)
# - loss_kd_per_sentence -> (batch_size, distillation_num_beams)
# Output:
# - weights * teacher_sequences_prob * loss_kd_per_sentence -> (batch_size, distillation_num_beams) [broadcasting]
if self.args.use_ranking:
weights = self.get_rank_based_exp_decay_weights(K=self.args.distillation_num_beams, beta=self.args.beta_decay)
loss_kd = torch.sum(weights * teacher_sequences_prob * loss_kd_per_sentence, axis=-1) # (batch_size,)
else:
loss_kd = torch.sum(teacher_sequences_prob * loss_kd_per_sentence, axis=-1) # (batch_size,)
# Because the default cross-entropy loss is computed with reduction='mean', we need to
# also take the mean of the sequence log-probabilities to be consistent:
loss_kd = torch.mean(loss_kd,) # (1,)
# Return weighted student loss
loss = self.args.alpha_ce * loss_ce + (1. - self.args.alpha_ce) * loss_kd
return (loss, student_output_wrt_labels) if return_outputs else loss
def get_rank_based_exp_decay_weights(self, K: int, beta: float) -> torch.Tensor:
"""
Returns a tensor of shape (K,) containing the weights for the rank-based exponential decay.
"""
assert beta > 0, f"The `beta` parameter must be > 0. Got `{beta}`."
weights = torch.zeros(K).to(self.device)
for k in range(1, K + 1):
weights[k - 1] = np.exp(- beta * (k - 1))
weights /= torch.sum(weights)
return weights
|
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import './favoritos.css';
import { toast } from 'react-toastify'
function Favoritos(){
const [filmes, setFilmes] = useState([]);
useEffect(()=>{
const minhaLista = localStorage.getItem('@devflix');
setFilmes(JSON.parse(minhaLista) || []);
}, [])
function excluirFilme(id){
let filtroFimes = filmes.filter((item) => {
return(item.id !== id)
})
setFilmes(filtroFimes)
localStorage.setItem('@devflix', JSON.stringify(filtroFimes))
toast.success('Filme excluido com sucesso')
}
return(
<div className='meusFilmes'>
<h1>Meus Filmes</h1>
{filmes.length === 0 && <span>Você não possui nenhum filme salvo :(</span>}
<ul>
{filmes.map((item)=>{
return(
<li key={item.id}>
<img src={`https://image.tmdb.org/t/p/original/${item.backdrop_path}`} alt={item.title}/>
<span>{item.title}</span>
<div>
<Link to={`/filme/${item.id}`}>Ver Detalhes</Link>
<button onClick={() => excluirFilme(item.id)}>Excluir</button>
</div>
</li>
);
})}
</ul>
</div>
);
}
export default Favoritos;
|
(function () {
// form
const form = document.getElementById('noteForm');
// main fields
const name = document.getElementById('name');
const poster = document.getElementById('poster');
const genre = document.getElementById('genre');
const producer = document.getElementById('producer');
const description = document.getElementById('description');
const date = document.getElementById('date');
function isGenreSelected() {
let count = genre.querySelectorAll("input:checked").length;
return count > 0;
}
function getSelectedGenresIDs() {
let selected = genre.querySelectorAll("input:checked")
let IDs = [];
for (let i = 0; i < selected.length; i++) {
IDs.push(selected[i].id);
}
return IDs;
}
function createNote() {
let note = new {
name: name,
poster: poster,
genre: getSelectedGenresIDs(),
date: date.value,
producer: producer,
description: description
}
}
function isFieldsFilled() {
return name.value.length > 0
&& poster.value.length > 0
&& producer.value.length > 0
&& description.value.length > 0
&& isGenreSelected()
&& poster.value !== "";
}
function isCorrectName() {
return name.value.length >= 5 && name.value.length <= 50;
}
function isCorrectDescription() {
return description.value.length >= 20 && description.value.length <= 5000;
}
function isCorrectProducer() {
return producer.value.length >= 5 && producer.value.length <= 50;
}
function isCorrectDate() {
let temp = date.value.split("-");
let year = 1 * temp[0];
let month = 1 * temp[1];
return month >= 0
&& month <= 12
&& year >= 1800
&& year <= new Date().getFullYear();
}
function isCorrectPoster() {
let files = poster.files;
if (files.length > 1) {
return false;
}
let file = files[0];
let name = file.name;
let re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(name)) {
return false;
}
if (file.size > 500000) {
return false;
}
const image = createImageBitmap(file);
return image.height === 600 && image.width === 400;
}
function isCorrectFormData() {
return isCorrectName()
&& isCorrectDate()
&& isCorrectDescription()
&& isCorrectPoster()
&& isCorrectProducer();
}
function validNoteForm() {
if (!isFieldsFilled()) {
alert("все поля должны быть заполнены")
return false;
}
if (!isCorrectFormData()) {
alert("проверьте введенные вами данные")
return false;
}
//TODO: check if this name is used DB!!!
return true;
}
function doPostRequest(url = '', data = {}) {
let response = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// credentials: 'include',
body: JSON.stringify(data),
});
return response.status;
}
function formHandler(e) {
e.preventDefault();
e.stopImmediatePropagation();
let isValid = validNoteForm();
if (!isValid) {
return;
}
let note = createNote();
//TODO: connect to server
let status = doPostRequest("", note);
if (status === 200) {
//TODO: show message that operation successful AND redirect back
}
else {
alert("произошла ошибка при добавлении записи");
}
}
function synchronizeGenres(e) {
}
document.addEventListener('load', synchronizeGenres);
form.addEventListener('submit', formHandler);
})()
|
import React, { useEffect, useState } from "react";
import gsap from "gsap";
export default function () {
const [images, setImages] = useState(null)
useEffect(() => {
getImages()
}, [])
const getImages = async () => {
try {
const response = await fetch('/api/images')
if (response.ok) {
const jsonResponse = await response.json()
setImages(jsonResponse.images)
}
} catch (err) {
console.error(err.message)
}
}
const imageEl = images?.map(el => (
<img src={el.image} key={el.id} alt="page image" className="slider-image" />
))
const buttonsSliderEl = images?.map(el => (
<button disabled="disabled" key={el.id} className='slider-button'></button>
))
// SLIDER IMAGE
const [length, setLength] = useState(0)
useEffect(() => {
if (!imageEl) return
setLength(imageEl.length)
}, [imageEl])
const [index, setIndex] = useState(0)
const changeIndex = () => setIndex(prevIndex => {
if (prevIndex === length - 1) return prevIndex = 0
else return prevIndex + 1
})
useEffect(() => {
const idInterval = setInterval(changeIndex, 5000)
return () => clearInterval(idInterval)
}, [length])
const clearDisplayAttr = (arrEl) => {
return arrEl.forEach(el => el.removeAttribute('display'))
}
const changeDisplayAttr = (arrEl, index) => {
if (!arrEl.length) return
clearDisplayAttr(arrEl)
arrEl[index].toggleAttribute('display')
}
useEffect(() => {
const sliderImages = document?.querySelectorAll('.slider-image')
const sliderButtons = document?.querySelectorAll('.slider-button')
changeDisplayAttr(sliderImages, index)
changeDisplayAttr(sliderButtons, index)
}, [index, imageEl])
// animation
useEffect(() => {
const sliderContainer = document.querySelector('.slider-container')
const sliderTextContainer = document.querySelector('.slider-text-container')
const tl = gsap.timeline({ defaults: { ease: 'power2.out', delay: .5 } })
tl.from(sliderContainer, { y: 30, opacity: 0, duration: 1 })
tl.from(sliderTextContainer.children, { y: 30, opacity: 0, duration: 1, stagger: 0.10 }, '-=1')
}, [])
return (
<div className="sign-slider-image-container">
<div className="slider-container">
{images && imageEl}
</div>
<div className="slider-text-container">
<h2>Unparalleled Templates</h2>
<p>Crafted by a team of professional designers, our templates are eunparalleled in the market</p>
<div className="slider-button-container">
{images && buttonsSliderEl}
</div>
</div>
</div>
)
}
|
#ifndef _include_guard_nightmareci_utf8_c_
#define _include_guard_nightmareci_utf8_c_
#include <stdint.h>
/**
* Decode a Unicode codepoint from a UTF-8-encoded string.
*
* \param codepoint a pointer receiving the decoded codepoint or NULL if the
* decoded data isn't desired
* \param str the start of the UTF-8 data to decode
* \returns the number of UTF-8-encoded bytes representing the codepoint or -1
* if errors were encountered during decoding
*/
int utf8_decode(uint32_t* codepoint, const char* const str);
/**
* Encode a Unicode codepoint to a UTF-8-encoded string.
*
* This could also be used just to get the number of bytes a codepoint needs
* (str == NULL), allocate that much memory, then call again to store the bytes
* (str != NULL).
*
* \param str the location where the UTF-8-encoded codepoint will be written or
* NULL if the encoded data isn't desired
* \param codepoint the codepoint to encode
* \param str_end the end of the buffer after str, the buffer being where
* UTF-8-encoded data can be written. If str == NULL, this
* parameter must be NULL.
* \returns the number of UTF-8-encoded bytes representing the codepoint or -1
* if errors were encountered during encoding
*/
int utf8_encode(char* const str, const uint32_t codepoint, char* const str_end);
#endif
|
import { BrowserModule } from '@angular/platform-browser';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ClockListComponent } from './shared/clock-list/clock-list.component';
import { ClockComponent } from './shared/clock/clock.component';
import { SelectorComponent } from './shared/selector/selector.component';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { reducers, metaReducers } from './core/ngrxState/mainAppReducers';
import { HttpClientModule } from '@angular/common/http';
import { CoreModule } from './core/core.module';
import { NZ_I18N } from 'ng-zorro-antd/i18n';
import { en_US } from 'ng-zorro-antd/i18n';
import { registerLocaleData } from '@angular/common';
import en from '@angular/common/locales/en';
import { AnalogClockComponent } from './shared/analog-clock/analog-clock.component';
import { NgZorroAntdModule } from 'ng-zorro-antd';
import { DigitalClockComponent } from './shared/digital-clock/digital-clock.component';
import { DigitalDisplayPipe } from './shared/pipes/digitalDisplayPipe/digital-display.pipe';
import { NzSelectModule } from 'ng-zorro-antd/select';
registerLocaleData(en);
@NgModule({
declarations: [
AppComponent,
ClockListComponent,
ClockComponent,
SelectorComponent,
AnalogClockComponent,
DigitalClockComponent,
DigitalDisplayPipe,
],
imports: [
NzSelectModule,
NgZorroAntdModule,
ReactiveFormsModule,
BrowserModule,
BrowserAnimationsModule,
EffectsModule.forRoot([]),
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
StoreModule.forRoot(reducers, { metaReducers }),
FormsModule,
CoreModule
],
providers: [{ provide: NZ_I18N, useValue: en_US }],
bootstrap: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
|
<?php
namespace herams\console\migrations;
use yii\db\Migration;
/**
* Handles the creation of table `{{%access_request}}`.
*/
class M230804162221CreateAccessRequestTable extends Migration
{
public function safeUp()
{
$this->createTable(
'{{%access_request}}',
[
'id' => $this->primaryKey(),
'target_class' => $this->string()->notNull(),
'target_id' => $this->integer()->notNull(),
'subject' => $this->string(),
'body' => $this->text(),
'permissions' => $this->json(),
'accepted' => $this->boolean(),
'response' => $this->text(),
'created_by' => $this->integer(),
'responded_by' => $this->integer(),
'responded_at' => $this->dateTime(),
'expires_at' => $this->dateTime(),
]
);
$this->createIndex(
'fk-access_request-created_by-user-id',
'{{%access_request}}',
['created_by']
);
$this->createIndex(
'i-access_request-target_class-target_id',
'{{%access_request}}',
['target_class', 'target_id']
);
$this->addForeignKey(
'fk-access_request-responded_by-user-id',
'{{%access_request}}',
['responded_by'],
'{{%user}}',
['id'],
'SET NULL',
'CASCADE'
);
}
public function safeDown()
{
$this->dropForeignKey('fk-access_request-responded_by-user-id', '{{%access_request}}');
$this->dropTable('{{%access_request}}');
}
}
|
package io.musicorum.mobile.views.settings
import android.content.Intent
import android.os.Bundle
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Error
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.graphics.drawable.toBitmap
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.viewModel
import io.musicorum.mobile.R
import io.musicorum.mobile.components.MusicorumTopBar
import io.musicorum.mobile.services.NotificationListener
import io.musicorum.mobile.ui.theme.ContentSecondary
import io.musicorum.mobile.ui.theme.EvenLighterGray
import io.musicorum.mobile.ui.theme.LighterGray
import io.musicorum.mobile.ui.theme.MostlyRed
import io.musicorum.mobile.ui.theme.Success
import io.musicorum.mobile.ui.theme.Typography
import io.musicorum.mobile.viewmodels.ScrobbleSettingsVm
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScrobbleSettings(vm: ScrobbleSettingsVm = viewModel()) {
val appBarState = rememberTopAppBarState(initialContentOffset = 700f)
val appBarBehavior = TopAppBarDefaults.pinnedScrollBehavior(state = appBarState)
val ctx = LocalContext.current
val styledSwitch =
SwitchDefaults.colors(
checkedTrackColor = MostlyRed,
uncheckedThumbColor = ContentSecondary,
uncheckedTrackColor = LighterGray,
uncheckedBorderColor = EvenLighterGray
)
val lifecycle = LocalLifecycleOwner.current
val scrobblePoint = vm.scrobblePoint.observeAsState(50f).value
val enabled = vm.isEnabled.observeAsState(false).value
val updatesNowPlaying = vm.updateNowPlaying.observeAsState(false).value
val mediaApps = vm.availableApps.observeAsState(emptyList()).value
val enabledPackageSet = vm.enabledPackageSet.observeAsState(emptySet()).value
val showSpotifyModal = vm.showSpotifyModal.observeAsState(false)
val hasPermission = vm.hasPermission.observeAsState(false).value
val notificationIntent =
Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS").apply {
val app = "${ctx.packageName}/${NotificationListener::class.java.name}"
val fragmentKey = ":settings:fragment_args_key"
val showFragmentKey = ":settings:show_fragment_args"
putExtra(fragmentKey, app)
putExtra(showFragmentKey, Bundle().apply { putString(fragmentKey, app) })
}
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
vm.checkNotificationPermission()
}
}
lifecycle.lifecycle.addObserver(observer)
onDispose { lifecycle.lifecycle.removeObserver(observer) }
}
LaunchedEffect(Unit) {
vm.checkNotificationPermission()
}
if (showSpotifyModal.value) {
SpotifyModal(
onDismiss = { vm.showSpotifyModal.value = false },
onEnable = { vm.enableSpotify() })
}
Scaffold(topBar = {
MusicorumTopBar(
text = "Scrobble Settings",
scrollBehavior = appBarBehavior,
fadeable = false
) {}
}) { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
.padding(horizontal = 20.dp)
.verticalScroll(rememberScrollState())
) {
Item(
stringResource(R.string.enable_scrobbling),
stringResource(R.string.device_scrobbling_description)
) {
Switch(
checked = enabled ?: false,
onCheckedChange = { vm.updateScrobbling(it) },
colors = styledSwitch
)
}
Item(
stringResource(R.string.notification_access),
stringResource(R.string.notification_permission_help_text),
intent = notificationIntent
) {
if (hasPermission == true) {
Icon(Icons.Rounded.Check, null, tint = Success)
} else Icon(Icons.Rounded.Error, null, tint = Color.Red)
}
Item(
stringResource(R.string.update_now_playing),
stringResource(R.string.update_now_playing_description)
) {
Switch(
checked = updatesNowPlaying ?: false,
onCheckedChange = { vm.updateNowPlaying(it) },
colors = styledSwitch
)
}
Column {
Item(
stringResource(R.string.scrobble_point),
stringResource(R.string.scrobble_point_description)
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text("30%", style = Typography.bodySmall, modifier = Modifier.alpha(.55f))
Text("90%", style = Typography.bodySmall, modifier = Modifier.alpha(.55f))
}
Slider(
value = scrobblePoint,
onValueChange = { vm.scrobblePoint.value = it },
valueRange = 30f..90f,
steps = 15,
onValueChangeFinished = { vm.updateScrobblePoint() }
)
}
SectionTitle(sectionName = stringResource(R.string.media_apps), padding = false)
Text(
text = stringResource(R.string.media_apps_description),
style = Typography.bodySmall,
modifier = Modifier.alpha(.55f)
)
mediaApps.forEach { app ->
ListItem(
headlineContent = { Text(text = app.displayName) },
leadingContent = {
Image(
app.logo.toBitmap().asImageBitmap(),
null,
modifier = Modifier.size(30.dp)
)
},
trailingContent = {
Switch(
checked = app.packageName in (enabledPackageSet ?: emptyList()),
onCheckedChange = { vm.updateMediaApp(app.packageName, it) },
colors = styledSwitch
)
}
)
}
}
}
}
@Composable
fun Item(
primaryText: String,
supportingText: String? = null,
intent: Intent? = null,
trail: (@Composable () -> Unit)? = null,
) {
val ctx = LocalContext.current
val source = remember { MutableInteractionSource() }
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp)
.then(
if (intent != null) {
Modifier.clickable(
enabled = true,
indication = null,
interactionSource = source
) { ctx.startActivity(intent) }
} else Modifier
)
) {
Column {
Text(primaryText, style = Typography.bodyLarge)
supportingText?.let {
Text(
it,
style = Typography.bodySmall,
modifier = Modifier
.alpha(.55f)
.widthIn(0.dp, if (trail == null) 400.dp else 270.dp)
)
}
}
trail?.let {
it()
}
}
}
@Composable
fun SpotifyModal(onEnable: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
icon = { Image(painterResource(R.drawable.spotify_icon), null) },
title = { Text(stringResource(R.string.enable_scrobbling_for_spotify)) },
text = { Text(stringResource(R.string.spotify_scrobble_description)) },
dismissButton = {
TextButton(onClick = { onDismiss() }) {
Text(stringResource(R.string.dismiss))
}
},
confirmButton = {
TextButton(onClick = {
onDismiss()
onEnable()
}) {
Text(stringResource(R.string.enable))
}
},
containerColor = LighterGray
)
}
|
<template>
<div>
<table>
<thead>
<tr>
<td>考点</td>
<td>编号</td>
<td>教程页面</td>
<td>历年真题</td>
</tr>
</thead>
<tbody >
<tr v-for=" (item, index) in data.items" >
<td><a :href="item.path">{{ item.title }}</a></td>
<td>{{ item.frontmatter.No }}</td>
<td>{{ item.frontmatter.page }}</td>
<td>{{ item.frontmatter.test }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
data: {
items:[]
}
}
},
props: ['tag'],
created: function () {
this.show();
},
computed: {
pages () {
const pages = [];
if (this.tag) {
this.$site.pages.forEach(item => {
if (item.frontmatter.tags) {
let tags = item.frontmatter.tags.split("|");
if (tags.indexOf(this.tag) >= 0) {
pages.push (item);
}
}
});
}
return pages;
},
},
methods: {
show() {
this.data.items = this.pages;
}
}
}
</script>
|
import React, { useContext } from "react";
import { Link, NavLink } from "react-router-dom";
import { Button, Divider, Grid, Header, Icon, Segment } from "semantic-ui-react";
import { deleteToDo, getToDo, postToDo } from "../api/api";
import { ToDoContext } from "./ToDoProvider";
export default function ToDoList() {
const {tasks, setTasks, setMessage} = useContext(ToDoContext);
function handleDelete(id: number) {
deleteToDo(id);
setTasks(tasks.filter(t => t.Id !== id));
setMessage({
success: true,
header: 'Success',
content: 'Task successsfully deleted'
});
}
function toggleActive(id: number) {
const task = getToDo(id);
if (task) {
task.Edited = new Date();
task.Active = !task.Active;
postToDo(task);
setMessage({
success: true,
header: 'Success',
content: 'Task successsfully edited'
});
}
}
return (
<>
<Header as='h2' textAlign='center' > List of tasks</Header>
{tasks.length > 0 && tasks.map( task => (
<Segment key={task.Id}>
<Header>{task.Content}</Header>
<Grid>
<Grid.Column floated='left' mobile={16} tablet={8} computer={8}>
<Button size='mini' type='button' onClick={() => toggleActive(task.Id)} color={task.Active ? 'orange' : 'teal'}>{task.Active ? 'Active' : 'Already done'}</Button>
{task.Created < task.Edited ?
<p>Edited: {task.Edited.toLocaleDateString()} at {task.Edited.toLocaleTimeString()}</p>
: <p>Created: {task.Created.toLocaleDateString()} at {task.Created.toLocaleTimeString()}</p>}
</Grid.Column>
<Grid.Column floated='right' mobile={16} tablet={7} computer={7}>
<div className='ui two buttons'>
<Button color='green' as={Link} to={`/edittodo/${task.Id}`}>Edit</Button>
<Button color='orange' onClick={()=>handleDelete(task.Id)}>Delete</Button>
</div>
</Grid.Column>
</Grid>
</Segment>
))}
<Divider horizontal>
<Header as='h4'>
<Icon name='edit outline' />
New Task
</Header>
</Divider>
<Button as={NavLink} to='/newtodo' positive content='Create Task'/>
</>
)
}
|
package com.atguigu.app.dws;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.CartAddUuBean;
import com.atguigu.utils.ClickHouseUtil;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.MyKafkaUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import java.time.Duration;
/**
* @author: shade
* @date: 2022/7/27 20:31
* @description:
*/
public class DwsTradeCartAddUuWindow {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
//TODO 读取kafka加购topic,转为json对象
DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtils.getFlinkKafkaConsumer("dwd_trade_cart_add", "DwsTradeCartAddUuWindow"));
SingleOutputStreamOperator<JSONObject> jsonDS = kafkaDS.map(new MapFunction<String, JSONObject>() {
@Override
public JSONObject map(String value) throws Exception {
return JSON.parseObject(value);
}
});
//TODO 添加watermark
SingleOutputStreamOperator<JSONObject> jsonWithWMDS = jsonDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
.withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
@Override
public long extractTimestamp(JSONObject element, long recordTimestamp) {
String create_time = element.getString("create_time");
String operate_time = element.getString("operate_time");
if (operate_time == null) {
return DateFormatUtil.toTs(create_time, true);
} else {
return DateFormatUtil.toTs(operate_time, true);
}
}
}));
//TODO keyby
KeyedStream<JSONObject, String> keybyDS = jsonWithWMDS.keyBy(json -> json.getString("user_id"));
//TODO 状态编程,并转为javabean
SingleOutputStreamOperator<CartAddUuBean> processDS = keybyDS.process(new KeyedProcessFunction<String, JSONObject, CartAddUuBean>() {
ValueState<String> lastState;
@Override
public void open(Configuration parameters) throws Exception {
ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("lastState", String.class);
stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1)).build());
lastState = getRuntimeContext().getState(stateDescriptor);
}
@Override
public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, CartAddUuBean>.Context ctx, Collector<CartAddUuBean> out) throws Exception {
String lastdt = lastState.value();
String curdt = "";
String create_time = value.getString("create_time");
String operate_time = value.getString("operate_time");
if (operate_time == null) {
curdt = create_time.split(" ")[0];
} else {
curdt = operate_time.split(" ")[0];
}
if (lastdt == null || !lastdt.equals(curdt)) {
lastState.update(curdt);
out.collect(new CartAddUuBean("", "", 1L, 0L));
}
}
});
//TODO 聚合
SingleOutputStreamOperator<CartAddUuBean> reduceDS = processDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
.reduce(new ReduceFunction<CartAddUuBean>() {
@Override
public CartAddUuBean reduce(CartAddUuBean value1, CartAddUuBean value2) throws Exception {
value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
return value1;
}
}, new AllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
@Override
public void apply(TimeWindow window, Iterable<CartAddUuBean> values, Collector<CartAddUuBean> out) throws Exception {
CartAddUuBean next = values.iterator().next();
next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
next.setTs(System.currentTimeMillis());
out.collect(next);
}
});
//TODO 写到clickhouse
reduceDS.print();
reduceDS.addSink(ClickHouseUtil.getJdbcSink("insert into dws_trade_cart_add_uu_window values(?,?,?,?)"));
//TODO 启动
env.execute();
}
}
|
"Represents an Untappd Beer Search Result"
type UntappdProductSearchResult {
beers: UntappdSearchResultBeers,
breweries: UntappdSearchResultBreweries,
brewery_id: Int,
found: Int,
limit: Int,
offset: Int,
message: String,
parsed_term: String,
search_type: String,
search_version: Float,
term: String,
time_taken: Float,
type_id: Int
}
"Represents an Untappd Beer Search Resultset"
type UntappdSearchResultBeers {
count: Int
items: [UntappdSearchResultBeer]
}
"Represents an Untappd Beer Search Result"
type UntappdSearchResultBeer {
checkin_count: Int
beer: UntappdBeer
brewery: UntappdBrewery
}
"Represents an Untappd Beer"
type UntappdBeer {
auth_rating: Float
bid: Int
beer_abv: Float
beer_active: Boolean
beer_description: String
beer_ibu: Float
beer_label: String
beer_label_hd: String
beer_name: String
beer_slug: String
beer_style: String
brewery: UntappdBrewery
# checkins: UntappdBeerCheckinResponse
created_at: String # DateTime # comes back like 'Fri, 13 May 2011 19:35:42 +0000'
in_production: Boolean
is_homebrew: Boolean
is_in_production: Boolean # ooph... Untappd
# media: UntappdBeerMediaResponse
rating_count: Int
rating_score: Float
# similar: UntappdBeerSimilarResponse
# stats: UntappdBeerStatsResponse
weighted_rating_score: Float
# vintags: UntappdBeerVintageResponse
}
extend type Query {
"Returns the results of an Untappd Product Search"
untappdProducts(
q: String,
"""
Page offset, where page size defined by limit
"""
offset: Int = 0,
"""
Max: 50
Default: 25
"""
limit: Int = 25
# sort does not seem to be implemented, despite the Untappd docs
# """
# By default, results are sorted by ... name?
# Set this to sort by one of the other allowed fields
# """
# sort: UntappdSortByField = beginsAt
): UntappdProductSearchResult
"Returns an Untappd Product by Id"
untappdProduct(untappdBeerId: Int): UntappdBeer
}
|
import { app, BrowserWindow } from "electron";
import log from "electron-log";
import { autoUpdater } from "electron-updater";
import { startDiscordRPC } from "./discord";
import loadFlashPlugin from "./flash-loader";
import startMenu from "./menu";
import { getUrlFromCommandLine, PROTOCOL, replaceProtocolToDomain } from "./protocol";
import createStore from "./store";
import createWindow from "./window";
log.initialize();
console.log = log.log;
if (!app.requestSingleInstanceLock()) {
app.quit();
process.exit(0);
}
const store = createStore();
if (process.platform === 'linux') {
app.commandLine.appendSwitch('no-sandbox');
}
loadFlashPlugin(app);
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
autoUpdater.checkForUpdatesAndNotify();
let mainWindow: BrowserWindow;
// Someone tried to run a second instance, we should focus our window.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.on("second-instance", (_, commandLine, ___) => {
if (!mainWindow) {
return;
}
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.focus();
const url = getUrlFromCommandLine(commandLine);
mainWindow.loadURL(url);
});
app.on('ready', async () => {
mainWindow = await createWindow(store);
// Some users was reporting problems with cache.
await mainWindow.webContents.session.clearHostResolverCache();
startMenu(store, mainWindow);
startDiscordRPC(store, mainWindow);
mainWindow.on('closed', () => {
mainWindow = null;
});
});
// Handle the protocol on MacOS.
app.on('open-url', (event, url) => {
event.preventDefault();
mainWindow.loadURL(replaceProtocolToDomain(url));
});
app.setAsDefaultProtocolClient(PROTOCOL);
app.on('window-all-closed', async () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
const discordClient = store.private.get('discordState')?.client;
if (discordClient) {
await discordClient.destroy();
}
app.quit();
process.exit(0);
}
});
app.on('activate', async () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
mainWindow = await createWindow(store);
}
});
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const calc_1 = require("./calc");
const app = (0, express_1.default)();
app.get("/ping", (_req, res) => {
res.send("pong");
});
app.post("/calculate", (req, res) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { value1, value2, op } = req.body;
if (!value1 || isNaN(Number(value1))) {
return res.status(400).send({ error: "..." });
}
const result = (0, calc_1.calculator)(Number(value1), Number(value2), op);
return res.send({ result });
});
const PORT = 3003;
app.listen(PORT, () => {
console.log(`Server running on ${PORT}`);
});
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Lossy.ScriptableObjects.Config
{
[CreateAssetMenu(fileName = "CreditsConfig", menuName = "Configs/CreditsConfigScriptableObject",
order = 1)]
public class CreditsConfigScriptableObject : ScriptableObject
{
[SerializeField] private List<CreditPair> _creditPairs;
public IReadOnlyList<CreditPair> CreditPairs => _creditPairs;
}
[Serializable]
public class CreditPair
{
public CreditsJobTitle JobTitle;
public string CreditName;
}
public enum CreditsJobTitle
{
Community = 1,
Production = 2,
GameDesign = 3,
Programming = 4,
QualityAssurance = 5,
ArtDirection = 6,
CharacterArt = 7,
TechnicalArt = 8,
VisualEffects = 9,
Rigging = 10,
UserInterfaceOrExperience = 11,
Animation = 12,
Marketing = 13,
Audio = 14,
VoiceActing = 15,
AlacrityArthouse = 16,
VideoProduction = 17,
AdditionalArtDevelopment = 18,
Cinematics = 19,
MusicCredits = 20,
Platform = 21,
DataPlatforms = 22,
Publishing = 23,
LiveGameOps = 24,
CustomerSupport = 25,
HumanResources = 26,
Localization = 27,
CreativeServices = 28,
MarketingCommunications = 29,
IT = 30,
OfficeServices = 31,
CEO = 32,
}
}
|
<?php
namespace jeannick\phpmvc\db;
use jeannick\phpmvc\Application;
use jeannick\phpmvc\Model;
abstract class DbModel extends Model
{
abstract public function tableName(): string;
abstract public function attributes(): array;
abstract public function primaryKey(): string;
public function save()
{
$tableName = $this->tableName();
$attributes = $this->attributes();
$params = array_map(function ($attr) {
return ":$attr";
}, $attributes);
$statement = self::prepare("INSERT INTO $tableName (".implode(',', $attributes).")
VALUES (".implode(',', $params).")");
foreach ($attributes as $attribute){
$statement->bindValue(":$attribute", $this->{$attribute});
}
$statement->execute();
return true;
}
public function findOne($where) //[email => [email protected], firstname => Jeannick]
{
$tableName = static::tableName();
$attributes = array_keys($where);
// $sql = implode("AND",array_map(fn($attr) => "$attr = :$attr", $attributes));
$sql = implode ("AND",array_map(function ($attr) {
return "$attr = :$attr";
}, $attributes));
//$sql = implode("AND",array_map(function($attr){ return ":$attr";}, $attributes));
$statement = self::prepare("SELECT * FROM $tableName WHERE $sql");
foreach ($where as $key => $item){
$statement->bindValue(":$key",$item);
}
$statement->execute();
return $statement->fetchObject(static::class);
}
public static function prepare($sql)
{
return Application::$app->db->pdo->prepare($sql);
}
}
|
import { EventEmitter, Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { Ingredients } from '../shared/ingredient.model';
@Injectable({
providedIn: 'root',
})
export class ShoppingListService {
ingredientsChanged = new Subject<Ingredients[]>();
private ingredients: Ingredients[] = [
new Ingredients('Apples', 5),
new Ingredients('Tomatoes', 10),
];
constructor() {}
addIngredient(ingredient: Ingredients) {
this.ingredients.push(ingredient);
this.ingredientsChanged.next(this.ingredients.slice());
}
addIngredients(ingredients: Ingredients[]) {
this.ingredients.push(...ingredients);
this.ingredientsChanged.next(this.ingredients.slice());
}
getIngredients() {
return this.ingredients.slice();
}
}
|
"""
Vector geometry conversion
A great deal of geospatial data is available not in gridded form, but in
vectorized form: as points, lines, and polygons. In the Python data ecosystem,
these geometries and their associated data are generally represented by a
geopandas GeoDataFrame.
Xugrid provides a number of utilities to use such data in combination with
unstructured grids. These are demonstrated below.
"""
# %%
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
import xugrid as xu
# %%
# We'll once again use the surface elevation data example.
uda = xu.data.elevation_nl()
uda.ugrid.plot(vmin=-20, vmax=90, cmap="terrain")
# %%
# Conversion to GeoDataFrame
# --------------------------
#
# A UgridDataArray or UgridDataset can be directly converted to a GeoDataFrame,
# provided it only contains a spatial dimension (and not a dimension such as
# time). When calling
# ``.to_geodataframe``, a shapely Polygon is created for every face (cell).
gdf = uda.ugrid.to_geodataframe()
print(gdf)
# %%
# We see that a GeoDataFrame with 5248 rows is created: one row for each face.
#
# Conversion from GeoDataFrame
# ----------------------------
#
# We can also make the opposite conversion: we can create a UgridDataSet from a
# GeoDataFrame.
#
back = xu.UgridDataset.from_geodataframe(gdf)
back
# %%
# .. note::
# Not every GeoDataFrame can be converted to a ``xugrid`` representation!
# While an unstructured grid topology is generally always a valid collection
# of polygon geometries, not every collection of polygon geometries is a
# valid grid: polygons should be convex and non-overlapping to create a valid
# unstructured grid.
#
# Secondly, each polygon fully owns its vertices (nodes), while the face of a
# UGRID topology shares its nodes with its neighbors. All the vertices of the
# polygons must therefore be exactly snapped together to form a connected
# mesh.
#
# Hence, the ``.from_geodataframe()`` is primarily meant to create ``xugrid``
# objects from data that were originally created as triangulation or
# unstructured grid, but that were converted to vector geometry form.
#
# "Rasterizing", or "burning" vector geometries
# ---------------------------------------------
#
# Rasterizing is a common operation when working with raster and vector data.
# While we cannot name the operation "rasterizing" when we're dealing with
# unstructured grids, there is a clearly equivalent operation where we mark
# cells that are covered or touched by a polygon.
#
# In this example, we mark the faces that are covered by a certain province.
#
# We start by re-projecting the provinces dataset to the coordinate reference
# system (CRS), from WGS84 (EPSG:4326) to the Dutch National coordinate system
# (RD New, EPSG: 28992). Then, we give each province a unique id, which we
# burn into the grid.
provinces = xu.data.provinces_nl().to_crs(28992)
provinces["id"] = range(len(provinces))
burned = xu.burn_vector_geometry(provinces, uda, column="id")
burned.ugrid.plot()
# %%
# This makes it very easy to classify and group data. Let's say
# we want to compute the average surface elevation per province:
burned = xu.burn_vector_geometry(provinces, uda, column="id")
uda.groupby(burned).mean()
# %%
# This is a convenient way to create masks for specific regions:
utrecht = provinces[provinces["name"] == "Utrecht"]
burned = xu.burn_vector_geometry(utrecht, uda)
xmin, ymin, xmax, ymax = utrecht.buffer(10_000).total_bounds
fig, ax = plt.subplots()
burned.ugrid.plot(ax=ax)
burned.ugrid.plot.line(ax=ax, edgecolor="black", linewidth=0.5)
utrecht.plot(ax=ax, edgecolor="red", facecolor="none", linewidth=1.5)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# %%
# By default, ``burn_vector_geometry`` will only include grid faces whose
# centroid are located in a polygon. We can also mark all intersected faces
# by setting ``all_touched=True``:
burned = xu.burn_vector_geometry(utrecht, uda, all_touched=True)
fig, ax = plt.subplots()
burned.ugrid.plot(ax=ax)
burned.ugrid.plot.line(ax=ax, edgecolor="black", linewidth=0.5)
utrecht.plot(ax=ax, edgecolor="red", facecolor="none", linewidth=1.5)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# %%
# We can also use such "masks" to e.g. modify specific parts of the grid data:
modified = (uda + 50.0).where(burned == 1, other=uda)
modified.ugrid.plot(vmin=-20, vmax=90, cmap="terrain")
# %%
# Note that ``all_touched=True`` is less suitable when differently valued
# polygons are present that share borders. While the centroid of a face is
# contained by only a single polygon, the area of the polygon may be located
# in more than one polygon. In this case, the results of each polygon will
# overwrite each other.
by_centroid = xu.burn_vector_geometry(provinces, uda, column="id")
by_touch = xu.burn_vector_geometry(provinces, uda, column="id", all_touched=True)
fig, axes = plt.subplots(ncols=2, figsize=(10, 5))
by_centroid.ugrid.plot(ax=axes[0], add_colorbar=False)
by_touch.ugrid.plot(ax=axes[1], add_colorbar=False)
for ax, title in zip(axes, ("centroid", "all touched")):
burned.ugrid.plot.line(ax=ax, edgecolor="black", linewidth=0.5)
utrecht.plot(ax=ax, edgecolor="red", facecolor="none", linewidth=1.5)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.set_title(title)
# %%
# This function can also be used to burn points or lines into the faces of an
# unstructured grid.
#
# The exterior boundaries of the province polygons will provide
# a collection of linestrings that we can burn into the grid:
lines = gpd.GeoDataFrame(geometry=provinces.exterior)
burned = xu.burn_vector_geometry(lines, uda)
fig, ax = plt.subplots()
burned.ugrid.plot(ax=ax)
burned.ugrid.plot.line(ax=ax, edgecolor="black", linewidth=0.5)
provinces.plot(ax=ax, edgecolor="red", facecolor="none", linewidth=1.5)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# %%
# We can also burn points.
province_centroids = gpd.GeoDataFrame(geometry=provinces.centroid)
burned = xu.burn_vector_geometry(province_centroids, uda)
fig, ax = plt.subplots()
burned.ugrid.plot(ax=ax)
provinces.plot(ax=ax, edgecolor="red", facecolor="none")
# %%
# Finally, it's also possible to combine multiple geometry types in a single
# burn operation.
combined = pd.concat([lines, province_centroids])
burned = xu.burn_vector_geometry(combined, uda)
burned.ugrid.plot()
# %%
# Polygonizing
# ------------
#
# We can also do the opposite operation: turn collections of same-valued grid
# faces into vector polygons. Let's classify the elevation data into below and
# above the boundary of 5 m above mean sea level:
classified = uda > 5
polygonized = xu.polygonize(classified)
polygonized.plot(facecolor="none")
# %%
# We see that the results consists of two large polygons, in which the
# triangles of the triangular grid have been merged to form a single polygon,
# and many smaller polygons, some of which correspond one to one to the
# triangles of the grid.
#
# .. note::
# The produced polygon edges will follow exactly the face boundaries. When
# the data consists of many unique values (e.g. unbinned elevation data), the
# result will essentially be one polygon per face. In such cases, it is more
# efficient to use ``xugrid.UgridDataArray.to_geodataframe``, which directly
# converts every face to a polygon.
#
# Snap to grid
# ------------
#
# The examples above deal with data on the faces of the grid. However, data can
# also be associated with the nodes or edges of the grid. For example, we can
# snap line data to exactly follow the edges (the face boundaries):
linestrings = gpd.GeoDataFrame(geometry=utrecht.exterior)
snapped_uds, snapped_gdf = xu.snap_to_grid(linestrings, uda, max_snap_distance=1.0)
fig, ax = plt.subplots()
snapped_gdf.plot(ax=ax)
snapped_uds.ugrid.grid.plot(ax=ax, edgecolor="gray", linewidth=0.5)
utrecht.plot(ax=ax, edgecolor="red", facecolor="none", linewidth=0.75)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# %%
# There are (arguably) many ways in which a linestring could be snapped to
# edges. The function above uses the criterion the following criterion: if a
# part of the linestring is located between the centroid of a face and the
# centroid of an edge, it is snapped to that edge.
#
# This sometimes result in less (visually) pleasing results, such as the two
# triangles in the lower left corner which are surrounded by the snapped edges.
# In general, results are best when the line segments are relatively large
# compare to the grid faces.
|
#!/usr/bin/python
# Copyright 2015 Google Inc. 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.
import flatbuf as flatbuffers
import MyGame.Sample.Color
import MyGame.Sample.Equipment
import MyGame.Sample.Monster
import MyGame.Sample.Vec3
import MyGame.Sample.Weapon
def main():
# -------------------------------------------------------------------------
bldr = flatbuffers.Builder()
with bldr.create(MyGame.Sample.Monster) as orc:
orc.add('Name', 'Orc')
sword = bldr.create(MyGame.Sample.Weapon,
{'Name': 'Sword', 'Damage': 3})
axe = bldr.create(MyGame.Sample.Weapon,
{'Name': 'Axe', 'Damage': 5})
orc.add('Weapons', [sword, axe])
orc.add('EquippedType', MyGame.Sample.Equipment.Equipment.Weapon)
orc.add('Equipped', axe)
pos = bldr.create(MyGame.Sample.Vec3, [1.0, 2.0, 3.0])
orc.add('Pos', pos)
orc.add('Hp', 300)
orc.add('Color', MyGame.Sample.Color.Color.Red)
MyGame.Sample.Monster.MonsterStartInventoryVector(bldr, 10)
for i in reversed(range(0, 10)):
bldr.PrependByte(i)
inv = bldr.EndVector(10)
orc.add('Inventory', inv)
buf = orc.output()
# -------------------------------------------------------------------------
# copy and paste from flatbuffer's tutorial
# builder = flatbuffers.Builder(0)
#
# # Create some weapons for our Monster ('Sword' and 'Axe').
# weapon_one = builder.CreateString('Sword')
# weapon_two = builder.CreateString('Axe')
#
# MyGame.Sample.Weapon.WeaponStart(builder)
# MyGame.Sample.Weapon.WeaponAddName(builder, weapon_one)
# MyGame.Sample.Weapon.WeaponAddDamage(builder, 3)
# sword = MyGame.Sample.Weapon.WeaponEnd(builder)
#
# MyGame.Sample.Weapon.WeaponStart(builder)
# MyGame.Sample.Weapon.WeaponAddName(builder, weapon_two)
# MyGame.Sample.Weapon.WeaponAddDamage(builder, 5)
# axe = MyGame.Sample.Weapon.WeaponEnd(builder)
#
# # Serialize the FlatBuffer data.
# name = builder.CreateString('Orc')
#
# MyGame.Sample.Monster.MonsterStartInventoryVector(builder, 10)
# # Note: Since we prepend the bytes, this loop iterates in reverse order.
# for i in reversed(range(0, 10)):
# builder.PrependByte(i)
# inv = builder.EndVector(10)
#
# MyGame.Sample.Monster.MonsterStartWeaponsVector(builder, 2)
# # Note: Since we prepend the data, prepend the weapons in reverse order.
# builder.PrependUOffsetTRelative(axe)
# builder.PrependUOffsetTRelative(sword)
# weapons = builder.EndVector(2)
#
# pos = MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)
#
# MyGame.Sample.Monster.MonsterStart(builder)
# MyGame.Sample.Monster.MonsterAddPos(builder, pos)
# MyGame.Sample.Monster.MonsterAddHp(builder, 300)
# MyGame.Sample.Monster.MonsterAddName(builder, name)
#
# MyGame.Sample.Monster.MonsterAddInventory(builder, inv)
#
# MyGame.Sample.Monster.MonsterAddColor(builder,
# MyGame.Sample.Color.Color().Red)
# MyGame.Sample.Monster.MonsterAddWeapons(builder, weapons)
# MyGame.Sample.Monster.MonsterAddEquippedType(
# builder, MyGame.Sample.Equipment.Equipment().Weapon)
# MyGame.Sample.Monster.MonsterAddEquipped(builder, axe)
# orc = MyGame.Sample.Monster.MonsterEnd(builder)
#
# builder.Finish(orc)
#
# # We now have a FlatBuffer that we could store on disk or send over a network.
#
# # ...Saving to file or sending over a network code goes here...
#
# # Instead, we are going to access this buffer right away (as if we just
# # received it).
# buf = builder.Output()
# Note: We use `0` for the offset here, since we got the data using the
# `builder.Output()` method. This simulates the data you would store/receive
# in your FlatBuffer. If you wanted to read from the `builder.Bytes` directly,
# you would need to pass in the offset of `builder.Head()`, as the builder
# actually constructs the buffer backwards.
monster = MyGame.Sample.Monster.Monster.GetRootAsMonster(buf, 0)
# Note: We did not set the `Mana` field explicitly, so we get a default value.
assert monster.Mana() == 150
assert monster.Hp() == 300
assert monster.Name() == 'Orc'
assert monster.Color() == MyGame.Sample.Color.Color.Red
assert monster.Pos().X() == 1.0
assert monster.Pos().Y() == 2.0
assert monster.Pos().Z() == 3.0
# Get and test the `inventory` FlatBuffer `vector`.
for i in xrange(monster.InventoryLength()):
assert monster.Inventory(i) == i, "Inventory: {} != {}".format(monster.Inventory(i), i)
# Get and test the `weapons` FlatBuffer `vector` of `table`s.
expected_weapon_names = ['Sword', 'Axe']
expected_weapon_damages = [3, 5]
for i in xrange(monster.WeaponsLength()):
assert monster.Weapons(i).Name() == expected_weapon_names[i]
assert monster.Weapons(i).Damage() == expected_weapon_damages[i]
# Get and test the `equipped` FlatBuffer `union`.
assert monster.EquippedType() == MyGame.Sample.Equipment.Equipment.Weapon
# An example of how you can appropriately convert the table depending on the
# FlatBuffer `union` type. You could add `elif` and `else` clauses to handle
# the other FlatBuffer `union` types for this field.
if monster.EquippedType() == MyGame.Sample.Equipment.Equipment.Weapon:
# `monster.Equipped()` returns a `flatbuffers.Table`, which can be used
# to initialize a `MyGame.Sample.Weapon.Weapon()`, in this case.
union_weapon = MyGame.Sample.Weapon.Weapon()
union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos)
assert union_weapon.Name() == "Axe"
assert union_weapon.Damage() == 5
print 'The FlatBuffer was successfully created and verified!'
if __name__ == '__main__':
main()
|
# Toolbar
**Toolbars display information and actions related to the context.**
<DemoBlock demo="default" />
## Anatomy
A toolbar has three sections. An optional contextual icon button and a title on the left, contextual actions on the right.
<img width="100%" src="assets/anatomy.png" />
## Examples
### Dialog toolbar
<DemoBlock demo="dialog" />
### Media picker toolbar
<DemoBlock demo="media-picker" />
### Contextual icon button
<DemoBlock demo="back" />
### File list widget
<DemoBlock demo="file-widget" />
### Accessibility concerns
Toolbars are simple layout blocks without any particular semantic or ARIA role.
### Properties
<PropTable component="Toolbar" />
|
import React from "react";
import { Link, useNavigate } from "react-router-dom";
import styles from "./CategoryItem.module.scss";
function CategoryItem({ category }) {
const { imageUrl, title, route } = category;
const navigate = useNavigate();
function onNavigateHandler() {
navigate(route);
}
return (
<div className={styles["category-container"]} onClick={onNavigateHandler}>
<div
className={styles["background-image"]}
style={{ backgroundImage: `url(${imageUrl})` }}
/>
<div className={styles["category-body-container"]}>
<h2>{title}</h2>
<p>Shop Now</p>
</div>
</div>
);
}
export default CategoryItem;
|
import {
Modal,
ModalOverlay,
ModalContent,
ModalBody,
Button,
Flex,
Text,
useDisclosure,
} from "@chakra-ui/react";
import { FaTimes } from "react-icons/fa";
interface Props {
buttonText: string;
title: string;
children: React.ReactNode;
}
const ModalWrapper: React.FC<Props> = ({ buttonText, title, children }) => {
const { isOpen, onOpen, onClose } = useDisclosure();
return (
<>
<Button variant="green" onClick={onOpen}>
{buttonText}
</Button>
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent maxW={900} w="100%" borderTopRadius="lg">
<Flex
bg="emerald"
borderTopRadius="md"
justifyContent="space-between"
alignItems="center"
px={6}
py={4}
>
<Text fontSize="3xl" color="white">
{title}
</Text>
<Button
bg="emerald"
border="none"
color="white"
size="xl"
_hover={{ bg: "emerald" }}
onClick={onClose}
>
<FaTimes size={30} />
</Button>
</Flex>
<ModalBody>{children}</ModalBody>
</ModalContent>
</Modal>
</>
);
};
export default ModalWrapper;
|
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "usuarios".
*
* @property int $id
* @property string $nombre
* @property string $apellido1
* @property string $apellido2
* @property string $email
* @property string $password
* @property string $provincia
* @property int $id_rol
* @property string $username
* @property int $id_imagen
*/
class Usuarios extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* @var string Auth key attribute
*/
public $auth_key;
/**
* @var string Registration token attribute
*/
public $reg_token;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'usuarios';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['nombre', 'apellido1', 'apellido2', 'email', 'password', 'provincia','id_rol','username','id_imagen'], 'required', 'message' => 'Este campo es obligatorio.'],
[['auth_key', 'reg_token'], 'safe'],
[['nombre', 'apellido1', 'apellido2', 'email', 'provincia','username'], 'string', 'max' => 50],
[['password'], 'string', 'max' => 255, 'min' => 6, 'tooShort' => 'Contraseña no valida.'],
// [['password'], 'match', 'pattern' => '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]*$/', 'message' => 'La contraseña debe contener al menos una letra minúscula, una letra mayúscula y un número.'],
[['email'], 'unique', 'message' => 'El correo electrónico ya está en uso. Por favor, elige otro.'],
[['email'], 'email'],
[['id_rol'], 'integer'],
[['id_imagen'], 'integer'],
[['id_imagen'], 'exist', 'skipOnError' => true, 'targetClass' => Imagenes::class, 'targetAttribute' => ['id_imagen' => 'id']],
[['username'], 'unique', 'message' => 'Nombre de usuario "{value}" ya existe. Por favor, elige otro.'],
[['auth_key'], 'string', 'max' => 200],
[['reg_token'], 'string', 'max' => 200],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'nombre' => Yii::t('app', 'Nombre'),
'apellido1' => Yii::t('app', 'Primer apellido'),
'apellido2' => Yii::t('app', 'Segundo apellido'),
'email' => Yii::t('app', 'Email'),
'password' => Yii::t('app', 'Contraseña'),
'provincia' => Yii::t('app', 'Provincia'),
'id_rol' => Yii::t('app', 'Rol'),
'username' => Yii::t('app', 'Nombre de usuario'),
'id_imagen' => Yii::t('app', 'Imagen'),
'reg_token' => Yii::t('app', 'reg_token'),
'auth_key' => Yii::t('app', 'auth_key'),
];
}
/**
* {@inheritdoc}
* @return UsuariosQuery the active query used by this AR class.
*/
public static function find()
{
return new UsuariosQuery(get_called_class());
}
private function genKey()
{
$len=200;
$key = "";
$str = str_split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
$max = count($str)-1;
for($i=0; $i<$len; $i++)
{
$key .= $str[rand(0, $max)];
}
return $key;
}
public function setAuthKey(){
$this->auth_key=$this->genKey();
}
public function setRegToken(){
$this->reg_token=$this->genKey();
}
public function setRol(){
$this->id_rol=6;
}
public function getAuthKey(){
return $this->auth_key;
}
public function getRegToken(){
return $this->reg_token;
}
public function validateAuthKey($authKey)
{
return $this->auth_key === $authKey;
}
public function validateRegToken($regToken)
{
return $this->reg_token === $regToken;
}
public static function findIdentity($id)
{
return self::find()->where(['id'=>$id])->one();
}
public static function findByEmail($email){
return self::find()->where(['email'=>$email])->one();
}
public static function getRol($id){
$usuario = self::findOne($id);
return $usuario ? $usuario->id_rol : null;
}
public static function findByUsername($username)
{
return self::findOne(['username' => $username]);
}
public function validatePassword($password)
{
if( Yii::$app->security->validatePassword($password, $this->password))
{
return true;
}
else
{
return false;
}
}
public function getId()
{
return $this->id;
}
public static function getSessionRol(){
return self::getRol(Yii::$app->user->id);
}
public static function getSessionUser(){
return self::findIdentity(Yii::$app->user->id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return self::find()->where(['auth_key'=>$token])->one()['id'];
}
public static function getNombre($id){
$usuario = self::findOne($id);
return $usuario ? $usuario->nombre : null;
}
public static function login($username, $password)
{
$usuario = self::findByUsername($username);
if ($usuario && $usuario->validatePassword($password)) {
return Yii::$app->user->login($usuario);
}
return false;
}
/**
* Gets query for [[Imagen]].
*
* @return \yii\db\ActiveQuery
*/
public function getImagen()
{
return $this->hasOne(Imagenes::class, ['id' => 'id_imagen']);
}
}
|
'use client'
import React from "react";
import {Dropdown, DropdownTrigger, DropdownMenu, DropdownItem, Button} from "@nextui-org/react";
import { Fruit } from "@prisma/client";
export default function FruitsDropDown( {fruits}:{fruits: Fruit[]} ) {
const [selectedKeys, setSelectedKeys] = React.useState(new Set(["Select Fruit"]));
const selectedValue = React.useMemo(
() => Array.from(selectedKeys).join(", ").replaceAll("_", " "),
[selectedKeys]
);
return (
<Dropdown>
<DropdownTrigger>
<Button
variant="bordered"
className="capitalize"
>
{selectedValue}
</Button>
</DropdownTrigger>
<DropdownMenu
aria-label="Single selection example"
variant="flat"
disallowEmptySelection
selectionMode="single"
selectedKeys={selectedKeys}
onSelectionChange={setSelectedKeys}
>
{fruits.map((fruit) => (
<DropdownItem key={fruit.name}>{fruit.name}</DropdownItem>
))}
</DropdownMenu>
</Dropdown>
);
}
|
import { animate, state, style, transition, trigger ,keyframes } from '@angular/animations';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-about-me',
templateUrl: './about-me.component.html',
styleUrls: ['./about-me.component.css'],
animations: [
trigger('AboutMeAanimation', [
state('void', style({
transform: 'scale(0)',
opacity: 0,
})),
state('*', style({
trasform: 'scale(1)',
opacity: 1,
})),
transition('void=>*', [animate('1000ms ease-out')])
]),
trigger('randomMovement', [
transition('* <=> *', [
animate('10s linear', keyframes([
style({ transform: 'translate3d(0, 0, 0)', offset: 0 }),
style({ transform: 'translate3d(10px, -10px, 0)', offset: 0.25 }),
style({ transform: 'translate3d(-10px, 10px, 0)', offset: 0.50 }),
style({ transform: 'translate3d(10px, 10px, 0)', offset: 0.75 }),
style({ transform: 'translate3d(0px, 0px, 0px)', offset: 1.0 })
]))
])
])
]
})
export class AboutMeComponent implements OnInit{
ngOnInit()
{
this.animate();
}
movingElementState: string = "start";
animate()
{
const toggleState = () => {
this.movingElementState = this.movingElementState === 'start' ? 'end' : 'start';
setTimeout(toggleState, 10000); // Adjust the duration to match your animation time
};
toggleState();
}
}
|
import React from 'react';
import { Task } from '../../data/Models/Task';
import styles from '../../styles/common/Task.module.scss';
import Slider from './Slider';
import TaskMini from './TaskMini';
interface Props {
task: Task
}
const Task: React.FC<Props> = ({ task }) => {
return (
<div className={styles['task-card']}>
<h1>{task.title}</h1>
<div className={styles['task-body']}>
<div className={styles.dates}>
<div className={styles['start-date']}>
Start Date: { task.startDate }
</div>
<div className={styles['end-date']}>
End Date: { task.endDate }
</div>
</div>
<div className={styles.description}>
{ task.description }
</div>
{
task.subTasks ?
<div className={styles['sub-tasks']}>
<Slider
components={
task.subTasks.map((subTask, idx) => <TaskMini task={subTask} key={idx}/>)
}
/>
</div> :
<></>
}
</div>
</div>
);
};
export default Task;
|
//
// StepperBasic.swift
// SwiftUIBasic_review
//
// Created by Joy on 2023/03/24.
//
import SwiftUI
struct StepperBasic: View {
@State var stepperValue: Int = 0
@State var widthChange: CGFloat = 0
var body: some View {
VStack{
//기본 Stepper
Stepper("기본 Stepper: \(stepperValue)", value: $stepperValue)
Divider()
RoundedRectangle(cornerRadius: 25)
.frame(width: 100 + widthChange, height: 100)
// 증가, 감소 Stepper
Stepper {
Text("직사각형 너비 변화")
} onIncrement: {
differentWidth(amount: 20)
} onDecrement: {
differentWidth(amount: -20)
}
}
.padding()
}
func differentWidth(amount: CGFloat) {
withAnimation(.easeInOut) {
widthChange += amount
}
}
}
struct StepperBasic_Previews: PreviewProvider {
static var previews: some View {
StepperBasic()
}
}
|
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import seaborn as sns
features = pd.read_csv("./features.csv")
chosen_features = ['Std Saturation', 'Hue Std', 'Contrast', 'Min Saturation', 'CIVE', 'CIVE Ratio', 'ExG-ExR Ratio']
all_features = [
"Mean Brightness", "Std Brightness", "Max Brightness", "Min Brightness",
"Hue Hist Feature 1", "Hue Hist Feature 2", "Hue Std", "Contrast",
"Mean Saturation", "Std Saturation", "Max Saturation", "Min Saturation",
"SIFT Features", "Texture Contrast", "Texture Dissimilarity",
"Texture Homogeneity", "Texture Energy", "Texture Correlation",
"Texture ASM", "Excess Green Index", "Excess Red Index", "CIVE",
"ExG-ExR Ratio", "CIVE Ratio"
]
def analyze_variance():
numeric = features.select_dtypes(include=[np.number])
scaler = MinMaxScaler()
scaled = scaler.fit_transform(numeric)
scaled_df = pd.DataFrame(scaled, columns=numeric.columns)
variances_scaled = scaled_df.var()
top_3_features_scaled = variances_scaled.sort_values(ascending=False).head(3).index.tolist()
print("top_3_features_scaled")
print(top_3_features_scaled)
print("variances: ")
print(variances_scaled.sort_values(ascending=False))
def quantile_discretization(num_of_bins):
for feature in chosen_features:
feature_ = features[feature]
sorted_features_vals = feature_.sort_values()
quantiles = np.linspace(0, 1, num_of_bins)[1:-1] # Exclude 0 and 1
# print("quantiles: ")
# print(quantiles)
split_points = sorted_features_vals.quantile(quantiles)
subintervals = pd.cut(sorted_features_vals, bins=[-np.inf] + split_points.tolist() + [np.inf], labels=False)
features[feature + ' Interval'] = subintervals
# print("Split Points:")
# print(split_points)
print("\nUpdated DataFrame with Subintervals:")
print(features[[feature, feature + ' Interval']].head(10))
features.to_csv("features.csv", index=False)
def write_image_type_preformances():
si = OracleComputation(
# Tuple of two numbers: (128, 128), (256, 256), or (512, 512)
image_resolution=(
256,
256,
),
# slim or squeeze
model_architecture="squeeze",
dataset="geok",
preformance_analysis=True,
# Do you want to generate a mask/image overlay
save_image=False,
# Was segmentation model trained using transfer learning
is_trans=True,
# Was segmentation model trained with find_best_fitting (utilising
# model that has the highest difference in iou between widths
is_best_fitting=False,
)
network1_preformances = []
network2_preformances = []
network3_preformances = []
network4_preformances = []
for index, row in features.iterrows():
path = row['Filename']
print(path)
preformances = si.infer(path)
print("preformances")
print(preformances)
# add preformances
network1_preformances.append(preformances[0.25])
network2_preformances.append(preformances[0.5])
network3_preformances.append(preformances[0.75])
network4_preformances.append(preformances[1.0])
if si.model_architecture == "squeeze":
features['ActualSqueezeNetwork1Preformance'] = pd.Series(network1_preformances)
features['ActualSqueezeNetwork2Preformance'] = pd.Series(network2_preformances)
features['ActualSqueezeNetwork3Preformance'] = pd.Series(network3_preformances)
features['ActualSqueezeNetwork4Preformance'] = pd.Series(network4_preformances)
elif si.model_architecture == "slim":
features['ActualSlimNetwork1Preformance'] = pd.Series(network1_preformances)
features['ActualSlimNetwork2Preformance'] = pd.Series(network2_preformances)
features['ActualSlimNetwork3Preformance'] = pd.Series(network3_preformances)
features['ActualSlimNetwork4Preformance'] = pd.Series(network4_preformances)
print(features.head())
save = True
if save:
features.to_csv('features.csv', index=False)
def analyze_image_type_preformances():
# group rows by Max Saturation Interval,Hue Hist Feature 2 Interval
grouped = features.groupby(['Max Saturation Interval', 'Hue Hist Feature 2 Interval', 'Mean Brightness Interval'])
for (max_sat, hue_hist, mean_bright), group in grouped:
averages = group[['ActualSlimNetwork1Preformance', 'ActualSlimNetwork2Preformance', 'ActualSlimNetwork3Preformance', 'ActualSlimNetwork4Preformance', 'ActualSqueezeNetwork1Preformance', 'ActualSqueezeNetwork2Preformance', 'ActualSqueezeNetwork3Preformance', 'ActualSqueezeNetwork4Preformance']].mean()
group_size = group.shape[0]
print(f"Group - Max Saturation: {max_sat}, Hue Hist Feature 2: {hue_hist}, Mean Brightness: {mean_bright}")
print(f"Number of rows in this group: {group_size}")
print("Averages:")
print(averages)
print("\n") # Newline for better readability
def model_usage_versus_feature(feature_name, features, save_path):
# Calculate quartiles for the feature
quartiles = np.quantile(features[feature_name], [0.25, 0.5, 0.75])
print(f'Feature name: {feature_name}')
print(f'Quartiles: {quartiles}')
# Determine the quartile for each row
conditions = [
(features[feature_name] <= quartiles[0]),
(features[feature_name] > quartiles[0]) & (features[feature_name] <= quartiles[1]),
(features[feature_name] > quartiles[1]) & (features[feature_name] <= quartiles[2]),
(features[feature_name] > quartiles[2])
]
choices = ['1st Quartile', '2nd Quartile', '3rd Quartile', '4th Quartile']
features['Quartile'] = np.select(conditions, choices)
performance_columns = [
'ActualSlimNetwork1Preformance', 'ActualSlimNetwork2Preformance',
'ActualSlimNetwork3Preformance', 'ActualSlimNetwork4Preformance',
'ActualSqueezeNetwork1Preformance', 'ActualSqueezeNetwork2Preformance',
'ActualSqueezeNetwork3Preformance', 'ActualSqueezeNetwork4Preformance'
]
# Preparing data for the plot
performance_means = {col: [] for col in performance_columns}
for quartile in choices:
quartile_data = features[features['Quartile'] == quartile]
for col in performance_columns:
if quartile_data[col].size > 0:
average_performance = quartile_data[col].mean()
performance_means[col].append(average_performance)
else:
performance_means[col].append(np.nan)
# Plotting with a larger figure size
fig, ax = plt.subplots(figsize=(12, 8))
# Calculate the width of each bar so that they all fit within the quartile grouping
n_groups = len(choices)
n_bars = len(performance_columns)
total_width = 0.8 # Total space allocated for all bars in one group
bar_width = total_width / n_bars # Individual bar width
x = np.arange(len(choices)) # The label locations
# Calculate the x offset for each bar
bar_offsets = (np.arange(n_bars) - n_bars / 2) * bar_width + bar_width / 2
for i, col in enumerate(performance_columns):
means = performance_means[col]
if not all(np.isnan(means)):
# Adjust the bar's x position based on its offset
ax.bar(x + bar_offsets[i], means, width=bar_width, label=col)
# Define the x-axis labels and their positions
ax.set_xlabel('Quartiles')
ax.set_ylabel('Average Performance')
ax.set_title(f'Average Performance per Quartile for {feature_name}')
ax.set_xticks(x)
ax.set_xticklabels(choices)
# Place the legend outside of the figure/plot
ax.legend(bbox_to_anchor=(1.1, 1.05), loc='upper left')
# Adjust layout to make room for the legend and prevent clipping of tick-labels
plt.tight_layout(rect=[0, 0, 0.75, 1]) # Adjust the right boundary of the layout
# Save the figure
plt.savefig(save_path, bbox_inches='tight') # Ensure the entire plot is saved, including the legend
# Optionally, close the plot to free up memory
plt.close(fig)
def feature_preformance_correlation(features):
# Drop non-numeric columns
numeric_features = features.select_dtypes(include=[np.number])
# Calculate correlation matrix for numeric features only
correlation_matrix = numeric_features.corr()
# Select only the columns for performance
performance_columns = ['ActualSlimNetwork1Preformance', 'ActualSlimNetwork2Preformance',
'ActualSlimNetwork3Preformance', 'ActualSlimNetwork4Preformance',
'ActualSqueezeNetwork1Preformance', 'ActualSqueezeNetwork2Preformance',
'ActualSqueezeNetwork3Preformance', 'ActualSqueezeNetwork4Preformance']
# Filter the correlation matrix to show only correlations with performance columns
performance_correlation = correlation_matrix[performance_columns].drop(performance_columns)
# Plotting the correlations
plt.figure(figsize=(12, 8))
sns.heatmap(performance_correlation, annot=True, fmt=".2f", cmap='coolwarm')
plt.title('Feature Correlation with Performance')
plt.xticks(rotation=45, ha='right')
plt.yticks(rotation=0)
plt.tight_layout()
# Save the figure
plt.savefig('./graphs/feature_correlation_with_performance.png')
# Close the plot
plt.close()
return performance_correlation
def maximum_correlation(correlation_matrix, k=3, ignore_feature='IoU Weeds'):
# Drop the ignored feature from the correlation matrix
correlation_matrix = correlation_matrix.drop(ignore_feature, axis=0, errors='ignore')
# Calculate the average correlation for Slim and Squeeze networks separately
slim_correlations = correlation_matrix.filter(regex='Slim').mean(axis=1).nlargest(k)
squeeze_correlations = correlation_matrix.filter(regex='Squeeze').mean(axis=1).nlargest(k)
return slim_correlations, squeeze_correlations
def minimum_correlation(correlation_matrix, k=3, ignore_feature='IoU Weeds'):
# Drop the ignored feature from the correlation matrix
correlation_matrix = correlation_matrix.drop(ignore_feature, axis=0, errors='ignore')
# Calculate the average correlation for Slim and Squeeze networks separately
slim_correlations = correlation_matrix.filter(regex='Slim').mean(axis=1).nsmallest(k)
squeeze_correlations = correlation_matrix.filter(regex='Squeeze').mean(axis=1).nsmallest(k)
return slim_correlations, squeeze_correlations
# quantile_discretization(4)
# analyze_image_type_preformances()
def plot_features():
for feature in chosen_features:
model_usage_versus_feature(feature, features, f'./graphs/{feature}_plot.png')
# plot_features()
def plot_max_correlation():
correlation_matrix = feature_preformance_correlation(features)
max_correlations_slim, max_correlations_squeeze = maximum_correlation(correlation_matrix, k=10)
return max_correlations_slim, max_correlations_squeeze
def plot_bar_chart(max_correlations, title, filename):
features = max_correlations.index.tolist()
values = max_correlations.values
plt.figure(figsize=(10, 6))
bars = plt.bar(features, values, color='skyblue')
plt.xlabel('Features')
plt.ylabel('Correlation')
plt.title(title)
# Rotate the x-axis labels to avoid overlapping, and optionally, make them smaller
plt.xticks(rotation=45, ha='right', fontsize=10) # ha is the horizontal alignment
# Save the plot as an image file
plt.savefig(filename, format='png', bbox_inches='tight')
# Show the plot
plt.show()
def plot_max_correlations():
max_correlations_slim, max_correlations_squeeze = plot_max_correlation()
plot_bar_chart(max_correlations_slim, 'Maximum Correlations - Slim', './graphs/max_correlations_slim.png')
plot_bar_chart(max_correlations_squeeze, 'Maximum Correlations - Squeeze', './graphs/max_correlations_squeeze.png')
# plot_max_correlations()
def plot_min_correlations():
correlation_matrix = feature_preformance_correlation(features)
min_correlations_slim, min_correlations_squeeze = minimum_correlation(correlation_matrix, k=10)
plot_bar_chart(min_correlations_slim, 'Minimum Correlations - Slim', './graphs/min_correlations_slim.png')
plot_bar_chart(min_correlations_squeeze, 'Minimum Correlations - Squeeze', './graphs/min_correlations_squeeze.png')
# plot_min_correlations()
def feature_range_versus_performance(features, chosen_features, performance_metric):
for feature in chosen_features:
plt.figure(figsize=(10, 6))
plt.scatter(features[feature], features[performance_metric], color='blue')
plt.title(f'{feature} vs {performance_metric}')
plt.xlabel(feature)
plt.ylabel(performance_metric)
plt.grid(True)
# Save each plot with a unique name based on the feature
plt.savefig(f'./plots/{feature}_correlation_with_{performance_metric}.png')
plt.close()
# feature_range_versus_performance(features, all_features, 'new_unet_performance')
|
---
title: 订阅并请求访问 [!DNL On Demand] 高级库存交易
description: 了解如何订阅和请求访问,[!DNL On Demand] 交易。
feature: DSP On Demand Inventory
source-git-commit: 3059a5b211a8a219b02930f7f5763d5ec1467b8e
workflow-type: tm+mt
source-wordcount: '393'
ht-degree: 0%
---
# 订阅并请求访问 [!DNL On Demand] 高级库存交易
*对于具有帐户类型的用户不可用 [!UICONTROL Ad Network], [!UICONTROL Publisher Audience Extension]和 [!UICONTROL Other];具有类别的广告商 [!UICONTROL Other];和转销商*
您可以请求单个交易或订阅发布者以请求发布者的所有交易。 当您订阅发布者时,DSP会自动代表您请求发布者提供的任何新交易。
一旦交易成功 [已批准](/help/dsp/inventory/on-demand-inventory-view-status.md),默认情况下会将其作为定位所有 [!DNL On Demand] 库存。 新交易也可用作现有投放的目标,但您必须手动编辑投放设置以将交易添加为目标。
## 订阅所有出版商的交易
1. 在主菜单中,单击 **[!UICONTROL Inventory]>[!UICONTROL On Demand]**.
1. (可选)按以下任一条件筛选可用的交易或发布者:
* 关键词搜索
* **[!UICONTROL Publisher Region]**
* **[!UICONTROL Media Type]**
* 您请求的交易或订阅,包括已批准和拒绝的交易(**[!UICONTROL Currently subscribed to]**)
* 您已获得批准的交易(**[!UICONTROL Currently have access to]**)
* 交易来源 **[!UICONTROL TV Broadcasters]**
* 接受“调音”创意的出版商的交易
**[!UICONTROL Tune-In]**)
* 发布者已对其应用了21个以上定位并接受酒精广告(**[!UICONTROL Legal drinking age]**)
1. 执行以下任一操作:
* (订阅最近添加的发布者)在发布者的顶部轮播中,将光标悬停在发布者徽标上,然后单击 **[!UICONTROL Subscribe]**.
* (订阅任何发布者)单击 **[!UICONTROL Subscription view]**,将光标悬停在发布者徽标上,然后单击 **[!UICONTROL Subscribe]**.
## 请求对单个交易的访问权限
1. 在主菜单中,单击 **[!UICONTROL Inventory]>[!UICONTROL On Demand]**.
1. (可选)按以下任一条件筛选可用的交易或发布者:
* 关键词搜索
* **[!UICONTROL Publisher Region]**
* **[!UICONTROL Media Type]**
* 您请求的交易或订阅,包括已批准和拒绝的交易(**[!UICONTROL Currently subscribed to]**)
* 您已获得批准的交易(**[!UICONTROL Currently have access to]**)
* 交易来源 **[!UICONTROL TV Broadcasters]**
* 接受“调音”创意的出版商的交易
**[!UICONTROL Tune-In]**)
* 发布者已对其应用了21个以上定位并接受酒精广告(**[!UICONTROL Legal drinking age]**)
1. 执行以下任一操作:
* 要请求最近添加的交易,请执行以下操作:
1. 在发布者的顶部轮播中,将光标悬停在发布者徽标上,然后单击 **[!UICONTROL See Deals]**.
1. 要订购单个交易,请单击 **[!UICONTROL Request]** 在 [!UICONTROL Action] 列。
* 从 [!UICONTROL Deal] 视图:
1. 单击 **[!UICONTROL Deal view]**.
1. 单击 **[!UICONTROL Request]** 在 [!UICONTROL Action] 列。
>[!MORELIKETHIS]
>
>* [关于 [!DNL On Demand] Premium Inventory](on-demand-inventory-about.md)
>* [查看 [!DNL On Demand] 交易请求和订阅](on-demand-inventory-view-status.md)
>* [按需重新请求Premium库存交易](on-demand-inventory-rerequest.md)
>* [[!DNL On Demand] 亚太地区的Premium Inventory Publishers](on-demand-inventory-publishers-apac.md)
>* [[!DNL On Demand] 澳大利亚和新西兰的Premium Inventory出版商](on-demand-inventory-publishers-anz.md)
>* [[!DNL On Demand] 欧洲、中东和非洲的Premium Inventory Publishers](on-demand-inventory-publishers-emea.md)
>* [[!DNL On Demand] 北美的Premium Inventory Publishers](on-demand-inventory-publishers-na.md)
|
import { shell } from "electron";
import { difference, cloneDeep, partition, keyBy, omit } from "lodash";
import { z } from "zod";
import { IpcPlugin, AppContext } from "..";
import { UUID_REGEX } from "../../../shared/domain";
import { NoteSort, createNote, Note } from "../../../shared/domain/note";
import { Attachment } from "../../../shared/domain/protocols";
import { isDevelopment } from "../../../shared/env";
import { NoteUpdateParams } from "../../../shared/ipc";
import { writeJson, loadJson } from "../../json";
import {
registerAttachmentsProtocol,
clearAttachmentsProtocol,
parseAttachmentPath,
} from "../../protocols/attachments";
import { NOTE_SCHEMAS } from "../../schemas/notes";
import { isChildOf, openInBrowser } from "../../utils";
import * as fs from "fs";
import * as p from "path";
import { logger } from "../../logger";
export const ATTACHMENTS_DIRECTORY = "attachments";
export const METADATA_FILE_NAME = "metadata.json";
export const MARKDOWN_FILE_NAME = "index.md";
const noteUpdateSchema: z.Schema<NoteUpdateParams> = z.object({
name: z.string().optional(),
parent: z.string().optional(),
sort: z.nativeEnum(NoteSort).optional(),
content: z.string().optional(),
});
export const noteIpcPlugin: IpcPlugin = {
onInit: async ({ config, browserWindow }) => {
const { noteDirectory } = config.content;
if (noteDirectory) {
registerAttachmentsProtocol(noteDirectory);
}
// Override how all links are open so we can send them off to the user's
// web browser instead of opening them in the electron app.
browserWindow.webContents.setWindowOpenHandler(details => {
void openInBrowser(details.url);
return { action: "deny" };
});
return () => {
if (noteDirectory) {
clearAttachmentsProtocol();
}
};
},
"notes.getAll": async ctx => {
const noteDirectory = getNoteDirectory(ctx);
if (!fs.existsSync(noteDirectory)) {
return [];
}
const notes = await loadNotes(noteDirectory);
return notes;
},
"notes.create": async (ctx, params) => {
const { blockAppFromQuitting } = ctx;
const noteDirectory = getNoteDirectory(ctx);
const note = createNote(params);
await blockAppFromQuitting(async () => {
await saveNoteToFS(noteDirectory, note);
});
return note;
},
"notes.update": async (ctx, id, props) => {
const { blockAppFromQuitting } = ctx;
const noteDirectory = getNoteDirectory(ctx);
const note: NoteFile = await loadNoteFromFS(noteDirectory, id);
const update = await noteUpdateSchema.parseAsync(props);
if (update.name != null) {
note.name = update.name;
}
// Allow unsetting parent
if ("parent" in update) {
note.parent = update.parent;
}
// Allow unsetting sort
if ("sort" in update) {
note.sort = update.sort;
}
if (update.content != null) {
note.content = update.content;
}
// Sanity check to ensure no extra props were passed
if (
isDevelopment() &&
Object.keys(props).length > Object.keys(update).length
) {
const diff = difference(Object.keys(props), Object.keys(update));
logger.warn(`ipc notes.update does not support keys: ${diff.join(", ")}`);
}
note.dateUpdated = new Date();
await blockAppFromQuitting(async () => {
await saveNoteToFS(noteDirectory, note);
});
},
"notes.moveToTrash": async (ctx, id) => {
const noteDirectory = getNoteDirectory(ctx);
// Gonna leave this as-is because it might just be pre-optimizing, but this
// could be a bottle neck down the road having to load in every note before
// we can delete one if the user has 100s of notes.
const everyNote = await loadNotes(noteDirectory, true);
const recursive = async (noteId: string) => {
const notePath = p.join(noteDirectory, noteId);
await shell.trashItem(notePath);
const children = everyNote.filter(n => n.parent === noteId);
for (const child of children) {
await recursive(child.id);
}
};
await recursive(id);
},
"notes.openAttachments": async (ctx, noteId) => {
if (!UUID_REGEX.test(noteId)) {
throw new Error(`Invalid noteId ${noteId}`);
}
const noteDirectory = getNoteDirectory(ctx);
// shell.openPath doesn't allow relative paths.
const attachmentDirPath = p.resolve(
noteDirectory,
noteId,
ATTACHMENTS_DIRECTORY,
);
if (!fs.existsSync(attachmentDirPath)) {
await fs.promises.mkdir(attachmentDirPath);
}
const err = await shell.openPath(attachmentDirPath);
if (err) {
throw new Error(err);
}
},
"notes.openAttachmentFile": async (ctx, href) => {
const noteDirectory = getNoteDirectory(ctx);
const attachmentPath = parseAttachmentPath(noteDirectory, href);
if (!fs.existsSync(attachmentPath)) {
throw new Error(`Attachment ${attachmentPath} doesn't exist.`);
}
const err = await shell.openPath(attachmentPath);
if (err) {
throw new Error(err);
}
},
"notes.importAttachments": async (ctx, noteId, rawAttachments) => {
const noteDirectory = getNoteDirectory(ctx);
const noteAttachmentsDirectory = p.join(
noteDirectory,
noteId,
ATTACHMENTS_DIRECTORY,
);
if (!fs.existsSync(noteAttachmentsDirectory)) {
await fs.promises.mkdir(noteAttachmentsDirectory);
}
const attachments: Attachment[] = [];
for (const attachment of rawAttachments) {
// Don't allow directories to be drag and dropped into notes because if we
// automatically insert a link for every note to the markdown file it could
// spam the file with a ton of links.
if ((await fs.promises.lstat(attachment.path)).isDirectory()) {
continue;
}
// Only copy over the attachment if it was outside of the note's attachment
// directory. This prevents us from duplicating the file if the user were
// to drag and drop a file that is already a known attachment.
if (!isChildOf(noteAttachmentsDirectory, attachment.path)) {
// Ensure filename is always unique by appending a number to the end of it
// if we detect the file already exists.
const parsedFile = p.parse(attachment.name);
const originalName = parsedFile.name;
let copyNumber = 1;
while (
fs.existsSync(p.join(noteAttachmentsDirectory, attachment.name))
) {
attachment.name = `${originalName}-${copyNumber}${parsedFile.ext}`;
copyNumber += 1;
// Prevent infinite loops, and fail softly.
if (copyNumber > 1000) {
logger.warn(
`Tried fixing duplicate attachment name ${attachment.name} but failed 1000 times.`,
);
continue;
}
}
await fs.promises.copyFile(
attachment.path,
p.join(noteAttachmentsDirectory, attachment.name),
);
}
attachments.push({
name: attachment.name,
// Drag-and-drop attachments always go to root directory
path: attachment.name,
// Image MIME types always start with "image".
// https://www.iana.org/assignments/media-types/media-types.xhtml
type: attachment.mimeType.includes("image") ? "image" : "file",
mimeType: attachment.mimeType,
});
}
return attachments;
},
};
export function getNoteDirectory(ctx: AppContext): string {
const { config } = ctx;
if (config.content.noteDirectory == null) {
throw new Error(`No note directory set.`);
}
return config.content.noteDirectory;
}
export type NoteMetadata = Omit<Note, "content" | "children">;
export type NoteMarkdown = Pick<Note, "content">;
export type NoteFile = NoteMetadata & NoteMarkdown;
export async function loadNotes(
noteDirectoryPath: string,
flatten?: boolean,
): Promise<Note[]> {
if (!fs.existsSync(noteDirectoryPath)) {
return [];
}
const entries = await fs.promises.readdir(noteDirectoryPath, {
withFileTypes: true,
});
const everyNote = (
await Promise.all(
entries
.filter(e => isNoteSubdirectory(noteDirectoryPath, e))
.map(p => loadNoteFromFS(noteDirectoryPath, p.name)),
)
).map(n => ({ ...n, children: [] }));
if (!flatten) {
return buildNoteTree(everyNote);
} else {
return everyNote;
}
}
export function buildNoteTree(flattened: Note[]): Note[] {
// We nuke children to prevent duplicates when we rebuild the tree.
const clonedFlattened = cloneDeep(flattened).map(c => ({
...c,
children: [],
}));
const [roots, nested] = partition(clonedFlattened, n => n.parent == null);
const lookup = keyBy<Note>(clonedFlattened, "id");
for (const n of nested) {
const parent = lookup[n.parent!];
if (parent == null) {
throw new Error(
`Couldn't find parent note (id: ${n.parent}) for note (id: ${n.id})`,
);
}
parent.children.push(n);
}
return roots;
}
export async function saveNoteToFS(
noteDirectoryPath: string,
note: NoteFile,
): Promise<void> {
const notePath = p.join(noteDirectoryPath, note.id);
if (!fs.existsSync(notePath)) {
await fs.promises.mkdir(notePath);
}
const metadataPath = p.join(notePath, METADATA_FILE_NAME);
const markdownPath = p.join(notePath, MARKDOWN_FILE_NAME);
const [metadata, content] = splitNoteIntoFiles(note);
await writeJson(metadataPath, NOTE_SCHEMAS, metadata);
if (!fs.existsSync(markdownPath)) {
const s = await fs.promises.open(markdownPath, "w");
await s.write(content, null, "utf-8");
await s.close();
} else {
await fs.promises.writeFile(markdownPath, content, {
encoding: "utf-8",
});
}
}
export async function loadNoteFromFS(
noteDirectoryPath: string,
noteId: string,
): Promise<NoteFile> {
const metadataPath = p.join(noteDirectoryPath, noteId, METADATA_FILE_NAME);
const metadata = await loadJson<NoteMetadata>(metadataPath, NOTE_SCHEMAS);
const markdownPath = p.join(noteDirectoryPath, noteId, MARKDOWN_FILE_NAME);
const markdown = await fs.promises.readFile(markdownPath, {
encoding: "utf-8",
});
return {
...metadata,
content: markdown,
};
}
export function splitNoteIntoFiles(note: NoteFile): [NoteMetadata, string] {
const metadata: NoteMetadata = omit(note, "content", "children");
return [metadata, note.content];
}
export function isNoteSubdirectory(
noteDirectoryPath: string,
entry: fs.Dirent,
): boolean {
const isMatch = entry.isDirectory() && UUID_REGEX.test(entry.name);
if (!isMatch) {
return false;
}
const metadataPath = p.join(
noteDirectoryPath,
entry.name,
METADATA_FILE_NAME,
);
const markdownPath = p.join(
noteDirectoryPath,
entry.name,
MARKDOWN_FILE_NAME,
);
// Attachment directory doesn't need to be checked because it'll be re-created
// the first time the user attempts to add an attachment.
return fs.existsSync(metadataPath) && fs.existsSync(markdownPath);
}
|
package com.capstone.liveAloneCommunity.controller.email;
import com.capstone.liveAloneCommunity.dto.email.EmailAuthRequestDto;
import com.capstone.liveAloneCommunity.dto.email.EmailAuthValidateRequestDto;
import com.capstone.liveAloneCommunity.exception.email.EmailNotSentException;
import com.capstone.liveAloneCommunity.repository.email.EmailAuthRepository;
import com.capstone.liveAloneCommunity.service.email.EmailAuthService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static com.capstone.liveAloneCommunity.service.email.EmailAuthComponent.SENDER;
@SpringBootTest
@AutoConfigureMockMvc
public class VerifyEmailAuthTest {
@Autowired
private MockMvc mvc;
@Autowired
private EmailAuthService emailAuthService;
@Autowired
private EmailAuthRepository emailAuthRepository;
@BeforeEach
void clearDB(){
emailAuthRepository.deleteAll();
}
private String getEmailAuth(){
return emailAuthService.sendEmail(new EmailAuthRequestDto(SENDER.getValue())).getAuthNum();
}
@Test
@DisplayName("이메일 검증에 성공하면 200코드를 반환한다.")
public void verifyTest_Success() throws Exception{
//given
EmailAuthValidateRequestDto emailAuthValidateRequestDto = new EmailAuthValidateRequestDto(SENDER.getValue(), getEmailAuth());
//expected
mvc.perform(MockMvcRequestBuilders.post("/api/email/verify")
.contentType(MediaType.APPLICATION_JSON)
.content(makeJson(emailAuthValidateRequestDto)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.success").value(true))
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value(200))
.andDo(MockMvcResultHandlers.print());
}
@Test
@DisplayName("올바르지 않은 이메일 형식으로 요청을 하면 이를 알려주고 400코드로 예외처리한다..")
public void verifyTest_Fail_Email_Not_Format() throws Exception{
//given
EmailAuthValidateRequestDto emailAuthValidateRequestDto = new EmailAuthValidateRequestDto("janghee", "testtest");
//expected
mvc.perform(MockMvcRequestBuilders.post("/api/email/verify")
.contentType(MediaType.APPLICATION_JSON)
.content(makeJson(emailAuthValidateRequestDto)))
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.success").value(false))
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value(400))
.andExpect(MockMvcResultMatchers.jsonPath("$.result.failMessage")
.value("올바르지 않은 이메일 형식입니다."))
.andDo(MockMvcResultHandlers.print());
}
@Test
@DisplayName("인증번호를 전송한 적 없는 이메일로 인증요청을 할 경우, 인증요청을 다시 하도록 문구를 반환한다.")
public void verifyTest_Fail_Email_Not_Sent() throws Exception{
//given
EmailAuthValidateRequestDto emailAuthValidateRequestDto = new EmailAuthValidateRequestDto(SENDER.getValue(), "testtest");
//expected
mvc.perform(MockMvcRequestBuilders.post("/api/email/verify")
.contentType(MediaType.APPLICATION_JSON)
.content(makeJson(emailAuthValidateRequestDto)))
.andExpect(MockMvcResultMatchers.status().isNotFound())
.andExpect(MockMvcResultMatchers.jsonPath("$.success").value(false))
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value(404))
.andExpect(MockMvcResultMatchers.jsonPath("$.result.failMessage")
.value("이메일 인증 요청을 한 적이 없습니다. 인증 요청해주세요."))
.andDo(MockMvcResultHandlers.print());
}
@Test
@DisplayName("인증번호가 올바르지 않을 경우 400에러와 인증번호가 불일치함을 반환한다.")
public void verifyTest_Fail_AuthNum_Different() throws Exception{
//given
EmailAuthValidateRequestDto emailAuthValidateRequestDto = new EmailAuthValidateRequestDto(SENDER.getValue(), getEmailAuth()+"A");
//expected
mvc.perform(MockMvcRequestBuilders.post("/api/email/verify")
.contentType(MediaType.APPLICATION_JSON)
.content(makeJson(emailAuthValidateRequestDto)))
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.success").value(false))
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value(400))
.andExpect(MockMvcResultMatchers.jsonPath("$.result.failMessage")
.value("인증번호가 일치하지 않습니다."))
.andDo(MockMvcResultHandlers.print());
}
private String makeJson(Object object) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(object);
}
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/pages/home/home.component';
import { FindComponent } from './components/pages/find/find.component';
import { ListComponent } from './components/pages/list/list.component';
import { DrawComponent } from './components/pages/draw/draw.component';
import { SingleComponent } from './components/pages/single/single.component';
import { StatisticsComponent } from './components/pages/statistics/statistics.component';
import { SignComponent } from './components/pages/sign/sign.component';
import { AdminHomeComponent } from './components/pages/admin-home/admin-home.component';
import { AdminFindComponent } from './components/pages/admin-find/admin-find.component';
import { AddComponent } from './components/pages/add/add.component';
const routes: Routes = [
{path:'lista',component:ListComponent},
{path:'lista/:searchTerm',component:ListComponent},
{path:'', component:HomeComponent},
{path:'znajdz', component:FindComponent},
{path:'funkcje', component:DrawComponent},
// {path:'car/:id', component:SingleComponent},
{path:'admin',component:SignComponent},
{path:'dane',component:StatisticsComponent},
{path:'adminHome',component:AdminHomeComponent},
{path:'adminFind',component:AdminFindComponent},
{path:'dodaj',component:AddComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import { BookSchema } from "../types";
import { BookCategoryField, BookSortField } from "../consts";
import { DeepPartial } from "@reduxjs/toolkit";
import { bookModelActions, bookModelReducer } from "./bookSlice";
import { fetchBooks } from "../services/fetch-books";
import { GoogleBooksApiAnswer } from "@/shared/api/instance/books";
const testIds = ["Тихий", "Дон", "Книга"];
const testEntities = [{
"Тихий": {id: "0", title: "Тихий", authors: ["Author name"], categories: ["some category"], image: "", description: ""},
"Дон": {id: "1", title: "Дон", authors: ["Author name"], categories: ["some category"], image: "", description: ""},
"Книга": {id: "2", title: "Книга", authors: ["Author name"], categories: ["some category"], image: "", description: ""}
}]
const apiAnswer: GoogleBooksApiAnswer = {
totalItems: 185,
items: [
{
id: "0",
volumeInfo: {
title: "Тестовая",
authors: ["Author name"],
categories: ["some category"],
imageLinks: {
small: "",
smallThumbnail: "",
thumbnail: "",
medium: "",
large: "",
extraLarge: ""
},
description: "",
}
},
{
id: "1",
volumeInfo: {
title: "Тестовая 2",
authors: ["Author name"],
categories: ["some category"],
imageLinks: {
small: "",
smallThumbnail: "",
thumbnail: "",
medium: "",
large: "",
extraLarge: ""
},
description: "",
}
},
{
id: "2",
volumeInfo: {
title: "Тестовая 3",
authors: ["Author name"],
categories: ["some category"],
imageLinks: {
small: "",
smallThumbnail: "",
thumbnail: "",
medium: "",
large: "",
extraLarge: ""
},
description: "",
}
}
]
};
const newIds = ["Тестовая", "Тестовая 2", "Тестовая 3"];
const newEntitiesWithReplace = {
"Тестовая": {id: "0", title: "Тестовая", authors: ["Author name"], categories: ["some category"], image: "" , description: ""},
"Тестовая 2": {id: "1", title: "Тестовая 2", authors: ["Author name"], categories: ["some category"], image: "" , description: ""},
"Тестовая 3": {id: "2", title: "Тестовая 3", authors: ["Author name"], categories: ["some category"], image: "" , description: ""}
}
const newEntitiesWithoutReplace = {
"Тихий": {id: "0", title: "Тихий", authors: ["Author name"], categories: ["some category"], image: "", description: ""},
"Дон": {id: "1", title: "Дон", authors: ["Author name"], categories: ["some category"], image: "", description: ""},
"Книга": {id: "2", title: "Книга", authors: ["Author name"], categories: ["some category"], image: "", description: ""},
"Тестовая": {id: "0", title: "Тестовая", authors: ["Author name"], categories: ["some category"], image: "" , description: ""},
"Тестовая 2": {id: "1", title: "Тестовая 2", authors: ["Author name"], categories: ["some category"], image: "" , description: ""},
"Тестовая 3": {id: "2", title: "Тестовая 3", authors: ["Author name"], categories: ["some category"], image: "" , description: ""}
}
// const data: BookSchema = {
// search: "",
// sort: BookSortField.RELEVANCE,
// categoryField: BookCategoryField.ALL,
// hasMore: true,
// maxResults: 30,
// index: 0,
// ids: testIds,
// entities: testEntities[0]
// }
describe("bookSlice.test", () => {
// Базовые экшены'
test("set sort", () => {
const state: DeepPartial<BookSchema> = {
sort: BookSortField.RELEVANCE, ids: [], entities: {}
};
expect(bookModelReducer(state as BookSchema, bookModelActions.setSort(BookSortField.NEWEST)))
})
test("set search", () => {
const state: DeepPartial<BookSchema> = {
search: ""
};
expect(bookModelReducer(state as BookSchema, bookModelActions.setSearch("Тихий Дон")))
})
test("set category", () => {
const state: DeepPartial<BookSchema> = {
categoryField: BookCategoryField.ALL
};
expect(bookModelReducer(state as BookSchema, bookModelActions.setCategoryField(BookCategoryField.BIOGRAPHY)))
})
// Асинхронные экшены
test("test fetchBooks pending without replace", () => {
const state: DeepPartial<BookSchema> = {
isLoading: false,
error: "error"
};
expect(
bookModelReducer(
state as BookSchema,
fetchBooks.pending("", { replace: false })
)
).toEqual({
isLoading: true,
error: undefined
})
})
test("test fetchBooks pending with replace", () => {
const state: DeepPartial<BookSchema> = {
ids: testIds,
entities: testEntities[0],
isLoading: false
}
expect(
bookModelReducer(
state as BookSchema,
fetchBooks.pending("", { replace: true })
)
).toEqual(
{
ids: [],
entities: {},
isLoading: true
}
)
})
test("test fetchBooks rejected", () => {
const state: DeepPartial<BookSchema> = {
error: undefined,
isLoading: true
}
expect(
bookModelReducer(
state as BookSchema,
fetchBooks.rejected(null, "", {replace: false}, "error")
// rejected(Error, arg, FetchMetaArgs, RejectWithValue)
)
).toEqual(
{
error: "error",
isLoading: false
}
)
})
test("fetchBooks fullfiled without replace", () => {
const state: DeepPartial<BookSchema> = {
found: 3,
ids: testIds,
entities: testEntities[0],
hasMore: true,
isLoading: true,
}
expect(
bookModelReducer(
state as BookSchema,
fetchBooks.fulfilled(apiAnswer, "", { replace: false })
)
).toEqual({
hasMore: false,
isLoading: false,
found: 3,
ids: [...testIds, ...newIds],
entities: newEntitiesWithoutReplace
})
})
test("fetchBooks fullfiled with replace", () => {
const state: DeepPartial<BookSchema> = {
found: 0,
ids: testIds,
entities: testEntities[0],
hasMore: true,
isLoading: true,
}
expect(
bookModelReducer(
state as BookSchema,
fetchBooks.fulfilled(apiAnswer, "", { replace: true })
)
).toEqual({
hasMore: false,
isLoading: false,
found: apiAnswer.totalItems,
ids: [...newIds],
entities: newEntitiesWithReplace
})
})
})
|
import { Redis, type RedisOptions } from 'ioredis'
import { ms } from 'expresso-core'
interface SetOptions {
expiryMode?: string | any[]
timeout?: string | number
}
export class RedisProvider {
private readonly _options: RedisOptions
constructor(options: RedisOptions) {
this._options = options
}
public client(): Redis {
const client = new Redis(this._options)
return client
}
/**
*
* @param key
* @param data
* @param options
*/
public async set(
key: string,
data: any,
options?: SetOptions
): Promise<void> {
const client = this.client()
const defaultTimeout = options?.timeout ?? ms('1d') / 1000
await client.setex(key, defaultTimeout, JSON.stringify(data))
}
/**
*
* @param key
* @returns
*/
public async get<T>(key: string): Promise<T | null> {
const client = this.client()
const data = await client.get(key)
if (!data) {
return null
}
const parseData = JSON.parse(data) as T
return parseData
}
/**
*
* @param key
*/
public async delete(key: string): Promise<void> {
const client = this.client()
await client.del(key)
}
/**
*
* @param prefix
*/
public async deleteByPrefix(prefix: string): Promise<void> {
const client = this.client()
const keys = await client.keys(`${prefix}:*`)
const pipeline = client.pipeline()
keys.forEach((key) => {
pipeline.del(key)
})
await pipeline.exec()
}
}
|
<!doctype html>
<html lang="en" xmlns:th="http://www/thymeleaf.org"
th:replace="base::layout(~{::section})">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<section>
<div class="container mt-3 mb-3">
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="my-card">
<!-- <div th:if="${message}" class="alert alert-dismissible fade show"
th:classappend="${message.type}" role="alert">
<span th:text="${message.content}"></span>
<button type="button" class="close" data-dismiss="alert"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> -->
<div class="container text-center">
<img style="width: 150px;" th:src="@{/img/register.png}"
alt="register pic" />
</div>
<h1 class="text-center">Register here !!!</h1>
<form th:action="@{/do-register}" method="post"
th:object="${user}">
<div class="form-group">
<label for="form-name">Your name</label> <input type="text"
class="form-control" id="form-name"
aria-describedby="emailHelp" th:value="${user.name}"
th:classappend="${#fields.hasErrors('name') ? 'is-invalid' : ''}"
name="name" required placeholder="Enter name">
<div th:each="e : ${#fields.errors('name')}" th:text="${e}"
id="validationServer03Feedback" class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="form-email">Your email</label> <input type="email"
class="form-control" id="form-email"
aria-describedby="emailHelp" th:value="${user.email}"
th:classappend="${#fields.hasErrors('email') ? 'is-invalid' : ''}"
name="email" required placeholder="Enter email">
<div th:each="e : ${#fields.errors('email')}" th:text="${e}"
id="validationServer03Feedback" class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="form-password">Your password</label> <input
type="password" class="form-control" id="form-password"
th:classappend="${#fields.hasErrors('password') ? 'is-invalid' : ''}"
aria-describedby="emailHelp" name="password" required
placeholder="Enter password">
<div th:each="e : ${#fields.errors('password')}" th:text="${e}"
id="validationServer03Feedback" class="invalid-feedback"></div>
</div>
<div class="form-group">
<textarea name="about" th:text="${user.about}"
class="form-control" id="form-about" rows="5" required
placeholder="Enter about yourself"></textarea>
</div>
<div class="form-check">
<input type="checkbox" name="agreement" class="form-check-input"
id="exampleCheck1"> <label class="form-check-label"
for="exampleCheck1">Agree terms and conditions</label>
</div>
<div class="container text-center">
<button type="submit" class="btn btn-lg btn-primary">Submit</button>
<button type="reset" class="btn btn-lg btn-warning">Reset</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(()=>{
$(".nav-item").removeClass("active");
$("#signup-route").addClass("active");
});
</script>
</section>
</body>
</html>
|
import Vue from 'vue'
import Vuex from 'vuex'
// @ts-ignore
import {getCellphone,getUserdetail,getUserplaylist,getShareresource,getResourceLike} from '@/api/index.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//音乐时间
musicTime:'',
//歌词
lyricGroup:{},
//歌曲ID
musicId:0,
//歌曲列表
list:[],
//登录
user: JSON.parse(localStorage.getItem('feng') as string) || {
isLogin:false,
account:{},//账号信息
cookie:{},
profile:{},//个人信息
getDetail:{},//用户详情
playlist:[],//用户个人列表
},
},
mutations: {
//换算音乐时间
calculateMusic(state,time) {
let oal = time/1000
let min = oal/60
min = Math.trunc(min)
let sec = oal-min*60
sec = Math.trunc(sec)
let m = ''
let s = ''
if(min < 10) m = '0'+ min
else m = JSON.stringify(min)
if(sec < 10) s = '0' + sec
else s = JSON.stringify(sec)
state.musicTime = m + ':' + s
},
//分解歌词
lyricTime(state,lyric) {
let lyricArr = lyric.split('[').slice(1)//对"["进行分割
let lyricObj = {}
lyricArr.forEach((item:any) => {
let arr = item.split(']')//再对"]"进行分割
//换算时间,单位:秒
let m = parseInt(arr[0].split(':')[0])
let s = parseInt(arr[0].split(':')[1])
arr[0] = m*60 + s
if(arr[1] != '\n') {//去除歌词中的换算符
// @ts-ignore
lyricObj[arr[0]] = arr[1]
}
})
state.lyricGroup = lyricObj
},
musicUrl(state,id){
if(state.musicId != id){
state.musicId = id
}
},
musicList(state,list){
if(state.list != list){
state.list = list
}
},
setData(state,Value){//存储到浏览器的cookie
localStorage.setItem('feng',JSON.stringify(Value))
state.user = Value
}
},
getters:{
//实时刷新musicId
getMusicUrl:state =>{
return state.musicId
},
getList:state =>{
return state.list
},
getLogin:state =>{
return state.user.isLogin
}
},
actions: {
async checkout(context,phone){
let player = await getCellphone(phone.account,phone.password)
if(player.data.code === 200){
context.state.user.isLogin = true
context.state.user.cookie = player.data.cookie
context.state.user.account = player.data.account
context.state.user.profile = player.data.profile
let userDeatil = await getUserdetail(player.data.account.id)
let playlistValue = await getUserplaylist(player.data.account.id)
context.state.user.playlist = playlistValue.data.playlist
context.state.user.getDetail = userDeatil.data
context.commit('setData',context.state.user)
}
return player
},
async getShare(state,content){//分享动态
await getShareresource(content.type,content.id,content.msg,content.cookie)
},
async setResourceLike(state,like){
console.log(like);
await getResourceLike(like.t,like.type,like.id,like.cookie)
}
},
modules: {
}
})
|
<?php
define(
'TAX_RATES',
array(
'Single' => array(
'Rates' => array(10, 12, 22, 24, 32, 35, 37),
'Ranges' => array(0, 10275, 41775, 89075, 170050, 215950, 539900),
'MinTax' => array(0, 1027.5, 4807.5, 15213.5, 34647.5, 49335.5, 162718)
),
'Married_Jointly' => array(
'Rates' => array(10, 12, 22, 24, 32, 35, 37),
'Ranges' => array(0, 20550, 83550, 178150, 340100, 431900, 647850),
'MinTax' => array(0, 2055, 9615, 30427, 69295, 98671, 174235.5)
),
'Married_Separately' => array(
'Rates' => array(10, 12, 22, 24, 32, 35, 37),
'Ranges' => array(0, 10275, 41775, 89075, 17050, 215950, 323925),
'MinTax' => array(0, 1027.5, 4807.50, 15213.50, 34647.50, 49335.50, 87126.75)
),
'Head_Household' => array(
'Rates' => array(10, 12, 22, 24, 32, 35, 37),
'Ranges' => array(0, 14650, 55900, 89050, 170050, 215950, 539900),
'MinTax' => array(0, 1465, 6415, 13708, 33148, 47836, 161218.50)
)
)
);
// IncomeTax function calculates the taxable income based on the tax bracket
function incomeTax($taxableIncome, $status)
{
if ($taxableIncome < 0)
return 0;
// define the tax rates constant to extract the arrays for the
// tax rates, tax ranges, and minimum taxes.
$tax_brackets = TAX_RATES[$status]['Rates'];
$ranges = TAX_RATES[$status]['Ranges'];
$minTax = TAX_RATES[$status]['MinTax'];
// initialize the tax bracket to zero
$taxBracket = 0;
$incTax = 0.0;
// define the range of the array in the ranges
$index = count($ranges);
for ($i = count($ranges) - 1; $i >= 0; $i--) {
if ($taxableIncome > $ranges[$i]) {
$index = $i;
break;
}
}
$incTax = $minTax[$index] + $tax_brackets[$index] * ($taxableIncome - $ranges[$index]) / 100;
/*
While loop is to find the tax bracket for the taxable income.
the increment of tax bracket until it is greater the upper limit
of the current bracket.
*/
// while ($taxableIncome > $ranges[$taxBracket + 1]) {
// $taxBracket++;
// }
// calculate the income tax by adding the minimum tax for the bracket that
// exceed the lower limit of the bracket and multiply by the tax rate.
// $incTax = $minTax[$taxBracket] + ($tax_brackets[$taxBracket] / 100) *
// ($taxableIncome - $ranges[$taxBracket]);
return $incTax;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HW4 Part2 - Nguyen</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Income Tax Calculator</h3>
<form class="form-horizontal" method="post">
<div class="form-group">
<label class="control-label col-sm-2">Enter Net Income:</label>
<div class="col-sm-10">
<input type="number" step="any" name="netIncome" placeholder="Taxable Income" required autofocus>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<?php
// Fill in the rest of the PHP code for form submission results
if (isset($_POST['netIncome'])) {
// get data from the form and store the data in the income variable
$income = $_POST['netIncome'];
// retrieve the status of the taxble income bracket data.
$single = incomeTax($income, 'Single');
$marriedJoint = incomeTax($income, 'Married_Jointly');
$marriedSep = incomeTax($income, 'Married_Separately');
$household = incomeTax($income, 'Head_Household');
?>
<!-- display the net income in a format USD. -->
<p>With a net taxable income of $
<?php echo number_format($_POST['netIncome'], 2) ?>
<!-- Display the income tax bracket based on the status in a table -->
<table class="table table-striped">
<thead>
<tr>
<th width="20%">Status</th>
<th>Tax</th>
</tr>
</thead>
<tbody>
<tr>
<td>Single</td>
<td>$<?php echo number_format($single, 2) ?></td>
</tr>
<tr>
<td>Married Filing Jointly</td>
<td>$<?php echo number_format($marriedJoint, 2) ?></td>
</tr>
<tr>
<td>Married Filing Separately</td>
<td>$<?php echo number_format($marriedSep, 2) ?></td>
</tr>
<tr>
<td>Head of Household</td>
<td>$<?php echo number_format($household, 2) ?></td>
</tr>
</tbody>
</table>
<?php } ?>
<h3>2022 Tax Brackets and Tax Rates (for filing in 2023)</h3>
<?php
/*
The foreach loop through the bracket array and display the
taxable income of the taxable range.
*/
foreach (TAX_RATES as $status => $bracketArray) {
$ranges = $bracketArray['Ranges'];
$min = $bracketArray['MinTax'];
$tax_brackets = $bracketArray['Rates'];
$len = count($ranges);
?>
<h4><?php echo $status?></h4>
<!-- display the table head of the tax rate -->
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th width="30%">Taxable Income</th>
<th >Tax Rate</th>
</tr>
</thead>
<tbody>
<!-- The first bracket -->
<tr>
<td>
$<?php echo number_format($ranges[0])?> - $<?php echo number_format($ranges[1]) ?>
</td>
<td>
<?php echo $tax_brackets[0]?>%
</td>
</tr>
<!-- loop through the innerloop length, intialize index one
to the second of the last index array -->
<?php for($i = 1; $i < ($len - 1); $i++){
?>
<tr>
<td>$<?php echo number_format($ranges[$i]+1) ?> - $<?php echo number_format($ranges[$i+1])?>
</td>
<td>
$<?php echo number_format($min[$i], 2) ?> plus <?php echo $tax_brackets[$i]?>
% of the amount over $<?php echo number_format($ranges[$i])?>
</td>
</tr>
<?php } ?>
<!-- // display the last index data in a table -->
<tr>
<td>
$<?php echo number_format($ranges[$len - 1] + 1)?> or more
</td>
<td>
$<?php echo number_format($min[$len - 1], 2)?> plus <?php $tax_brackets[$i]?>
% of the amount over $<?php echo number_format($ranges[$i])?>
</td>
</tr>
</tbody>
</table>
<?php } ?>
</div>
</body>
</html>
|
<?php
namespace App\Form;
use App\Entity\User;
use Doctrine\DBAL\Types\JsonType;
use Doctrine\DBAL\Types\ArrayType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('username', TextType::class, [
'label' => "Nom d'utilisateur",
'required' => false,
])
->add('email', TextType::class, [
'label' => 'Adresse email',
'required' => false,
])
->add('password', RepeatedType::class, [
'type' => PasswordType::class,
'invalid_message' => 'Les deux mots de passe doivent correspondre.',
'required' => false,
'first_options' => [
'label' => 'Mot de passe',
],
'second_options' => [
'label' => 'Tapez le mot de passe à nouveau',
],
])
->add('roleSelection', ChoiceType::class, [
'choices' => [
'Role utilisateur' => 'ROLE_USER',
'Role administrateur' => 'ROLE_ADMIN',
],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => User::class,
'validation_groups' => ['base','createUser']
]);
}
}
|
<?php
include '../connectDB.php';
$message = "";
// Xử lý thêm màu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_colors'])) {
$colors = $_POST['colors'];
$stmt_add = $conn->prepare("INSERT INTO colors (color_code, color_hex, color_group, color_group_main) VALUES (?, ?, ?, ?)");
$stmt_check = $conn->prepare("SELECT color_code FROM colors WHERE color_code = ?");
foreach ($colors as $color) {
$color_code = $color['color_code'];
$color_hex = $color['color_hex'];
$color_group = $color['color_group'];
$color_group_main = $color['color_group_main'];
// Kiểm tra xem color_code đã tồn tại hay chưa
$stmt_check->bind_param("s", $color_code);
$stmt_check->execute();
$stmt_check->store_result();
if ($stmt_check->num_rows > 0) {
$message .= "Màu với mã code $color_code đã tồn tại.<br>";
} else {
$stmt_add->bind_param("ssss", $color_code, $color_hex, $color_group, $color_group_main);
$stmt_add->execute();
}
}
$stmt_add->close();
$stmt_check->close();
}
// Xử lý sửa màu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_color'])) {
$color_id = $_POST['color_id'];
$color_code = $_POST['color_code'];
$color_hex = $_POST['color_hex'];
$color_group = $_POST['color_group'];
$color_group_main = $_POST['color_group_main'];
$sql_edit = "UPDATE colors SET color_code = ?, color_hex = ?, color_group = ?, color_group_main = ? WHERE color_id = ?";
$stmt_edit = $conn->prepare($sql_edit);
$stmt_edit->bind_param("ssssi", $color_code, $color_hex, $color_group, $color_group_main, $color_id);
$stmt_edit->execute();
$stmt_edit->close();
}
// Xử lý xóa màu
if (isset($_GET['delete'])) {
$color_id = $_GET['delete'];
$sql_delete = "DELETE FROM colors WHERE color_id = ?";
$stmt_delete = $conn->prepare($sql_delete);
$stmt_delete->bind_param("i", $color_id);
$stmt_delete->execute();
$stmt_delete->close();
}
// Lấy danh sách các màu sắc và nhóm màu
$sql_colors = "SELECT color_id, color_code, color_hex, color_group, color_group_main FROM colors ORDER BY color_group_main, color_group";
$result_colors = $conn->query($sql_colors);
$colors = array();
if ($result_colors->num_rows > 0) {
while ($row = $result_colors->fetch_assoc()) {
$colors[] = $row;
}
}
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quản lý màu sắc</title>
<link rel="stylesheet" href="path/to/your/css/styles.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<main id="main-manage-colors">
<section class="header-manage-colors">
<h1>Quản lý màu sắc</h1>
</section>
<section class="content-manage-colors">
<h2>Thêm màu mới</h2>
<form method="POST" action="" id="addColorsForm">
<div id="colorFieldsContainer">
<div class="color-field">
<label for="color_code[]">Mã màu:</label>
<input type="text" name="colors[0][color_code]" class="color_code" required>
<label for="color_hex[]">Màu HEX:</label>
<input type="text" name="colors[0][color_hex]" class="color_hex" required>
<span class="color_preview" style="display: inline-block; width: 50px; height: 20px;"></span>
<label for="color_group[]">Nhóm màu:</label>
<input type="text" name="colors[0][color_group]" class="color_group" required>
<label for="color_group_main[]">Nhóm màu chính:</label>
<input type="text" name="colors[0][color_group_main]" class="color_group_main" required>
</div>
</div>
<button type="button" id="addMoreColors">Thêm màu khác</button>
<button type="submit" name="add_colors">Thêm màu</button>
</form>
<h2>Danh sách màu sắc</h2>
<table>
<thead>
<tr>
<th>Mã màu</th>
<th>Màu HEX</th>
<th>Mã HEX</th>
<th>Nhóm màu</th>
<th>Nhóm màu chính</th>
<th>Hành động</th>
</tr>
</thead>
<tbody>
<?php foreach ($colors as $color): ?>
<tr>
<td><?php echo htmlspecialchars($color['color_code']); ?></td>
<td><div style="background-color: <?php echo htmlspecialchars($color['color_hex']); ?>; width: 50px; height: 20px;"></div></td>
<td><?php echo htmlspecialchars($color['color_hex']); ?></td>
<td><?php echo htmlspecialchars($color['color_group']); ?></td>
<td><?php echo htmlspecialchars($color['color_group_main']); ?></td>
<td>
<a href="../php/edit_color.php?color_id=<?php echo $color['color_id']; ?>">Sửa</a>
<a href="?delete=<?php echo $color['color_id']; ?>" onclick="return confirm('Bạn có chắc chắn muốn xóa màu này?');">Xóa</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</section>
</main>
<script>
$(document).ready(function() {
var colorIndex = 1;
$('#addMoreColors').click(function() {
var newField = `
<div class="color-field">
<label for="color_code[]">Mã màu:</label>
<input type="text" name="colors[${colorIndex}][color_code]" class="color_code" required>
<label for="color_hex[]">Màu HEX:</label>
<input type="text" name="colors[${colorIndex}][color_hex]" class="color_hex" required>
<span class="color_preview" style="display: inline-block; width: 50px; height: 20px;"></span>
<label for="color_group[]">Nhóm màu:</label>
<input type="text" name="colors[${colorIndex}][color_group]" class="color_group" required>
<label for="color_group_main[]">Nhóm màu chính:</label>
<input type="text" name="colors[${colorIndex}][color_group_main]" class="color_group_main" required>
</div>`;
$('#colorFieldsContainer').append(newField);
colorIndex++;
});
$(document).on('input', '.color_hex', function() {
var hexValue = $(this).val();
$(this).siblings('.color_preview').css('background-color', hexValue);
});
});
</script>
</body>
</html>
<style>
</style>
|
import React, { useState } from "react";
import { VariantTypes } from "../sharedTypes";
import { Typography } from "../Typo";
interface TabsType extends React.ComponentPropsWithRef<"div"> {
tabsValue: SingleTab[];
className?: string;
variant: VariantTypes;
}
interface SingleTab {
title: string;
id: string;
content: React.ReactNode;
}
export const Tabs = ({ className, tabsValue, variant, ...rest }: TabsType) => {
const [activeTabId, setactiveTabId] = useState<string>(tabsValue[0].id);
const changeActiveHandler = (item: SingleTab) => {
setactiveTabId(item.id);
};
const bgItems: Record<VariantTypes, string> = {
info: "bg-sky-50",
danger: "bg-red-50",
success: "bg-green-50",
warning: "bg-orange-50",
default: "bg-slate-50",
};
return (
<div {...rest} className="block">
<div className="flex rounded-md overflow-hidden w-fit">
{tabsValue.map((el: SingleTab, index: number) => (
<div
className={`w-fit px-3 py-1 border-r-2 last-of-type:border-r-0 cursor-pointer duration-150 ${
el.id === activeTabId ? bgItems[variant] : "bg-slate-50"
} `}
key={`tab-header-${el.id}-${index}`}
onClick={() => changeActiveHandler(el)}
>
<Typography
variant="h6"
colorVariant={el.id === activeTabId ? variant : "default"}
>
{el.title}
</Typography>
</div>
))}
</div>
<div className="my-2">
<div className="translate-y-5">
{tabsValue.map((el: SingleTab, index: number) => (
<div
key={`active-tab-${index}`}
className={`${
el.id === activeTabId
? "block duration-500 -translate-y-5 opacity-100"
: "max-h-0 invisible pointer-events-none opacity-0"
}`}
>
{el.content}
</div>
))}
</div>
</div>
</div>
);
};
Tabs.displayName = Tabs;
|
from typing import Optional, Literal
from uuid import uuid4
from fastapi import FastAPI, HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
import random
import os
import json
# *I want to create an API for an e-commerce book store where I can see all the books in my catalog.
# *I also would like to add new ones and things like that.
# List of paths:
# / = root path
# /list-books = shows me all the books I have in my catalog
# /book-by-index/{index} = if i give it a specific number, I can get that exact book and nothing else-
# I want this to take a number for example: /book-by-index/0
# /get-random-book = recommending random books to my customers
# /add-book = for adding books to my catalog. The data for this will be sent through a request body
# /get-book?id = if I have the id or unique identifier of a book, I might want the API to get that book directly.
# This will use a Query parameter
app = FastAPI()
# TODO: Creating a data model (Book Model)
# In fastapi, to create a data model i need to create a class-
# that extends from the base model object (pydantic basemodel)
class Book(BaseModel):
name: str
price: float
# this Literal will be so that the user can pick from fiction or non-fiction
genre: Literal["fiction", "non-fiction"]
# this is for string conversion and also converts it to a random id
book_id: Optional[str] = uuid4().hex
# *Saving the books data in memory as a json file
BOOKS_FILE = "books.json"
# *Global Variable acting like fake database for the books
BOOK_DATABASE = []
if os.path.exists(BOOKS_FILE):
with open(BOOKS_FILE, "r") as f:
# When I add my books I want it to save in this json
BOOK_DATABASE = json.load(f)
# TODO: Create root/home path
@app.get("/")
async def home():
return {"Message": "Welcome to my bookstore!"}
# TODO: Create list-books path
@app.get("/list-books")
async def list_books():
return {"books": BOOK_DATABASE}
# TODO: Create book-by-index path
# I need to detect when an index is out of range and if the index is-
# out of range, I don't want the app to crash. I want to respond with a-
# error message.
@app.get("/book-by-index/{index}")
async def book_by_index(index: int):
# For the body of the function i want it to return the book that is at the index given
if index < 0 or index >= len(BOOK_DATABASE):
# Fail
raise HTTPException(404, f"Index {index} is out of range {len(BOOK_DATABASE)}.")
else:
return {"book": BOOK_DATABASE[index]}
# TODO: Create get-random-book path
@app.get("/get-random-book")
async def get_random_book():
# this will pick a random element out of the BOOK_DATABASE
return random.choice(BOOK_DATABASE)
# TODO: Create add-book path
@app.post("/add-book")
async def add_book(book: Book):
# when I add a book i want to give it a new uuid, so i want to overwrite the id and give it a new one.
book.book_id = uuid4().hex
# allows the data to be converted into json
json_book = jsonable_encoder(book)
BOOK_DATABASE.append(json_book)
with open(BOOKS_FILE, "w") as f:
# When I add my books I want it to save in this json
json.dump(BOOK_DATABASE, f)
return {"Message": f"The book {book} was added.", "book_id": book.book_id}
# TODO: Create get-book?id path (Request Body)
# *In fastapi and REST api's in general, there is a consept called request body.
# *If I send information to my post method like add-book-
# *aside from using a query parameter, I can also use a request body.
# *Which is basically a json object that is sent with the request.
# *Due to the request body being json object, means that my API can still be used-
# *across different paltforms.
# *Even though I am defining my book data structure in python, someone else can still use-
# *this API, aslong as they can build a similar data structure. Whether its in JS, C#, -
# *or whatever platform is communicating with this API
@app.get("/get-book")
async def get_book(book_id: str):
# This is not a real database, its just a list. But if it was a real database then a string look-
# up or a key look-up should be fairly quick. Because I dont care much for the backend at the moment-
# I will brute force it and i will get every element and find the book with the id.
for book in BOOK_DATABASE:
if book["book_id"] == book_id:
return book
raise HTTPException(404, f"Book not found: {book_id}")
|
class Solution {
public:
int maxNonOverlapping(vector<int>& nums, int target) {
int n = nums.size();
int ans=0, sum=0;
unordered_map<int,int> mp;
for(int i=0 ; i<n ; i++){
// Keep adding nums[i] to sum
sum += nums[i];
// If sum == target or (sum-target) is present, then increment ans and make sum=0 and clear the map. It is because once we got a subarray, we cannot use it again, and hence we need to clear our hashmap and also make sum=0
if(sum==target || mp.find(sum-target)!=mp.end()){
ans++;
sum=0;
mp.clear();
}
// else we insert sum in our map
else{
mp[sum]++;
}
}
return ans;
}
};
|
import { useContext, useState } from 'react';
import './login.scss';
import {Link, useNavigate, useNavigation} from 'react-router-dom';
import { AuthContext } from '../../contexts/authContext';
function Login() {
const navigation = useNavigation();
const navigate = useNavigate();
const [inputs, setInputs] = useState({
username:"",
password:""
});
const [err, setErr] = useState(null);
const {login} = useContext(AuthContext)
const handleChange =(e)=>{
setInputs((prev)=>({
...prev,
[e.target.name]:e.target.value
}))
}
const handleLogin = async(e)=>{
e.preventDefault();
try {
await login(inputs);
await setInputs({
username:"",
password:""
});
navigate("/");
} catch (error) {
setErr(error.response.data);
}
}
return (
<div className='login'>
<div className="card">
<div className="left">
<h1>Hello World</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet magnam architecto vitae molestiae harum illo saepe quam, vel obcaecati recusandae, assumenda, nam doloremque? </p>
<span>Don't you have an account?</span>
<Link to="/register">
<button>Register</button>
</Link>
</div>
<div className="right">
<h1>Login</h1>
<form onSubmit={handleLogin}>
<input type="text" value={inputs.username} placeholder='Username' name="username" onChange={handleChange}/>
<input type="password" value={inputs.password} placeholder='Password' name="password" onChange={handleChange} />
{err && err}
{navigation.state == "loading" ? <button type='submit'>"Loading"</button> : <button type='submit'>Login</button>}
</form>
</div>
</div>
</div>
)
}
export default Login
|
module List where
import Prelude
hiding (replicate, map, filter)
import Nat
replicate :: Nat -> a -> [a]
replicate O _ = []
replicate (S n) x = x : (replicate n x)
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = (f x) : (map f xs)
filter :: (a -> Bool) -> [a] -> [a]
filter f [] = []
filter f (x:xs)
| f x = x : filter f xs
| otherwise = filter f xs
|
//! [TITLE]
// Counting Duplicates
//! [DESCRIPTION]
// Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
//! [EXAMPLES]
// "abcde" -> 0 # no characters repeats more than once
// "aabbcde" -> 2 # 'a' and 'b'
// "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)
// "indivisibility" -> 1 # 'i' occurs six times
// "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
// "aA11" -> 2 # 'a' and '1'
// "ABBA" -> 2 # 'A' and 'B' each occur twice
//! [SOLUTION]
function duplicateCount(text: string): number {
const countLetter = new Map();
const counter = 0;
[...text.toLowerCase()].forEach((letter) => {
return countLetter.has(letter)
? countLetter.set(letter, countLetter.get(letter) + 1)
: countLetter.set(letter, 1);
});
return [...countLetter.entries()].filter(
(val: [string, number]) => val[1] > 1
).length;
}
//! [CHECK]
console.log(duplicateCount('abcde'));
console.log(duplicateCount('aabbcde'));
console.log(duplicateCount('aabBcde'));
console.log(duplicateCount('indivisibility'));
console.log(duplicateCount('Indivisibilities'));
console.log(duplicateCount('aA11'));
console.log(duplicateCount('ABBA'));
|
package com.example.homework24.presentation.screen.home
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import com.example.homework24.R
import com.example.homework24.databinding.FragmentHomePageBinding
import com.example.homework24.presentation.base.BaseFragment
import com.example.homework24.presentation.event.HomePageEvents
import com.example.homework24.presentation.extensions.safeNavigateWithArguments
import com.example.homework24.presentation.extensions.showSnackBar
import com.example.homework24.presentation.screen.adapter.ClickCallBack
import com.example.homework24.presentation.screen.adapter.HomePageRecyclerAdapter
import com.example.homework24.presentation.state.HomePageState
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
@AndroidEntryPoint
class HomePageFragment : BaseFragment<FragmentHomePageBinding>(FragmentHomePageBinding::inflate),ClickCallBack {
private val viewModel: HomePageViewModel by viewModels()
private lateinit var myAdapter: HomePageRecyclerAdapter
override fun bind() {
viewModel.onEvent(HomePageEvents.LoadPage)
myAdapter = HomePageRecyclerAdapter(this)
binding.recyclerView.adapter = myAdapter
}
override fun bindObservers() {
bindStateObservers()
bindErrorObservers()
bindNavigationObservers()
}
private fun bindStateObservers(){
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED){
viewModel.uiStateFlow.collect(){
handleResult(it)
}
}
}
}
private fun bindErrorObservers(){
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED){
viewModel.oneTimeEventFlow.collect(){
showErrorMessage(it)
}
}
}
}
private fun bindNavigationObservers(){
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED){
viewModel.navigationEventFlow.collect(){
handleNavigationEvent(it)
}
}
}
}
private fun handleNavigationEvent(navEvent:HomePageNavigationEvent){
when(navEvent){
is HomePageNavigationEvent.NavigateToDetails -> navigateToDetailsPage(navEvent.id)
}
}
private fun navigateToDetailsPage(id:Int){
val bundle = bundleOf("id" to id)
findNavController().safeNavigateWithArguments(R.id.action_homePageFragment_to_detailsFragment,bundle)
}
private fun handleResult(state: HomePageState){
showLoader(state.isLoading)
state.isSuccess?.let {
myAdapter.submitList(it)
}
}
private fun showErrorMessage(errorMessage:String){
binding.root.showSnackBar(errorMessage)
}
private fun showLoader(loading:Boolean){
binding.progressBar.visibility = if(loading) View.VISIBLE else View.GONE
}
override fun postClicked(id: Int) {
viewModel.onEvent(HomePageEvents.OpenDetailsPage(id))
}
}
|
import React, {useEffect, useState} from "react";
import Banner from "components/Banner";
import Titulo from "components/Titulo";
function CadFilme (){
const [name, setName] = useState("");
const [gender, setGender] = useState ("");
const [favorito, setFavorito] = useState ("");
const [image_url, setImage_url] = useState ("");
const [message, setMessage] = useState ("");
let handleSubimit = async (e) => {
e.preventDefault();
try {
let res = await fetch ("http//localhost:3000/filmes", {
method: "POST",
headers: {
'Conect-Type': 'application/json'
},
body: JSON.stringify({name,gender,favorito,image_url})
});
let resJson = await res.json();
if (res.status === 201) {
setName("");
setGender("");
setFavorito("");
setImage_url("");
setMessage("User crated successfully")
} else {
setMessage("Some error occured");
}
}catch (err) {
console.log(err);
}
};
return (
<>
<Banner imagem={favorito} />
<Titulo>
<h1>Cadastrar Filmes</h1>
</Titulo>
<section className="formulario">
<form onSubmit={handleSubimit}>
<div className="campo-texto">
<input
type="text"
value={name}
placeholder="Inserir nome"
onChange={(e) => setName(e.target.value)}/>
<input
type="text"
value={gender}
placeholder="Inserir genero"
onChange={(e) => setGender(e.target.value)}/>
<input
type="text"
value={image_url}
placeholder="Inserir url da imagem"
onChange={(e) => setImage_url(e.target.value)}/>
<button className="botao" type="submit">
Inserir Filme
</button>
<div className="message">{message ? <p>{message}</p> : null}</div>
</div>
</form>
</section>
{/* <Formulario aoFilmeCadastro={filme => aoNovoFilmeAdicionado(filme)}/> */}
</>
)
}
export default CadFilme;
|
<%-- EL을 사용하기 위해서는, page 디렉티브의 isELIgnored 속성을 false 로 설정해야한다. 하지만 명시하지 않을 경우 기본값이 false 이다. --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<%request.setCharacterEncoding("UTF-8");%>
<html>
<head>
<meta charset="UTF-8">
<head>
<title>파일 업로드창</title>
</head>
<body>
<pre>
1. servlet에 요청해 파일을 업로드.
2. 파일 업로드 시 반드시 encType을 multipart/form-data로 설정해야한다.
</pre>
<hr>
<form action="${contextPath}/upload.do" method="post" enctype="multipart/form-data">
파일1: <input type="file" name="file1"><br>
파일2: <input type="file" name="file2"> <br>
파라미터1: <input type="text" name="param1"> <br>
파라미터2: <input type="text" name="param2"> <br>
파라미터3: <input type="text" name="param3"> <br>
<input type="submit" value="업로드">
</form>
</body>
</html>
|
import React, { useState, useEffect } from "react";
import { useParams, useHistory } from "react-router-dom";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";
import Selector from "../partsSelector/partsSelector";
import "./planEdit.css";
import axios from "axios";
export default function EditPlan(props) {
// Vehicle type selection
const { id, objID } = useParams();
const history = useHistory();
const url = "/type/" + id;
console.log(id, objID);
// get editing details by id
const [planID, setPlanID] = useState();
const [planName, setPlanName] = useState();
const [spareParts, setValue] = useState([]);
const [planDescription, setPlanDescription] = useState();
const [planEstHours, setPlanEstHours] = useState();
const [amount, setAmount] = useState();
const [discount, setDiscount] = useState();
const [total, settotal] = useState();
useEffect(() => {
let getPlanCard = () => {
axios
.get(
"http://localhost:3001/api/maintenance/PlanCard/" + id + "/" + objID
)
.then((res) => {
setPlanID(res.data.planID);
setPlanName(res.data.planName);
setValue(res.data.spareParts);
setPlanDescription(res.data.planDescription);
setPlanEstHours(res.data.planEstHours);
setAmount(res.data.amount);
setDiscount(res.data.discount);
settotal(res.data.total);
});
};
getPlanCard();
}, []);
// onSelect set price
function setPrice(price) {
var total = 0;
var tot;
for (let i = 0; i < price.length; i++) {
total += price[i];
}
tot = total - discount;
setAmount(total);
settotal(tot);
}
// onDeselect remove price
function removePrice(price) {
var total = 0;
var tot;
for (let i = 0; i < price.length; i++) {
total += price[i];
}
tot = total - discount;
setAmount(total);
settotal(tot);
}
const totChange = () => {
if (discount == 0) {
settotal(amount);
} else if (discount < 0) {
alert("Please enter valid amounts");
} else if (total < 0) {
alert("Please enter valid amounts");
}
};
// updated data array
const planDetailSet = {
planID,
planName,
spareParts,
planDescription,
planEstHours,
amount,
discount,
total,
};
//Update The PlanCard
const updateThisPlan = (e) => {
e.preventDefault();
axios
.put(
"http://localhost:3001/api/maintenance/updatePlan/" + id + "/" + objID,
planDetailSet
)
.then(() => {
alert("Plan card update successful");
history.push(url);
})
.catch((err) => {
console.log(err);
});
};
// Bill calculation
function billCalcualtion(e) {
setDiscount(e.target.value);
settotal(amount - e.target.value);
}
function TotalCalculation(amm) {
settotal(amm - discount);
}
return (
<div
className="chamoddata"
style={{ marginTop: "40px", marginBottom: "40px" }}
>
<h2>Edit Current Plan</h2>
<h5>Vehicle Type :- {id}</h5>
<hr />
<div className="newPlanContainer">
<form
className="cfc"
onSubmit={(e) => {
updateThisPlan(e);
}}
>
<div className="planDetails">
<div className="planID idInForm">
<label className="planIdLabel idLabel">Plan ID</label>
<input className="adding" defaultValue={planID} disabled />
</div>
<br></br>
<br></br>
<br></br>
<div className="form-floating mb-3">
<input
type="text"
class="form-control f-con"
id="planTitle"
placeholder="Plan title"
required
defaultValue={planName}
onChange={(e) => {
setPlanName(e.target.value);
}}
/>
<label for="planTitle" className="lab">
Plan title
</label>
</div>
<div className="selectorCtrl">
<Selector
getValue={(e) => {
setValue(e.map((data) => data));
setPrice(e.map((p) => p.price));
}}
sp={spareParts}
removeValue={(e) => {
setValue(e.map((data) => data));
removePrice(e.map((p) => p.price));
}}
/>
</div>
<br></br>
<br></br>
<div class="form-floating">
<textarea
class="form-control f-con ta"
placeholder="Leave a comment here"
id="floatingTextarea2"
style={{ height: "200px" }}
defaultValue={planDescription}
onChange={(e) => {
setPlanDescription(e.target.value);
}}
></textarea>
<label className="lab" for="floatingTextarea2">
Description
</label>
</div>
<br></br>
<div className="form-floating mb-3" style={{ width: "200px" }}>
<input
type="Number"
class="form-control f-con"
id="estHours"
placeholder="estHours"
required
step="0.10"
defaultValue={planEstHours}
onChange={(e) => {
setPlanEstHours(e.target.value);
}}
/>
<label for="planTitle" className="lab">
EST Hours
</label>
</div>
<div className="bill">
<label className="invo">INVOICE</label>
<br></br>
<div className="allbillLabels">
<label className="labelBill">AMOUNT</label>
<label className="labelBill">DISCOUNT</label>
<label className="labelBill">TOTAL</label>
</div>
<div className="allbillInputs">
<input
className="inputBill"
type="number"
min="0"
defaultValue={amount}
onChange={(e) => {
setAmount(e.target.value);
TotalCalculation(e.target.value);
}}
/>
<input
className="inputBill dis"
type="number"
placeholder="0.00"
min="0"
defaultValue={discount}
onChange={(e) => {
billCalcualtion(e);
totChange(e);
}}
/>
<input
className="inputBill"
type="number"
value={total}
disabled
/>
</div>
</div>
<hr className="sep" />
<div className="btnCon">
<Link to={url}>
<Button className="btns">CANCEL</Button>
</Link>
<Button type="Submit" className="btns create">
UPDATE
</Button>
</div>
</div>
</form>
</div>
</div>
);
}
|
import * as React from 'react';
import IconButton from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Link from 'next/link';
//Icons
import MenuIcon from '@mui/icons-material/Menu';
//hooks
import { useUser } from '@auth0/nextjs-auth0';
export default function BasicMenu() {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const { user } = useUser();
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleSessionButtons = () => {
if (user ) {
return (
<MenuItem onClick={handleClose}>
<a href="/api/auth/logout">
Cerrar sesión
</a>
</MenuItem>
)
} else {
return (
<MenuItem onClick={handleClose}>
<a href="/api/auth/login">
Iniciar sesión
</a>
</MenuItem>
)
}
}
return (
<div>
<IconButton
id="basic-button"
aria-controls={open ? 'basic-menu' : undefined}
aria-haspopup="true"
aria-expanded={open ? 'true' : undefined}
onClick={handleClick}
color="inherit"
>
<MenuIcon />
</IconButton>
<Menu
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
'aria-labelledby': 'basic-button',
}}
>
<MenuItem onClick={handleClose}>
<Link href="/about">
Sobre Nosotros
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link href="/ranking">
Ranking
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link href="/">
Inicio
</Link>
</MenuItem>
{handleSessionButtons()}
</Menu>
</div>
);
}
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<meta name="csrf-token" content="{{ csrf_token() }}" />
<title>{{env('APP_NAME')}}</title>
<!-- Custom fonts for this template-->
<link href="{{asset('libs/fontawesome-free/css/all.min.css')}}" rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Custom styles for this template-->
<link href="{{asset('libs/sbadmin/css/sb-admin-2.css')}}" rel="stylesheet">
<link href="{{asset('libs/datatables/dataTables.bootstrap4.min.css')}}" rel="stylesheet">
<link href="{{asset('libs/datatables/select.bootstrap4.min.css')}}" rel="stylesheet">
<link rel="icon" href="../../../img/icono.png">
</head>
<body id="page-top">
@auth
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
@include('layouts.docente.sidebar')
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
<!-- Sidebar Toggle (Topbar) -->
<button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
<i class="fa fa-bars"></i>
</button>
<!-- Topbar Search
<form
class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-light border-0 small" placeholder="Search for..."
aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" type="button">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
-->
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Nav Item - Search Dropdown (Visible Only XS) -->
<!-- Dropdown - Messages -->
<!-- Nav Item - Alerts -->
<div class="topbar-divider d-none d-sm-block"></div>
<!-- Nav Item - User Information -->
<li class="nav-item dropdown no-arrow">
<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mr-2 d-none d-lg-inline text-gray-600 small"> <b>Docente: </b> {{auth()->user()->nombre}}</span>
<img class="img-profile rounded-circle"
src="{{asset('img/undraw_profile.svg')}}">
</a>
<!-- Dropdown - User Information -->
<div class="dropdown-menu dropdown-menu-right shadow animated--grow-in"
aria-labelledby="userDropdown">
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Salir
</a>
</div>
</li>
</ul>
</nav>
<!-- End of Topbar -->
<!-- Begin Page Content -->
@include('layouts.docente.content')
</div>
<!-- End of Main Content -->
<!-- Footer -->
@include('layouts.partials.footer')
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">¿Cerrar sesión?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Presiona el botón 'Salir' para cerrar tu sesión actual.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancelar</button>
<a class="btn btn-primary" href="/logout">Salir</a>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="{{asset('libs/jquery/jquery.min.js')}}"></script>
<script src="{{asset('libs/bootstrap/js/bootstrap.bundle.min.js')}}"></script>
<!-- Core plugin JavaScript-->
<script src="{{asset('libs/jquery-easing/jquery.easing.min.js')}}"></script>
<!-- Scripts custom generales -->
<script src="{{asset('libs/sbadmin/js/sb-admin-2.js')}}"></script>
<script src="{{asset('libs//datatables/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('libs//datatables/dataTables.bootstrap4.min.js')}}"></script>
<script src="{{asset('libs//datatables/dataTables_idioma.js')}}"></script>
<!-- Bootbox -->
<script src="{{asset('libs/sbadmin/js/bootbox.all.min.js')}}"></script>
<!-- Scripts custom de cada página -->
@include('layouts.partials.scripts')
@endauth
@guest
<p>Te perdiste güachín?</p>
@endguest
</body>
</html>
|
//---------------------------------------------------------------------------
//! @file Client.cpp
//! @brief クライアントクラス
//---------------------------------------------------------------------------
#include "Client/BaseClient.h"
#include "Server/BaseServer.h"
#include <sstream>
namespace _network {
//---------------------------------------------------------------------------
//! コンストラクタ
//---------------------------------------------------------------------------
BaseClient::BaseClient()
{
}
//---------------------------------------------------------------------------
//! デストラクタ
//---------------------------------------------------------------------------
BaseClient::~BaseClient()
{
}
//---------------------------------------------------------------------------
//! 繋がる
//---------------------------------------------------------------------------
void BaseClient::Connect()
{
_socket.CreateTCP();
_network::SocketAddress addr;
addr.SetIPv4(127, 0, 0, 1);
addr.SetPortNum(3000);
_socket.Connect(addr);
_status = Status::Connecting;
}
//---------------------------------------------------------------------------
//! POLL更新 -> CheckPoll()
//---------------------------------------------------------------------------
void BaseClient::UpdatePollFD()
{
PollFD pf;
GetPollFD(pf);
if(_PollFD(&pf, 1, 0)) {
CheckPoll(pf);
}
}
//---------------------------------------------------------------------------
//! ネットワーク中断する
//---------------------------------------------------------------------------
void BaseClient::Close()
{
_status = Status::Closed;
printf_s("> client %p: close\n", this);
_socket.Close();
}
//---------------------------------------------------------------------------
//! 送信の判定
//---------------------------------------------------------------------------
bool BaseClient::NeedSend() const
{
return _sendBufferOffset < _sendBuffer.size();
}
//---------------------------------------------------------------------------
//! 受信の判定
//---------------------------------------------------------------------------
bool BaseClient::NeedRecv() const
{
return !NeedSend();
}
//---------------------------------------------------------------------------
//! 受信
//---------------------------------------------------------------------------
void BaseClient::OnRecv()
{
size_t n = _socket.AvailableBytesToRead();
if(!n) {
Close();
return;
}
_recvBuffer.resize(n);
auto* p = &*(_recvBuffer.begin());
int ret = _socket.Recv(p, n);
if(ret <= 0) {
Close();
return;
}
_recvBuffer.push_back(0);
HandleCmd(_recvBuffer);
_recvBuffer.clear();
}
//---------------------------------------------------------------------------
//! 送信
//---------------------------------------------------------------------------
void BaseClient::OnSend()
{
if(_status == Status::Connecting) {
_status = Status::Connected;
}
if(_sendBuffer.size() <= 0) {
return;
}
size_t ret = _socket.Send(_sendBuffer.data(), _sendBuffer.size());
if(ret <= 0) {
Close();
return;
}
printf_s("Send: %s\n", _sendBuffer.c_str());
_sendBuffer.clear();
//_sendBufferOffset += ret;
}
//---------------------------------------------------------------------------
//! 繋がっている
//---------------------------------------------------------------------------
void BaseClient::Connected()
{
_status = Status::Connected;
printf_s("connected\n");
}
//---------------------------------------------------------------------------
//! ネットワークパケットの収発 (recv / Send)
//---------------------------------------------------------------------------
void BaseClient::CheckPoll(PollFD& fd)
{
if(fd.CanRead()) {
OnRecv();
}
if(fd.CanWrite()) {
OnSend();
}
}
//---------------------------------------------------------------------------
//! ソケット取得
//---------------------------------------------------------------------------
_network::Socket& BaseClient::GetSocket()
{
return _socket;
}
//---------------------------------------------------------------------------
//! PollFD取得
//---------------------------------------------------------------------------
void BaseClient::GetPollFD(PollFD& pf)
{
bool write = false;
if(_status == Status::Connecting) {
write = true;
}
if(_status == Status::Connected && _sendBuffer.size())
write = true;
pf.Reset(_socket, true, write);
}
//---------------------------------------------------------------------------
//! ソケット有効か
//---------------------------------------------------------------------------
bool BaseClient::IsValid()
{
return _socket.IsVaild();
}
//---------------------------------------------------------------------------
//! サーバーと繋がっているか
//---------------------------------------------------------------------------
bool BaseClient::IsConnected()
{
return _status == Status::Connected;
}
//---------------------------------------------------------------------------
//! サーバーがクライアントの通信を許可する
//---------------------------------------------------------------------------
void BaseClient::AcceptFromListenSocket(Socket& listenSocket)
{
listenSocket.Accept(_socket);
_pollfd.fd = _socket.GetSocket();
Connected();
}
//---------------------------------------------------------------------------
//! 送信バッファ
//---------------------------------------------------------------------------
void BaseClient::SetSendBuffer(const std::string& sendMsg)
{
_sendBuffer.append(sendMsg);
}
//---------------------------------------------------------------------------
//! Send Bufferの中身をプリント
//---------------------------------------------------------------------------
void BaseClient::PrintSendBuffer()
{
printf_s("%s", _sendBuffer.c_str());
}
} // namespace _network
|
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ficha de Solicitação de Passaporte - SME</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
:root {
--base-color: #FDDC0F;
--background-color: #0D0D2C;
--text-color: #FFFFFF;
}
body {
font-family: Arial, sans-serif;
color: var(--text-color);
background-color: var(--background-color);
margin: 0;
}
.header {
background-image: url('img/b.jpg'); /* Substitua 'header-background.jpg' pelo caminho da sua imagem */
background-size: cover;
background-position: center;
color: var(--text-color);
padding: 20px;
}
.header .container {
display: flex;
align-items: center;
justify-content: space-between;
}
.header .logo {
max-height: 60px;
}
.header .menu {
list-style: none;
display: flex;
gap: 20px;
margin: 0;
padding: 0;
}
.header .menu li a {
color: var(--text-color);
text-decoration: none;
font-weight: bold;
display: flex;
align-items: center;
gap: 8px;
}
.header .menu li a:hover {
color: var(--base-color);
}
.section {
padding: 40px 20px;
}
.home-section {
background-color: var(--background-color);
color: var(--background-color);
}
.button-primary {
background-color: var(--background-color);
color: var(--text-color);
border: 1px solid var(--text-color);
padding: 10px 20px;
cursor: pointer;
font-size: 16px;
}
.button-primary:hover {
background-color: #e0c20f; /* Um tom mais escuro do amarelo */
}
.container {
color: var(--text-color);
}
.card {
background-color: var(--background-color);
color: var(--text-color);
padding: 20px;
margin: 10px;
border: 1px solid var(--base-color);
border-radius: 8px;
}
.footer {
background-color: var(--background-color);
color: var(--text-color);
padding: 20px 0;
text-align: center;
}
.footer-icons {
margin-top: 10px;
}
.footer-icons a {
color: var(--text-color);
margin: 0 10px;
text-decoration: none;
font-size: 1.5em;
}
.footer-icons a:hover {
color: var(--base-color);
}
.form-group label {
color: var(--text-color);
}
.form-group input, .form-group textarea {
width: 100%;
padding: 10px;
margin-top: 5px;
margin-bottom: 20px;
border: 1px solid var(--base-color);
border-radius: 4px;
}
.form-group input:focus, .form-group textarea:focus {
outline: none;
border-color: #e0c20f;
}
</style>
</head>
<body>
<header class="header">
<div class="container">
<img src="img/logo.png" alt="Logo SME" class="logo">
<nav>
<ul class="menu">
<li><a href="#home"><i class="fas fa-home"></i> Home</a></li>
<li><a href="#sobre"><i class="fas fa-info-circle"></i> Sobre</a></li>
<li><a href="#servicos"><i class="fas fa-concierge-bell"></i> Serviços</a></li>
<li><a href="#solicitacao"><i class="fas fa-passport"></i> Solicitação</a></li>
</ul>
</nav>
</div>
</header>
<section id="home" class="section home-section">
<div class="home-background"></div>
<div class="container">
<h1>Bem-vindo ao SME</h1>
<p>Seu portal para solicitação de passaporte.</p>
</div>
</section>
<section id="sobre" class="section">
<div class="container">
<h2>Sobre o SME</h2>
<p>O Serviço de Migração e Emigração (SME) é responsável pela emissão e controle de passaportes.</p>
</div>
</section>
<section id="servicos" class="section">
<div class="container">
<h2>Nossos Serviços</h2>
<div class="row">
<div class="card">
<h3>Serviço de Emissão de Passaporte</h3>
<p>Procedimento para solicitar um novo passaporte.</p>
</div>
<div class="card">
<h3>Serviço de Renovação de Passaporte</h3>
<p>Renovação de passaporte expirado ou próximo da data de validade.</p>
</div>
<div class="card">
<h3>Serviço de Passaporte Emergencial</h3>
<p>Emissão rápida de passaporte em casos de emergência.</p>
</div>
</div>
</div>
</section>
<section id="solicitacao" class="section">
<div class="container">
<h2>Solicitação de Passaporte</h2>
<p>Preencha o formulário abaixo para solicitar seu passaporte.</p>
<form action="php/solicitar.php" method="POST">
<div class="form-group">
<label for="nome">Nome Completo:</label>
<input type="text" id="nome" name="nome" required>
</div>
<div class="form-group">
<label for="data_nascimento">Data de Nascimento:</label>
<input type="date" id="data_nascimento" name="data_nascimento" required>
</div>
<div class="form-group">
<label for="email">Endereço de E-mail:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="telefone">Telefone:</label>
<input type="tel" id="telefone" name="telefone" required>
</div>
<div class="form-group">
<label for="endereco">Endereço Completo:</label>
<textarea id="endereco" name="endereco" rows="4" required></textarea>
</div>
<button type="submit" class="button-primary">Enviar Solicitação</button>
</form>
</div>
</section>
<footer class="footer">
<div class="container">
<p>© 2024 SME. Todos os direitos reservados.</p>
<div class="footer-icons">
<a href="https://www.instagram.com" target="_blank"><i class="fab fa-instagram"></i></a>
<a href="https://www.facebook.com" target="_blank"><i class="fab fa-facebook-f"></i></a>
<a href="mailto:[email protected]"><i class="fas fa-envelope"></i></a>
</div>
</div>
</footer>
</body>
</html>
|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flutter code sample for DropdownButton.style
import 'package:flutter/material.dart';
class Dropdown_Button_Style extends StatelessWidget {
const Dropdown_Button_Style({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Dropdown_Button_Style_Widget(),
),
);
}
}
class Dropdown_Button_Style_Widget extends StatefulWidget {
const Dropdown_Button_Style_Widget({Key? key}) : super(key: key);
@override
State<Dropdown_Button_Style_Widget> createState() => _Dropdown_Button_Style_WidgetState();
}
class _Dropdown_Button_Style_WidgetState extends State<Dropdown_Button_Style_Widget> {
List<String> options = <String>['One', 'Two', 'Free', 'Four'];
String dropdownValue = 'One';
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
color: Colors.blue,
child: DropdownButton<String>(
value: dropdownValue,
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
style: const TextStyle(color: Colors.blue),
selectedItemBuilder: (BuildContext context) {
return options.map((String value) {
return Text(
dropdownValue,
style: const TextStyle(color: Colors.white),
);
}).toList();
},
items: options.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
);
}
}
|
import { Button } from "react-bootstrap";
import { useNavigate } from "react-router-dom";
import useProducts from "../../serviceHooks/useProducts";
import { useContext, useMemo, useState } from "react";
import ThemeContext from "../../Contexts/ThemeContext";
const categories = ["smartphones", "laptops"];
const ProductPage = () => {
const navigate = useNavigate();
const { theme, setTheme } = useContext(ThemeContext);
const [category, setCategory] = useState("");
const { data, isLoading, isSuccess } = useProducts();
const productsList = useMemo(() => {
return category
? data?.filter((product) => product.category === category)
: data;
}, [category, data]);
return (
<div>
<h1>Product Page</h1>
<Button
className="btn-info"
onClick={() =>
theme === "light" ? setTheme("dark") : setTheme("light")
}
>
Change Theme
</Button>
<div className="my-10">
<Button
className="btn-warning"
onClick={() => setCategory(categories[0])}
>
Smartphones
</Button>
<Button
className="btn-warning"
onClick={() => setCategory(categories[1])}
>
Laptops
</Button>
</div>
<ul>
{isLoading ? (
<div className="d-flex align-items-center">
<div
className="spinner-border ml-auto"
role="status"
aria-hidden="true"
></div>
</div>
) : (
isSuccess &&
productsList?.map((product) => (
<li key={product.id}>
<Button
type="button"
className={theme === "light" ? "btn-primary" : "btn-dark"}
onClick={() => navigate(`${product.title}/${product.id}`)}
>
{product.title}
</Button>
</li>
))
)}
</ul>
</div>
);
};
export default ProductPage;
|
import {
privateProcedure,
publicProcedure,
router,
} from './trpc'
import { getKindeServerSession } from '@kinde-oss/kinde-auth-nextjs/server'
import { TRPCError } from '@trpc/server'
import { db } from '@/db'
import { z } from 'zod'
import { INFINITE_QUERY_LIMIT } from '@/config/infinite-query'
import { getPineconeClient } from '@/lib/pinecone'
import { absoluteUrl } from '@/lib/utils'
import {
getUserSubscriptionPlan,
stripe,
} from '@/lib/stripe'
import { PLANS } from '@/config/stripe'
// define all api endpoints here
export const appRouter = router({
//api 1
authCallback: publicProcedure.query(async () => {
const { getUser } = getKindeServerSession()
const user = await getUser()
if (!user?.id || !user?.email)
throw new TRPCError({ code: 'UNAUTHORIZED' })
// check if the user is in the database
const dbUser = await db.user.findFirst({
where: {
id: user.id,
},
})
if (!dbUser) {
// create user in db
await db.user.create({
data: {
id: user.id,
email: user.email,
},
})
}
return { success: true }
}),
//api 2
getUserFiles: privateProcedure.query(async ({ ctx }) => {
// obtained from the middle where context
const { userId } = ctx
return await db.file.findMany({
where: {
userId,
},
})
}),
//api 3
deleteFile: privateProcedure
// enforce types at runtime (make sure we always pass the id to this function)
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
const { userId } = ctx
const file = await db.file.findFirst({
where: {
id: input.id,
// ensure its the owner that deletes
userId,
},
})
if (!file) throw new TRPCError({ code: 'NOT_FOUND' })
await db.file.delete({
where: {
id: input.id,
},
})
try{
// delete vector pinecone
const {client: pinecone, pineconeIndex} = await getPineconeClient()
const ns = pineconeIndex.namespace(file.id)
await ns.deleteAll()
// console.log("vector deleted")
}catch(err){
console.log(err)
}
try{
console.log("deleting")
// delete all messages
await db.message.deleteMany({
where: {
File: file,
userId,
fileId: file.id
},
})
await db.message.deleteMany({
where: {
fileId: null
},
})
}catch(err){
console.log(err)
}
return file
}),
//api 4
getFile: privateProcedure
.input(z.object({ key: z.string() }))
.mutation(async ({ ctx, input }) => {
const { userId } = ctx
const file = await db.file.findFirst({
where: {
key: input.key,
userId,
},
})
if (!file) throw new TRPCError({ code: 'NOT_FOUND' })
return file
}),
//api 5
getFileUploadStatus: privateProcedure
.input(z.object({ fileId: z.string() }))
.query(async ({ input, ctx }) => {
const file = await db.file.findFirst({
where: {
id: input.fileId,
userId: ctx.userId,
},
})
if (!file) return { status: 'PENDING' as const }
return { status: file.uploadStatus }
}),
//api 6
// infinitely fetch users message from db as user scrolls
// .nullish mean it is optional
getFileMessages: privateProcedure
.input(
z.object({
limit: z.number().min(1).max(100).nullish(),
cursor: z.string().nullish(),
fileId: z.string(),
})
)
.query(async ({ ctx, input }) => {
const { userId } = ctx
const { fileId, cursor } = input
const limit = input.limit ?? INFINITE_QUERY_LIMIT
const file = await db.file.findFirst({
where: {
id: fileId,
userId,
},
})
if (!file) throw new TRPCError({ code: 'NOT_FOUND' })
// fetch all the messages related to the file
const messages = await db.message.findMany({
take: limit + 1, // the +1 will serve as the cursor once in view, gets the next limit
where: {
fileId,
},
orderBy: {
createdAt: 'desc',
},
cursor: cursor ? { id: cursor } : undefined, // once cursor, determine the next batch
// select just the things we want
select: {
id: true,
isUserMessage: true,
createdAt: true,
text: true,
},
})
// gets the last one and saves it to be used as the cursor
let nextCursor: typeof cursor | undefined = undefined
if (messages.length > limit) {
const nextItem = messages.pop()
nextCursor = nextItem?.id
}
return {
messages,
nextCursor,
}
}),
// api 7 stripe
createStripeSession: privateProcedure.mutation(
async ({ ctx }) => {
const { userId } = ctx
// on server side you cant use just relative urls
const billingUrl = absoluteUrl('/dashboard/billing')
if (!userId)
throw new TRPCError({ code: 'UNAUTHORIZED' })
const dbUser = await db.user.findFirst({
where: {
id: userId,
},
})
if (!dbUser)
throw new TRPCError({ code: 'UNAUTHORIZED' })
const subscriptionPlan =
await getUserSubscriptionPlan()
if (
subscriptionPlan.isSubscribed &&
dbUser.stripeCustomerId
) {
const stripeSession =
await stripe.billingPortal.sessions.create({
customer: dbUser.stripeCustomerId,
return_url: billingUrl,
})
return { url: stripeSession.url }
}
const stripeSession =
await stripe.checkout.sessions.create({
success_url: billingUrl,
cancel_url: billingUrl,
payment_method_types: ['card', 'paypal'],
mode: 'subscription',
billing_address_collection: 'auto',
line_items: [
{
// filter to get the pro plan price
price: PLANS.find((plan) => plan.name === 'Pro'
)?.price.priceIds.test,
quantity: 1,
},
],
metadata: {
userId: userId,
},
})
return { url: stripeSession.url, }
}
),
})
// This tells app whihc api routes exists and which data types they return
export type AppRouter = typeof appRouter
|
n, m = map(int, input().split())
nums = [] # 숫자가 담길 스택
def dfs():
if len(nums) == m: # 재귀함수로 반복 -> 함수 출력 조건을 먼저 걸어준다.
print(' '.join(map(str, nums)))
return
for i in range(1, n + 1): # 1부터 n까지의 자연수 중 선택
if i in nums: # 이미 선택한 숫자라면..
continue # 경우의 수에서 배제 -> 백트래킹
nums.append(i) # 스택에 추가
dfs() # 동작 후
nums.pop() # 스택에서 제거 -> 이전의 상황으로 돌아옴.
dfs()
|
function gerarNumerosEntre(min,max) {
if(min > max) {
[max,min] = [min,max]
}
return new Promise(resolve => {
setTimeout(function() {
const aleatorio = parseInt(Math.random() * (max - min +1)) + min
resolve(aleatorio)
},3000);
})
}
function gerarVariosNumeros() {
return Promise.all([
gerarNumerosEntre(1,60,4000), //entre 1 e 60 em 4 segundos
gerarNumerosEntre(1,60,1000),
gerarNumerosEntre(1,60,500),
gerarNumerosEntre(1,60,100),
gerarNumerosEntre(1,60,1500)
])
}
console.time('promise')
gerarVariosNumeros()
.then(numeros => console.log(numeros))
.then(() => {
console.timeLog('promise')
console.timeEnd('promise')
})
|
import fs from "fs";
import * as path from "path";
function loadResource(resourcePath: string): string {
const fullResourcePath = path.join(__dirname, "..", "resources", ...resourcePath.split("/"));
return fs.readFileSync(fullResourcePath, { encoding: "utf-8" });
}
async function asyncSleep(millis: number): Promise<void> {
return new Promise(resolve => {
setTimeout(resolve, millis);
});
}
async function main(): Promise<void> {
console.log("Reading our super important report...");
await asyncSleep(500);
let rawReport;
try {
rawReport = loadResource("report.json");
}
catch (err) {
console.error("Failed reading our report :(");
console.error(err);
process.exit(1);
}
console.log("Parsing the report...");
await asyncSleep(1000);
let report;
try {
report = JSON.parse(rawReport);
}
catch(err) {
console.error("Failed parsing our report. Was it not good enough? :(");
console.error(err);
process.exit(1);
}
console.log("Report parsed successfully!");
console.log("Now printing our report continuously to show how good we are!");
while (true) {
console.log(report);
await asyncSleep(15*1000);
}
}
void main();
|
import React from 'react'
import { useState } from 'react'
import Progress from '../../components/Progress/Progress'
import './Upload.css'
import { message } from 'antd'
import { useRef } from 'react'
import { Link } from 'react-router-dom'
function Upload() {
const [fileList, setFilesList] = useState([])
const preRef = useRef(null)
const countRef = useRef(0)
const fileOnChange = () => {
let files = document.getElementById('inputFile').files
if (files.length > 50 || files.length + countRef.current > 50) {
message.warn('单次最大上传五十张文件')
} else {
let tempFilesList = []
for (let i = 0; i < files.length; i++) {
//图片格式限制
if (
files[i].type === 'image/gif' ||
files[i].type === 'image/jpg' ||
files[i].type === 'image/jpeg' ||
files[i].type === 'image/png'
) {
tempFilesList.push(files[i])
} else {
message.warn('图片格式限制(jpg,png,gif)')
}
}
setFilesList([...fileList, ...tempFilesList])
countRef.current += tempFilesList.length
}
}
const handleDelete = () => {
countRef.current -= 1
if (countRef.current === 0) {
setFilesList([])
}
console.log(countRef.current);
}
const uploadConfirm = () => {
if (countRef.current === 0) {
message.warn('当前未选择任何图片')
} else {
message.success('确认上传成功')
setFilesList([])
}
}
return (
<>
<div className="upload-container">
<label style={{ display: countRef.current === 0 || fileList.length === 0 ? true : 'none' }} htmlFor="inputFile">
<div className='add'>
<div>点击添加图片</div>
<span>最多可同时上传50张图片(支持格式jpg,jpeg,png,gif)</span>
</div>
</label>
<div ref={preRef} className='pre-container'>
{fileList.map((item) => (
<Progress handleDelete={handleDelete} key={item.name} file={item}></Progress>
))}
</div>
<input accept="image/jpg,image/gif,image/png,image/jpeg" style={{ display: 'none' }} multiple id='inputFile' type="file" onChange={fileOnChange} />
<div style={{ display: countRef.current === 0 || fileList.length === 0 ? 'none' : true }}>
<label htmlFor="inputFile"><div className='button' onClick={uploadConfirm}>继续上传</div></label>
<Link to="/"><div className='button'>返回主页</div></Link>
</div>
</div>
</>
)
}
export default Upload
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.