text
stringlengths 184
4.48M
|
|---|
import { Button, Pressable, Text, TouchableHighlight, View } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context';
import * as MediaLibrary from 'expo-media-library'
import { AVPlaybackStatus, Audio } from 'expo-av'
import { useContext, useEffect, useState } from 'react';
import { getAssetsFromAlbum } from '../utils/getAssetsFromAlbum';
import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams } from 'expo-router';
import { AssetsContext } from '../contexts/AssetsContext';
import { AudioPlayer } from '../components/shared/AudioPlayer';
export default function AudioPage() {
const context = useContext(AssetsContext);
if(!context) return;
const [assets, setAssets] = context;
const {color} = useLocalSearchParams();
const [play, setPlay] = useState(false);
const [audio, setAudio] = useState<Audio.Sound | null>(null);
const [audioAsset, setAudioAsset] = useState<MediaLibrary.Asset>();
const [dataPlaybackInfo, setDataPlaybackInfo] = useState<{isBuffering: boolean, durationMillis: number|undefined, positionMillis: number}>()
useEffect(() => {
getAssetsFromAlbum('WhatsApp Audio', 'audio')
.then((assets) => {
setAssets(Array.from(assets))
})
}, [])
// useEffect(() => {
// if(!play) {
// audio?.playAsync();
// setPlay(true)
// } else {
// audio?.pauseAsync();
// setPlay(false)
// }
// }, [play, setPlay]);
useEffect(() => {
if(dataPlaybackInfo?.durationMillis) {
setTimeout(() => {
audio?.pauseAsync();
}, dataPlaybackInfo.durationMillis * 0.1)
}
}, [dataPlaybackInfo?.durationMillis])
const onPlaybackStatusUpdate = (status: AVPlaybackStatus) => {
if (!status.isLoaded) {
if (status.error) {
console.log(`Encountered a fatal error during playback: ${status.error}`);
}
}
else {
setDataPlaybackInfo({
isBuffering: status.isBuffering,
durationMillis: status.durationMillis,
positionMillis: status.positionMillis,
})
}
}
async function playRandomAudio() {
try {
const randomIndex = Math.floor(Math.random() * assets.length);
const randomAudioAsset = assets[randomIndex];
const newAudio = new Audio.Sound();
setAudio(newAudio);
await newAudio.loadAsync({ uri: randomAudioAsset.uri });
newAudio.setOnPlaybackStatusUpdate(onPlaybackStatusUpdate)
await newAudio.playAsync();
setAudioAsset(randomAudioAsset);
} catch (error) {
console.log('Error playing random audio:', error);
}
}
const handleAudioPlayback = async () => {
if(!audio) return;
setPlay(e => !e);
if(!play) {
await audio?.playAsync();
} else {
await audio?.pauseAsync();
}
}
return (
<SafeAreaView style={{backgroundColor: color as string}} className='flex-1'>
<View>
<Text className='text-center p-5 text-xl'>Audio</Text>
{audioAsset?.filename && <Text>{audioAsset?.filename}</Text>}
{!audioAsset && <Pressable className=' rounded bg-white text-black p-2 m-2' onPress={() => playRandomAudio()} >
<Text className='text-center'>
Estoy preparado!
</Text>
</Pressable> }
{audioAsset && <TouchableHighlight >
<View className='bg-white shadow-xl m-2 rounded-xl flex justify-center items-center pl-[3px] aspect-square self-center'>
<Ionicons name={play ? "play" : "pause"} size={60} color={color as string} onPress={handleAudioPlayback} />
</View>
</TouchableHighlight>}
{dataPlaybackInfo && <AudioPlayer color={color as string} dataPlaybackInfo={dataPlaybackInfo} />}
</View>
</SafeAreaView>
)
}
|
import { KycComponent } from './pages/kyc/kyc.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CanActivateRouteGuard } from '@core/guards/can-activate-route.guard';
import { LogGuard } from '@core/guards/log.guard';
import { CommonComponent } from './common/common.component';
import { CommonSdkComponent } from './common-sdk/common-sdk.component';
const routes: Routes = [
{
path: '',
redirectTo: 'auth',
pathMatch: 'full'
},
{
path: 'auth',
// canActivate: [LogGuard],
loadChildren: () =>
import('./pages/auth/auth.module').then((m) => m.AuthModule),
},
{
path: 'kyc',
component: KycComponent,
// canActivate: [CanActivateRouteGuard],
children: [
{
path: '',
loadChildren: () =>
import('./pages/pages.module').then((m) => m.PagesModule),
},
],
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
providers: [CanActivateRouteGuard, LogGuard],
exports: [RouterModule],
})
export class AppRoutingModule {}
|
import { CldOgImage } from 'next-cloudinary';
interface OgImageProps {
title: string;
twitterTitle: string;
}
const OgImage = ({ title, twitterTitle }: OgImageProps) => {
return (
<CldOgImage
src={`assets/cloudinary-social-background`}
overlays={[
{
width: 2000,
crop: 'fit',
position: {
y: -160
},
text: {
color: 'white',
fontFamily: 'Source Sans Pro',
fontSize: 200,
fontWeight: 'black',
text: title,
alignment: 'center',
lineSpacing: -50
}
},
{
publicId: 'assets/cloudinary-white',
position: {
x: -190,
y: 180,
},
},
{
publicId: 'assets/netlify-white',
height: 160,
position: {
x: 380,
y: 190,
},
},
{
position: {
y: 320
},
text: {
color: 'white',
fontFamily: 'Source Sans Pro',
fontSize: 60,
fontWeight: 'bold',
text: 'netlify.cloudinary.dev'
}
}
]}
alt=""
/>
)
}
export default OgImage;
|
package com.psh.taskito.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.UUID
@Entity(tableName = "tasks")
data class Task constructor(
@ColumnInfo(name = "title")
var title: String = "",
@ColumnInfo(name = "description")
var description: String = "",
@ColumnInfo(name = "completed")
var isCompleted: Boolean = false,
@PrimaryKey @ColumnInfo(name = "id")
var id: String = UUID.randomUUID().toString()
) {
val titleForList: String
get() = title.ifEmpty { description }
val isActive
get() = !isCompleted
val isEmpty
get() = title.isEmpty() || description.isEmpty()
}
|
"use client";
import React, { useRef } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
function PanelAuthPage() {
const router = useRouter();
const username = useRef("");
const password = useRef("");
const inputHandler = (
e: React.ChangeEvent<HTMLInputElement>,
key: string
) => {
if (key === "username") {
username.current = e.target.value;
} else {
password.current = e.target.value;
}
};
const onLogin = async () => {
await signIn("credentials", {
// callbackUrl: process.env.NEXTAUTH_URL,
redirect: false,
password: password.current,
username: username.current,
}).then((res) => {
if (res?.ok) {
router.replace("/pandora/movie");
} else {
alert("username / password salah");
}
});
};
return (
<div className="flex flex-1 justify-center items-center">
<div className="flex flex-col justify-center items-center p-4 rounded-md bg-[#fff]">
<h1 className="text-3xl mb-4">AUTH</h1>
<label htmlFor="username">Username</label>
<input
className="outline-none mb-4 border-solid border-secondary border-[1px] rounded px-2"
type="text"
name="username"
autoComplete="off"
onChange={(e) => inputHandler(e, "username")}
/>
<label htmlFor="password">Password</label>
<input
onKeyDown={(e) => {
if (e.key == "Enter") {
onLogin();
}
}}
className="outline-none mb-4 border-solid border-secondary border-[1px] rounded px-2"
type="password"
name="password"
autoComplete="off"
onChange={(e) => inputHandler(e, "password")}
/>
<button
className="bg-secondary rounded py-2 px-6 text-sm"
onClick={onLogin}
>
LOGIN
</button>
</div>
</div>
);
}
export default PanelAuthPage;
|
import { StyleGroupDefinition, StylePropertyDefinition } from '../../types/common';
export const styleProperties: Array<StylePropertyDefinition> = [
{
name: 'tablePreviewGridPaddingLeft',
cssProperty: 'padding-left',
displayName: 'Grid Left padding',
description: 'Left padding for table preview grid.',
selector: '.comp.compTablePreviewGrid._noAnchorGrid',
},
{
name: 'tablePreviewGridPaddingRight',
cssProperty: 'padding-right',
displayName: 'Grid Right padding',
description: 'Right padding for table preview grid.',
selector: '.comp.compTablePreviewGrid._noAnchorGrid',
},
{
name: 'tablePreviewGridPaddingTop',
cssProperty: 'padding-top',
displayName: 'Grid Top padding',
description: 'Top padding for table preview grid.',
selector: '.comp.compTablePreviewGrid._noAnchorGrid',
},
{
name: 'tablePreviewGridPaddingBottom',
cssProperty: 'padding-bottom',
displayName: 'Grid Bottom padding',
description: 'Bottom padding for table preview grid.',
selector: '.comp.compTablePreviewGrid._noAnchorGrid',
},
{
name: 'anchoredGridPaddingLeft',
cssProperty: 'padding-left',
displayName: 'Grid Left padding',
description: 'Left padding for table preview grid.',
selector: '.comp.compTablePreviewGrid ._anchorGrid',
},
{
name: 'anchoredGridPaddingRight',
cssProperty: 'padding-right',
displayName: 'Grid Right padding',
description: 'Right padding for table preview grid.',
selector: '.comp.compTablePreviewGrid ._anchorGrid',
},
{
name: 'anchoredGridPaddingTop',
cssProperty: 'padding-top',
displayName: 'Grid Top padding',
description: 'Top padding for table preview grid.',
selector: '.comp.compTablePreviewGrid ._anchorGrid',
},
{
name: 'anchoredGridPaddingBottom',
cssProperty: 'padding-bottom',
displayName: 'Grid Bottom padding',
description: 'Bottom padding for table preview grid.',
selector: '.comp.compTablePreviewGrid ._anchorGrid',
},
{
name: 'tablePreviewGridGapBetween',
cssProperty: 'gap',
displayName: 'Gap between children',
description: 'Gap between children of table preview grid.',
defaultValue: '5px',
selector:
'.comp.compTablePreviewGrid ._anchorGrid, .comp.compTablePreviewGrid._noAnchorGrid',
},
];
export const styleDefaults = new Map<string, string>(
styleProperties
.filter(e => !!e.defaultValue)
.map(({ name, defaultValue }) => [name, defaultValue!]),
);
|
package com.example.di_practica2_ejercicio4_tema3
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ShopItemAdapter(var listaItems: ArrayList<ShopItem>) : RecyclerView.Adapter<ShopItemAdapter.ItemViewHolder>() {
lateinit var onClick : (View) -> Unit
//La clase declarada como itemViewHolder hereda, es, un ViewHolder
class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var titulo: TextView
private var subtitulo: TextView
private var estrellas: RatingBar
private var puntuacion: TextView
private var imagen: ImageView
init {
titulo = itemView.findViewById(R.id.tvTitulo)
subtitulo = itemView.findViewById(R.id.tvSubtitulo)
estrellas = itemView.findViewById(R.id.rbEstrellas)
puntuacion = itemView.findViewById(R.id.tvPuntuacion)
imagen = itemView.findViewById(R.id.ivImagen)
}
fun bindTarjeta(item: ShopItem, onClick: (View) -> Unit) = with(itemView) {
titulo.setText(item.titulo)
subtitulo.setText(item.subtitulo)
imagen.setImageResource(item.imagen)
estrellas.onRatingBarChangeListener = RatingBar.OnRatingBarChangeListener{ratingBar, rating, fromUser ->
puntuacion.text = rating.toString()
}
setOnClickListener { onClick(itemView) }
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ItemViewHolder {
val itemView = LayoutInflater.from(viewGroup.context).inflate(R.layout.card_item, viewGroup, false)
return ItemViewHolder(itemView)
}
override fun onBindViewHolder(viewHolder: ItemViewHolder, pos: Int) {
val item = listaItems.get(pos)
viewHolder.bindTarjeta(item, onClick)
}
override fun getItemCount(): Int {
return listaItems.size
}
override fun getItemViewType(position: Int): Int {
return position
}
}
|
import { Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { error } from 'console';
import { NgxUiLoaderService } from 'ngx-ui-loader';
import { ProductService } from 'src/app/services/product.service';
import { SnackbarService } from 'src/app/services/snackbar.service';
import { GlobalConstants } from 'src/app/shared/global-constants';
import { ConfirmationComponent } from '../dialog/confirmation/confirmation.component';
import { ProductComponent } from '../dialog/product/product.component';
import { environment } from 'src/environments/environment';
@Component({
selector: 'app-manage-product',
templateUrl: './manage-product.component.html',
styleUrls: ['./manage-product.component.scss']
})
export class ManageProductComponent implements OnInit {
displayedColumns: string[] = ['name', 'categoryName', 'description', 'price', 'image', 'edit'];
dataSource: any;
responseMessage: any;
constructor(private productService: ProductService,
private ngxService: NgxUiLoaderService,
private dialog: MatDialog,
private snackbarService: SnackbarService,
private router: Router) { }
ngOnInit(): void {
this.ngxService.start();
this.tableData();
}
tableData() {
this.productService.getProducts().subscribe((response: any) => {
response = response.map ((data:any) =>{
if (data.image){
data.image = environment.apiUrl + '/images/upload_images/' + data.image;
return data;
}
return data
})
this.ngxService.stop();
this.dataSource = new MatTableDataSource(response)
}, (error: any) => {
this.ngxService.stop();
console.log(error);
if (error.error?.message) {
this.responseMessage = error.error?.message;
}
else {
this.responseMessage = GlobalConstants.genericError;
}
this.snackbarService.openSnackBar(this.responseMessage, GlobalConstants.error);
})
}
applyFilter(event:Event){
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}
handleAddAction(){
const dialogConfig = new MatDialogConfig();
dialogConfig.data ={
action: 'Add'
}
dialogConfig.width = '850px';
const dialogRef = this.dialog.open(ProductComponent, dialogConfig);
this.router.events.subscribe(()=>{
dialogRef.close();
});
const sub = dialogRef.componentInstance.onAddProduct.subscribe(
(response)=>{
this.tableData();
}
)
}
handleEditAction(values:any){
const dialogConfig = new MatDialogConfig();
dialogConfig.data ={
action: 'Edit',
data:values
}
dialogConfig.width = '850px';
const dialogRef = this.dialog.open(ProductComponent, dialogConfig);
this.router.events.subscribe(()=>{
dialogRef.close();
});
const sub = dialogRef.componentInstance.onEditProduct.subscribe(
(response)=>{
this.tableData();
}
)
}
handleDeleteAction(values:any){
const dialogConfig = new MatDialogConfig();
dialogConfig.data = {
message:'delete '+values.name+' product'
};
const dialogRef = this.dialog.open(ConfirmationComponent, dialogConfig);
const sub = dialogRef.componentInstance.onEmitStatusChange.subscribe((response)=>{
this.ngxService.start();
this.deleteProduct(values.id);
dialogRef.close();
})
}
deleteProduct(id:any){
this.productService.delete(id).subscribe((response:any)=>{
this.ngxService.stop();
this.tableData();
this.responseMessage = response?.message;
this.snackbarService.openSnackBar(this.responseMessage, "success");
},(error:any)=>{
this.ngxService.stop();
console.log(error);
if (error.error?.message) {
this.responseMessage = error.error?.message;
}
else {
this.responseMessage = GlobalConstants.genericError;
}
this.snackbarService.openSnackBar(this.responseMessage, GlobalConstants.error);
})
}
onChange(status:any, id:any){
var data ={
status:status.toString(),
id:id
}
this.productService.updateStatus(data).subscribe((response:any)=>{
this.ngxService.stop();
this.responseMessage = response?.message;
this.snackbarService.openSnackBar(this.responseMessage, "succes");
}, (error:any)=>{
this.ngxService.stop();
console.log(error);
if (error.error?.message) {
this.responseMessage = error.error?.message;
}
else {
this.responseMessage = GlobalConstants.genericError;
}
this.snackbarService.openSnackBar(this.responseMessage, GlobalConstants.error);
})
}
}
|
import { expect, it } from "bun:test";
import { SEED_MAP_KEYS, getDestinationFromSource } from "./solvePart1";
it("should return soil from seed", () => {
const seedToSoilMaps = [
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 50],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 98],
[SEED_MAP_KEYS.RANGE_LENGTH, 2],
]),
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 52],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 50],
[SEED_MAP_KEYS.RANGE_LENGTH, 48],
]),
];
expect(getDestinationFromSource(79, seedToSoilMaps)).toEqual(81);
expect(getDestinationFromSource(14, seedToSoilMaps)).toEqual(14);
expect(getDestinationFromSource(55, seedToSoilMaps)).toEqual(57);
expect(getDestinationFromSource(13, seedToSoilMaps)).toEqual(13);
});
it("should return fertilizer from soil", () => {
const soilToFertilizerMaps = [
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 0],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 15],
[SEED_MAP_KEYS.RANGE_LENGTH, 37],
]),
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 37],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 52],
[SEED_MAP_KEYS.RANGE_LENGTH, 2],
]),
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 39],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 0],
[SEED_MAP_KEYS.RANGE_LENGTH, 15],
]),
];
expect(getDestinationFromSource(81, soilToFertilizerMaps)).toEqual(81);
expect(getDestinationFromSource(14, soilToFertilizerMaps)).toEqual(53);
expect(getDestinationFromSource(57, soilToFertilizerMaps)).toEqual(57);
expect(getDestinationFromSource(13, soilToFertilizerMaps)).toEqual(52);
});
it("should return water from fertilizer", () => {
const fertilizerToWaterMaps = [
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 49],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 53],
[SEED_MAP_KEYS.RANGE_LENGTH, 8],
]),
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 0],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 11],
[SEED_MAP_KEYS.RANGE_LENGTH, 42],
]),
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 42],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 0],
[SEED_MAP_KEYS.RANGE_LENGTH, 7],
]),
new Map([
[SEED_MAP_KEYS.DESTINATION_RANGE_START, 57],
[SEED_MAP_KEYS.SOURCE_RANGE_START, 7],
[SEED_MAP_KEYS.RANGE_LENGTH, 4],
]),
];
expect(getDestinationFromSource(81, fertilizerToWaterMaps)).toEqual(81);
expect(getDestinationFromSource(53, fertilizerToWaterMaps)).toEqual(49);
expect(getDestinationFromSource(57, fertilizerToWaterMaps)).toEqual(53);
expect(getDestinationFromSource(52, fertilizerToWaterMaps)).toEqual(41);
});
|
import { NextFunction, Request, Response } from 'express';
import mongoose from 'mongoose';
import { Comment, Post, User } from '../models/index.js';
/**
* Get user info.
*/
export async function getUserInfo(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
const user = await User.findById(
req.params.userID,
'username friends image'
)
.populate('friends.user', 'username')
.lean()
.exec();
res.json({
success: true,
user,
});
return;
} catch (err) {
next(err);
}
}
/**
* Get user's posts.
*/
export async function getUserPosts(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
const posts = await Post.find({ author: req.params.userID })
.populate('author', 'username')
.exec();
res.json({
success: true,
posts,
});
return;
} catch (err) {
next(err);
}
}
/**
* Get user's comments.
*/
export async function getUserComments(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
const comments = await Comment.find({ author: req.params.userID })
.populate('author', 'username')
.lean()
.exec();
res.json({
success: true,
comments,
});
return;
} catch (err) {
next(err);
}
}
/**
* Send friend request to user.
*/
export async function sendFriendRequest(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
if (req.user == null) return;
const result = await req.user.sendFriendRequest(req.params.userID);
res.json(result);
return;
} catch (err) {
next(err);
}
}
/**
* Accept incoming friend request.
*/
export async function acceptFriendRequest(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
if (req.user == null) return;
const result = await req.user.acceptFriendRequest(req.params.userID);
res.json(result);
return;
} catch (err) {
next(err);
}
}
/**
* Reject incoming friend request.
*/
export async function rejectFriendRequest(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
if (req.user == null) return;
const result = await req.user.rejectFriendRequest(req.params.userID);
res.json(result);
return;
} catch (err) {
next(err);
}
}
/**
* Reject incoming friend request.
*/
export async function deleteFromFriends(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
if (req.user == null) return;
const result = await req.user.deleteFromFriends(req.params.userID);
res.json(result);
return;
} catch (err) {
next(err);
}
}
/**
* Upload new profile picture.
*/
export async function uploadProfilePicture(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
if (req.user == null) return;
if (!req.file) {
res.json({
success: false,
message: 'No file in request',
});
return;
}
const id = req.params.userID;
if (!req.user._id.equals(id)) {
res.json({
success: false,
message: 'Cannot change other peoples profile pics',
});
return;
}
if (!mongoose.Types.ObjectId.isValid(id)) {
res.json({
success: false,
message: 'User id in url is wrong',
});
return;
}
const path = req.file.path.replace(/\\/g, '/');
const user = await User.findByIdAndUpdate(
id,
(req.body = { image: `http://localhost:3000/${path}` }),
{ new: true }
).exec();
res.json({
success: true,
message: 'Profile image changed successfully',
user,
});
return;
} catch (err) {
console.log(err);
next(err);
}
}
|
import path from "path";
import fs from "fs";
import matter from "gray-matter";
import readingTime from "reading-time";
import { TBlogCard } from "../types";
const articlesPath = path.join(process.cwd(), "src/articles");
export async function getSlug() {
const articles = fs.readdirSync(articlesPath);
return articles.map((path) => {
// holds the paths to the directory of the article
const parts = path.split("/");
const fileName = parts[parts.length - 1]; // gets the last part of path with /name.mdx
const [slug, _extension] = fileName.split(".");
return slug;
});
}
export async function getArticleFromSlug(slug) {
const articleDir = path.join(articlesPath, `${slug}.mdx`);
const source = fs.readFileSync(articleDir);
const { content, data } = matter(source);
return {
content,
frontmatter: {
slug,
excerpt: data.excerpt,
title: data.title,
publishedAt: data.publishedAt,
readingTime: readingTime(String(source)).text,
...data,
},
};
}
// get the path that stores all the articles or blog post
export async function getAllArticles() {
const articles = fs.readdirSync(articlesPath);
return articles
.map((article) => {
const source = fs.readFileSync(path.join(articlesPath, article));
const data = matter(source).data as TBlogCard;
return [
{
...data,
slug: article.replace(".mdx", ""),
readingTime: readingTime(String(source)).text,
},
];
})
.flat(1);
}
|
import { IWeb } from '@pnp/sp/presets/all'
import { IProvisioningConfig } from '../provisioningconfig'
import { ICustomAction } from '../schema'
import { HandlerBase } from './handlerbase'
import { createBatch } from '@pnp/sp/batching'
/**
* Describes the Custom Actions Object Handler
*/
export class CustomActions extends HandlerBase {
/**
* Creates a new instance of the ObjectCustomActions class
*
* @param config - Provisioning config
*/
constructor(config: IProvisioningConfig) {
super('CustomActions', config)
}
/**
* Provisioning Custom Actions
*
* @param web - The web
* @param customactions - The Custom Actions to provision
*/
public async ProvisionObjects(
web: IWeb,
customActions: ICustomAction[]
): Promise<void> {
super.scope_started()
try {
const existingActions = await web.userCustomActions
.select('Title')<{ Title: string }[]>()
const [batch, execute] = createBatch(web)
customActions
.filter((action) => {
return !existingActions.some(
(existingAction) => existingAction.Title === action.Title
)
})
.map((action) => {
web.userCustomActions.using(batch).add(action)
})
await execute()
super.scope_ended()
} catch (error) {
super.scope_ended(error)
throw error
}
}
}
|
import 'dart:ui';
import 'package:energy_dashboard/core/resources/color_palette.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
enum AmpelType{
energy,
gas
}
extension AmpelTypeExtension on AmpelType{
String get jsonKey{
switch(this){
case AmpelType.energy:
return 'ampelStatusStrom';
case AmpelType.gas:
return 'ampelStatusGas';
}
}
SvgPicture get icon{
switch(this){
case AmpelType.energy:
return SvgPicture.asset('assets/icons/nav_bar/Energy-fill.svg', width: 23, height: 23, colorFilter: ColorFilter.mode(iconColor, BlendMode.srcIn));
case AmpelType.gas:
return SvgPicture.asset('assets/icons/nav_bar/Gas-fill.svg', width: 23, height: 23, colorFilter: ColorFilter.mode(iconColor, BlendMode.srcIn));
}
}
Color get iconColor{
switch(this){
case AmpelType.energy:
return ColorPalette.energyIconColor;
case AmpelType.gas:
return ColorPalette.gasIconColor;
}
}
static AmpelType typeByJsonKey(String key){
switch(key){
case 'ampelStatusStrom':
return AmpelType.energy;
case 'ampelStatusGas':
return AmpelType.gas;
default:
throw Exception('[AmpelType] typeByJsonName: Invalid json name: $key');
}
}
}
|
# Average distance to infected
from graph_attribute_generic_with_cases import GenericGraphAttributeWithCases
import pandas as pd
import numpy as np
import utils
import positive_db_functions as pos_fun
# This Class has multiple attributes names
# Dictionary to include property values
property_values = {}
# Attribute name
property_values['attribute_name'] = 'percetange_contact_change'
class GraphPercentageContactChange(GenericGraphAttributeWithCases):
'''
Script that computes the average distance to infected
'''
def __init__(self):
# Initilizes the super class
GenericGraphAttributeWithCases.__init__(self, property_values)
def compute_attribute(self, nodes, edges):
'''
Main Method to Implement
This method must be implemented by the subclass. It receives compact nodes and edges and
must output the corresponding attribute. This method must return unique identifiers and it's good
practice to include all identifiers. In case its a graph attribute the dataframe must contain only one row and the
identifier column is ignored
params
nodes (pd.DataFrame) Pandas Dataframe with the nodes of the graph:
- identifier (str): Id of the node
- weight (int): Weight of the node (see get_compact_nodes)
edges (pd.DataFrame) Pandas dataFrame with the grouped edglist (undirected)
- id1 (str)
- id2 (str)
- weight (num) Weight od the edge (see get_compact_edgelist)
returns
pd.DataFrame with the following structure
- attribute_name (str): The attribute nam
- value (float): The value of the attribute
'''
raise ValueError('Should not enter here')
def compute_attribute_for_interval(self, location_id ):
'''
Method that computes the attribute of the class for the given dates. Edit this method if the attributes requieres more than just the nodes and
the ids. See weighted_pagerank for an example.
parameters
- location_id(str): The graph id
- start_date_string (str): Start date in %Y-%m-%d
- end_date_string (str): End date in %Y-%m-%d
returns
pd.DataFrame with the structure of the output of the method compute_attribute
'''
query = f"""
SELECT AVG(attribute_value) as value
FROM {utils.nodes_attribute_table}
WHERE location_id = "{location_id}" AND attribute_name = "distance_to_infected" AND date = "{end_date_string}"
"""
df = utils.run_simple_query(self.client, query)
# Extracts the value
value = df['value'].values[0]
attributes_graph = ['number_of_cases_accumulated',
'largest_eigenvalue_unweighted',
'graph_size',
'average_distance_to_infected',
'graph_num_edges',
'powerlaw_degree_ks_statistic',
'powerlaw_degree_is_dist',
'number_of_contacts',
'largest_eigenvalue_weighted',
'graph_transitivity',
'pagerank_gini_index',
'eigenvector_gini_index',
'personalized_pagerank_gini_index',
'powerlaw_degree_p_value',
'powerlaw_degree_alpha']
df_city = df_graph_attributes.copy()
df_city = df_city.query("type=='city'")
df_city = df_city.set_index('location_id','attribute_value')
df = []
for location_id in set(df_city.index.values) :
type_id = df_city.loc[location_id]['type'].unique()[0]
df_location_id = df_city.loc[location_id].set_index('attribute_name')
df_location_id = df_location_id.copy().loc[['number_of_contacts', 'graph_num_edges', 'graph_size']] #, 'largest_eigenvalue_unweighted', 'largest_eigenvalue_weighted']]
df_location_id['date'] = pd.to_datetime(df_location_id['date'])
df_location_id = df_location_id.sort_values(by='date')
df_graph_attr_treatment = df_location_id.pivot_table(values='attribute_value', index='date', columns='attribute_name', aggfunc='first')
num_contacts_baseline = df_graph_attr_treatment['number_of_contacts'].iloc[:3].mean()
graph_size_baseline = df_graph_attr_treatment['graph_size'].iloc[:3].mean()
df_graph_attr_treatment[ 'num_contacts_change_percentage' ] = df_graph_attr_treatment.apply(lambda x: (x['number_of_contacts']-num_contacts_baseline)/num_contacts_baseline*100, axis=1)
df_graph_attr_treatment[ 'num_contacts_change_percentage_weighted' ] = df_graph_attr_treatment.apply(lambda x: (x['number_of_contacts']-num_contacts_baseline)/num_contacts_baseline*x['graph_size']/graph_size_baseline*100, axis=1 )
df_graph_attr_treatment = df_graph_attr_treatment.dropna()
df_graph_attr_treatment['location_id'] = location_id
df_graph_attr_treatment['type'] = type_id
df.append(df_graph_attr_treatment)
df_response = pd.concat(df)
return(df_response)
####################################################################################################################
# df_graph_attributes = pd.read_csv('/Users/chaosdonkey06/Dropbox/covid_graphs/graph_attributes/graph_attributes.csv')
|
#include "sdl_wrapper.h"
#include "state.h"
#include "body.h"
#include <SDL2/SDL2_gfxPrimitives.h>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h> // for debugging
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
const char WINDOW_TITLE[] = "CS 3";
const int WINDOW_WIDTH = 1000;
const int WINDOW_HEIGHT = 500;
const double MS_PER_S = 1e3;
const double REMOVE_X_POSITION = -100.0;
const double RENDER_INTERVAL = 50;
int WIDTH = 800;
int HEIGHT = 600;
/**
* The coordinate at the center of the screen.
*/
vector_t center;
/**
* The coordinate difference from the center to the top right corner.
*/
vector_t max_diff;
/**
* The SDL window where the scene is rendered.
*/
SDL_Window *window;
/**
* The renderer used to draw the scene.
*/
SDL_Renderer *renderer;
/**
* The keypress handler, or NULL if none has been configured.
*/
key_handler_t key_handler = NULL;
/**
* SDL's timestamp when a key was last pressed or released.
* Used to mesasure how long a key has been held.
*/
uint32_t key_start_timestamp;
/**
* The value of clock() when time_since_last_tick() was last called.
* Initially 0.
*/
clock_t last_clock = 0;
/** Computes the center of the window in pixel coordinates */
vector_t get_window_center(void) {
int *width = malloc(sizeof(*width)), *height = malloc(sizeof(*height));
assert(width != NULL);
assert(height != NULL);
SDL_GetWindowSize(window, width, height);
vector_t dimensions = {.x = *width, .y = *height};
free(width);
free(height);
return vec_multiply(0.5, dimensions);
}
/**
* Computes the scaling factor between scene coordinates and pixel coordinates.
* The scene is scaled by the same factor in the x and y dimensions,
* chosen to maximize the size of the scene while keeping it in the window.
*/
double get_scene_scale(vector_t window_center) {
// Scale scene so it fits entirely in the window
double x_scale = window_center.x / max_diff.x,
y_scale = window_center.y / max_diff.y;
return x_scale < y_scale ? x_scale : y_scale;
}
/** Maps a scene coordinate to a window coordinate */
vector_t get_window_position(vector_t scene_pos, vector_t window_center) {
// Scale scene coordinates by the scaling factor
// and map the center of the scene to the center of the window
vector_t scene_center_offset = vec_subtract(scene_pos, center);
double scale = get_scene_scale(window_center);
vector_t pixel_center_offset = vec_multiply(scale, scene_center_offset);
vector_t pixel = {.x = round(window_center.x + pixel_center_offset.x),
// Flip y axis since positive y is down on the screen
.y = round(window_center.y - pixel_center_offset.y)};
return pixel;
}
/**
* Converts an SDL key code to a char.
* 7-bit ASCII characters are just returned
* and arrow keys are given special character codes.
*/
char get_keycode(SDL_Keycode key) {
switch (key) {
case SDLK_LEFT:
return LEFT_ARROW;
case SDLK_UP:
return UP_ARROW;
case SDLK_RIGHT:
return RIGHT_ARROW;
case SDLK_DOWN:
return DOWN_ARROW;
case SDLK_SPACE:
return SPACE;
default:
// Only process 7-bit ASCII characters
return key == (SDL_Keycode)(char)key ? key : '\0';
}
}
/*Initializes all surfaces, music, fonts, and window*/
void sdl_init(vector_t min, vector_t max, list_t *loaded_surfaces, list_t *fonts) {
int w = 10;
int h = 20;
// Check parameters
assert(min.x < max.x);
assert(min.y < max.y);
center = vec_multiply(0.5, vec_add(min, max));
max_diff = vec_subtract(max, center);
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT,
SDL_WINDOW_RESIZABLE);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
//// Music initialization
if(Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
fprintf(stderr, "\n failed to open audio \n");
//// Image initialization
SDL_Rect texr; texr.x = WIDTH/2; texr.y = HEIGHT/2; texr.w = w*2; texr.h = h*2;
IMG_Init(IMG_INIT_PNG);
// create beaver surface
SDL_Surface *surface = IMG_Load( "assets/beaver.png");
list_add(loaded_surfaces, surface);
// create ground surface
surface = IMG_Load( "assets/ground.png");
list_add(loaded_surfaces, surface);
// create water surface
surface = IMG_Load( "assets/water.png");
list_add(loaded_surfaces, surface);
// create sky surface
surface = IMG_Load( "assets/space.png");
list_add(loaded_surfaces, surface);
// create welcome page
surface = IMG_Load( "assets/welcome.png");
list_add(loaded_surfaces, surface);
// create gameplay page
surface = IMG_Load( "assets/gameplay.png");
list_add(loaded_surfaces, surface);
// create transition page for level 1
surface = IMG_Load( "assets/transition1.png");
list_add(loaded_surfaces, surface);
// create transition page for level 2
surface = IMG_Load( "assets/transition2.png");
list_add(loaded_surfaces, surface);
// create ending page
surface = IMG_Load( "assets/endgame.png");
list_add(loaded_surfaces, surface);
// create lose game page
surface = IMG_Load( "assets/losegame.png");
list_add(loaded_surfaces, surface);
// coin
surface = IMG_Load( "assets/coin.png");
list_add(loaded_surfaces, surface);
// power-ups
surface = IMG_Load( "assets/boba.png");
list_add(loaded_surfaces, surface);
surface = IMG_Load( "assets/coffee.png");
list_add(loaded_surfaces, surface);
surface = IMG_Load( "assets/ice_cube.png");
list_add(loaded_surfaces, surface);
surface = IMG_Load( "assets/job_offer.png");
list_add(loaded_surfaces, surface);
// enemies
surface = IMG_Load( "assets/crow.png");
list_add(loaded_surfaces, surface);
surface = IMG_Load( "assets/deadline.png");
list_add(loaded_surfaces, surface);
surface = IMG_Load( "assets/shark.png");
list_add(loaded_surfaces, surface);
surface = IMG_Load( "assets/trash.png");
list_add(loaded_surfaces, surface);
// Text initialization
TTF_Init();
// Text colors
// black
SDL_Color black = {0, 0, 0};
// white
SDL_Color white = {255, 255, 255};
//Fonts for score and lives for ground
TTF_Font* Sans = TTF_OpenFont("assets/OpenSans.ttf", 10);
assert(Sans != NULL);
text_t *text = text_init(150,50, (vector_t) {.x = 10, .y = 10},(void *)Sans, black);
list_add(fonts, text);
text = text_init(80,50,(vector_t) {.x = 10, .y = 50}, (void *)Sans, black);
list_add(fonts, text);
//Fonts for score and lives for water
text = text_init(150,50,(vector_t) {.x = 10, .y = 10}, (void *)Sans, black);
list_add(fonts, text);
text = text_init(80,50,(vector_t) {.x = 10, .y = 50}, (void *)Sans, black);
list_add(fonts, text);
//Fonts for score and lives for sky
text = text_init(150,50,(vector_t) {.x = 10, .y = 10}, (void *)Sans, white);
list_add(fonts, text);
text = text_init(80,50,(vector_t) {.x = 10, .y = 50}, (void *)Sans, white);
list_add(fonts, text);
//Fonts for score and lives for transition
text = text_init(200,100,(vector_t) {.x = 210, .y = 180}, (void *)Sans, black);
list_add(fonts, text);
//Fonts for score and lives for endgame and lost game
text = text_init(200,100,(vector_t) {.x = 430, .y = 250}, (void *)Sans, black);
list_add(fonts, text);
}
bool sdl_is_done(state_t *state) {
SDL_Event *event = malloc(sizeof(*event));
assert(event != NULL);
while (SDL_PollEvent(event)) {
switch (event->type) {
case SDL_QUIT:
free(event);
Mix_CloseAudio();
return true;
case SDL_KEYDOWN:
case SDL_KEYUP:
// Skip the keypress if no handler is configured
// or an unrecognized key was pressed
if (key_handler == NULL)
break;
char key = get_keycode(event->key.keysym.sym);
if (key == '\0')
break;
uint32_t timestamp = event->key.timestamp;
if (!event->key.repeat) {
key_start_timestamp = timestamp;
}
key_event_type_t type =
event->type == SDL_KEYDOWN ? KEY_PRESSED : KEY_RELEASED;
double held_time = (timestamp - key_start_timestamp) / MS_PER_S;
key_handler(key, type, held_time, state);
break;
}
}
free(event);
return false;
}
void sdl_clear(void) {
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
}
void sdl_draw_polygon(list_t *points, rgb_color_t color) {
// Check parameters
size_t n = list_size(points);
assert(n >= 3);
assert(0 <= color.r && color.r <= 1);
assert(0 <= color.g && color.g <= 1);
assert(0 <= color.b && color.b <= 1);
vector_t window_center = get_window_center();
// Convert each vertex to a point on screen
int16_t *x_points = malloc(sizeof(*x_points) * n),
*y_points = malloc(sizeof(*y_points) * n);
assert(x_points != NULL);
assert(y_points != NULL);
for (size_t i = 0; i < n; i++) {
vector_t *vertex = list_get(points, i);
vector_t pixel = get_window_position(*vertex, window_center);
x_points[i] = pixel.x;
y_points[i] = pixel.y;
}
// Draw polygon with the given color
filledPolygonRGBA(renderer, x_points, y_points, n, color.r * 255,
color.g * 255, color.b * 255, 255);
free(x_points);
free(y_points);
}
void sdl_show(void) {
// Draw boundary lines
vector_t window_center = get_window_center();
vector_t max = vec_add(center, max_diff),
min = vec_subtract(center, max_diff);
vector_t max_pixel = get_window_position(max, window_center),
min_pixel = get_window_position(min, window_center);
SDL_Rect *boundary = malloc(sizeof(*boundary));
boundary->x = min_pixel.x;
boundary->y = max_pixel.y;
boundary->w = max_pixel.x - min_pixel.x;
boundary->h = min_pixel.y - max_pixel.y;
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
free(boundary);
SDL_RenderPresent(renderer);
}
void sdl_render_scene(scene_t *scene, double dt)
{
sdl_clear();
scene_tick(scene, dt);
Mix_Music *music = NULL;
music = Mix_LoadMUS("assets/life.wav");
// If music is not playing, play music
if ( !Mix_PlayingMusic())
{
if (music == NULL)
fprintf(stderr, "\n music path is empty\n");
Mix_PlayMusic( music, -1);
}
// Free music chunks
else if (music != NULL)
{
// clean up our resources
Mix_FreeMusic(music);
}
int bodies = scene_bodies(scene);
list_t *surfaces = scene_get_surfaces(scene);
// draw all the bodies
for (int i = 0; i <bodies; i++) {
// do not draw the beaver for transition level
if (bodies == 2 && i == 1){
break;
}
body_t *body = scene_get_body(scene, i);
list_t *shape = body_get_shape(body);
picture_t *picture = body_get_picture(body);
vector_t pos = body_get_centroid(body);
// If no picture data saved, render as polygon
if (picture == NULL && (pos.x < WINDOW_WIDTH + RENDER_INTERVAL && pos.x > -RENDER_INTERVAL))
{
sdl_draw_polygon(shape, body_get_color(body));
}
//Rendering photos
else if ((pos.x < WINDOW_WIDTH + RENDER_INTERVAL && pos.x > -RENDER_INTERVAL))
{
size_t pic_l = pic_length(picture);
size_t pic_w = pic_width(picture);
// the position of the picture is the position of the lower corner
SDL_Rect img_container = {pos.x - pic_l/2, WINDOW_HEIGHT - (pos.y + pic_w/2), pic_l, pic_w};
SDL_RenderCopy(renderer, SDL_CreateTextureFromSurface(renderer, list_get(surfaces, pic_index(picture))), NULL, &img_container);
}
// delete body if out of scene
vector_t add = body_get_centroid(body);
if (add.x < REMOVE_X_POSITION)
{
body_remove(body);
}
list_free(shape);
}
// showing text for all scenes
if (scene_get_fonts(scene) != NULL)
{
for(size_t i = 0; i<list_size(scene_get_font_indexs(scene)); i++)
{
const char *context_string = malloc(sizeof(char)*20);
if (i == 0)
{
// converting score from int to string
sprintf(context_string, "Score : %zu", (int)scene_get_score(scene));
}
else
{
// converting lives from int to string
sprintf(context_string, "Live: %zu", body_get_lives(scene_get_body(scene, 1)));
}
// rendering text
text_t *text = (text_t*)list_get(scene_get_fonts(scene), *((size_t*)(list_get(scene_get_font_indexs(scene),i))));
SDL_Surface* surfaceMessage =
TTF_RenderText_Solid((TTF_Font*)text_get_font(text), context_string, (SDL_Color)text_get_color(text));
if (surfaceMessage >=0 && renderer!=NULL)
{
// now you can convert it into a texture
SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
assert(Message != NULL);
SDL_Rect Message_rect; //create a rect
vector_t text_center = text_get_center(text);
Message_rect.x = text_center.x; //controls the rect's x coordinate
Message_rect.y = text_center.y; // controls the rect's y coordinte
Message_rect.w = text_get_length(text); // controls the width of the rect
Message_rect.h = text_get_width(text); // controls the height of the rect
SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
SDL_FreeSurface(surfaceMessage);
SDL_DestroyTexture(Message);
}
free(context_string);
}
}
sdl_show();
}
void sdl_on_key(key_handler_t handler) { key_handler = handler; }
double time_since_last_tick(void) {
clock_t now = clock();
double difference = last_clock
? (double)(now - last_clock) / CLOCKS_PER_SEC
: 0.0; // return 0 the first time this is called
last_clock = now;
return difference;
}
|
import React, { useEffect, useRef, useState } from 'react'
import { Message } from '../../models/messages'
import { convoParticipantsNames, convoParticipantsNicknames } from '../../queries/conversations'
import { useGetMessages, useSendMessage } from '../../queries/messages'
import { useGetUsers } from '../../queries/users'
import { useDashboardStore } from '../../stores/dashboard'
import { PaperAirplaneIcon, XMarkIcon } from '@heroicons/react/24/outline'
import ActivityIndicator from './activity-indicator'
import { UserStatus } from '../../models/user'
export default function MessagesView() {
const currentUser = useDashboardStore(state => state.currentUser)
const messagesEndRef = useRef<null | HTMLDivElement>(null);
const [enteredMessage, setEnteredMessage] = useState("")
const [file, setFile] = useState<File>();
const { selectedConversation, setSelectedConversation, reset: dashboardStoreReset } = useDashboardStore()
const users = useGetUsers();
const messages = useGetMessages(selectedConversation?.id);
const sendMessage = useSendMessage();
const fileInputRef = useRef(null)
const handleSendMessage = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
let trimmedMessage = enteredMessage.trim();
if (!trimmedMessage && !file) return;
sendMessage.mutate({ conversationId: selectedConversation!.id, content: enteredMessage, file: file });
setEnteredMessage("");
setFile(undefined);
// @ts-ignore
fileInputRef.current.value = null;
}
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setFile(event.target.files![0]);
}
useEffect(() => {
// scroll to bottom every time messages change
if (messages.isSuccess) {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}
}, [messages.data]);
if (messages.isLoading || users.isLoading) {
return <div>Loading...</div>
}
if (messages.isError || users.isError) {
const error = messages.error || users.error;
return <div>Error: {error}</div>
}
return (<>
<div id="dashboard-content" className="flex flex-col flex-1 min-w-[320px] bg-base-100 h-screen max-h-screen rounded-r-2xl">
{selectedConversation ? (<>
<div id="dashboard-content__header" className="flex flex-row items-center justify-between p-4 bg-base-200">
<div id="header-user" className="flex flex-row items-center justify-center">
<ActivityIndicator userStatus={
users.data?.find((user) => user.id === selectedConversation.userIds.find((id) => id !== currentUser!.id))?.status || UserStatus.Offline
} />
<span className="text-2xl font-bold ml-2">
{selectedConversation.name ? selectedConversation.name : convoParticipantsNames(selectedConversation.userIds, users.data!, currentUser)}
</span>
<span className='text-base-content/50 text-sm font-normal ml-4'>
{convoParticipantsNicknames(selectedConversation.userIds, users.data!, currentUser)}
</span>
</div>
<div className='flex flex-row items-center gap-2'>
<button className="btn btn-square btn-sm" onClick={() => setSelectedConversation(null)}>
<XMarkIcon className="w-5 h-5" />
</button>
</div>
</div>
<div id="dashboard-content__messages" className="flex flex-col flex-1 py-4 px-2 min-content overflow-auto">
<div className="flex-1"></div>
{messages.data!.map((message: Message) => {
return (
<div key={message.id} className={`chat ${message.authorId === currentUser?.id ? "chat-end" : "chat-start"} `}>
<div className={"chat-header"}>{message.authorName}</div>
<div className={`chat-bubble ${message.authorId === currentUser?.id ? "chat-bubble-primary" : ""}`}>
{message.content.includes("http") ? <a className={"link"} href={message.content} target={"_blank"}>{message.content}</a> : message.content}
</div>
</div>
)
})}
<div ref={messagesEndRef}></div>
</div>
<form onSubmit={handleSendMessage} id="dashboard-send__message" className="flex flex-row flex-2 items-center p-2 bg-base-300">
<div className="input-group">
<input type="text" placeholder="Type your message" className="input input-bordered w-full" value={enteredMessage} onChange={event => setEnteredMessage(event.target.value)} />
<input ref={fileInputRef} className="file-input file-input-bordered file-input-primary max-w-xs" type="file" onChange={handleFileChange}/>
<button className="btn btn-secondary gap-2">
Send
<PaperAirplaneIcon className="w-5 h-5" />
</button>
</div>
</form>
</>) : (
<div className="flex flex-col flex-1 items-center justify-center">
<p className="text-2xl font-bold">Select a conversation to start chatting</p>
</div>
)}
</div>
</>)
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Moderator Panel</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>Moderator Panel</h1>
<label for="password">Password:</label>
<input type="password" id="password">
<button onclick="login()">Login</button>
<div id="moderatorPanel" style="display:none;">
<h2>All Pastes</h2>
<table id="pasteTable">
<thead>
<tr>
<th>Paste ID</th>
<th>Delete</th>
<th>Deletion Reason</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p id="deleteResult"></p>
</div>
<script>
async function login() {
const password = document.getElementById('password').value;
try {
const response = await axios.post('/moderator/login', { password });
if (response.data.success) {
document.getElementById('moderatorPanel').style.display = 'block';
loadPastes();
} else {
alert('Incorrect password');
}
} catch (error) {
console.error(error);
alert('Login failed');
}
}
async function loadPastes() {
const password = document.getElementById('password').value;
try {
const response = await axios.get(`/pastes?password=${password}`);
const pastes = response.data;
const tbody = document.getElementById('pasteTable').querySelector('tbody');
tbody.innerHTML = '';
for (const pasteId in pastes) {
if (pastes[pasteId].deleted) continue;
const tr = document.createElement('tr');
const idTd = document.createElement('td');
idTd.innerText = pasteId;
tr.appendChild(idTd);
const deleteBtn = document.createElement('button');
deleteBtn.innerText = 'Delete';
deleteBtn.onclick = () => deletePaste(pasteId);
const deleteTd = document.createElement('td');
deleteTd.appendChild(deleteBtn);
tr.appendChild(deleteTd);
const reasonInput = document.createElement('input');
reasonInput.type = 'text';
reasonInput.setAttribute('data-paste-id', pasteId);
const reasonTd = document.createElement('td');
reasonTd.appendChild(reasonInput);
tr.appendChild(reasonTd);
tbody.appendChild(tr);
}
} catch (error) {
console.error(error);
}
}
async function deletePaste(pasteId) {
const password = document.getElementById('password').value;
const reasonInput = document.querySelector(`input[data-paste-id="${pasteId}"]`);
const reason = reasonInput.value;
try {
const response = await axios.delete(`/paste/${pasteId}`, { data: { password, reason }
});
if (response.data.success) {
document.getElementById('deleteResult').innerText = `Paste ${pasteId} deleted successfully`;
loadPastes();
} else {
document.getElementById('deleteResult').innerText = `Failed to delete paste ${pasteId}`;
}
} catch (error) {
console.error(error);
document.getElementById('deleteResult').innerText = `Failed to delete paste ${pasteId}`;
}
}
</script>
</body>
</html>
|
import React from 'react';
import { View, Text, Image, Pressable, StyleSheet, Alert } from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
const PreviewScreen = () => {
const navigation = useNavigation();
const route = useRoute();
const { imageUri, recognizedText, meterId } = route.params;
console.log('PreviewScreen imageUri:', imageUri);
console.log('PreviewScreen recognizedText:', recognizedText);
const getCurrentDate = () => {
const date = new Date();
const year = date.getFullYear();
const month = (`0${date.getMonth() + 1}`).slice(-2); // Months are 0-based, so add 1
const day = (`0${date.getDate()}`).slice(-2);
return `${year}-${month}-${day}`;
};
const handleSubmit = async () => {
try {
const token = await AsyncStorage.getItem('userToken');
if (!token) {
throw new Error('No token found');
}
const lectura = uniqueDetectedNumbers.join('');
const fecha = getCurrentDate();
console.log('medidorId:', meterId);
console.log('lectura:', lectura);
console.log('fecha:', fecha);
const response = await axios.post(
`http://192.168.1.91:8080/cliente/medidores/${meterId}/consumos`,
{
lectura,
fecha
},
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
console.log('Response from backend:', response.data);
Alert.alert('Lectura Enviada', 'Su lectura se ha enviado', [
{
text: 'OK',
onPress: () => navigation.navigate('HomeScreen'),
},
]);
} catch (error) {
console.error('Error submitting data', error);
Alert.alert('Error', 'Error enviando la lectura');
}
};
const detectedNumbers = recognizedText.body ? JSON.parse(recognizedText.body).detectedNumbers : [];
const uniqueDetectedNumbers = [...new Set(detectedNumbers)];
return (
<View style={styles.container}>
<Text style={styles.headerTitle}>Previsualización</Text>
<View style={styles.textContainer}>
<Text style={styles.textTitle}>Lectura Reconocida:</Text>
{uniqueDetectedNumbers.length > 0 ? (
<Text style={styles.numberText}>
{uniqueDetectedNumbers.join(', ')}
</Text>
) : (
<Text style={styles.numberText}>No se detectaron números.</Text>
)}
</View>
{imageUri && <Image source={{ uri: imageUri }} style={styles.image} />}
<Pressable
style={({ pressed }) => [
{
backgroundColor: pressed ? '#FF1493' : '#CCCCCC',
},
styles.button,
]}
onPress={() => navigation.goBack()}
>
<Text style={styles.buttonText}>Retomar</Text>
</Pressable>
<Pressable
style={({ pressed }) => [
{
backgroundColor: pressed ? '#FF1493' : '#CCCCCC',
},
styles.button,
]}
onPress={handleSubmit}
>
<Text style={styles.buttonText}>Enviar imagen</Text>
</Pressable>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
padding: 20,
backgroundColor: '#FFFFFF',
},
headerTitle: {
fontSize: 24,
fontWeight: 'bold',
color: '#333333',
marginBottom: 20,
},
image: {
width: 350, // Ajustar el tamaño de la imagen
height: 250,
marginBottom: 20,
borderRadius: 10,
},
textContainer: {
marginBottom: 20,
padding: 10,
borderRadius: 8,
alignItems: 'center',
width: '100%',
},
textTitle: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 5,
color: '#333333',
},
numberText: {
fontSize: 24,
color: '#FF1493',
fontWeight: 'bold',
},
button: {
width: '80%',
padding: 15,
borderRadius: 10,
alignItems: 'center',
marginBottom: 10,
},
buttonText: {
color: '#333333',
fontSize: 16,
fontWeight: 'bold',
},
});
export default PreviewScreen;
|
{
// 변수와 클래스와 함수에 어떤 타입의 데이터를 전달할 수 있고 받아 올 수 있는지를 명확하게 작성하는 것이 제일 중요하다.
// 모듈을 작성하지 않고 그냥 파일을 작성하게 되면 모두 다 global scope로 책정이 된다. 다른 파일에서 이름이 충돌 될 수 있다.
// 그렇기 때문에 블럭을 이용해서 로컬 스코프로 작성
// var을 쓰지 말자
// 타입스크립트 코드는 어차피 타입스크립트 코드로 변환 되고 타겟 버전을 선택할 수 있기 때문에 let을 써도 브라우저 호환성 문제는 걱정할 필요 없다.
// 자바스크립트로만 프로젝트를 하더라도 많은 프로젝트에서 바벨을 이용해서 자바스크립트 최신 버전을 낮은 버전으로 변환해서 배포를 하고 있다.
// JavaScript
// Primitive: number, string, boolean, bigint, symbol, null, undefined
// Object: function, array....
// 타입스크립트에서 변수를 선언할 때 조금 더 엄격하게 타입을 정의하고 한 번 정의된 타입에는 다른 타입의 데이터는 담을 수가 없다.
// 기본 타입 정리
// number
const num: number = 1; // 소수점도 가능하다.
// string
const str: string = 'hello';
// boolean
const boal: boolean = false;
// undefined 비었는지 안비었는지 아직 결정 안됨
let age: number | undefined; // 단독으로 거의 쓰이지 않는다. null 보다는 undefined를 쓴다.
age = undefined;
age = 1;
function find(): number | undefined {
// 무언가를 찾는 함수가 있다고 했을 때 찾았다면 숫자를 리턴하고 찾지 못하면
// undefined를 리턴하도록 할 수 있다. 무언가가 있고 없을 떄 undefined를 많이 쓴다.
return undefined;
}
//null 비었다고 결정 됨
let person: null; // 단독으로 거의 안쓰인다.
person = null;
let person2: string | null;
// unknown unknown은 안쓰는게 좋다. 어떤 종류의 데이터가 담길 지 알수가 없는 타입, 어떤 데이터든 담을 수 있다.
// 쓰면 안좋은데 왜 있냐? 타입이 없는 자바스크립트와 연동해서 쓸 수 있기 때문이다. 타입스크립트에서 자바스크립트 라이브러리를 이용하는 경우에
// 자바스크립트에서 리턴하는 타입을 모를 수 있다. 그때 unknown을 쓸 수 있다.
let notSure: unknown = 0;
notSure = 'he';
notSure = true;
// any 어떤 것이든 담을 수 있는 변수, 안쓰는게 좋다.
let anything: any = 0;
anything = 'hello';
// void 함수에서 아무거도 리턴하지 않으면(undefined) void라는 타입이 된다. 보통은 함수에서 무언가를 리턴할 때 타입을 명시하는 것이
// 좋은 관례이다. void는 생략할 수 있다. 스타일 가이드에 따라 갈 것
function print(): void {
console.log('hello');
return;
}
let unusable: void = undefined; // 이렇게 선언하는 경우 없다고 보면 된다.
// never 리턴하지 않는 함수, 함수에서 절대 리턴되지 않는 경우에 명시하기 위해 쓰인다. 아래의 예제의 경우 에러를 던지거나, 무한 루프의 경우
function throwError(message: string): never {
// message => server (log)
throw new Error(message);
// while (true) {}
}
// object 원시타입을 제외한 모든 object 타입을 할당할 수 있다. 추상적이고 어떤것이든 담을 수 있는 타입은 안쓰는게 좋다.
// 배열, 객체 등 여러가지가 들어갈 수 있는 obj타입도 안쓰는게 좋다.
let obj: object;
function acceptSomeObject(obj: object) {}
acceptSomeObject({ name: 'ellie' });
acceptSomeObject({ animal: 'dog' });
}
|
import { Component, OnInit } from '@angular/core';
import {Card} from "../../model/card";
import {FormBuilder, FormGroup} from "@angular/forms";
import {ActivatedRoute} from "@angular/router";
import {TokenStorageService} from "../../model/auth/TokenStorageService";
import {CardService} from "../../service/card.service";
import {CardRequest} from "../../request/CardRequest";
import {CardReplenishRequest} from "../../request/CardReplenishRequest";
import {PayByCardRequest} from "../../request/PayByCardRequest";
import {CardSettingsRequest} from "../../request/CardSettingsRequest";
import {MessageService} from "primeng/api";
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.scss'],
providers: [MessageService]
})
export class CardComponent implements OnInit {
cards!: Card [];
displayAddCardModal!: boolean;
displaySettingsModal!: boolean;
displayReplenishmentModal!: boolean;
displayTransactionModal!: boolean;
formAddCard!: FormGroup;
formSettings!: FormGroup;
formReplenishment!: FormGroup;
formTransaction!: FormGroup;
paymentSystem = [
{name: "VISA", value: 0},
{name: "MASTERCARD", value: 1},
{name: "MIR", value : 2}
];
type = [
{name: "DEBIT", value: 0},
{name: "CREDIT", value: 1}
];
activity = [
{name: "Да", value: 1},
{name: "Нет", value: 0}
];
roundingStep = [
{name: "10", value: 0},
{name: "50", value: 1},
{name: "100", value: 2},
{name: "1000", value: 3}
];
selectedType: any;
selectedPaymentSystem: any;
selectedActivity: any;
selectedRound: any;
selectedCard: Card = {
active: false,
amount: 0,
cardExpiry: "",
cardNumber: "",
cardPaymentSystem: "",
cardRoundingStep: "",
cardTransactions: [],
cardType: "",
card_id: 0,
cvv: "",
embossingName: "",
encryptedPan: ""
};
info: any;
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private token: TokenStorageService,
private cardService: CardService,
private msg: MessageService
) {
this.cards = [];
}
ngOnInit(): void {
this.info = {
token: this.token.getToken(),
username: this.token.getUsername()
};
this.getCards();
this.formAddCard = this.formBuilder.group({
"paymentSystem": null,
"type": null
});
this.formSettings = this.formBuilder.group({
"active": null,
"roundingStep": null
});
this.formReplenishment! = this.formBuilder.group({
"amount": null
});
this.formTransaction! = this.formBuilder.group({
"name": null,
"category": null,
"amount": null
});
}
getCards(): void{
this.cardService.getCards().subscribe(
data => {
this.cards = data;
this.selectedCard = this.cards[0];
},
error => {
//
}
)
}
onSubmitAddCard(): void {
this.displayAddCardModal = false;
this.formAddCard.controls['paymentSystem'].setValue(this.selectedPaymentSystem.value);
this.formAddCard.controls['type'].setValue(this.selectedType.value);
// alert(JSON.stringify(this.formAddCard.value));
this.cardService.addCard(new CardRequest(this.formAddCard.value.paymentSystem, this.formAddCard.value.type)).subscribe(
data => {
this.msg.add({severity:'success', summary: 'Карты', detail: 'Карта успешно добавлена!'});
},
error => {
}
);
}
onSubmitSettings(): void {
this.displaySettingsModal = false;
this.formSettings.controls['active'].setValue(this.selectedActivity.value);
this.formSettings.controls['roundingStep'].setValue(this.selectedRound.value);
// alert(JSON.stringify(this.formSettings.value));
this.cardService.settingsCardById(new CardSettingsRequest(this.formSettings.value.active, this.formSettings.value.roundingStep), this.selectedCard.card_id).subscribe(
data => {
this.msg.add({severity:'success', summary: 'Карты', detail: 'Настройки успешно изменены!'});
this.ngOnInit();
},
error => {
}
);
}
onSubmitReplenishment(): void {
this.displayReplenishmentModal = false;
//alert(JSON.stringify(this.formReplenishment.value));
this.cardService.replenishCardById(new CardReplenishRequest(this.formReplenishment.value.amount), this.selectedCard.card_id).subscribe(
data => {
this.msg.add({severity:'success', summary: 'Карты', detail: 'Деньги успешно пополнены!'});
this.ngOnInit();
},
error => {
}
);
}
onSubmitTransaction(): void {
this.displayTransactionModal = false;
//alert(JSON.stringify(this.formTransaction.value));
this.cardService.payByCardById(new PayByCardRequest(this.formTransaction.value.name, this.formTransaction.value.category, this.formTransaction.value.amount), this.selectedCard.card_id).subscribe(
data => {
this.msg.add({severity:'success', summary: 'Карты', detail: 'Транзакция успешно проведена!'});
this.ngOnInit();
},
error => {
this.msg.add({severity:'error', summary: 'Карты', detail: 'На балансе не достаточно средств!'});
}
);
}
}
|
import copy
from os import stat
from components.episode_buffer import EpisodeBatch
from modules.mixers.qmix import ConcatStateHistoryQMixer, QMixer
from modules.mixers.qmix_attention import QMixerAttention
import torch as th
import torch.nn.functional as F
from torch.optim import RMSprop, Adam
import numpy as np
class HistoryQLearner:
def __init__(self, mac, scheme, logger, args):
self.args = args
self.mac = mac
self.logger = logger
self.params = list(mac.parameters())
self.last_target_update_episode = 0
self.state_history = getattr(args, "state_history", None)
self.mac_input_shape = int(np.prod(mac._get_input_shape(scheme)))
self.args.history_dim = [(self.args.episode_limit+1), args.n_agents, self.mac_input_shape]
self.mixer = None
if args.mixer is not None:
if args.mixer == "qmix":
if self.state_history == "state_history":
self.mixer = ConcatStateHistoryQMixer(args)
if self.state_history == "history":
args.state_shape = self.args.history_dim
self.mixer = QMixer(args)
if self.state_history == "hidden_state":
args.state_shape = [args.rnn_hidden_dim, args.n_agents]
self.mixer = QMixer(args)
if self.state_history == "attention":
args.state_shape = [args.rnn_hidden_dim]
args.observation_shape = [self.mac_input_shape]
self.mixer = QMixerAttention(args)
else:
raise ValueError("Mixer {} not recognised.".format(args.mixer))
self.params += list(self.mixer.parameters())
self.target_mixer = copy.deepcopy(self.mixer)
self.optimiser = RMSprop(params=self.params, lr=args.lr, alpha=args.optim_alpha, eps=args.optim_eps)
# a little wasteful to deepcopy (e.g. duplicates action selector), but should work for any MAC
self.target_mac = copy.deepcopy(mac)
self.log_stats_t = -self.args.learner_log_interval - 1
def train(self, batch: EpisodeBatch, t_env: int, episode_num: int):
# Get the relevant quantities
rewards = batch["reward"][:, :-1]
actions = batch["actions"][:, :-1]
terminated = batch["terminated"][:, :-1].float()
mask = batch["filled"][:, :-1].float()
mask[:, 1:] = mask[:, 1:] * (1 - terminated[:, :-1])
avail_actions = batch["avail_actions"]
# Calculate estimated Q-Values
history_batch = th.zeros([batch.batch_size, batch.max_seq_length, self.args.episode_limit+1, self.args.n_agents, self.mac_input_shape])
hidden_states_batch = []
observations = []
mac_out = []
self.mac.init_hidden(batch.batch_size)
for t in range(batch.max_seq_length):
agent_outs = self.mac.forward(batch, t=t) # Shape [batch_size, n_agents, n_actions]
mac_out.append(agent_outs)
inputs = self.mac._build_inputs(batch, t=t).view(batch.batch_size, self.args.n_agents, self.mac_input_shape)
observations.append(inputs)
hidden_states_batch.append(self.mac.hidden_states.view(batch.batch_size, self.args.n_agents, -1))
for t1 in range(t, batch.max_seq_length):
history_batch[:,t1,t,:,:] = inputs
mac_out = th.stack(mac_out, dim=1) # Concat over time
hidden_states_batch = th.stack(hidden_states_batch, dim=1).detach()
observations = th.stack(observations, dim=1)
# Pick the Q-Values for the actions taken by each agent
chosen_action_qvals = th.gather(mac_out[:, :-1], dim=3, index=actions).squeeze(3) # Remove the last dim
# Calculate the Q-Values necessary for the target
target_hidden_states_batch = []
target_mac_out = []
self.target_mac.init_hidden(batch.batch_size)
for t in range(batch.max_seq_length):
target_agent_outs = self.target_mac.forward(batch, t=t)
target_mac_out.append(target_agent_outs)
target_hidden_states_batch.append(self.target_mac.hidden_states.view(batch.batch_size, self.args.n_agents, -1))
# We don't need the first timesteps Q-Value estimate for calculating targets
target_mac_out = th.stack(target_mac_out[1:], dim=1) # Concat across time
# Mask out unavailable actions
target_mac_out[avail_actions[:, 1:] == 0] = -9999999 # From OG deepmarl
target_hidden_states_batch = th.stack(target_hidden_states_batch, dim=1).detach()
# Max over target Q-Values
if self.args.double_q:
# Get actions that maximise live Q (for double q-learning)
mac_out_detach = mac_out.clone().detach()
mac_out_detach[avail_actions == 0] = -9999999
cur_max_actions = mac_out_detach[:, 1:].max(dim=3, keepdim=True)[1]
target_max_qvals = th.gather(target_mac_out, 3, cur_max_actions).squeeze(3)
else:
target_max_qvals, cur_max_actions = target_mac_out.max(dim=3)
# Mix
if self.mixer is not None:
if self.state_history == "state_history":
chosen_action_qvals = self.mixer(chosen_action_qvals, batch["state"][:, :-1], history_batch[:, :-1])
target_max_qvals = self.target_mixer(target_max_qvals, batch["state"][:, 1:], history_batch[:, 1:])
elif self.state_history == "history":
chosen_action_qvals = self.mixer(chosen_action_qvals, history_batch[:, :-1])
target_max_qvals = self.target_mixer(target_max_qvals, history_batch[:, 1:])
elif self.state_history == "hidden_state":
chosen_action_qvals = self.mixer(chosen_action_qvals, hidden_states_batch[:, :-1])
target_max_qvals = self.target_mixer(target_max_qvals, target_hidden_states_batch[:, 1:])
elif self.state_history == "attention":
chosen_action_qvals = self.mixer(chosen_action_qvals, hidden_states_batch[:, :-1])
target_max_qvals = self.target_mixer(target_max_qvals, target_hidden_states_batch[:, 1:])
else:
chosen_action_qvals = self.mixer(chosen_action_qvals, batch["state"][:, :-1])
target_max_qvals = self.target_mixer(target_max_qvals, batch["state"][:, 1:])
N = getattr(self.args, "n_step", 1)
if N == 1:
# Calculate 1-step Q-Learning targets
targets = rewards + self.args.gamma * (1 - terminated) * target_max_qvals
else:
# N step Q-Learning targets
n_rewards = th.zeros_like(rewards)
gamma_tensor = th.tensor([self.args.gamma**i for i in range(N)], dtype=th.float, device=n_rewards.device)
steps = mask.flip(1).cumsum(dim=1).flip(1).clamp_max(N).long()
for i in range(batch.max_seq_length - 1):
n_rewards[:,i,0] = ((rewards * mask)[:,i:i+N,0] * gamma_tensor[:(batch.max_seq_length - 1 - i)]).sum(dim=1)
indices = th.linspace(0, batch.max_seq_length-2, steps=batch.max_seq_length-1, device=steps.device).unsqueeze(1).long()
n_targets_terminated = th.gather(target_max_qvals*(1-terminated),dim=1,index=steps.long()+indices-1)
targets = n_rewards + th.pow(self.args.gamma, steps.float()) * n_targets_terminated
# Td-error
td_error = (chosen_action_qvals - targets.detach())
ws = th.ones_like(td_error) * self.args.w
ws = th.where(td_error < 0, th.ones_like(td_error)*1, ws)
mask = mask.expand_as(td_error)
# 0-out the targets that came from padded data
masked_td_error = td_error * mask
# Normal L2 loss, take mean over actual data
loss = (ws.detach()*(masked_td_error ** 2)).sum() / mask.sum()
# Optimise
self.optimiser.zero_grad()
loss.backward()
grad_norm = th.nn.utils.clip_grad_norm_(self.params, self.args.grad_norm_clip)
self.optimiser.step()
if (episode_num - self.last_target_update_episode) / self.args.target_update_interval >= 1.0:
self._update_targets()
self.last_target_update_episode = episode_num
if t_env - self.log_stats_t >= self.args.learner_log_interval:
self.logger.log_stat("loss", loss.item(), t_env)
self.logger.log_stat("grad_norm", grad_norm, t_env)
mask_elems = mask.sum().item()
self.logger.log_stat("td_error_abs", (masked_td_error.abs().sum().item()/mask_elems), t_env)
self.logger.log_stat("q_taken_mean", (chosen_action_qvals * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)
self.logger.log_stat("target_mean", (targets * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)
agent_utils = (th.gather(mac_out[:, :-1], dim=3, index=actions).squeeze(3) * mask).sum().item() / (mask_elems * self.args.n_agents)
self.logger.log_stat("agent_utils", agent_utils, t_env)
self.log_stats_t = t_env
def _update_targets(self):
self.target_mac.load_state(self.mac)
if self.mixer is not None:
self.target_mixer.load_state_dict(self.mixer.state_dict())
self.logger.console_logger.info("Updated target network")
def cuda(self):
self.mac.cuda()
self.target_mac.cuda()
if self.mixer is not None:
self.mixer.cuda()
self.target_mixer.cuda()
def save_models(self, path):
self.mac.save_models(path)
if self.mixer is not None:
th.save(self.mixer.state_dict(), "{}/mixer.th".format(path))
th.save(self.optimiser.state_dict(), "{}/opt.th".format(path))
def load_models(self, path):
self.mac.load_models(path)
# Not quite right but I don't want to save target networks
self.target_mac.load_models(path)
if self.mixer is not None:
self.mixer.load_state_dict(th.load("{}/mixer.th".format(path), map_location=lambda storage, loc: storage))
self.optimiser.load_state_dict(th.load("{}/opt.th".format(path), map_location=lambda storage, loc: storage))
|
//
// RideActionView.swift
// UberClone
//
// Created by Renato Mateus on 10/05/21.
//
import MapKit
import UIKit
protocol RideActionViewDelegate: class {
func didTapConfirmUber()
}
class RideActionView: UIView {
//MARK: Properties
weak var delegate: RideActionViewDelegate?
var destination: MKPlacemark? {
didSet{
titleLabel.text = destination?.name
addressLabel.text = destination?.address
}
}
let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.text = "Test Address Title"
return label
}()
let addressLabel: UILabel = {
let label = UILabel()
label.textColor = .lightGray
label.font = UIFont.systemFont(ofSize: 16)
label.text = "148, CS 6, Stella Maris, Salvador"
return label
}()
private lazy var infoView: UIView = {
let view = UIView()
view.backgroundColor = .black
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 30)
label.textColor = .white
label.text = "X"
view.addSubview(label)
label.centerX(inView: view)
label.centerY(inView: view)
return view
}()
let uberXLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 18)
label.text = "UberX"
label.textAlignment = .center
return label
}()
private let actionButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .black
button.setTitle("CONFIRM UBERX", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(actionButtonPressed), for: .touchUpInside)
return button
}()
//MARK: Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Helpers
func configureView(){
backgroundColor = .white
addShadow()
let stack = UIStackView(arrangedSubviews: [titleLabel, addressLabel])
stack.axis = .vertical
stack.spacing = 4
stack.distribution = .fillEqually
addSubview(stack)
stack.centerX(inView: self)
stack.anchor(top: topAnchor, paddingTop: 12)
addSubview(infoView)
infoView.centerX(inView: self)
infoView.anchor(top:stack.bottomAnchor, paddingTop: 16)
infoView.setDimensions(height: 60, width: 60)
infoView.layer.cornerRadius = 60/2
addSubview(uberXLabel)
uberXLabel.anchor(top: infoView.bottomAnchor, paddingTop: 8)
uberXLabel.centerX(inView: self)
let separatorView = UIView()
separatorView.backgroundColor = .lightGray
addSubview(separatorView)
separatorView.anchor(top: uberXLabel.bottomAnchor, left: leftAnchor, right: rightAnchor, height: 0.75)
addSubview(actionButton)
actionButton.anchor(left: leftAnchor, bottom: safeAreaLayoutGuide.bottomAnchor, right: rightAnchor, paddingLeft: 12, paddingBottom: 12, paddingRight: 12, height: 50)
}
//MARK: Selectors
@objc func actionButtonPressed(){
delegate?.didTapConfirmUber()
}
}
|
package com.thinkmorestupidless.utils
import org.apache.pekko.http.scaladsl.model.headers.RawHeader
import com.thinkmorestupidless.betfair.auth.domain.{ApplicationKey, BetfairCredentials, Password, Username}
import com.thinkmorestupidless.betfair.core.impl._
object ConfigSupport {
def generateConfig(baseUri: String) = BetfairConfig(
HeaderKeys(ApplicationKeyHeaderKey("X-Application"), SessionTokenHeaderKey("X-Authentication")),
AuthConfig(
Cert(
CertFile("certfile.pkcs12"),
CertPassword("top-secret")
),
BetfairCredentials(
Username("bigjohn"),
Password("changeme"),
ApplicationKey("foobar")
),
LoginUri(s"$baseUri/login"),
SessionStoreConfig(SessionStoreProviderType.InMem, FileProviderConfig(FileProviderFilePath(".")))
),
ExchangeConfig(
List(
RawHeader("Content-Type", "application/json"),
RawHeader("Accept", "application/json"),
RawHeader("Accept-Charset", "UTF-8"),
RawHeader("Accept-Encoding", "gzip, deflate")
),
SocketConfig(
StreamsApiEnabled(true),
SocketFrameSize(102400),
SocketUri("stream-api.betfair.com"),
SocketPort(443),
OutgoingHeartbeat(false),
EagerConnection(true)
),
ExchangeUris(
CancelOrdersUri(s"$baseUri/cancelOrders/"),
ListClearedOrdersUri(s"$baseUri/listClearedOrders/"),
ListCompetitionsUri(s"$baseUri/listCompetitions/"),
ListCountriesUri(s"$baseUri/listCountries"),
ListCurrentOrdersUri(s"$baseUri/listCurrentOrders/"),
ListEventTypesUri(s"$baseUri/listEventTypes"),
ListEventsUri(s"$baseUri/listEvents"),
ListMarketCatalogueUri(s"$baseUri/listMarketCatalogue"),
ListMarketBookUri(s"$baseUri/listMarketBook"),
PlaceOrdersUri(s"$baseUri/placeOrders")
),
ExchangeLogging(LogExchangeRequests(true), LogExchangeResponses(true))
),
NavigationConfig(MenuUri(s"$baseUri/navigation/menu.json"))
)
}
|
import React from 'react';
import ReactDOM from 'react-dom/client';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { Index, loader as clientsLoader } from './pages/Index';
import { NewClient, action as newClientAction } from './pages/NewClient';
import {
EditClient,
loader as editClientLoader,
action as editClientAction,
} from './pages/EditClient';
import { action as deleteClientAction } from './components/Client';
import { Layout } from './components/Layout';
import { ErrorPage } from './components/ErrorPage';
import './index.css';
const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
{
index: true,
element: <Index />,
loader: clientsLoader,
errorElement: <ErrorPage />,
},
{
path: '/clientes/nuevo',
element: <NewClient />,
action: newClientAction,
errorElement: <ErrorPage />,
},
{
path: '/clientes/:clienteId/editar',
element: <EditClient />,
loader: editClientLoader,
action: editClientAction,
errorElement: <ErrorPage />,
},
{
path: '/clientes/:clienteId/eliminar',
action: deleteClientAction
}
],
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
|
interface ISection {
title: string;
text: string;
linkText: string;
}
const Section = (props: ISection) => {
return (
<div className="grid grid-cols-1 place-content-center max-w-[300px] lg:max-w-[445px] h-full sm:text-left text-center gap-[24px]">
<h2 className=" text-darkBlue lg:text-[40px] text-[32px] font-black font-fraunces">
{props.title}
</h2>
<p className="text-grayishBlue font-[18px] tracking-[-0.129px] leading-[30px]">
{props.text}
</p>
<div className="relative w-[137px] text-center justify-self-center sm:justify-self-start">
<a className="text-veryDarkDesaturatedBlue uppercase font-fraunces font-black text-[15px] tracking-[1px]">
{props.linkText}
</a>
<div
className="absolute bg-yellow h-[10px] w-full top-[15px] rounded-[28px] opacity-25"
style={{
zIndex: -10,
}}
></div>
</div>
</div>
);
};
export default Section;
|
# Switch Test Assertions from Truth to assertk
- Pull Request: [#7242](https://github.com/thunderbird/thunderbird-android/pull/7242)
## Status
- **Accepted**
## Context
Our project has been using the Truth testing library for writing tests. While Truth has served us well, it is primarily
designed for Java and lacks some features that make our Kotlin tests more idiomatic and expressive. As our codebase is
[primarily Kotlin](0001-switch-from-java-to-kotlin.md), we have been looking for a testing library that is more aligned
with Kotlin's features and idioms.
## Decision
We have decided to use [assertk](https://github.com/willowtreeapps/assertk) as the default assertions framework for
writing tests in our project. assertk provides a fluent API that is very similar to Truth, making the transition easier.
Moreover, it is designed to work well with Kotlin, enabling us to leverage Kotlin-specific features in our tests.
We've further committed to converting all pre-existing tests from Truth to assertk.
## Consequences
**Note**: The migration of all Truth tests to assertk has already been completed.
- **Positive Consequences**
- **Ease of Transition**: The syntax of assertk is very similar to Truth, which makes the migration process smoother.
- **Kotlin-Friendly**: assertk is designed specifically for Kotlin, allowing us to write more idiomatic and
expressive Kotlin tests.
- **Negative Consequences**
- **Dependency**: While we are replacing one library with another, introducing a new library always carries the risk
of bugs or future deprecation.
- **Migration Effort**: Existing tests written using Truth will need to be migrated to use assertk, requiring some
effort, although mitigated by the similar syntax.
|
// PACKAGES
import { EResourceType } from 'rettiwt-core';
// SERVICES
import { FetcherService } from '../internal/FetcherService';
// MODELS
import { RettiwtConfig } from '../../models/internal/RettiwtConfig';
import { User } from '../../models/public/User';
import { Tweet } from '../../models/public/Tweet';
// TYPES
import { CursoredData } from '../../models/public/CursoredData';
/**
* Handles fetching of data related to user account
*
* @public
*/
export class UserService extends FetcherService {
/**
* @param config - The config object for configuring the Rettiwt instance.
*
* @internal
*/
public constructor(config?: RettiwtConfig) {
super(config);
}
/**
* Get the details of a user.
*
* @param id - The username/id of the target user.
* @returns The details of the given user.
*
* @public
*/
public async details(id: string): Promise<User> {
let data: CursoredData<User>;
// If username is given
if (isNaN(Number(id))) {
// Fetching the requested data
data = await this.fetch<User>(EResourceType.USER_DETAILS, { id: id });
}
// If id is given
else {
// Fetching the requested data
data = await this.fetch<User>(EResourceType.USER_DETAILS_BY_ID, { id: id });
}
return data.list[0];
}
/**
* Get the list of users who are followed by the given user.
*
* @param userId - The rest id of the target user.
* @param count - The number of following to fetch, must be \<= 100.
* @param cursor - The cursor to the batch of following to fetch.
* @returns The list of users followed by the target user.
*
* @public
*/
public async following(userId: string, count?: number, cursor?: string): Promise<CursoredData<User>> {
// Fetching the requested data
const data = await this.fetch<User>(EResourceType.USER_FOLLOWING, {
id: userId,
count: count,
cursor: cursor,
});
return data;
}
/**
* Get the list followers of a given user.
*
* @param userId - The rest id of the target user.
* @param count - The number of followers to fetch, must be \<= 100.
* @param cursor - The cursor to the batch of followers to fetch.
* @returns The list of users following the target user.
*
* @public
*/
public async followers(userId: string, count?: number, cursor?: string): Promise<CursoredData<User>> {
// Fetching the requested data
const data = await this.fetch<User>(EResourceType.USER_FOLLOWERS, {
id: userId,
count: count,
cursor: cursor,
});
return data;
}
/**
* Get the list of tweets liked by the given user.
*
* @param userId - The rest id of the target user.
* @param count - The number of likes to fetch, must be \<= 100.
* @param cursor - The cursor to the batch of likes to fetch.
* @returns The list of tweets liked by the target user.
*
* @public
*/
public async likes(userId: string, count?: number, cursor?: string): Promise<CursoredData<Tweet>> {
// Fetching the requested data
const data = await this.fetch<Tweet>(EResourceType.USER_LIKES, {
id: userId,
count: count,
cursor: cursor,
});
return data;
}
/**
* Get the timeline of the given user.
*
* @param userId - The rest id of the target user.
* @param count - The number of timeline items to fetch, must be \<= 20.
* @param cursor - The cursor to the batch of timeline items to fetch.
* @returns The timeline of the target user.
*
* @remarks If the target user has a pinned tweet, the returned timeline has one item extra and this is always the pinned tweet.
*
* @public
*/
public async timeline(userId: string, count?: number, cursor?: string): Promise<CursoredData<Tweet>> {
// Fetching the requested data
const data = await this.fetch<Tweet>(EResourceType.USER_TWEETS, {
id: userId,
count: count,
cursor: cursor,
});
return data;
}
/**
* Get the reply timeline of the given user.
*
* @param userId - The rest id of the target user.
* @param count - The number of replies to fetch, must be \<= 20.
* @param cursor - The cursor to the batch of replies to fetch.
* @returns The reply timeline of the target user.
*
* @remarks If the target user has a pinned tweet, the returned reply timeline has one item extra and this is always the pinned tweet.
*
* @public
*/
public async replies(userId: string, count?: number, cursor?: string): Promise<CursoredData<Tweet>> {
// Fetching the requested data
const data = await this.fetch<Tweet>(EResourceType.USER_TWEETS_AND_REPLIES, {
id: userId,
count: count,
cursor: cursor,
});
// Filtering out other tweets made by other users in the same threads
data.list = data.list.filter((tweet) => tweet.tweetBy.id == userId);
return data;
}
}
|
function [AIC_curve, BIC_curve] = gmm_eval(X, K_range, repeats, params)
%GMM_EVAL Implementation of the GMM Model Fitting with AIC/BIC metrics.
%
% input -----------------------------------------------------------------
% o X : (N x M), a data set with M samples each being of dimension N.
% each column corresponds to a datapoint
% o K_range : (1 X K), Range of k-values to evaluate
% o repeats : (1 X 1), # times to repeat k-means
% o params : Structure containing the paramaters of the algorithm:
% * cov_type: Type of the covariance matric among 'full', 'iso',
% 'diag'
% * d_type: Distance metric for the k-means initialization
% * init: Type of initialization for the k-means
% * max_iter_init: Max number of iterations for the k-means
% * max_iter: Max number of iterations for EM algorithm
%
% output ----------------------------------------------------------------
% o AIC_curve : (1 X K), vector of min AIC values for K-range
% o BIC_curve : (1 X K), vector of min BIC values for K-range
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:size(K_range,2)
params.k = K_range(i);
for j = 1:repeats
[Priors, Mu, Sigma,~] = gmmEM(X, params);
[AIC, BIC] = gmm_metrics(X, Priors, Mu, Sigma, params.cov_type);
if(j == 1)
AIC_curve(params.k) = AIC;
BIC_curve(params.k) = BIC;
elseif(AIC < AIC_curve(params.k))
AIC_curve(params.k) = AIC;
BIC_curve(params.k) = BIC;
end
end
end
end
|
# IntelliJ IDEA basics
[toc]
The main goal of IntelliJ IDEA is to raise your productivity while you are writing code. We prepared some basic advice to level up the speed and comfort of your developing experience. Those are for common cases, but you can also find more on the [IntelliJ IDEA webpage](https://www.jetbrains.com/help/idea/discover-intellij-idea.html).
## 1. Use keyboard shortcuts
We encourage you to use keyboard shortcuts, because they can significantly speed up your coding and even reduce **the risks of Repetitive Strain Injury**. IntelliJ IDEA is a keyboard-centric IDE. You can choose one of the pre-configured shortcut schemes, or a keymap, in **File | Settings | Keymap**:

You can always take a closer look at the list of actions and corresponding shortcuts available via search:

Or, you can search for action by shortcut:

You can also [set up your own keymap](https://www.jetbrains.com/help/idea/configuring-keyboard-and-mouse-shortcuts.html) if you need a customizable list of shortcuts.
> **Note:** If you use the default keymap of your OS and want a nice-looking cheat sheet to print out, go to **Help | Keyboard Shortcuts PDF**.
## 2. Go to the dark side
IntelliJ IDEA initially uses the default light color scheme, but you can always switch to the dark Darcula scheme. You can switch to it in **File | Settings | Appearance & Behaviour | Appearance** by choosing Darcula under the Theme dropdown list:

**Note:** you can use `` ^ + ` `` (in macOS) or `` CTRL + ` ``(in Windows and Linux) to switch quickly between color schemes and keymaps.
## 3. Local Terminal
IntelliJ IDEA features a local terminal that makes it possible to access the command line. Depending on your platform, you can work with the command prompt, PowerShell, Bash, etc. Using the terminal, you can execute any command without leaving the IDE.
To run the console, press `⌥ F12` / `Alt + F12` or click the Terminal tool window button:

## 4. Conclusion
IntelliJ IDEA allows you to:
- choose the scheme of keyboard shortcuts in **File | Settings | Keymap** and take a look for the shortcut you need by searching
- change the theme in **File | Settings | Appearance & Behaviour | Appearance**
- open the terminal by `⌥ F12` / `Alt + F12` or press the Terminal window button
Now you have a solid background on how to use common IntelliJ features. It is time to put them into practice!
## 5. Related topics
Topic prerequisites:
1. [IntelliJ IDEA ](https://hyperskill.org/learn/step/37202)
|
import {Component} from '@angular/core';
import {MatDialog} from "@angular/material/dialog";
import {DialogTestComponent} from "./dialog-test/dialog-test.component";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'storybook-jest-app';
constructor(private matDialog: MatDialog) {
}
openDialog(): void {
const dialogRef = this.matDialog.open(DialogTestComponent, {});
dialogRef.afterOpened()
.subscribe({
next: (e) => {
console.log('Opened with', e);
}
});
dialogRef.afterClosed()
.subscribe({
next: (e) => {
console.log('Closed with', e);
}
});
}
}
|
const bcrypt = require('bcrypt');
const { validationResult } = require('express-validator');
const User = require('../models/User');
const Course = require('../models/Course');
const Category = require('../models/Category');
exports.createUser = async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).redirect('/login');
} catch (error) {
const errors = validationResult(req);
for (let i = 0; i <errors.array().length; i++) {
req.flash("error", `${errors.array()[i].msg}`);
}
res.status(400).redirect('/register');
}
};
exports.loginUser = async (req, res) => {
try {
const { email, password } = req.body; //useri çekiyoruz
// ikiside aynı oldugu icin direkt ({email}) olarak yazılabilir.
await User.findOne({ email: email }, (error, user) => {
//userin emaili ile databaseden o useri çekiyorum
if (user) {
bcrypt.compare(password, user.password, (error, same) => { // compare ile şifreleri karşılaştırıyoruz, same == true ise giris yaptırıyorum.
if(same) {
// USER SESSION
req.session.userID = user._id;
res.status(200).redirect('/');
} else {
req.flash("error", "Your password is not correct!");
res.status(400).redirect('/login');
}
});
} else {
req.flash("error", "User is not exist!");
res.status(400).redirect('/login');
}
});
} catch (error) {
res.status(400).json({
status: 'fail',
error,
});
}
};
exports.logoutUser = (req, res) => {
req.session.destroy(() => {
res.redirect('/');
});
};
exports.getDashboardPage = async (req, res) => {
const user = await User.findOne({_id: req.session.userID}).populate('courses'); // userin içerisindeki course'lara ulaşmak için populate kullandık
const categories = await Category.find();
const courses = await Course.find({user: req.session.userID});
const users = await User.find();
res.status(200).render('dashboard', {
pageName: "dashboard",
user,
categories,
courses,
users
});
};
exports.deleteUser = async (req, res) => {
try {
await User.findByIdAndRemove(req.params.id)
await Course.deleteMany({user:req.params.id})
res.status(200).redirect('/users/dashboard');
} catch (error) {
res.status(400).json({
status: 'fail',
error,
});
}
};
|
# How did I build an API with DDD ? - Part 1
DDD has been and is still a popular design trend in large and highly professional systems at the present time.
However, understanding the "academic" definitions of DDD is very time-consuming and to support programmers in general as well as those who are intending to learn about DDD in particular, so the can in a short time of "absorbing" the "academic" knowledge of DDD, I would like to present to readers very basic knowledge as well as illustraive examples through this series of articles on DDD. I look forward to well received by readers.
## Overview about the API
I built this API with the main purpose to practice more about DDD so I won't focus too much on complex functions. Basically my API can be described using a usecase diagram as follows:

This is basically an API that allows users to:
- Create a post with an attached photo (just like instagram)
- Comment / Like the post
- Follow / Unfollow other users
You guys can refer to my source code at: <https://github.com/tuananhhedspibk/NewAnigram-BE-DDD>
In this API, the two main technologies I used are:
- `nestjs` framework
- `mysql` database
## What is DDD ?
DDD (Domain Driven Design) is a way of designing "business-oriented" software - that is, taking the business or domain logic as the center of the system.
An example can be the system "banking operations" or "logistics operations".
If we only talk about concepts, it will be difficult to imagine what DDD is, so in this article I will try to illustrate each concept of DDD corresponding to my API code.
### Basic concepts in DDD
Because it is a "domain" driven design, **domain** is the main concept here. Revolving around the concept of domain, we have 3 main key words: **Domain**, **Model** and **Domain Model**.
**Domain** is a certain business field such as "banking business" or "logistics business", ...
**Model** is the process of abstracting objects as well as business operations. This process of modeling business into abstract objects is called **Modeling** or **Modeling**.
**Domain Model** are the models we obtain after the **Modeling** process above.
Going back to the API above, my APIs domain is `users have the ability to post and follow other users`. I will model it into 2 main models:
- User
- Post
These are also the two main "objects" in my API. To illustrate the above two models more clearly, I have the Domain Model diagram as follows:

Looking through this diagram, you can see:
- Basic properties of post: content, imageUrls, ...
- Basic user attributes: email, userName, password
- 1-n relationship between User-Post.
It's correct but still missing a lot, for example:
- Comments
- Like
- Following
- User detail (save user details such as: firstName, lastName, age, ...)
Not only that, in DDD we also have another very important concept which is **Aggregate**. Simply explained, an aggregate is a set of objects that are closely related to each other in terms of data and we must always ensure that.
For example:

A Club will have "Members", here we stipulate that the Club's status will be `FULL` if the value of `memberCount = 5`, the Club's status will be `STILL_FREE` if the value of `memberCount < 5`. From this rule, we see that between Club and Member there is a fairly close data relationship, so we can conclude that Club and Member will belong to the same aggregate. So the domain model diagram of Club and Member will be revised as follows:

Going back to the API, after considering Follow, Like, Comment and User Detail, I decided to divide the aggregate as follows:

A brief explanation is as follows: I divided my domain into 3 aggregates:
- User
- Post
- Follow
My API doesn't have as many data constraints as the Club and Member examples above, but organizing it in aggregate "units" will help the code express the business more clearly.
Take the example of User Aggregate: in this aggregate I store the user's basic information (email, password) and detailed information (nickName, avatarUrl) of the user through 2 objects `User` and `UserDetail` respectively. , here `User` will be called `Root Aggregate`.
One of the basic principles when working with aggregates is that aggregate information can only be updated through the `root aggregate`, meaning that here, updating information for `UserDetail` or `User` must be done through `User Aggregate` or in other words `User Object`.
You can see how I define `User Aggreate` at [this address](https://github.com/tuananhhedspibk/NewAnigram-BE-DDD/blob/main/src/domain/entity/user/index.ts) . You can see how I update `UserDetail` as follows:
```ts
export class UserEntity extends BaseEntity {
updateDetail(params: UpdateDetailParams) {
if (!this.detail) {
this.detail = new UserDetailEntity();
}
if (params.avatarURL) {
this.detail.avatarURL = params.avatarURL;
}
if (params.gender) {
this.detail.gender = params.gender;
}
if (params.nickName !== null) {
this.detail.nickName = params.nickName;
}
}
}
```
I created an `updateDetail` method inside the `UserEntity` class (this is the User Aggregate class), this method will update the user detail information so the actual user detail update will look like this:
```ts
const user = new UserEntity(); // Define User Aggregate
user.updateDetail({nickName: "testUser"}); // Update detail through user aggregate
```
And User aggregate will "aggregate" userDetail within it through the class property as follows:
```ts
class UserEntity extends BaseEntity {
detail: UserDetailEntity;
}
class UserDetailEntity extends BaseEntity {
id?: number;
active: boolean;
nickName: string;
avatarURL: string;
gender: UserDetailGender;
constructor() {
super();
}
}
```
Each method defined in the Aggregate class itself will represent the content of the business that the system is modeling, in the example above it is `updateDetail`.
Similar with `Post Aggregate` at [source code](https://github.com/tuananhhedspibk/NewAnigram-BE-DDD/blob/main/src/domain/entity/post/index.ts). `Post Aggregate` with `Post object` as the `root aggregate`, `Comment` & `Like` objects will be child objects that are "aggregated" inside `Post Aggregate` through class properties as follows:
```ts
class PostEntity extends BaseEntity {
likes: LikeEntity[];
comments: CommentEntity[];
}
class CommentEntity extends BaseEntity {
id?: number;
content: string;
userId: number;
postId: number;
}
class LikeEntity extends BaseEntity {
id?: number;
userId: number;
postId: number;
}
```
As for `Follow Aggregate`, it is quite simple, it only has 2 unique properties:
- srcUserId: id of the user is following.
- destUserId: id of the user being followed.
More specifically, you can read [here](https://github.com/tuananhhedspibk/NewAnigram-BE-DDD/blob/main/src/domain/entity/follow.ts)
## Wrap up
OK, so that's it, a very basic and important concept of DDD is **Aggregate**. Hopefully, through this introductory article, you have absorbed the first few concepts of DDD. Basically, after this section, I hope you can understand:
- What is a domain?
- What is Modeling?
- What is Domain Model?
- What is Aggregate? What characteristics does Aggregate have that are worth paying attention to?
There is also a small reminder for you that the two diagrams I presented above are `Usecase diagram` and `Domain model diagram`, I will not present in detail the definitions of the two types but its could be explained briefly as follow:
- `Usecase diagram` will show the main functions that the system will provide to users (this diagram must come **before** the domain model diagram)
- `Domain model diagram` will show how we model objects in our system. In this diagram, you need to pay attention to the following basic things:
① Divide the aggregate appropriately based on actual operations.
② Specify the properties of the aggregate as well as the child objects in it (you may not need to write the method).
③ Fully explain the business logic in the diagram (in bullet form).
This is the end of Part 1. See you again in the next articles in the series about DDD, thank you.
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>后台管理</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.min.js"></script>
<script src="../js/vue.min.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="../backStage/css/public.css"/>
</head>
<body>
<div id="app">
<!-- 头部导航栏 -->
<div class="nva">
<div class="nva-left">
<h3>播放记录</h3>
</div>
<div class="nva-right">
<h3 v-text="isGetName">用户名称</h3>
</div>
</div>
<!-- 头部导航栏结束 -->
<!-- 未登录或者无权限 -->
<div class="tip" :style="isAdmin?disibleStyle:showStyle">
<h3><a href="../login.html" target="_blank" v-text="isTip">请登录</a></h3>
</div>
<!--内容主盒子 -->
<div class="mian" id="jumpMian" :style="isAdmin?showStyle:disibleStyle">
<!-- 左侧栏 -->
<div class="mian-left">
<ul>
<li v-for="(itme,index) in silentnva" :style="index==0?liBack:''" @click="jump(index)"><a href="#" v-text="itme"></a><span>></span></li>
</ul>
</div>
<!-- 右侧栏 -->
<div class="mian-right">
<div class="header">
<input type="search" placeholder="请输入视频名称/关键字" v-model="serach_key" @keyup.enter="getVideo" />
<button @click="getVideo">查询</button>
<button @click="add">添加</button>
<a href="JavaScript:void(0)" @click="back_page"><</a>
<a href="JavaScript:void(0)" @click="next_page" v-show="isNull>=25">></a>
</div>
<div class="list">
<table class="table" border="0" cellspacing="0" cellpadding="10px">
<tr>
<th>选择</th>
<th>序号</th>
<th>视频评分</th>
<th>视频标题</th>
<th>视频链接</th>
<th>视频ID</th>
<th>视频封面</th>
<th>视频类型</th>
<th>视频标签</th>
</tr>
<tr v-for="(item,index) in video" :style="index%2==0?even:''">
<td><a href="javascript:void(0)" @click="edit(item.rate,item.title,item.url,item.id,item.cover,item.types,item.tag,item.number)">编辑</a>
<a href="javascript:void(0)" @click="del(item.title)">删除</a>
</td>
<td v-text="item.number"></td>
<td v-text="item.rate"></td>
<td v-text="item.title"></td>
<td v-text="item.url"></td>
<td v-text="item.id"></td>
<td v-text="item.cover"></td>
<td v-text="item.types"></td>
<td v-text="item.tag"></td>
</tr>
</table>
</div>
<div class="edit" :style="addOrEdit?showStyle:''">
<input type="number" placeholder="视频评分/必填" v-model="rate"/>
<input type="text" placeholder="视频标题/必填" v-model="title"/>
<input type="url" placeholder="视频链接/必填" v-model="url"/>
<input type="number" placeholder="视频id/必填" v-model="id"/>
<input type="url" placeholder="视频封面/必填" v-model="cover"/>
<input type="text" placeholder="视频类型/必填" v-model="types"/>
<input type="text" placeholder="视频标签/必填" v-model="tag"/>
<button type="button" @click="cance">取消</button>
<button type="button" @click="addSubmit">提交</button>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
//tr表格偶数时使用的背景样式
even: 'background-color: #c5c5c6;',
//控制右侧栏li标签背景
liBack:'background-color: #b2b2b3;',
//用于隐藏和显示表格(不是管理员时或未登录是将隐藏起来)
showStyle:'display: block !important;',
disibleStyle:'display: none !important;',
isAdmin:false,
//右侧栏
silentnva: ['视频管理', '用户管理', '评论管理', '返回首页', '退出登录'],
//用于接收昵称,登录后将显示昵称
isGetName:'未登录',
//数组
video: [],
//搜索
serach_key: '',
//用来分页,从0行开始取数据
page_start: 0,
//每次取25行数据
page_limit:25,
//来判断是否为最后一页,当video数组长度小于25时,说明已经是最后一页
isNull:25,
addOrEdit:false,
//用于页面提示是否登录或者不是管理员时显示相关提示
isTip:'请登录',
//添加,编辑
isEditAdd:'添加',
rate:'',
title:'',
url:'',
id:'',
cover:'',
types:'',
tag:'',
numberId:-1
},
methods: {
getVideo() {
axios.get('php/index_video.php', {
params: {
serach_key: this.serach_key,
page_start: this.page_start,
page_limit:this.page_limit
}
}).then(response => {
console.log(response.data);
if(response.data=="未登录"){
this.isAdmin = false;
this.isTip = '您还没有登录,点击此处马上登录!';
}
else if(response.data=="越权访问"){
this.isAdmin = false;
this.isTip = '您不是管理员,无法操作,请使用管理员身份登录,点击此处登录';
}
else{
this.video = response.data;
this.serach_key = '';
this.isAdmin = true;
//this.isNull用来判断是否为最后一页
if(this.page_start!=0){
this.isNull = this.video.length;
}
}
})
},
//上下翻页
next_page() {
this.page_start += 25;
this.getVideo();
},
back_page() {
if (this.page_start != 0) {
this.page_start -= 25;
this.getVideo();
}
},
jump(index){
if(index==1){
window.location.href = 'user.html';
}
if(index==2){
window.location.href = 'comment.html';
}
if(index==3){
window.location.href = '../index.html';
}
if(index==4){
axios.get('../php/logOut.php').then(response => {
this.getVideo();
this.isGetName = '登录';
})
}
},
//验证用户是否已经登录
userVrification: function() {
axios.get('../php/userVrification.php').then(response => {
if (response.data == false) {
this.isGetName = '登录';
} else {
this.isGetName = response.data;
console.log(response.data);
}
})
},
add(){
this.addOrEdit = true;
this.isEditAdd = '添加';
this.rate = '';
this.title = '';
this.url = '';
this.id = '';
this.cover = '';
this.types = '';
this.tag = '';
},
cance(){
this.addOrEdit = false;
this.isEditAdd = '添加';
},
//添加,修改数据
addSubmit(){
if(this.rate==''||this.title==''||this.url==''||this.id==''||this.cover==''||this.types==''||this.tag==''){
alert('请把信息填写完整');
}
else{
axios.get('php/index_edit_add.php',{
params:{
rate:this.rate,
title:this.title,
url:this.url,
id:this.id,
numberId:this.numberId,
cover:this.cover,
types:this.types,
tag:this.tag,
isEditAdd:this.isEditAdd
}
}).then(response => {
if(response.data==true){
alert("添加成功!");
this.getVideo();
this.isEditAdd = '添加';
}
if(response.data==false){
alert("该条信息已经存在");
}
/* if(response.data=="failed"){
alert("视频标题或者视频ID已经存在,请更换");
} */
if(response.data=="修改成功"){
alert("修改成功!");
this.getVideo();
this.isEditAdd = '添加';
this.addOrEdit = false;
}
if(response.data=="修改失败"){
alert("修改失败");
}
})
}
},
//删除
del(title){
if(confirm("您确定要执行该操作?")==true){
axios.get('php/index_delete.php?title='+title).then(response =>{
if(response.data==true){
alert("删除成功");
this.getVideo();
}
if(response.data==false){
alert("删除失败!");
}
})
}
},
//编辑修改信息
edit(rate,title,url,id,cover,types,tag,Id){
this.rate = rate;
this.title = title;
this.url = url;
this.id = id;
this.cover = cover;
this.types = types;
this.tag = tag;
this.numberId = Id;
//显示
this.addOrEdit = true;
location.href = "#jumpMian";
this.isEditAdd = "编辑";
}
},
mounted() {
this.getVideo();
this.userVrification();
}
})
</script>
</html>
|
from random import shuffle
class Card:
suits = ["spades",
"hearts",
"diamonds",
"clubs"]
values = [None, None,"2", "3",
"4", "5", "6", "7",
"8", "9", "10",
"Jack", "Queen",
"King", "Ace"]
def __init__(self, v, s):
"""suit + value are ints"""
self.value = v
self.suit = s
def __lt__(self, c2):
if self.value < c2.value:
return True
if self.value == c2.value:
return self.suit < c2.suit
return False
def __gt__(self, c2):
if self.value > c2.value:
return True
if self.value == c2.value:
return self.suit > c2.suit
return False
def __repr__(self):
v = self.values[self.value] +\
" of " + \
self.suits[self.suit]
return v
class Deck:
def __init__(self):
self.cards = []
for i in range(2, 15):
for j in range(4):
self.cards\
.append(Card(i,
j))
shuffle(self.cards)
def draw(self):
if len(self.cards) == 0:
return
return self.cards.pop()
class Player:
def __init__(self, name):
self.wins = 0
self.card = None
self.name = name
class Game:
def __init__(self):
name1 = input("p1 name ")
name2 = input("p2 name ")
self.deck = Deck()
self.p1 = Player(name1)
self.p2 = Player(name2)
def print_winner (self, winner):
w = "{} wins this round"
print(w.format(winner.name))
def print_draw(self, p1, p2):
d = "{} drew {} {} drew {}"
print(d.format(p1.name, p1.card, p2.name, p2.card))
def play_game(self):
cards = self.deck.cards
print("beginning War!")
while len(cards) >= 2:
m = "q to quit. Any " + \
"key to play:"
response = input(m)
if response == 'q':
break
self.p1.card = self.deck.draw()
self.p2.card = self.deck.draw()
self.print_draw(self.p1, self.p2)
if self.p1.card > self.p2.card:
self.p1.wins += 1
self.print_winner(self.p1)
else:
self.p2.wins += 1
self.print_winner(self.p2)
win = self.winner(self.p1,
self.p2)
print("War is over.{} wins"
.format(win))
def winner(self, p1, p2):
if p1.wins > p2.wins:
return p1.name
if p1.wins < p2.wins:
return p2.name
return "It was a tie!"
game = Game()
game.play_game()
|
<template>
<div class="py-4 container-fluid">
<div class="row">
<div class="col-12">
<button
class="btn-primary rounded px-5 py-1.9 mb-3"
type="button"
@click="showModal"
>
Add
</button>
<Modal v-show="isModalAddVisible" @close="closeModal">
<template v-slot:header>MEISY ANJARFIKA STECHOQ MODAL</template>
<template v-slot:body>
<div class="mt-3">
<form v-on:submit.prevent="submitAddList">
<div class="form-group">
<label for="title">Nama:</label>
<input
type="text"
class="form-control"
id="title"
v-model="input.title"
/>
</div>
<div class="form-group">
<label for="category">Role:</label>
<input
type="text"
class="form-control"
id="category"
v-model="input.category"
/>
</div>
<div class="form-group">
<label for="description">JobDesk:</label>
<textarea
type="text"
class="form-control"
id="description"
v-model="input.description"
></textarea>
</div>
<div class="text-center mt-4">
<button class="btn btn-primary px-6 fs-5" type="submit">
Save
</button>
</div>
</form>
</div>
</template>
<template v-slot:footer> @footerMeiMei </template>
</Modal>
<TodoTable />
</div>
</div>
</div>
</template>
<script>
import { mapActions } from "pinia";
import d$todo from "@/stores/dashboard/todo";
import Modal from "@/components/Modal.vue";
import TodoTable from "@/views/Dashboard/TodoTable.vue";
export default {
name: "Todo",
components: {
TodoTable,
Modal,
},
data: () => ({
input: {
title: "",
description: "",
category: "",
},
isModalAddVisible: false,
}),
methods: {
showModal() {
this.isModalAddVisible = true;
},
closeModal() {
this.isModalAddVisible = false;
},
...mapActions(d$todo, ["a$list", "a$add"]),
async submitAddList() {
try {
await this.a$add({ ...this.input });
await this.a$list();
this.isModalAddVisible = false;
this.input.title = "";
this.input.description = "";
this.input.category = "";
} catch (e) {
console.error(e);
}
},
},
};
</script>
<style></style>
|
class SupplierListResponse {
List<SupplierData>? data;
String? strMsg;
String? error;
SupplierListResponse({this.data, this.strMsg, this.error});
SupplierListResponse.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <SupplierData>[];
json['data'].forEach((v) {
data!.add(new SupplierData.fromJson(v));
});
}
strMsg = json['strMsg'];
error = json['error'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
data['strMsg'] = this.strMsg;
data['error'] = this.error;
return data;
}
}
class SupplierData {
int? intid;
String? strCompanyName;
String? strContactPersonName;
String? strContactMobilenumber;
String? strAddress;
SupplierData(
{this.intid,
this.strCompanyName,
this.strContactPersonName,
this.strContactMobilenumber,
this.strAddress});
SupplierData.fromJson(Map<String, dynamic> json) {
intid = json['intid'];
strCompanyName = json['strCompanyName'];
strContactPersonName = json['strContactPersonName'];
strContactMobilenumber = json['strContactMobilenumber'];
strAddress = json['strAddress'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['intid'] = this.intid;
data['strCompanyName'] = this.strCompanyName;
data['strContactPersonName'] = this.strContactPersonName;
data['strContactMobilenumber'] = this.strContactMobilenumber;
data['strAddress'] = this.strAddress;
return data;
}
}
class SupplierInvoiceList_Response {
List<SupplierInvoiceData>? data;
String? strMsg;
String? error;
SupplierInvoiceList_Response({this.data, this.strMsg, this.error});
SupplierInvoiceList_Response.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <SupplierInvoiceData>[];
json['data'].forEach((v) {
data!.add(new SupplierInvoiceData.fromJson(v));
});
}
strMsg = json['strMsg'];
error = json['error'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
data['strMsg'] = this.strMsg;
data['error'] = this.error;
return data;
}
}
class SupplierInvoiceData {
int? intid;
String? strInvoiceno;
String? strSuppliername;
String? strinvoicedate;
double? decTotal;
String? strImageFileName;
SupplierInvoiceData(
{this.intid,
this.strInvoiceno,
this.strSuppliername,
this.strinvoicedate,
this.decTotal,
this.strImageFileName});
SupplierInvoiceData.fromJson(Map<String, dynamic> json) {
intid = json['intid'];
strInvoiceno = json['StrInvoiceno'];
strSuppliername = json['strSuppliername'];
strinvoicedate = json['strinvoicedate'];
decTotal = json['decTotal'];
strImageFileName = json['strImageFileName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['intid'] = this.intid;
data['StrInvoiceno'] = this.strInvoiceno;
data['strSuppliername'] = this.strSuppliername;
data['strinvoicedate'] = this.strinvoicedate;
data['decTotal'] = this.decTotal;
data['strImageFileName'] = this.strImageFileName;
return data;
}
}
class EditSupplierInvoiceResponse {
List<SupplierInvoiceData1>? data1;
String? strMsg;
String? error;
EditSupplierInvoiceResponse({this.data1, this.strMsg, this.error});
EditSupplierInvoiceResponse.fromJson(Map<String, dynamic> json) {
if (json['data1'] != null) {
data1 = <SupplierInvoiceData1>[];
json['data1'].forEach((v) {
data1!.add(new SupplierInvoiceData1.fromJson(v));
});
}
strMsg = json['strMsg'];
error = json['error'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data1 != null) {
data['data1'] = this.data1!.map((v) => v.toJson()).toList();
}
data['strMsg'] = this.strMsg;
data['error'] = this.error;
return data;
}
}
class SupplierInvoiceData1 {
int? intid;
int? intCompanyId;
int? intSupplierId;
String? strInvoiceNo;
String? strInvoiceDate;
String? strDueDate;
double? decTotal;
double? decDiscount;
double? decGrandTotal;
double? decCGSTTax;
double? decSGSTTax;
bool? bIsIncludeGST;
String? strFilePath;
String? strImageFileName;
String? strMemo;
SupplierInvoiceData1(
{this.intid,
this.intCompanyId,
this.intSupplierId,
this.strInvoiceNo,
this.strInvoiceDate,
this.strDueDate,
this.decTotal,
this.decDiscount,
this.decGrandTotal,
this.decCGSTTax,
this.decSGSTTax,
this.bIsIncludeGST,
this.strFilePath,
this.strImageFileName,
this.strMemo});
SupplierInvoiceData1.fromJson(Map<String, dynamic> json) {
intid = json['intid'];
intCompanyId = json['intCompanyId'];
intSupplierId = json['intSupplierId'];
strInvoiceNo = json['strInvoiceNo'];
strInvoiceDate = json['strInvoiceDate'];
strDueDate = json['strDueDate'];
decTotal = json['decTotal'];
decDiscount = json['decDiscount'];
decGrandTotal = json['decGrandTotal'];
decCGSTTax = json['decCGSTTax'];
decSGSTTax = json['decSGSTTax'];
bIsIncludeGST = json['bIsIncludeGST'];
strFilePath = json['strFilePath'];
strImageFileName = json['strImageFileName'];
strMemo = json['strMemo'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['intid'] = this.intid;
data['intCompanyId'] = this.intCompanyId;
data['intSupplierId'] = this.intSupplierId;
data['strInvoiceNo'] = this.strInvoiceNo;
data['strInvoiceDate'] = this.strInvoiceDate;
data['strDueDate'] = this.strDueDate;
data['decTotal'] = this.decTotal;
data['decDiscount'] = this.decDiscount;
data['decGrandTotal'] = this.decGrandTotal;
data['decCGSTTax'] = this.decCGSTTax;
data['decSGSTTax'] = this.decSGSTTax;
data['bIsIncludeGST'] = this.bIsIncludeGST;
data['strFilePath'] = this.strFilePath;
data['strImageFileName'] = this.strImageFileName;
data['strMemo'] = this.strMemo;
return data;
}
}
class SupplierInvoiceItemResponse {
List<SupplierInvoiceItemData1>? data1;
String? strMsg;
String? error;
SupplierInvoiceItemResponse({this.data1, this.strMsg, this.error});
SupplierInvoiceItemResponse.fromJson(Map<String, dynamic> json) {
if (json['data1'] != null) {
data1 = <SupplierInvoiceItemData1>[];
json['data1'].forEach((v) {
data1!.add(new SupplierInvoiceItemData1.fromJson(v));
});
}
strMsg = json['strMsg'];
error = json['error'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data1 != null) {
data['data1'] = this.data1!.map((v) => v.toJson()).toList();
}
data['strMsg'] = this.strMsg;
data['error'] = this.error;
return data;
}
}
class SupplierInvoiceItemData1 {
int? intid;
int? intInvoiceid;
String? strItemName;
int? intqty;
String? StrUnitName;
double? decRate;
double? totalAmount;
SupplierInvoiceItemData1(
{this.intid,
this.intInvoiceid,
this.strItemName,
this.intqty,
this.StrUnitName,
this.decRate,
this.totalAmount});
SupplierInvoiceItemData1.fromJson(Map<String, dynamic> json) {
intid = json['intid'];
intInvoiceid = json['IntInvoiceid'];
strItemName = json['strItemName'];
intqty = json['intqty'];
StrUnitName = json['StrUnitName'];
decRate = json['DecRate'];
totalAmount = json['TotalAmount'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['intid'] = this.intid;
data['IntInvoiceid'] = this.intInvoiceid;
data['strItemName'] = this.strItemName;
data['intqty'] = this.intqty;
data['StrUnitName'] = this.StrUnitName;
data['DecRate'] = this.decRate;
data['TotalAmount'] = this.totalAmount;
return data;
}
}
|
package com.hedvig.android.feature.profile.aboutapp
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.google.accompanist.web.WebView
import com.google.accompanist.web.rememberWebViewState
import com.hedvig.android.core.ui.appbar.TopAppBarWithBack
import hedvig.resources.R
private const val licensesUrl = "file:///android_asset/open_source_licenses.html"
@Composable
internal fun LicensesDestination(onBackPressed: () -> Unit) {
Surface(
color = MaterialTheme.colorScheme.background,
modifier = Modifier.fillMaxSize(),
) {
Column(
Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
) {
TopAppBarWithBack(
onClick = onBackPressed,
title = stringResource(R.string.PROFILE_ABOUT_APP_LICENSE_ATTRIBUTIONS),
contentPadding = WindowInsets.safeDrawing
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top)
.asPaddingValues(),
)
val state = rememberWebViewState(licensesUrl)
WebView(state = state)
}
}
}
|
<div class="grid-container" *ngIf="movieDetails">
<div class="grid-item"></div>
<div class="grid-container-in">
<div class="grid-item">
<div class="grid-item">
<button [routerLink]="['/movies']" class="btn details-button">
<span class="icon-home"></span>Back
</button>
</div>
<div class="grid-item">
<h2>{{movieDetails.title}}</h2>
</div>
<div class="grid-item">
<table class="table-noborder">
<tr>
<td style="flex-grow: 2">
<input type="image" src="{{movieDetails.poster}}" alt="Submit"
height="auto" width="180px">
</td>
<td style="flex-grow: 8">
<strong>Summary:</strong> {{movieDetails.summary}}
</td>
</tr>
</table>
</div>
<div class="grid-item">
<h4 class="details">Details</h4>
</div>
<div class="grid-item">
<table class="detailsTable">
<tr>
<td class="detailsCol">Box office</td>
<td class="detailsCol2" colspan="2">{{movieDetails.box_office | budget}}</td>
</tr>
<tr>
<td class="detailsCol">Budget</td>
<td class="detailsCol2">{{movieDetails.budget | budget}}</td>
</tr>
<tr>
<td class="detailsCol">Duration</td>
<td class="detailsCol2">{{movieDetails.duration | duration}}</td>
</tr>
<tr>
<td class="detailsCol">Producers</td>
<td class="detailsCol2">{{movieDetails.producers.join(', ')}}</td>
</tr>
<tr>
<td class="detailsCol">Cinematographers</td>
<td class="detailsCol2">{{movieDetails.cinematographers.join(', ')}}</td>
</tr>
</table>
</div>
</div>
</div>
<div class="grid-item"></div>
</div>
|
package guru.springframework.sfgpetclinic.service.springdatajpa;
import guru.springframework.sfgpetclinic.model.Speciality;
import guru.springframework.sfgpetclinic.model.Vet;
import guru.springframework.sfgpetclinic.repositories.SpecialityRepository;
import guru.springframework.sfgpetclinic.repositories.VetRepository;
import guru.springframework.sfgpetclinic.service.VetService;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Service
@Profile("springdatajpa")
public class VetSDJpaService implements VetService {
private final VetRepository vetRepository;
private final SpecialityRepository specialityRepository;
public VetSDJpaService(VetRepository vetRepository, SpecialityRepository specialityRepository) {
this.vetRepository = vetRepository;
this.specialityRepository = specialityRepository;
}
@Override
public Vet findById(Long id) {
return vetRepository.findById(id).orElse(null);
}
@Override
public Set<Vet> findAll() {
Set<Vet> vets = new HashSet<>();
vetRepository.findAll().forEach(vets::add);
return vets;
}
@Override
public Vet save(Vet vet) {
if (!vet.getSpecialities().isEmpty()){
for (Speciality speciality:vet.getSpecialities()) {
if(specialityRepository.findById(speciality.getId()).isEmpty()){
specialityRepository.save(speciality);
}
}
}
return vetRepository.save(vet);
}
@Override
public void deleteById(Long id) {
vetRepository.deleteById(id);
}
@Override
public void delete(Vet vet) {
vetRepository.delete(vet);
}
@Override
public void deleteAll(Map<Long, Vet> map) {
Set<Vet> vets = new HashSet<>();
map.values().forEach(vets::add);
vetRepository.deleteAll(vets);
}
@Override
public Vet findByLastName(String lastName) {
return vetRepository.findByLastName(lastName);
}
}
|
# binary search trees
> trees are reference-based and behave similarly to linked lists— although trees are more complicated, we almost always work on a list starting from the root to conduct an operation
>
### binarySort
```java
void binarySort(Student[] a) {
int n = a.length;
Student[] b = new Student[n];
for(int i = 0; i<n; i++) {
b[i] = a[i];
}
int girls = 0, boys = n-1;
for(int i=0; i<b.length; i++) {
if(b[i].gender = 'F') {
a[girls++] = b[i];
} else {
a[boys--] = b[i];
}
}
}
//make use of girls and boys as indices from the start and end of the array
//this is not inplace because we are creating a new array
```
- to make this in-place, instead of creating a separate array to store the sorted elements, we can just perform the sorting directly on the input array
```java
void sortGrades(Student[] a) {
int n = a.length;
Student[] copy = new Student[n];
for (int i = 0; i < n; i++) {
copy[i] = a[i];
}
int count[] = new int[4]; // Assuming grades are 'A', 'B', 'C', 'D'
for (Student c : a) {
count[c.grade - 'A']++;
}
int cur[] = new int[4];
for (int i = 1; i < 4; i++) {
cur[i] = count[i - 1] + cur[i - 1];
}
Student[] output = new Student[n];
for (int i = n - 1; i >= 0; i--) {
int index = cur[copy[i].grade - 'A'];
output[index] = copy[i];
cur[copy[i].grade - 'A']++;
}
for (int i = 0; i < n; i++) {
a[i] = output[i];
}
}
```
### binarySort for 3 different keys
```java
void sortGrades(Student[] a) {
int n = a.length;
Student[] copy = new Student[n];
for(int i=0; i<n; i++) {
copy[i] = a[i];
} //takes an array of Student objects as input and creates a copy
int count[] = {0,0,0,0}; //counts occurrences of each grade A,B,C,D
for(Student c: a) {
count[c.grade - 'A']++; //current grade - A finds the difference between grades
} //then we increment the count array to move to the enxt element in the array
int cur[] = {0,0,0,0};
cur[1] = count[0]; //represents A
cur[2] = cur[1] + count[1]; //total counts of As and Bs and Cs
cur[3] = cur[2] + count[2]; //total of all grades
for(int i = 0; i<n; i++) {
a[cur[copy[i].grade - 'A']++] = copy[i];
}//iterates through copy array and assigns each Student object to its correct position in the original array
}
```
# quicksort
- in every step, we choose a **pivot p**, and divide the array into two parts such that
- every element in the left is no larger than p
- and every element in the right is larger than p
- p itself can be the first, last, or middle element
## recursive quicksort
```java
package binarytrees;
public class RecursiveQuicksort {
static void naive(int[] a, int low, int high) {
if(low >= high) {
return;
}
int pivot = a[high]; //p is the last element
int[] b = new int[high - low + 1]; //new array with the length of original array
for(int i = 0; i<b.length; i++) {
b[i] = a[low+i]; //we copy the values of the original array to b
}
int l = low, r = high;
for(int i=0; i<b.length; i++) {
if(b[i] <= pivot) { //if element in b is less than pivot
a[l++] = b[i]; //move it to the left of the original array
} else {
a[r--] = b[i]; //otheriwse move it to the right of the original array
}
}
naive(a, low, l-2); //recursively sort the left subarray
naive(a, r+1, high); //recursively sort the right subarray
}
public static void main(String[] args) {
int[] a = {14, 8, 10, 89, 32, 50, 77, 38};
naive(a, 0, a.length - 1);
for(int num : a) {
System.out.print(num + " ");
}
}
}
/*
after the partitioning loop, the variable l points to the index where the next element smaller than or equal to the pivot should be placed--
using l-1 would include the last element placed in the left subarray, leading to redundant comparisons-- by incrementing l before placing
an element in the left subarray, l points to the first index where an element larger than the pivot is found. therefore, when making the recursive call,
l-2 is used to exclude the last element placed in the left subarray
*/
```
- it is a divide and conquer algorithm, so we consider #levels and work at each level
- the work of each partition is proportional to the number of elements under concern, so each level uses O(n) time
- the running time of the whole algorithm depends on #levels (iterations) which depends on whether the partitions are balanced, which depends on the pivot values chosen in each step
- so, if we always choose the last element as pivot, the worst case is a **sorted array**— this is because since quicksort always chooses the last element, when the array is already sorted, the pivot will always be the largest element— so as a result, the subarrays will be unbalanced since the other subarray is literally empty and this is inefficient because the partitioning step only reduces the problem size by one element per recursive call
- the worst cases: **n → n-1 → n-2 → n-3 → … → 1**
> in the worst case, quicksort takes o($n^2$) time | in the best case, it takes o(n(log(n)) time
>
- the best cases are when:
1. each partition is **almost even**
2. log(n) levels with O(n) at each level
### comparison of merge sort and quicksort
| | mergesort | quicksort |
| --- | --- | --- |
| divide | O(1) | Θ(n) |
| combine | Θ(n) | 0 |
| levels | Θ(logn) | log n ~ n - 1 |
| best time | Θ(n log(n)) | Θ(n log(n)) |
| average time | Θ(n log(n)) | Θ(n log(n)) |
| worst time | Θ(n log(n)) | Θ(n$^2$) |
- in quicksort, the only thing we need to do is divide
## improvements
- choice of “good” pivots:
- **random pivot** — the worst case stays the same, but you shouldn’t always be unlucky
- **median-of-three pivot** — choosing the median of the first, middle, and last elements of the partition is good for sorted arrays but bad cases still exist (1,x,…,x,1,y,…,y,1)
- **dual pivots** — partition into three parts
- using **insertion sort** when the partition is small
### hoare partitioning scheme
- two indices, each in its own while loop, start at opposite ends of the array and step toward each other, looking for items that need to be swapped
- when an index finds an item that needs to be swapped, its while loop exits
- when both while loops exit, the items are swapped — when both while loops exit, and the indices have been met or passed each other, the partition is complete
```java
public class QuickSort {
private static void insertion(int[] a, int low, int high) { //use insertion sort to sort the array if the length is small-- ALMOST sorted
for(int i=low+1; i<=high; i++) {
int key = a[i];
int j = i-1;
while(j >= low && key < a[j]) {
a[j+1] = a[j];
j--;
}
a[j+1] = key;
}
}
private static int partition(int[] a, int low, int high) {
int pivot = a[high]; //pivot is the LAST element
int i = low, j = low; //i is used to iterate from low to high; j is used to keep track of the boundary between pivot
while(i <= high) {
if(a[i] > pivot) { i++; } //if value at ith position is greater than pivot value, we move onto the next value (don't do anything)
else { int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j++; } //else we swap the ith value with j which holds the boundary between greater than or less than pivots
}
return j-1; //return the value right before the pivot
}
public static void QS(int[] a, int low, int high) {
while(low < high) {
if(high-low < 10) { //if length is less than 10, insertion sort!
insertion(a, low, high);
break;
} else {
int p = partition(a, low, high); //we partition to find the current location of the pivot
if(p-low < p-high) { //if left subarray is smaller than right subarray
QS(a, low, p-1); //we sort the the left subarray
low = p+1; //when sorted, we update low as p+1
} else {
QS(a, p+1, high); //otherwise, we sort the right subarray
high = p-1; //afterwards, we update high to p-1
}
}
}
}
public static void main(String[] args) {
int[] a = {14, 8, 10, 89, 32, 50, 77, 38};
QS(a, 0, a.length-1);
for(int num : a) {
System.out.print(num + " ");
}
}
}
```
| | best sorting algorithm to use |
| --- | --- |
| sorted array | bubble or insertion |
| reversely sorted array | merge or quick sort |
| array with identical elements | any stable sort |
| almost sorted array | insertion sort |
| random array | merge or quick sort |
### you sort (almost) sorted arrays a lot
- sorting twice doesn’t make your array more sorted— it can take much longer actually
- most of the time, we are sorting an “almost” sorted array
- **insertion is the best**, then cocktail sort, then bidirectional bubble sort
## review: mergesort
- divide a big problem into smaller problems and solve each one separately
- both binary search and mergesort divide arrays in the same way
- **binary search**: left half (⌊n−1/2⌋) and right half (⌊n/2⌋)
- **mergesort**: left half (⌊n+1/2⌋) and right half (⌊n/2⌋)
- for iterative implementation: bottom-up
### terminologies
| path | a sequence of edges, each starting with the node of the previous edge ends |
| --- | --- |
| length of a path | the number of edges in it |
| root | any node may be considered to be the root of a subtree which consists of its children, and its children’s children, and so on |
| depth | length of path from root to node |
| height of a node | length of longest path from that node down to a leaf |
| height of a tree | height of a tree is the height of its root
all leaves have a height of 0 |
> #nodes in a tree of depth k is between k+1 and $2^k$$^+$$^1 -1$
>
> depth of a tree of n nodes is between ⌊log n⌋ and n-1
>
> a binary tree is perfect if all leaves on the same level and each non-leaf node has exactly two children
>
> - all perfect binary trees are complete
### complete trees
- a binary tree is complete if all leaves at the bottom level are as far to the left as possible and every other level is completely filled
```java
public class BinaryTree<T> {
private class Node<T> :
T data;
public Node<T> leftChild, rightChild;
}
Node<T> root;
}
```
- the number of null references (absent children of the nodes) in a binary tree of n nodes is (n+1)
### implementations
- for each node, use a linked list to store references to its children— each node stores the reference to its first child and its next sibling
- to augment a binary tree with bidirectional links, you can add either parent pointers or sibling pointers to each node
```java
// class containing left and right child
// of current node and key value
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class BinaryTree {
// root of Binary Tree
Node root;
// constructors
BinaryTree(int key) {
root = new Node(key);
}
BinaryTree() {
root = null;
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
// create root
tree.root = new Node(1);
/* Following is the tree after above statement
1
/ \
null null
*/
tree.root.left = new Node(2);
tree.root.right = new Node(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
null null null null */
tree.root.left.left = new Node(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 null null null
/ \
null null
*/
}
}
```
### traversals
```java
class Node {
int key;
Node left, right;
public Node(int item) {
key = item; //the actual data of each node
left = right = null; //initialize left and right nodes as null
}
}
public class TreeTraversals {
Node root;
public TreeTraversals() {
root = null;
}
void printInorder(Node node) {
if (node == null) {
return;
}
printInorder(node.left); //recurs all left nodes first
System.out.print(node.key + " "); //then prints key IN BETWEEN nodes
printInorder(node.right); //recurs all right nodes last
}
void printPostOrder(Node node) {
if (node == null) {
return;
}
printPostOrder(node.left); //recurs left nodes
printPostOrder(node.right); //recurs right nodes
System.out.print(node.key + " "); //prints key AFTER children have been visited
}
void printPreOrder(Node node) {
if (node == null) {
return;
}
System.out.print(node.key + " "); //prints key BEFORE children have been visited
printPreOrder(node.left); //recurs left nodes
printPreOrder(node.right); //recurs right nodes
}
public static void main(String[] args) {
TreeTraversals tree = new TreeTraversals();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.print("Inorder traversal of binary tree is ");
tree.printInorder(tree.root); // 4 2 5 1 3 -- left.left -> left -> left.right -> key -> right
System.out.println();
System.out.print("PostOrder traversal of binary tree is ");
tree.printPostOrder(tree.root); //4 5 2 3 1 -- left.left -> left.right -> left -> right -> key
System.out.println();
System.out.print("PreOrder traversal of binary tree is ");
tree.printPreOrder(tree.root); //1 2 4 5 3 -- key -> left -> left.left -> left.right -> right
}
}
```
## level-wise traversal
```java
import java.util.LinkedList;
import java.util.Queue;
public class LevelWise {
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
static void levelOrder(Node root) {
if (root == null) { return; }
Queue<Node> q = new LinkedList<>(); //we create a new node
q.add(root); //pushing root node into queue
q.add(null); //push a delimiter into the queue to indicate the END of a current level
while (!q.isEmpty()) { //continue the loop until the queue is empty
Node curr = q.poll(); //remove the front node from the queue
if (curr == null) { //if the current node is a delimiter
if (!q.isEmpty()) { //check if the queue is still not empty
q.add(null); //we push in another delimiter
System.out.println(); //separate levels
}
} else { //if current node is not null
if (curr.left != null) { q.add(curr.left); } //pushing left child of node
if (curr.right != null) { q.add(curr.right); } //pushing right child of node
System.out.print(curr.data + " "); //print the data of the current queue
}
}
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);
levelOrder(root);
}
}
```
- two different trees can have the same inorder sequence
- how do we uniquely build the tree?
- Inorder traversal: □□□X■■■■■
Postorder traversal: □□□■■■■■X
- Inorder traversal: □□□X■■■■■
Preorder traversal: X□□□■■■■■
- Postorder traversal: □□□■■■■■X
Preorder traversal: X□□□■■■■■
# searching a tree
- in a binary search tree, every node is
- larger than nodes in its left subtree, and
- smaller than nodes in its right subtree
- example
- 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10 → 11 → 12 → 13 → 14
- the running time of search is O(d), where d is the **depth/height** of the tree, but the worst case is d = n-1, when the tree is skewed
- binary trees with depth O(log (n)) are considered balanced— there is balance between the number of nodes in the left subtree and the number of nodes in the right subtree of each node
```java
BinarySearchTree < Student > tree = new BinarySearchTree < Student >();
int [] ids = {214 ,562 ,83 ,115 ,97 ,722 ,398 ,798 ,408 ,199 ,37};
String [] names = { " Chan ␣ Eason " , " Cheung ␣ Jacky " , " Winnie " ,
" Ho ␣ Denise " , " Mickey " , " Leung ␣ Gigi " , " Joey ␣ Yung " ,
" Teddy " , " Peppa " , " Tse ␣ Kay " , " Andy ␣ Lau " };
for (int i = 0; i < 11; i ++) {
tree.insert (ids[i], new Student(ids[i], names[i]));
```
- any order in which no node is earlier than its parent
## successor in BST
- the **successor** of a node is the node whose key immediately follow it
- the **predecessor** of a node is the node whose key immediately precedes it
- if x has a right child, the minimum node of its right subtree— otherwise, on the path from the root to x, the first node on which we turn left
## finding successor/predecessor
- **the successor of node x:**
- if x has a right child, then the successor of x is the **minimum** in the **right** subtree— follow x’s **right pointers**, then follow **left pointers** until there are no more
- if x does not have a right child, then find the lowest ancestor of x whose left child is also an ancestor of x
- when searching for x, record the last node whose left subtree is used
- **the predecessor of node x:**
- if x has a left child, then the successor of x is the **maximum** in the **left** subtree— follow x’s **left pointers**, then follow **right pointers** until there are no more
- if x does not have a left child, then find the lowest ancestor of x whose right child is also an ancestor of x
- when searching for x, record the last node whose right subtree is used
## deleting a node
- to delete a leaf, set the link from its parent to it to be null— simply removing a non-leaf breaks the tree
- to delete a node x with one child y, set the link from x’s parent to x to y
| x has no children | set the child field in its parent to null |
| --- | --- |
| x has one child | set the child field in its parent to point to its child |
| x has two children | replace x with its successor y (minimum of x’s right subtree) |
- easy if the right child of x has no left child (115 and 562)— otherwise we need to find some node to replace y (083 and 214)
```java
class BinarySearchTree {
class Node {
int key;
Node left, right;
Node(int item) {
key = item;
left = right = null;
}
}
Node root;
void inorder(Node root) {
if (root != null) {
inorder(root.left); //recur left nodes
System.out.print(root.key + " "); //print key node IN BETWEEN children
inorder(root.right); //recur right nodes
}
}
Node insert(Node node, int key) {
if (node == null)
return new Node(key); //if tree is empty, insert new node
if (key < node.key) //if key is less than current key
node.left = insert(node.left, key); //insert new node in left subtree
else if (key > node.key)
node.right = insert(node.right, key); //otherwise, insert node in right subtree
return node;
}
Node deleteNode(Node root, int key) {
if (root == null) //base case-- if key was not found in tree
return root;
if (root.key > key) { //key to be deleted is smaller than current key
root.left = deleteNode(root.left, key); //recurs deleteNode on left child
return root;
} else if (root.key < key) { //else if key to be deleted is greater than current key
root.right = deleteNode(root.right, key); //recurs deleteNode on right child
return root;
}
//if one of the children is empty!!
if (root.left == null) { //if node to be deleted has no left child
Node temp = root.right; //replaces the node with its right child
return temp;
} else if (root.right == null) { //if node to be deleted has no right child
Node temp = root.left; //replaces the node with its left child
return temp;
}
//if both children exist!!
else {
Node succParent = root; //keeps track of parent of the successor node
Node succ = root.right; //initializes variable to the right child of current node (successor is always in right subtree)
while (succ.left != null) { //iterate down the left child of current node until it finds leftmost leaf node in right subtree
succParent = succ;
succ = succ.left;
}
if (succParent != root) //if successor is not an immediate right child of the node to be deleted
succParent.left = succ.right; //left pointer will point to successor's right child
else
succParent.right = succ.right; //else, right pointer of parent will point to successors right child
root.key = succ.key; //key of node to be deleted is replaced with key of successor node
return root;
}
}
// Driver Code
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
tree.root = tree.insert(tree.root, 50);
tree.insert(tree.root, 30);
tree.insert(tree.root, 20);
tree.insert(tree.root, 40);
tree.insert(tree.root, 70);
tree.insert(tree.root, 60);
System.out.print("Original BST: ");
tree.inorder(tree.root);
System.out.println("\n\nDelete a Leaf Node: 20");
tree.root = tree.deleteNode(tree.root, 20);
System.out.print("Modified BST tree after deleting Leaf Node:\n");
tree.inorder(tree.root);
System.out.println("\n\nDelete Node with single child: 70");
tree.root = tree.deleteNode(tree.root, 70);
System.out.print("Modified BST tree after deleting single child Node:\n");
tree.inorder(tree.root);
System.out.println("\n\nDelete Node with both child: 50");
tree.root = tree.deleteNode(tree.root, 50);
System.out.print("Modified BST tree after deleting both child Node:\n");
tree.inorder(tree.root);
}
}
```
|
from datetime import datetime
from django.db.models import F, Count
from drf_spectacular.utils import extend_schema, OpenApiParameter
from rest_framework import viewsets, mixins, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from theatre.models import (
TheatreHall,
Genre,
Actor,
Play,
Performance,
Reservation,
)
from theatre.permissions import AnonReadOnly
from theatre.serializers import (
TheatreHallSerializers,
GenreSerializer,
ActorSerializer,
PlaySerializer,
PlayListSerializer,
PlayDetailSerializer,
PlayImageSerializer,
PerformanceSerializer,
PerformanceListSerializer,
PerformanceDetailSerializer,
ReservationSerializer,
ReservationListSerializer,
)
class GenreViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixin,
GenericViewSet,
):
queryset = Genre.objects.all()
serializer_class = GenreSerializer
class ActorViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixin,
GenericViewSet,
):
queryset = Actor.objects.all()
serializer_class = ActorSerializer
class TheatreHallViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
GenericViewSet,
):
queryset = TheatreHall.objects.all()
serializer_class = TheatreHallSerializers
class PlayViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet,
):
queryset = Play.objects.prefetch_related("actors", "genres")
serializer_class = PlaySerializer
@staticmethod
def _params_str_to_int(params_in_url: str) -> list:
"""Converts a list of string IDs to a list of integers"""
return [int(param) for param in params_in_url.split(",")]
def get_queryset(self):
"""Retrieve the plays with filters"""
title = self.request.query_params.get("title")
genres = self.request.query_params.get("genres")
actors = self.request.query_params.get("actors")
queryset = self.queryset
if title:
queryset = queryset.filter(title__icontains=title)
if genres:
genres_id = self._params_str_to_int(genres)
queryset = queryset.filter(genres__id__in=genres_id)
if actors:
actors_id = self._params_str_to_int(actors)
queryset = queryset.filter(actors__id__in=actors_id)
return queryset.distinct()
def get_serializer_class(self):
if self.action == "list":
return PlayListSerializer
if self.action == "retrieve":
return PlayDetailSerializer
if self.action == "upload_image":
return PlayImageSerializer
return PlaySerializer
@action(
methods=["GET", "POST"],
detail=True,
url_path="upload-image",
)
def upload_image(self, request, pk=None):
"""Endpoint for uploading image to specific play"""
play = self.get_object()
serializer = self.get_serializer(play, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@extend_schema(
parameters=[
OpenApiParameter(
"title",
type=str,
description="Filter by title",
required=False,
),
OpenApiParameter(
"genres",
type={"type": "list", "items": {"type": "number"}},
description="Filter by genre",
required=False,
),
OpenApiParameter(
"actors",
type={"type": "list", "items": {"type": "number"}},
description="Filter by actors",
required=False,
)
]
)
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
class PerformanceViewSet(viewsets.ModelViewSet):
queryset = (
Performance.objects.all()
.select_related("play", "theatre_hall")
.annotate(tickets_available=(
F("theatre_hall__rows") * F("theatre_hall__seats_in_row")
- Count("tickets")
))
)
serializer_class = PerformanceSerializer
permission_classes = (AnonReadOnly, )
def get_queryset(self):
"""Retrieve the performances with filters"""
date = self.request.query_params.get("data")
play_id_str = self.request.query_params.get("play")
queryset = self.queryset
if date:
date = datetime.strptime(date, "%Y-%m-%d").date()
queryset = queryset.filter(show_time__date=date)
if play_id_str:
queryset = queryset.filter(play_id=int(play_id_str))
return queryset
def get_serializer_class(self):
if self.action == "list":
return PerformanceListSerializer
if self.action == "retrieve":
return PerformanceDetailSerializer
return PerformanceSerializer
@extend_schema(
parameters=[
OpenApiParameter(
"date",
type=str,
description="Filter by date",
required=False,
),
OpenApiParameter(
"play",
type=int,
description="Filter by genre",
required=False,
),
]
)
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
class ReservationViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericViewSet,
):
queryset = Reservation.objects.prefetch_related(
"tickets__performance__play",
"tickets__performance__theatre_hall"
)
serializer_class = ReservationSerializer
permission_classes = (IsAuthenticated, )
def get_queryset(self):
return self.queryset.filter(user=self.request.user)
def get_serializer_class(self):
if self.action == "list":
return ReservationListSerializer
return ReservationSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
|
import React, { FC, useCallback, useEffect, useState } from 'react';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import CardHeader from '@mui/material/CardHeader';
import { trpc } from 'src/app/_trpc/client';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch';
import Checkbox from '@mui/material/Checkbox';
import { debounce } from 'lodash';
import toast from 'react-hot-toast';
type ListItemType = {
key: string;
label: string;
value: boolean;
};
type ListType = ListItemType & {
subsections?: ListItemType[];
};
export const AccountConfigureClinicalProfileCard: FC = () => {
const { data, isLoading } = trpc.organization.getConfigureClinicalProfile.useQuery(undefined, {
refetchOnWindowFocus: false,
});
const [configureClinicalProfile, setConfigureClinicalProfile] = useState<ListType[] | null>(null);
const mutate = trpc.organization.saveConfigureClinicalProfile.useMutation();
const saveConfigureClinicalProfile = debounce(async (updatedSettings: ListType[]) => {
try {
await mutate.mutateAsync({
quick_notes: updatedSettings.find((item) => item.key === 'quick_notes')?.value || false,
allergies: updatedSettings.find((item) => item.key === 'allergies')?.value || false,
problems: updatedSettings.find((item) => item.key === 'problems')?.value || false,
medications: updatedSettings.find((item) => item.key === 'medications')?.value || false,
vitals: updatedSettings.find((item) => item.key === 'vitals')?.value || false,
vitals_subsections:
updatedSettings
.find((item) => item.key === 'vitals')
?.subsections?.filter((subItem) => subItem.value)
.map((subItem) => subItem.key) || [],
history: updatedSettings.find((item) => item.key === 'history')?.value || false,
history_subsections:
updatedSettings
.find((item) => item.key === 'history')
?.subsections?.filter((subItem) => subItem.value)
.map((subItem) => subItem.key) || [],
});
toast.success('Clinical profile settings saved successfully', {
id: 'clinical-profile-settings-saved-successfully',
});
} catch (e) {
toast.error(e.message);
}
}, 1000); // 500ms delay
const onChange = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
saveConfigureClinicalProfile.cancel(); // Cancel the previous debounce
const { name, checked } = event.target;
if (configureClinicalProfile) {
const updated = configureClinicalProfile.map((item) => {
if (item.key === name) {
return {
...item,
value: checked,
};
}
if (item.subsections) {
return {
...item,
subsections: item.subsections.map((subItem) => {
if (subItem.key === name) {
return {
...subItem,
value: checked,
};
}
return subItem;
}),
};
}
return item;
});
setConfigureClinicalProfile(updated);
saveConfigureClinicalProfile(updated);
}
},
[saveConfigureClinicalProfile, configureClinicalProfile],
);
useEffect(() => {
if (data) {
setConfigureClinicalProfile([
{
key: 'quick_notes',
label: 'Quick Notes',
value: data?.quick_notes || false,
},
{
key: 'vitals',
label: 'Vitals',
value: data?.vitals || false,
subsections: [
{
key: 'height',
label: 'Height',
value: data?.vitals_subsections.includes('height') || false,
},
{
key: 'weight',
label: 'Weight',
value: data?.vitals_subsections.includes('weight') || false,
},
{
key: 'bmi',
label: 'BMI',
value: data?.vitals_subsections.includes('bmi') || false,
},
{
key: 'blood_pressure',
label: 'Blood Pressure',
value: data?.vitals_subsections.includes('blood_pressure') || false,
},
{
key: 'temperature',
label: 'Temperature',
value: data?.vitals_subsections.includes('temperature') || false,
},
{
key: 'heart_rate',
label: 'Heart Rate',
value: data?.vitals_subsections.includes('heart_rate') || false,
},
{
key: 'respiratory_rate',
label: 'Respiratory Rate',
value: data?.vitals_subsections.includes('respiratory_rate') || false,
},
{
key: 'oxygen_saturation',
label: 'Oxygen Saturation',
value: data?.vitals_subsections.includes('oxygen_saturation') || false,
},
],
},
{
key: 'allergies',
label: 'Allergies',
value: data?.allergies || false,
},
{
key: 'problems',
label: 'Problem List',
value: data?.problems || false,
},
{
key: 'history',
label: 'History',
value: data?.history || false,
subsections: [
{
key: 'family_history',
label: 'Family History',
value: data?.history_subsections.includes('family_history') || false,
},
{
key: 'social_history',
label: 'Social History',
value: data?.history_subsections.includes('social_history') || false,
},
{
key: 'past_medical_history',
label: 'Past Medical History',
value: data?.history_subsections.includes('past_medical_history') || false,
},
{
key: 'past_surgical_history',
label: 'Past Surgical History',
value: data?.history_subsections.includes('past_surgical_history') || false,
},
{
key: 'diet',
label: 'Diet',
value: data?.history_subsections.includes('diet') || false,
},
{
key: 'habits',
label: 'Habits',
value: data?.history_subsections.includes('habits') || false,
},
{
key: 'exercises',
label: 'Exercises',
value: data?.history_subsections.includes('exercises') || false,
},
{
key: 'other',
label: 'Other',
value: data?.history_subsections.includes('other') || false,
},
],
},
{
key: 'medications',
label: 'Medications',
value: data?.medications || false,
},
]);
}
}, [data]);
return (
<Card>
<CardHeader title="Configure Clinical Profile" />
<CardContent>
{isLoading && <div>Loading...</div>}
<FormGroup>
{configureClinicalProfile?.map((item) => (
<React.Fragment key={item.key}>
<FormControlLabel
control={
<Switch
name={item.key}
checked={item.value}
onChange={onChange}
/>
}
label={item.label}
/>
{item.subsections && (
<FormGroup sx={{ marginLeft: 4 }}>
{item.subsections.map((subItem) => (
<FormControlLabel
key={subItem.key}
control={
<Checkbox
disabled={!item.value}
name={subItem.key}
checked={subItem.value}
onChange={onChange}
/>
}
label={subItem.label}
/>
))}
</FormGroup>
)}
</React.Fragment>
))}
</FormGroup>
</CardContent>
</Card>
);
};
|
package com.shileiyu.baseapp.ui.glide;
import android.content.Context;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import java.io.InputStream;
import okhttp3.OkHttpClient;
/**
* @author shilei.yu
* @since on 2018/3/28.
*/
public class OkHttpGlideUrlLoader implements ModelLoader<GlideUrl, InputStream> {
private OkHttpClient mClient;
public OkHttpGlideUrlLoader(OkHttpClient client) {
mClient = client;
}
@Override
public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
return new OkHttpFetcher(mClient, model);
}
public static final class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
private OkHttpClient client;
public Factory(OkHttpClient client) {
this.client = client;
}
public Factory() {
client = new OkHttpClient();
}
@Override
public ModelLoader<GlideUrl, InputStream> build(Context context, GenericLoaderFactory factories) {
return new OkHttpGlideUrlLoader(client);
}
@Override
public void teardown() {
}
}
}
|
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
}
if number % 3 == 0 {
println!("number is divisible by 3");
}
if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
return_loop();
multi_loop();
loop_while();
while_array();
for_loop();
for_range();
// loop_it();
}
/* fn loop_it() {
loop {
println!("again!");
}
} */
fn return_loop() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}
fn multi_loop() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}
fn loop_while() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}
fn while_array() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
fn for_loop() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}
fn for_range() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}
|
#include "3-calc.h"
/**
* main - Perform simple operation between two numbers.
*
* @argc: Argument count.
* @argv: Argument vecteur.
*
* Return: 0 Success.
*/
int main(int argc, char *argv[])
{
int (*operation)(int, int);
if (argc != 4)
{
printf("Error\n");
exit(98);
}
operation = get_op_func(argv[2]);
if (operation == 0)
{
printf("Error\n");
exit(99);
}
printf("%d\n", operation(atoi(argv[1]), atoi(argv[3])));
return (0);
}
|
import urllib.parse
import hashlib
import hmac
import base64
import requests
import time
import json
import os
api_url = 'https://api.kraken.com'
api_key = os.environ.get('KRAKEN_API_KEY')
api_sec = os.environ.get('KRAKEN_API_SEC')
def make_nonce():
return { "nonce": str(int(time.time()*1000)) }
def get_kraken_signature(urlpath, data, secret):
postdata = urllib.parse.urlencode(data)
encoded = (str(data['nonce']) + postdata).encode()
message = urlpath.encode() + hashlib.sha256(encoded).digest()
mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
sigdigest = base64.b64encode(mac.digest())
return sigdigest.decode()
# Attaches auth headers and returns results of a POST request
def kraken_request(uri_path, data):
headers = {}
headers['API-Key'] = api_key
headers['API-Sign'] = get_kraken_signature(uri_path, data, api_sec)
req = requests.post((api_url + uri_path), headers=headers, data=data)
return req
def public_get(arg):
resp = requests.get(api_url+'/0/public/'+arg)
if resp.status_code != 200:
raise requests.ApiError('StatusCode: {}'.format(resp.status_code))
else:
return resp
def public_get_with_pair(arg, pair):
resp = requests.get(api_url+'/0/public/'+arg+'?pair='+pair)
if resp.status_code != 200:
raise requests.ApiError('StatusCode: {}'.format(resp.status_code))
else:
return resp
def private_post(arg, data):
resp = kraken_request("/0/private/"+arg, data)
if resp.status_code != 200:
raise requests.ApiError('StatusCode: {}'.format(resp.status_code))
else:
return resp
def get_asset_pairs(pairs):
return public_get("AssetPairs?pair="+pairs)
def add_market_order(pair, type, qty):
return private_post(
'AddOrder',
dict (
make_nonce(),
**{
"ordertype": "market",
"type": type,
"volume": qty,
"pair": pair
}
)
)
def list_open_orders():
return private_post('OpenOrders', make_nonce())
def list_closed_orders():
return private_post('ClosedOrders', make_nonce())
def query_orders(orders):
return private_post(
'QueryOrders',
dict (
make_nonce(),
**{
"txid": orders,
"trades": "true"
}
)
)
def pp(dictionary):
print(json.dumps(dictionary.json(), indent=4))
def __main__():
print("Kraken trade api")
#pp(public_get_with_pair("Depth", "XRPUSD"))
#pp(public_get("Time"))
#pp(public_get_with_pair("Ticker", "XBTUSD"))
#pp(private_post('Balance', make_nonce()))
#pp(add_market_order("XRPUSD", "buy", 10))
#pp(get_asset_pairs("SOLOUSD"))
#pp(add_market_order("XRPUSD", "sell", 10))
#pp(list_open_orders())
#pp(list_closed_orders())
pp(query_orders("OWRSNA-LSZ7T-NIVGN5"))
# pretty print dictionary
#pp(query_orders("OWRSNA-LSZ7T-NIVGN5"))
__main__()
|
import './Team.scss'
import allan from '../../assets/Headshots/allan.jpg'
import ammar from '../../assets/Headshots/ammarpic.jpg'
import bella from '../../assets/Headshots/bellakim.jpeg'
import damian from '../../assets/Headshots/damian.png'
import daniel from '../../assets/Headshots/danielzhang.jpg'
import ellie from '../../assets/Headshots/elliekim.jpeg'
import hooman from '../../assets/Headshots/Hooman.jpg'
import jeffrey from '../../assets/Headshots/jeffrey.jpg'
import jim from '../../assets/Headshots/jimwang.jpg'
import khurram from '../../assets/Headshots/khurram.png'
import ali from '../../assets/Headshots/Ali.jpg'
import lifeng from '../../assets/Headshots/Lifeng.jpg'
import shamir from '../../assets/Headshots/shamir.png'
import leo from '../../assets/Headshots/leo.jpeg'
import { LazyLoadImage } from "react-lazy-load-image-component";
import 'react-lazy-load-image-component/src/effects/blur.css';
const people = [
{
name: 'Ali Elnagmi',
picture: ali,
link: 'https://www.linkedin.com/in/ali-elnagmi/',
role: 'Co-Lead'
},
{
name: "Khurram Shaikh",
picture: khurram,
link: 'https://www.linkedin.com/in/khurramshaikh/',
role: 'Co-Lead'
},
{
name: "Jeffrey Zang",
picture: jeffrey,
link: 'https://www.linkedin.com/in/jeffreyzang2007',
role: 'Co-Lead'
},
{
name: "Hooman Reza Nezhad",
picture: hooman,
link: 'https://www.linkedin.com/in/hooman-nezhad/',
role: 'Finance Lead'
},
{
name: 'Shamir Khan',
picture: shamir,
link: 'https://www.linkedin.com/in/shamir-khan-40698123b/',
role: 'Finance'
},
{
name: 'Ellie Kim',
picture: ellie,
link: 'https://www.linkedin.com/in/ellie-k-b072b4252/',
role: 'Finance'
},
{
name: 'Leo Peng',
picture: leo,
link: 'https://www.linkedin.com/in/leo-peng-272683238/',
role: 'Finance'
},
{
name: 'Ammar Ahmad',
picture: ammar,
link: 'https://www.linkedin.com/in/ammar-ahmad-784470255/',
role: 'Logistics'
},
{
name: 'Allan George',
picture: allan,
link: 'https://www.linkedin.com/in/allan-george-003891239/',
role: 'Logistics'
},
{
name: "Damian Nikolic",
picture: damian,
link: 'https://www.linkedin.com/in/damian-nikolic-638813250/',
role: 'Logistics'
},
{
name: 'Daniel Zhang',
picture: daniel,
link: 'https://www.linkedin.com/in/daniel-zhang-0770a0249/',
role: 'Logistics'
},
{
name: 'Bella Kim',
picture: bella,
link: 'https://www.linkedin.com/in/gayeunbella/',
role: 'Marketing'
},
{
name: 'Jim Wang',
picture: jim,
link: 'https://www.linkedin.com/in/jim-wang-263877212/',
role: 'Marketing'
},
{
name: "Li Feng Yin",
picture: lifeng,
link: 'https://www.linkedin.com/in/lifeng-yin/',
role: 'Tech'
}
]
const Team = () => {
return (
<div id='team'>
<h3 className='text-center'>Our Team</h3>
<p className='text-center'>The people working to make RythmHacks a reality</p>
<div className='team-people'>
{people.map((person) => {
return (
<div className='person'>
<LazyLoadImage src={person.picture} className='person picture'
alt='headshot' onClick={() => window.open(person.link)} effect='blur'></LazyLoadImage>
<p className='person name'>{person.name}</p>
<p>{person.role}</p>
</div>
)
})}
</div>
</div>
)
}
export default Team
|
<template>
<label>選択済みのタグ</label>
<template v-for="id of checkedTags" :key="id">
<input type="hidden" name="tags[]" :value="id">
<span class="selectTag">{{ tagName(id) }}<i class="fas fa-times" @click="removeTag(id)"></i></span>
</template>
<label>タグ一覧</label>
<div class="row">
<template v-for="tag of tags" :key="tag.id">
<div class="col m2">
<label class="checkTag" :id="'label' + tag.id">
<input type="checkbox" v-model="checkedTags" :value="tag.id" @change="updateTagCount">
<div class="tagName" v-text="tag.name.replaceAll(/<wbr>/g, '')"></div>
<img class="tagLogo" :src="tag.logo">
</label>
</div>
</template>
</div>
</template>
<script>
var tags = JSON.parse(document.getElementById("tagsJSON").text);
if (document.getElementById("checkedTagsJSON")) {
var checkedTags = JSON.parse(document.getElementById("checkedTagsJSON").text);
} else {
var checkedTags = [];
}
export default {
data() {
return {
tags: tags,
checkedTags: checkedTags,
};
},
emits: ["tomixy_updatetagcount"],
mounted() {
this.updateTagCount();
},
methods: {
tagName(id) {
for (var tag of this.tags) {
if (tag.id == id) {
return tag.name;
}
}
},
updateTagCount() {
this.$emit('tomixy_updatetagcount', this.checkedTags.length);
},
removeTag(id) {
this.checkedTags.splice(this.checkedTags.indexOf(id), 1);
document.getElementById('label' + id).classList.remove('checkedTag');
this.updateTagCount();
}
}
}
</script>
|
/*
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};
|
import React, { useState, useEffect } from 'react';
import {
Typography,
Grid,
Box,
Card,
createTheme,
ThemeProvider,
Button,
CardActionArea,
} from '@mui/material';
import FlashQuizCard from './FlashQuizCard';
function FlashQuiz({ quizCards, setFlashQuizMode }) {
const [quizArray, setQuizArray] = useState([]);
const [selection, setSelection] = useState();
const [score, setScore] = useState(0);
useEffect(() => {
mixUp();
}, []);
const select = (id, content) => {
if (!selection) {
setSelection({id: id, content: content});
modifyStatus(id, 2);
} else {
if (selection.id * id > 0) {
setSelection({ id: id, content: content});
modifyStatus(selection.id, 1);
modifyStatus(id, 2);
} else {
let front = selection;
let back = {id: id, content: content};
if (selection.id > 0) {
front = {id: id, content: content};
back = selection;
}
const result = quizCards.filter((card) => {
return (card.front === front.content && card.back === back.content);
})
if (result.length === 0) {
modifyStatus(id, 1);
modifyStatus(selection.id, 1);
} else {
modifyStatus(id, 3);
modifyStatus(selection.id, 3);
const newScore = score + 1;
if (newScore === 6) {
setFlashQuizMode(false);
}
setScore(newScore);
}
setSelection(null);
}
}
};
const modifyStatus = (id, status) => {
const result = quizArray.map((word) => {
if (word.id === id) {
word.status = status;
}
return word;
})
setQuizArray(result);
};
const mixUp = () => {
console.log('called')
let refArray = [];
for (let i = 0; i < quizCards.length; i++) {
refArray.push(i);
};
let result = [];
for (let i = 0; i < quizCards.length; i++) {
const randomNumber = Math.floor(Math.random() * refArray.length);
const backIndex = refArray.splice(randomNumber, 1);
// Create left array
const left = { content: quizCards[i].front, id: (i+1)*-1, status: 1 }
result.push(left);
// Create right array
const right = { content: quizCards[backIndex].back, id: i+1, status: 1 }
result.push(right);
};
setQuizArray(result);
};
if (quizArray) return (
<Grid item display="flex" justifyContent="center" alignItems="center" xs={12}>
<Box margin={2}>
<Grid container sx={{ maxWidth: 900 }}>
{ quizArray.map((word) => (
<>
<Grid item display="flex" justifyContent="center" alignItems="center" xs={6}>
<FlashQuizCard word={word} select={select} />
</Grid>
</>
))}
</Grid>
</Box>
</Grid>
)
}
export default FlashQuiz;
|
import {Button, Form, Input, Select, Space} from 'antd';
import {API_URL} from "@/services/HttpService";
import StoryService from "@/pages/api/Story";
import {useRouter} from "next/router";
import {MinusCircleOutlined, PlusOutlined} from "@ant-design/icons";
import React from 'react';
const StoryForm = ({room, story}) => {
const router = useRouter();
const formRef = React.useRef(null);
formRef.current?.setFieldsValue({
name: story.name,
description: story.description,
room: room.id,
id: story.id,
});
const onFinish = async (values) => {
if (values.stories !== undefined) {
const firstStory = {name:values.name, description:values.description, room:values.room, id:values.id};
values.stories.splice(0, 0, firstStory);
} else {
values.stories = [{name:values.name, description:values.description, room:values.room, id:values.id}];
}
for (const story1 of values.stories) {
if(story1.id !== undefined) {
await StoryService.update(story1);
} else {
await StoryService.add(story1);
}
}
await router.push('/rooms/'+room.id);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const handleChange = (value) => {
console.log(`selected ${value}`);
};
return (
<Form
ref={formRef}
name="story"
labelCol={{span: 8,}}
wrapperCol={{span: 16,}}
style={{maxWidth: 600,}}
initialValues={{remember: true,}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
>
<Space
align="baseline"
>
<Space.Compact direction="vertical">
<Form.Item label="Nom de l'US"
name='name'
rules={[
{
required: true,
message: "Ajouter un nom à l'US.",
},
]}
initialValue={story.name}
>
<Input placeholder="Nom de l'US"/>
</Form.Item>
<Form.Item label="Description"
name='description'
initialValue={story.description}
>
<Input.TextArea placeholder="Description"/>
</Form.Item>
<Form.Item
name='room'
initialValue={room.id} hidden
>
<Input/>
</Form.Item>
<Form.Item
name='id'
initialValue={story.id} hidden
>
<Input/>
</Form.Item>
</Space.Compact>
</Space>
{story.id === undefined ? (
<Form.List name="stories">
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, ...restField }) => (
<Space
key={key}
align="baseline"
>
<Space.Compact direction="vertical">
<Form.Item label="Nom de l'US"
{...restField}
name={[name, 'name']}
rules={[
{
required: true,
message: "Ajouter un nom à l'US.",
},
]}
initialValue=""
>
<Input placeholder="Nom de l'US"/>
</Form.Item>
<Form.Item label="Description"
{...restField}
name={[name, 'description']}
>
<Input.TextArea placeholder="Description"/>
</Form.Item>
<Form.Item
{...restField}
name={[name, 'room']}
initialValue={room.id} hidden
>
<Input/>
</Form.Item>
<Form.Item
{...restField}
name={[name, 'id']} hidden
>
<Input/>
</Form.Item>
</Space.Compact>
<MinusCircleOutlined onClick={() => remove(name)} />
</Space>
))}
{story.id === undefined ? (
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}></Button>
</Form.Item>
) : null}
</>
)}
</Form.List>
) : null}
</Form>
);
}
export async function getStaticProps(context) {
const room = {
id: "",
name: "",
description: "",
points: "",
uuid: "",
connectedUsers: "[]",
suite: "",
team: "",
user: "",
};
const story = {
name: "",
description: "",
room: "",
id: "",
};
return {
props: {
room,
story,
},
}
}
export default StoryForm;
|
# 코드 리뷰 테스트 매니저
## Creator
### 설명
creator는 여러 개의 코드 리뷰 테스트용 리포지토리를 자동으로 생성하기 위한 스크립트입니다. \
아래 명령어는 code-review-test-1부터 code-review-test-100까지의 리포지토리와 PR을 생성합니다.
```bash
code-review-test $ ./code-review-test-manager/creator 1 100
```
생성된 리포지토리 하나는 한 명의 지원자에게 할당됩니다. 지원자는 리포지토리에 있는 하나의 PR을 리뷰하게 됩니다.
### Requirements
- Git
- [Github CLI](https://cli.github.com/)
### 사용 방법
1. 로컬 환경에 코드 리뷰 테스트용 디렉터리를 만든다.
```bash
$ mkdir code-review-test
$ cd code-review-test
```
2. 이미 만들어둔 코드 리뷰 테스트 프로젝트 리포지토리가 있다면 클론하고, 없다면 새로 만든다.
- 클론
- PR을 위한 브랜치까지 Pull 받아야 한다.
```bash
code-review-test $ git@github.com:$ORG_NAME/original-code-review-test.git
code-review-test $ git@github.com:33577/code-review-test-manager.git
code-review-test $ cd original-code-review-test
code-review-test/original-code-review-test $ git pull origin add-reservation-service:add-reservation-service
code-review-test/original-code-review-test $ cd ..
```
- 본 단계를 수행한 이후, 아래와 같은 디렉터리 구조여야 한다.
```
- code-review-test
- original-code-review-test
- code-review-test-manager # This Repository
```
3. gh (github cli)를 설치하고 로그인한다.
```bash
code-review-test $ brew install gh
code-review-test $ gh auth login
```
4. creator의 ORG_NAME을 설정한다.
5. creator를 실행한다.
- 아래 명령어는 code-review-test-1부터 code-review-test-100까지의 리포지토리와 PR을 생성한다.
```bash
code-review-test $ ./code-review-test-manager/creator 1 100
```
6. 생성된 리포지토리에 지원자를 Collaborator로 초대한다.
- [[Github Docs] 조직의 리포지토리에 외부 협력자 추가
](https://docs.github.com/ko/enterprise-cloud@latest/organizations/managing-user-access-to-your-organizations-repositories/adding-outside-collaborators-to-repositories-in-your-organization)
|
#include <iostream>
#define DEFAULT_SIZE 10
using std::cout;
template <typename T>
class stack
{
private:
int top, max_size;
T* arr;
public:
stack();
stack(int);
void push(T);
T pop();
T peek();
bool empty() { return (top < 0) ? true : false; }
void print();
};
template <typename T>
stack<T>::stack()
{
max_size = DEFAULT_SIZE;
arr = new T[max_size];
top = -1;
}
template <typename T>
stack<T>::stack(int size)
{
max_size = DEFAULT_SIZE;
arr = new T[max_size];
top = -1;
}
template <typename T>
void stack<T>::push(T item)
{
if (top == max_size - 1)
{
T *new_arr = new T[max_size * 2];
for (int i = 0; i <= top; i++)
new_arr[i] = arr[i];
delete arr;
arr = new_arr;
max_size *= 2;
}
arr[++top] = item;
}
template <typename T>
T stack<T>::pop()
{
return arr[top--];
}
template <typename T>
void stack<T>::print()
{
cout << "[ ";
for (int i = 0; i <= top; i++)
cout << arr[i] << " ";
cout << "]\n";
}
template <typename T>
T stack<T>::peek()
{
return arr[top];
}
|
import React, { useState } from 'react';
import { bool, func, object, string, button } from 'prop-types';
import classNames from 'classnames';
import Button from 'components/shared-ui/button';
import { CustomCurrentRefinements, CustomRangeSlider, CustomRefinementList } from 'components/shared-ui/AlgoliaCustomWidgets';
/**
* Mobile Filter Menu
* @params {{isActive?: boolean, close: function, facetMenu: object}} param0
* @returns {React.ReactElement}
*/
export const MobileFilterMenu = ( {
isActive = false,
close,
facetMenu,
showFeatureFilter,
transformFeatureFilterItems,
currencySymbol,
filterOperator
} ) => {
const [showFacetContainer, setShowFacetContainer] = useState( null );
const [showApplyBtn, setShowApplyBtn] = useState( false );
const selectFilter = ( facet ) => {
return ( facet !== showFacetContainer ? setShowFacetContainer( facet ) : setShowFacetContainer( null ) );
};
function handleRefinements( items ) {
if ( items.length > 0 && !showApplyBtn ) setShowApplyBtn( true );
if ( items.length === 0 && showApplyBtn ) setShowApplyBtn( false );
}
function handleSelectFilterWrap( filter ) {
return function () {
selectFilter( filter );
};
}
return (
<div className={ classNames( 'mobile-filter-menu', { hidden: !isActive } ) }>
<div className='mobile-filter-menu__header'>
<h3 className='mobile-filter-menu__title'>Filter</h3>
<button onClick={ close } className='mobile-filter-menu__cancel'></button>
</div>
<ul className='mobile-filter-menu__list'>
<li className={ classNames( 'mobile-filter-menu__item', { hidden: !showFeatureFilter } ) }>
<div className='mobile-filter-menu__item-text' onClick={ handleSelectFilterWrap( facetMenu.FEATURES ) } onKeyUp={ handleSelectFilterWrap( facetMenu.FEATURES ) } role={ button } tabIndex={ 0 }>
Features
<span className={ classNames( 'mobile-filter-menu__item-icon', { 'mobile-filter-menu__item-icon-active': showFacetContainer === facetMenu.FEATURES } ) }></span>
</div>
<div className={ classNames( 'feature-container', { hidden: showFacetContainer !== facetMenu.FEATURES } ) }>
<CustomRefinementList
attribute={ facetMenu.FEATURES } className={ classNames( 'facet-features', { hidden: showFacetContainer !== facetMenu.FEATURES } ) }
transformItems={ transformFeatureFilterItems }
operator={ filterOperator }
/>
</div>
</li>
<li className='mobile-filter-menu__item'>
<div className='mobile-filter-menu__item-text' onClick={ handleSelectFilterWrap( facetMenu.PRICE ) } onKeyUp={ handleSelectFilterWrap( facetMenu.PRICE ) } role={ button } tabIndex={ 0 }>
Price Range
<span className={ classNames( 'mobile-filter-menu__item-icon', { 'mobile-filter-menu__item-icon-active': showFacetContainer === facetMenu.PRICE } ) }></span>
</div>
<div className={ classNames( 'facet-container', { hidden: showFacetContainer !== facetMenu.PRICE } ) }>
<CustomRangeSlider
attribute={ facetMenu.PRICE }
className={ classNames( 'facet-price', { hidden: showFacetContainer !== facetMenu.PRICE } ) }
currencySymbol={ currencySymbol }
/>
</div>
</li>
</ul>
<div className='mobile-filter-fixed-buttons'>
{ showApplyBtn && (
<div className='mobile-filter-select__actions'>
<Button
colorScheme='green'
size='large'
onClick={ close }
className='mobile-filter-select__apply-btn'
>
Apply
</Button>
</div>
) }
<div className='mobile-filter-clear__actions'>
<CustomCurrentRefinements
translations={{ reset: 'Clear Filters' }}
handleItems={ handleRefinements }
/>
</div>
</div>
</div>
);
};
MobileFilterMenu.defaultProps = {
isActive: false
};
MobileFilterMenu.propTypes = {
isActive: bool,
close: func,
facetMenu: object,
showFeatureFilter: bool,
transformFeatureFilterItems: func,
currencySymbol: string,
filterOperator: string
};
|
#ifndef DISCOREQUEST_H
#define DISCOREQUEST_H
#include <QObject>
#include <QString>
#include <QList>
#include <QDomDocument>
#include <xmpp_task.h>
#include <xmpp_jid.h>
#define XMLNS_DISCO_INFO ("http://jabber.org/protocol/disco#info")
class FeatureList;
class FeatureListManager;
/*! \brief Class to initiate disco#info request */
class DiscoRequest : public XMPP::Task
{
Q_OBJECT
public:
/*! \brief Construct disco#info request to create new entry in manager. */
DiscoRequest(XMPP::Task *parent, FeatureListManager *manager=NULL);
/*! \brief Construct request to update existing features. */
DiscoRequest(XMPP::Task *parent, FeatureList *features);
void get(const QString &jid, const QString &node);
virtual bool take(const QDomElement &element);
void setFeatureManager(FeatureListManager *manager);
QString node()
{ return m_node; }
signals:
void featuresUpdated();
protected slots:
void updateFeatureManager();
protected:
virtual void onGo();
virtual void onDisconnect();
private:
QDomDocument m_document;
QString m_jid;
QString m_node;
FeatureListManager *m_flm;
FeatureList *m_features;
bool m_delete_features;
};
/*! \brief Class for requesting all features of one JID.
It sends as many disco#request is needed for extensions.
*/
class FeaturesUpdateRequest : public QObject
{
Q_OBJECT
typedef QList<XMPP::Jid> JidList;
public:
FeaturesUpdateRequest(XMPP::Client *client, FeatureList *features, const QString &Jid);
void setCapsParams(const QString &node, const QString &ver, const QString &hash, const QString &ext);
void go();
FeatureList * features()
{ return m_features; }
QString jid()
{ return m_jid.full(); }
DiscoRequest * DiscoNodeRequest(const QString &subnode);
void addJid(const XMPP::Jid &jid);
public slots:
void oneRequestFinished();
signals:
void finished(FeaturesUpdateRequest *ur);
private:
XMPP::Client *m_client;
FeatureList *m_features;
XMPP::Jid m_jid;
int m_requestspending;
int m_errorcode;
JidList m_jids;
};
#endif
|
/*
* @Author: Ahmed Badra
* @title: IOT application for remote vital signals monitoring
* @mcu: ESP8266
*/
#include "DHT.h"
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
/* DHT's connection options */
#define DHTPIN 0 // what digital pin the DHT11 is conected to
#define DHTTYPE DHT11 // setting the type as DHT11
DHT dht(DHTPIN, DHTTYPE);
/* server link */
const char *server_url = "http://mighty-headland-68010.herokuapp.com/";// Nodejs application endpoint
/***************************** PROTOTYPES DECLARATIONS ********************************/
void sendPOSTRequest(const char* server_url, const char* route, String urlencodedParams);
void sendGETRequest(const char* server_url, const char* route);
/***************************** objects used in the applications ***********************/
WiFiClient client;
HTTPClient http;
/*
* @brief: function to be executed once at the beginning of the program
* @description: function that handles these tasks
* 01. setup the serial Monitor and the DHT sensor connection then wait 3 seconds
* 02. get a list of the available active connections, print them on the serial monitor
* 03. input the SSID name of the Network you want to connect to
* 04. input the SSID Password of the Network you want to connect to
* 05. use the inputs (name, password) to connect to the Network
* 06. loop over the connection state, wait 0.5 second for each check on the state
*/
void setup() {
/* setup the serial Monitor and the DHT sensor connection then wait 3 seconds */
Serial.begin(9600);
dht.begin();
delay(3000);
/* get a list of the available active connections, print them on the serial monitor */
uint8_t n = WiFi.scanNetworks();
for(uint8_t i = 0; i < n; i++){
Serial.print(i);
Serial.print(". ");
Serial.println(WiFi.SSID(i));
}
/* input the SSID name of the Network you want to connect to */
Serial.print("enter the SSID name to connect with: ");
while (Serial.available() == 0){ /* Wait for user input */ }
String ssid_name = Serial.readString();
/* remove the \n in the end of the input */
ssid_name[ssid_name.length() -1] = '\0';
Serial.println();
/* input the SSID Password of the Network you want to connect to */
Serial.println("enter the password: ");
while (Serial.available() == 0){ /* Wait for user input */ }
String password = Serial.readString();
/* remove \n in the end of the input */
password[password.length() -1] = '\0';
/* use the inputs (name, password) to connect to the Network */
Serial.print(ssid_name + ", " + password);
WiFi.begin(ssid_name, password);
/* poll over the connection successfully state of the WiFi module */
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
delay(1000);
}
/*
* @brief: function for periodic execution of the program
* @description: function that handles these tasks periodically
* 01. read the temperature and humedity
* 02. print them on the serial monitor
* 03. send them to the server
* 04. wait 0.5 second
* 05. back to step 01
*/
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
Serial.print("Humidity = ");
Serial.print(h);
Serial.print("% ");
Serial.print("Temperature = ");
Serial.print(t);
Serial.println("C ");
String urlencodedParams = "temp_value=" + String(t, 3) + "&hum_value=" + String(h, 3);
sendPOSTRequest(server_url, "addreadings", urlencodedParams.c_str());
delay(500);
}
/*
* function for sending POST request with some parameters
*/
void sendPOSTRequest(const char* server_url, const char* route, String urlencodedParams)
{
String service_url = String(server_url) + String(route);
http.begin(client, service_url);
http.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
int httpCode = http.POST(urlencodedParams);
if(httpCode > 0){
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = http.getString();
Serial.print("Response: ");Serial.println(payload);
}
}else{
Serial.printf("[HTTP] GET... failed, error: ");
Serial.println(http.errorToString(httpCode).c_str());
}
http.end();
}
/*
* function for sending GET request with some parameters
*/
void sendGETRequest(const char* server_url, const char* route)
{
String service_url = String(server_url) + String(route);
http.begin(client, service_url);
int httpCode = http.GET();
if(httpCode > 0){
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = http.getString();
Serial.print("Response: ");Serial.println(payload);
}
}else{
Serial.printf("[HTTP] GET... failed, error: ");
Serial.println(http.errorToString(httpCode).c_str());
}
http.end();
}
|
package com.liansheng.carworld.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kongzue.dialog.v3.CustomDialog;
import com.liansheng.carworld.R;
import com.liansheng.carworld.activity.OrderDetailsActivity;
import com.liansheng.carworld.activity.logic.OtherLogic;
import com.liansheng.carworld.activity.logic.UserLogic;
import com.liansheng.carworld.adapter.home.ChildOrderAdapter;
import com.liansheng.carworld.bean.TransporterBean;
import com.liansheng.carworld.bean.other.PageBean;
import com.liansheng.carworld.kit.Constant;
import com.liansheng.carworld.net.JsonCallback;
import com.liansheng.carworld.net.NetApi;
import com.liansheng.carworld.net.UrlKit;
import com.liansheng.carworld.utils.ViewUtils;
import java.util.HashMap;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.droidlover.xdroid.tools.utils.ActivityManage;
import cn.droidlover.xdroid.tools.utils.Util;
import cn.droidlover.xrecyclerview.XRecyclerContentLayout;
import cn.droidlover.xrecyclerview.XRecyclerView;
import okhttp3.Call;
public class OrderChildListFrag extends BaseFragment {
@BindView(R.id.contentLayout)
XRecyclerContentLayout contentLayout;
private ChildOrderAdapter orderAdapter;
private String status = "";
Unbinder unbinder;
public static OrderChildListFrag newInstance(String type) {
Bundle args = new Bundle();
args.putString(Constant.KEY_TYPE, type);
OrderChildListFrag fragment = new OrderChildListFrag();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = super.onCreateView(inflater, container, savedInstanceState);
unbinder = ButterKnife.bind(this, rootView);
initAdapter();
status = getArguments().getString(Constant.KEY_TYPE);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && UserLogic.isLogin()) {
getOrder(status, 0);
}
}
@Override
public void onResume() {
super.onResume();
if (getUserVisibleHint() && UserLogic.isLogin()) {
getOrder(status, 0);
}
}
private void initAdapter() {
orderAdapter = new ChildOrderAdapter(null);
contentLayout.getRecyclerView().verticalLayoutManager(context);
contentLayout.getRecyclerView().setAdapter(orderAdapter);
orderAdapter.setOnItemClickListener((adapter, view, position) -> {
TransporterBean item = (TransporterBean) adapter.getItem(position);
Intent bundle = new Intent();
bundle.putExtra("id", item.getId());
ActivityManage.push(OrderDetailsActivity.class, bundle);
});
contentLayout.getSwipeRefreshLayout().setColorSchemeResources(R.color.order, R.color.order2, R.color.end);
contentLayout.emptyView(ViewUtils.getEmptyView(getBaseActivity(), R.mipmap.bg_home_order));
contentLayout.getRecyclerView()
.setOnRefreshAndLoadMoreListener(new XRecyclerView.OnRefreshAndLoadMoreListener() {
@Override
public void onRefresh() {
getOrder(status, 0);
}
@Override
public void onLoadMore(int page) {
getOrder(status, page);
}
});
contentLayout.loadingView(View.inflate(getBaseActivity(), R.layout.view_loading, null));
contentLayout.getRecyclerView().useDefLoadMoreView();
// contentLayout.getRecyclerView().addItemDecoration(new DividerItemDecoration(getBaseActivity(), DividerItemDecoration.VERTICAL));
}
private void getOrder(String status, int page) {
HashMap<String, Object> map = new HashMap<>();
map.put("pageIndex", page);
map.put("pageSize", Constant.DEFULT_RESULT);
map.put("privately", true);
map.put("status", status);
map.put("showAccount", true);
NetApi.get(UrlKit.TRANSPORT_ORDER, map, new JsonCallback() {
@Override
public void onSuccess(String response, int id) {
PageBean<TransporterBean> home = new Gson().fromJson(response, new TypeToken<PageBean<TransporterBean>>() {
}.getType());
OtherLogic.updateAdapter(page, orderAdapter, home, contentLayout);
if (home.getItems().size() > 0) {
// getAdapter().clearData();
orderAdapter.addData(home.getItems());
for (int i = 0; i < home.getItems().size(); i++) {
TransporterBean bean = home.getItems().get(i);
if (bean.getStatus().equals("completion") && TextUtils.isEmpty(bean.getAssessType())) {
showAssessdialog(bean.getId());
break;
}
}
}
}
});
}
String assess = "";
public void showAssessdialog(String id) {
CustomDialog.build(getBaseActivity(), R.layout.dialog_assess, new CustomDialog.OnBindView() {
@Override
public void onBind(final CustomDialog dialog, View v) {
Button btnOk = v.findViewById(R.id.btn_ok);
ImageView ivClose = v.findViewById(R.id.iv_close);
ImageView ivGood = v.findViewById(R.id.iv_good);
ImageView ivBad = v.findViewById(R.id.iv_bad);
ivGood.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
assess = "good";
ivBad.setSelected(false);
ivGood.setSelected(true);
}
});
ivBad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
assess = "bad";
ivBad.setSelected(true);
ivGood.setSelected(false);
}
});
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getAccess(assess, id);
dialog.doDismiss();
}
});
ivClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.doDismiss();
}
});
}
})
.setFullScreen(true)
.show();
}
public void getAccess(String type, String id) {
NetApi.postAssess(getBaseActivity().getLoginResult().getToken(), id, type, new JsonCallback() {
@Override
public void onSuccess(String response, int id) {
// XToastUtils.success("感谢评价!");
Util.toast("感谢评价");
}
});
}
@Override
public void initData(Bundle savedInstanceState) {
}
@Override
public int getLayoutId() {
return R.layout.frag_list;
}
}
|
package hr.fer.oprpp1.custom.collections;
/**
* A class that represents a general collection of objects.
* <p>
* It is used as a base class for other collections.
*
* @author Marko Šelendić
* @version 1.0
* @see ArrayIndexedCollection
* @see LinkedListIndexedCollection
*/
public class Collection {
protected Collection() {
}
/**
* Returns true only if the collection contains no objects and false otherwise.
*
* @return true if the collection contains no objects, false otherwise
*/
public boolean isEmpty() {
return this.size() == 0;
}
/**
* Returns the number of currently stored objects in this collection.
*
* @return number of currently stored objects
*/
public int size() {
return 0;
}
/**
* Adds the given object into this collection.
*
* @param value object to be added to the collection
*/
public void add(Object value) {
}
/**
* Returns true only if the collection contains given value as determined by equals method.
*
* @param value value to be checked if it is in the collection
* @return true if the collection contains given value, false otherwise
*/
public boolean contains(Object value) {
return false;
}
/**
* Returns true only if the collection contains given value as determined by equals method and removes one occurrence of it.
*
* @param value value to be removed from the collection
* @return true if the collection contains given value, false otherwise
*/
public boolean remove(Object value) {
return false;
}
/**
* Allocates new array with size equals to the size of this collection,
* fills it with collection content and returns the array.
*
* @return new array filled with objects from this collection
*/
public Object[] toArray() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Calls processor.process(.) for each element of this collection.
*
* @param processor processor whose method process(.) is called for each element of this collection
*/
public void forEach(Processor processor) {
}
/**
* Adds all elements from the given collection to this collection.
* <p>
* The given collection remains unchanged.
*
* @param other collection whose elements are added to this collection
*/
public void addAll(Collection other) {
class LocalProcessor extends Processor {
@Override
public void process(Object value) {
Collection.this.add(value);
}
}
other.forEach(new LocalProcessor());
}
/**
* Removes all elements from this collection.
*/
public void clear() {
}
}
|
import { useRouter } from 'next/router';
import Link, { LinkProps } from 'next/link';
import { ReactElement, cloneElement } from 'react';
interface ActiveLinkProps extends LinkProps {
children: ReactElement;
}
export function ActiveLink({ children, ...props }: ActiveLinkProps) {
const { asPath } = useRouter();
const current = asPath === props.href ? 'page' : 'false';
return (
<Link {...props}>
{cloneElement(children, {
'aria-current': current
})}
</Link>
);
}
|
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
/**
* http exception 받아서 대신 처리해주는 작업.
* 다른 exception들을 추가해보면 좋을것 같다
*/
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
|
import {service} from '@loopback/core';
import {get, param, response} from '@loopback/rest';
import {
CurrencyWithTransaction,
StatisticData,
StatisticService,
UserGrowthData,
} from '../services';
export class StatisticController {
constructor(
@service(StatisticService)
private statisticService: StatisticService,
) {}
@get('/stats/user-growth')
@response(200, {
description: 'User Growth',
})
async getUserGrowth(
@param.query.string('limit') limit = 7,
): Promise<UserGrowthData[]> {
return this.statisticService.userGrowth(limit);
}
@get('/stats/top-currencies')
@response(200, {
description: 'Top Currencies',
})
async getTopCurrency(
@param.query.number('limit') limit = 5,
): Promise<CurrencyWithTransaction[]> {
return this.statisticService.topCurrencies(limit);
}
@get('/stats/average')
@response(200, {
description: 'Averages',
})
async getAverage(): Promise<StatisticData> {
return this.statisticService.average();
}
@get('/stats/median')
@response(200, {
description: 'Medain',
})
async getMedian(): Promise<StatisticData> {
return this.statisticService.median();
}
}
|
import { Dialog, Transition } from '@headlessui/react';
import { XMarkIcon } from '@heroicons/react/24/outline';
import { Fragment } from 'react';
import { Link } from 'react-router-dom';
import logoLight from '~/assets/logo-light.png';
import { INamespace } from '~/types/Namespace';
import Nav from './Nav';
type SidebarProps = {
namespaces: INamespace[];
sidebarOpen: boolean;
setSidebarOpen: (sidebarOpen: boolean) => void;
};
export default function Sidebar(props: SidebarProps) {
const { namespaces, sidebarOpen, setSidebarOpen } = props;
return (
<>
<Transition.Root show={sidebarOpen} as={Fragment}>
<Dialog
as="div"
className="relative z-40 md:hidden"
onClose={setSidebarOpen}
>
<Transition.Child
as={Fragment}
enter="transition-opacity ease-linear duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity ease-linear duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-gray-300 bg-opacity-75" />
</Transition.Child>
<div className="fixed inset-0 z-40 flex">
<Transition.Child
as={Fragment}
enter="transition ease-in-out duration-300 transform"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="transition ease-in-out duration-300 transform"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
<Dialog.Panel className="relative flex w-full max-w-xs flex-1 flex-col bg-violet-300 pb-4 pt-5">
<Transition.Child
as={Fragment}
enter="ease-in-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in-out duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="absolute right-0 top-0 -mr-12 pt-2">
<button
type="button"
className="ml-1 flex h-10 w-10 items-center justify-center rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"
onClick={() => setSidebarOpen(false)}
>
<span className="sr-only">Close sidebar</span>
<XMarkIcon
className="h-6 w-6 text-white"
aria-hidden="true"
/>
</button>
</div>
</Transition.Child>
<div className="mt-2 flex flex-shrink-0 items-center px-4">
<img
src={logoLight}
alt="logo"
width={549}
height={191}
className="h-10 w-auto"
/>
</div>
<div className="mt-5 h-0 flex-1 overflow-y-auto">
<Nav
sidebarOpen={sidebarOpen}
setSidebarOpen={setSidebarOpen}
namespaces={namespaces}
/>
</div>
</Dialog.Panel>
</Transition.Child>
<div className="w-14 flex-shrink-0" aria-hidden="true">
{/* Dummy element to force sidebar to shrink to fit close icon */}
</div>
</div>
</Dialog>
</Transition.Root>
{/* Static sidebar for desktop */}
<div className="hidden md:fixed md:inset-y-0 md:flex md:w-64 md:flex-col">
<div className="flex min-h-0 flex-1 flex-col bg-gray-200">
<div className="relative flex h-16 flex-shrink-0 items-center bg-violet-400 px-4 pt-2">
<Link to="/">
<img
src={logoLight}
alt="logo"
width={549}
height={191}
className="h-10 w-auto"
/>
</Link>
</div>
<div className="flex flex-1 flex-col overflow-y-auto">
<Nav className="py-4" namespaces={namespaces} />
</div>
</div>
</div>
</>
);
}
|
import logging # Import the logging module for logging
from selenium import webdriver # Import Selenium's webdriver module for browser automation
from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException # Import exceptions for error handling
from selenium.webdriver.common.by import By # Import By class for locating elements
from selenium.webdriver.support.ui import WebDriverWait # Import WebDriverWait for explicit waits
from selenium.webdriver.support import expected_conditions as EC # Import expected_conditions for defining expected conditions
from selenium.webdriver.chrome.options import Options # Import Options class to configure Chrome WebDriver
#More accurate result comes from not using Beautiful Soup in this code
class Granular:
def __init__(self):
self.driver = webdriver.Chrome() # Initialize Chrome WebDriver instance
self.driver.implicitly_wait(10) # Set implicit wait time to 10 seconds
self.page_load_timeout = 30 # Set timeout for page loading to 30 seconds
self.keywords = [
"granular consent", "specific consent", "individual consent",
"opt-in preferences", "select cookies", "customise preferences",
"manage cookies", "cookie settings", "cookie preferences",
"cookie options", "privacy settings", "privacy preferences",
"cookie policy", "cookie choices", "customise my choices"
] # Keywords indicating granular consent
def check_granular_consent(self, websites):
"""
Check for granular consent on the provided list of websites.
Parameters:
- websites (list): List of website URLs to check.
Returns:
- None
"""
for website in websites:
print("Checking granular consent for", website)
try:
self.driver.get(website) # Open the website URL
# Wait for the page to be fully loaded
WebDriverWait(self.driver, self.page_load_timeout).until(
EC.presence_of_element_located((By.TAG_NAME, 'body'))
)
# Search for keywords indicating granular consent
granular_consent_found = any(keyword in self.driver.page_source.lower() for keyword in self.keywords)
# Print results based on findings
if granular_consent_found:
print("Granular consent is provided.")
else:
print("Granular consent is not provided or indicated.")
except TimeoutException:
print("Timeout occurred while loading the page.")
except NoSuchElementException:
print("Element not found on the page.")
except WebDriverException as e:
print("WebDriver error:", e)
except Exception as e:
print("Error occurred:", e)
finally:
self.driver.delete_all_cookies() # Clear cookies after each website check
# Example usage:
if __name__ == "__main__":
checker = Granular() # Create an instance of Granular
websites_to_check = [
"https://www.bbc.co.uk/news", "https://www.birminghammail.co.uk/",
"https://www.independent.co.uk/", "https://news.sky.com/uk", "https://www.ebay.co.uk/", "https://www.amazon.co.uk/",
"https://www.shein.co.uk", "https://www.asos.com/", "https://www.facebook.com/login/",
"https://twitter.com/?lang=en", "https://www.instagram.com/",
"https://uk.linkedin.com/"
] # List of websites to check for granular consent
checker.check_granular_consent(websites_to_check)
|
import { FC } from "react";
interface MovieCardProps {
title: string,
body: string
}
const MovieCard: FC<MovieCardProps> = (props) => {
const { title, body } = props
return (
<div className="max-w-sm bg-white mx-auto rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-200 hover:-translate-y-4 duration-200 hover:animation-pulse">
<div className="p-5">
<h5 className="mb-2 text-2xl font-bold tracking-tight text-gray-200 dark:text-white">
{title}
</h5>
<p className="mb-3 font-normal text-gray-700 dark:text-gray-400">
{body.slice(0, 300)}
</p>
</div>
</div>
)
};
export default MovieCard;
|
import Route from '@ember/routing/route';
import classic from 'ember-classic-decorator';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { next } from '@ember/runloop';
import RSVP from 'rsvp';
@classic
export default class OptimizeRoute extends Route {
@service can;
breadcrumbs = [
{
label: 'Recommendations',
args: ['optimize'],
},
];
beforeModel() {
if (this.can.cannot('accept recommendation')) {
this.transitionTo('jobs');
}
}
async model() {
const summaries = await this.store.findAll('recommendation-summary');
const jobs = await RSVP.all(summaries.mapBy('job'));
await RSVP.all(
jobs
.filter(job => job)
.filterBy('isPartial')
.map(j => j.reload())
);
return summaries.sortBy('submitTime').reverse();
}
@action
reachedEnd() {
this.store.unloadAll('recommendation-summary');
next(() => {
this.transitionTo('optimize');
this.refresh();
});
}
}
|
import {
Component,
OnInit,
ChangeDetectionStrategy,
EventEmitter,
Input,
Output,
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SelectOption } from '../search-select/search-select.component';
@Component({
selector: 'app-dismiss-dialog',
templateUrl: './dismiss-dialog.component.html',
styleUrls: ['./dismiss-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DismissDialogComponent implements OnInit {
@Input() description: string;
@Input() selectSuggestions: SelectOption[];
@Input() reassignSelectSuggestions?: SelectOption[];
@Input() reassignLabel = 'Select New Assignee';
@Input() errors?;
@Output() closeEvent = new EventEmitter();
@Output() saveEvent = new EventEmitter<DismissSave>();
dismissForm: FormGroup;
get dismissedElement() {
return this.dismissForm.get('dismissedPerson').value;
}
get dismissalDate() {
return this.dismissForm.get('dismissalDate').value;
}
get reassignedElement() {
return this.dismissForm.get('reassignedElement').value;
}
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.dismissForm = this.fb.group({
dismissedPerson: [true, Validators.required],
dismissalDate: [null, Validators.required],
reassignedElement: [true, Validators.required],
});
}
close() {
this.closeEvent.emit(undefined);
}
save() {
this.saveEvent.emit({
dismissedElement: this.dismissedElement,
dismissalDate: this.dismissalDate,
reassignElement: this.reassignedElement,
});
}
}
export interface DismissSave {
dismissedElement: any;
dismissalDate: any;
reassignElement: any;
}
|
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shop_app/layout/shop_layout.dart';
import 'package:shop_app/modules/login/cubit/cubit.dart';
import 'package:shop_app/modules/signup/cubit/cubit.dart';
import 'package:shop_app/modules/signup/cubit/states.dart';
import 'package:shop_app/shared/components/components.dart';
import 'package:shop_app/shared/constants.dart';
import 'package:shop_app/shared/network/local/cache_helper.dart';
class SignUpScreen extends StatelessWidget {
SignUpScreen({Key? key}) : super(key: key);
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController nameController = TextEditingController();
TextEditingController phoneController = TextEditingController();
var formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: BlocProvider(
create: (BuildContext context) => RegisterCubit(),
child: BlocConsumer<RegisterCubit, RegisterStates>(
listener: (BuildContext context, state) {
if (state is RegisterSuccessesState) {
if (state.loginModel.status) {
print(state.loginModel.message);
print(state.loginModel.data.token);
toast(
text: state.loginModel.message,
state: ToastStates.SUCCESS,
);
CacheHelper.saveData(
key: 'token',
value: state.loginModel.data.token,
).then((value) {
token = state.loginModel.data.token;
navigateAndFinish(
context,
ShopLayout(),
);
});
} else {
toast(
text: state.loginModel.message,
state: ToastStates.ERROR,
);
}
}
},
builder: (BuildContext context, state) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: formKey,
child: Center(
child: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'REGISTER',
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 10.0,
),
Text(
'Register now to browse our all hot offers',
style:
Theme.of(context).textTheme.headline4!.copyWith(
fontSize: 16,
),
),
SizedBox(
height: 30.0,
),
defaultTextField(
keyboardType: TextInputType.emailAddress,
controller: emailController,
label: 'Email',
prefixIcon: Icons.mail_outline,
validator: (value) {
if (value!.isEmpty) {
return 'Please Enter Email Address';
}
if (value.contains('@') != true) {
return 'Please Enter valid Email Address';
}
},
),
SizedBox(
height: 20.0,
),
defaultTextField(
keyboardType: TextInputType.text,
controller: nameController,
label: 'Name',
prefixIcon: Icons.person,
validator: (value) {
if (value!.isEmpty) {
return 'Please Enter Your Name';
}
},
),
SizedBox(
height: 20.0,
),
defaultTextField(
keyboardType: TextInputType.phone,
controller: phoneController,
label: 'Phone',
prefixIcon: Icons.phone,
validator: (value) {
if (value!.isEmpty) {
return 'Please Enter Your phone';
}
},
),
SizedBox(
height: 20.0,
),
defaultTextField(
keyboardType: TextInputType.visiblePassword,
controller: passwordController,
label: 'Password',
prefixIcon: Icons.lock_outline,
isPassword: RegisterCubit.get(context).isPassword,
validator: (value) {
if (value!.isEmpty) {
return 'Please Enter Password';
}
if (value.length < 5) {
return 'Password is too short';
}
},
// onFieldSubmitted: (value) {
// if (formKey.currentState!.validate()) {
// RegisterCubit.get(context).userData(
// email: emailController.text,
// password: passwordController.text,
// name: nameController.text,
// phone: phoneController.text,
// );
// }
// },
suffixIcon: RegisterCubit.get(context).suffixIcon,
suffixPressed: () {
RegisterCubit.get(context)
.changePasswordVisibility();
},
),
SizedBox(
height: 20.0,
),
ConditionalBuilder(
condition: state is! RegisterLodingState,
builder: (context) => defaultButton(
title: 'Rigester',
onPressed: () {
if (formKey.currentState!.validate()) {
RegisterCubit.get(context).userData(
email: emailController.text,
name: nameController.text,
phone: phoneController.text,
password: passwordController.text,
);
}
},
),
fallback: (context) =>
Center(child: CircularProgressIndicator()),
),
],
),
),
),
),
);
},
),
),
);
}
}
|
package exmarkets
import (
"bytes"
"crypto/hmac"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"strconv"
"time"
"github.com/buger/jsonparser"
"github.com/herenow/atomic-gtw/gateway"
"github.com/herenow/atomic-gtw/utils"
)
const (
apiBase = "https://exmarkets.com"
apiGeneralInfo = apiBase + "/api/v1/general/info"
apiBook = apiBase + "/api/trade/v1/market/order-book"
apiWalletBalance = apiBase + "/api/trade/v1/account/balance"
apiCompletedOrders = apiBase + "/api/trade/v1/orders"
apiOpenOrders = apiBase + "/api/trade/v1/orders/open"
apiNewBuyOrder = apiBase + "/api/trade/v1/orders/buy"
apiNewSellOrder = apiBase + "/api/trade/v1/orders/sell"
apiCancelOrder = apiBase + "/api/trade/v1/orders/%s"
)
type API struct {
options gateway.Options
client *utils.HttpClient
}
func NewAPI(options gateway.Options) *API {
client := utils.NewHttpClient()
client.UseProxies(options.Proxies)
return &API{
options: options,
client: client,
}
}
type APIMarket struct {
Active bool `json:"active"`
Slug string `json:"slug"`
PricePrecision int `json:"price_precision"`
BasePrecision int `json:"base_precision"`
MinAmount float64 `json:"min_amount"`
}
type APIGeneralInfo struct {
Markets []APIMarket
}
func (a *API) GeneralInfo() (APIGeneralInfo, error) {
var res APIGeneralInfo
req, err := a.newPublicAPIRequest(http.MethodGet, apiGeneralInfo)
if err != nil {
return res, err
}
err = a.makeHttpRequest(req, &res)
return res, err
}
type APIBook struct {
Bids []APIPrice `json:"bids"`
Asks []APIPrice `json:"asks"`
}
type APIPrice struct {
Price float64 `json:"price,string"`
Amount float64 `json:"amount,string"`
}
func (a *API) Book(market string) (APIBook, error) {
var res APIBook
req, err := a.newPublicAPIRequest(http.MethodGet, apiBook)
if err != nil {
return res, err
}
params := req.URL.Query()
params.Set("market", market)
req.URL.RawQuery = params.Encode()
err = a.makeHttpRequest(req, &res)
return res, err
}
type APIWallet struct {
Wallets []APIBalance `json:"wallets"`
}
type APIBalance struct {
Currency string `json:"currency"`
Total float64 `json:"total,string"`
Available float64 `json:"available,string"`
Reserved float64 `json:"reserved,string"`
}
func (a *API) WalletsBalance() ([]APIBalance, error) {
var res APIWallet
req, err := a.newAPIRequest(http.MethodGet, apiWalletBalance, nil, nil)
if err != nil {
return res.Wallets, err
}
err = a.makeHttpRequest(req, &res)
return res.Wallets, err
}
type APIOrders struct {
Buy []APIOrder `json:"buy"`
Sell []APIOrder `json:"sell"`
}
type APIOrder struct {
ID json.Number `json:"id,Number"`
Type string `json:"type"`
Amount float64 `json:"amount,string"`
CurrentAmount float64 `json:"current_amount,string"`
Price float64 `json:"price,string"`
}
func (a *API) UserOrders(market, state string) (APIOrders, error) {
var uri string
if state == "open" {
uri = apiOpenOrders
} else {
uri = apiCompletedOrders
}
params := &url.Values{}
params.Set("market", market)
params.Set("limit", "100")
var res APIOrders
req, err := a.newAPIRequest(http.MethodGet, uri, params, nil)
if err != nil {
return res, err
}
err = a.makeHttpRequest(req, &res)
return res, err
}
func (a *API) NewOrder(side, market string, price, amount string) (APIOrder, error) {
var uri string
if side == "buy" {
uri = apiNewBuyOrder
} else {
uri = apiNewSellOrder
}
params := make(map[string]interface{})
params["market"] = market
params["type"] = "limit"
params["price"] = price
params["amount"] = amount
var res APIOrder
req, err := a.newAPIRequest(http.MethodPost, uri, nil, params)
if err != nil {
return res, err
}
err = a.makeHttpRequest(req, &res)
return res, err
}
func (a *API) CancelOrder(market, orderID string) (APIOrder, error) {
url := fmt.Sprintf(apiCancelOrder, orderID)
var res APIOrder
req, err := a.newAPIRequest(http.MethodDelete, url, nil, nil)
if err != nil {
return res, err
}
err = a.makeHttpRequest(req, &res)
return res, err
}
func (a *API) newPublicAPIRequest(method, uri string) (*http.Request, error) {
req, err := http.NewRequest(method, uri, nil)
return req, err
}
func (a *API) newAPIRequest(method, uri string, params *url.Values, bodyParams map[string]interface{}) (*http.Request, error) {
timestamp := time.Now().Unix()
expires := timestamp + 5 // Request expires in 5 seconds
nonce := timestamp + rand.Int63()
if method != http.MethodPost {
if params == nil {
params = &url.Values{}
}
params.Set("timestamp", strconv.FormatInt(expires, 10))
params.Set("nonce", strconv.FormatInt(nonce, 10))
}
var body []byte
var bodyReader io.Reader
if bodyParams != nil {
bodyParams["timestamp"] = expires
bodyParams["nonce"] = nonce
data, err := json.Marshal(bodyParams)
if err != nil {
return nil, fmt.Errorf("failed marshal body params, err: %s", err)
}
body = data
bodyReader = bytes.NewReader(body)
}
req, err := http.NewRequest(method, uri, bodyReader)
if err != nil {
return nil, err
}
signData := req.Method + req.URL.Path
// Set params
if params != nil {
req.URL.RawQuery = params.Encode()
signData += "?" + req.URL.RawQuery
}
if body != nil {
signData += string(body)
}
hmac := hmac.New(sha512.New, []byte(a.options.ApiSecret))
hmac.Write([]byte(signData))
signature := hex.EncodeToString(hmac.Sum(nil))
encodedToken := base64.StdEncoding.EncodeToString([]byte(a.options.ApiKey + ":" + signature))
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Authorization", "Basic "+encodedToken)
return req, nil
}
func (a *API) makeHttpRequest(req *http.Request, responseObject interface{}) error {
body, err := a.sendHttpRequest(req)
if err != nil {
return err
}
errVal, dataType, _, _ := jsonparser.Get(body, "error")
if dataType != jsonparser.NotExist {
return fmt.Errorf("api responded with error message: %s\nresponse body: %s", string(errVal), string(body))
}
if responseObject != nil {
err = json.Unmarshal(body, responseObject)
if err != nil {
return fmt.Errorf("failed to unmarshal json, body: %s, unmarshal err: %s", string(body), err)
}
}
return nil
}
func (a *API) sendHttpRequest(req *http.Request) ([]byte, error) {
res, err := a.client.SendRequest(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode == 401 {
return body, fmt.Errorf("Unauthorized request, msg: %s", string(body))
}
return body, nil
}
|
"""Logic to compose FTU from topology, PHS type and network connection information"""
import numpy as np
import sympy
from sympy import Expr, Matrix
import networkx as nx
import json
from collections import OrderedDict
from copy import deepcopy
composerSerializationEnabled = True
try:
import cloudpickle
except:
composerSerializationEnabled = False
from ftuutils import codegenerationutils
from ftuutils import latexgenerationutils
class SymbolicPHS:
"""
Symbolic Port Hamiltonian representation
"""
def __init__(
self,
J: Matrix,
R: Matrix,
B: Matrix,
Bhat: Matrix,
Q: Matrix,
E: Matrix,
C: Matrix,
ham: Expr,
s: Matrix,
u: Matrix,
usplit: Matrix,
vars: set,
parameters: dict,
statevalues: dict,
) -> None:
self.J = J
self.R = R
self.B = B # If Bhat is non-zero then this is Bbar
self.Bhat = Bhat
self.Q = Q
self.E = E
self.C = C
self.hamiltonian = ham
self.states = s
if isinstance(u, sympy.Matrix):
self.u = u
elif isinstance(u, sympy.Symbol):
self.u = Matrix([[u]])
elif isinstance(u, list):
self.u = Matrix([u])
else:
raise (f"Type of input u for creating PHS instance not supported!")
self.usplit = usplit
self.variables = vars
self.parameters = parameters
self.statevalues = statevalues
def getCopy(self, id: int):
"""Get a copy of the PHS instance with the symbol ids suffixed with id
Args:
id (int): Suffix id for PHS instance symbols
Returns:
SymbolicPHS: copy of instance
"""
nvars = dict()
for v in self.variables:
nv = sympy.Symbol(f"{v.name}_{id}")
nvars[v] = nv
variables = set(nvars.values())
parameters = dict()
for k, v in self.parameters:
parameters[k.xreplace(nvars)]["value"] = v["value"].xreplace(nvars)
statevalues = dict()
for k, v in self.statevalues:
statevalues[k.xreplace(nvars)] = v["value"].xreplace(nvars)
J = self.J.xreplace(nvars)
R = self.R.xreplace(nvars)
B = self.B.xreplace(nvars)
Bhat = self.Bhat
if self.Bhat is not None:
Bhat = self.Bhat.xreplace(nvars)
Q = self.Q.xreplace(nvars)
E = self.E.xreplace(nvars)
s = self.states.xreplace(nvars)
u = self.u.xreplace(nvars)
C = self.C
if self.C is not None:
C = self.C.xreplace(nvars)
ham = self.hamiltonian.xreplace(nvars)
return SymbolicPHS(
J,
R,
B,
Bhat,
Q,
E,
C,
ham,
s,
u,
deepcopy(self.usplit),
variables,
parameters,
statevalues,
)
def split(self, iosplit):
"""Split B matrix to suit the interior vs exterior IO elements
The Bcap,Bbar entries are set to zero as the u's need to be weighted zero
The row,column corresponding split(value True) dimensions are set to zero in Bcap (viceversa in Bbar)
Args:
iosplit (list): boolean array of dim u, bbar elements are true
Returns:
list: Bcap and Bbar/Bdash matrices
"""
Bcap = deepcopy(self.B)
Bbar = deepcopy(self.B)
for i, v in enumerate(iosplit):
if v:
Bcap[i, :] *= 0
Bcap[:, i] *= 0
else:
Bbar[i, :] *= 0
Bbar[:, i] *= 0
return [Bcap, Bbar]
@staticmethod
def getMatrix(mjson: dict) -> Matrix:
"""Get Sympy matrix from json description
Args:
mjson (dict): Matrix/Vector described as dictionary
Returns:
Matrix: Sympy Matrix
"""
nrows = mjson["rows"]
ncols = mjson["cols"]
return Matrix(list(map(sympy.parse_expr, mjson["elements"]))).reshape(
nrows, ncols
)
@staticmethod
def getJSONForMatrix(matrix) -> dict:
"""Convert Sympy Matrix to json
Args:
matrix (Sympy.Matrix): Sympy Matrix for conversion
Returns:
dict: Jsonable representation of sympy matrix
"""
rows = matrix.rows
cols = matrix.cols
elements = []
for i in range(rows):
for j in range(cols):
elements.append(sympy.latex(matrix[i, j]))
mjson = dict()
mjson["rows"] = rows
mjson["cols"] = cols
mjson["elements"] = elements
return mjson
@staticmethod
def getVariables(elem: list) -> set:
"""Convert from string to sympy varibales
Args:
elem (list): List of variables/expressions from which symbolic variable names need to be extracted
Raises:
Exception: When a list element cannot be parsed
Returns:
set: Set of variables extracted from the input list
"""
if type(elem) is list:
exps = list(map(sympy.parse_expr, elem))
res = set()
for e in exps:
res = res.union(e.free_symbols)
return res
elif type(elem) is str:
ee = sympy.parse_expr(elem)
return ee.free_symbols
else:
raise Exception(f"Input of Type {type(elem)} not supported by getVariables")
@staticmethod
def savePHSDefinition(phs):
"""Serialize the phs into json format
Args:
phs (SymbolicPHS): Target PHS object to be serialised
Returns:
dict: JSONable dict of the input PHS
"""
states = {"rows": len(phs.states), "cols": "1", "elements": phs.states}
hamexp = sympy.latex(phs.hamiltonian)
hamitonian = sympy.pretty(phs.hamiltonian)
matJ = SymbolicPHS.getJSONForMatrix(phs.J)
matR = SymbolicPHS.getJSONForMatrix(phs.R)
matB = SymbolicPHS.getJSONForMatrix(phs.B)
matBhat = {"rows": 0, "cols": 0, "elements": []}
if phs.Bhat is not None:
matBhat = SymbolicPHS.getJSONForMatrix(phs.Bhat)
matE = SymbolicPHS.getJSONForMatrix(phs.E)
matQ = SymbolicPHS.getJSONForMatrix(phs.Q)
matC = {"rows": 0, "cols": 0, "elements": []}
if phs.C is not None:
matC = SymbolicPHS.getJSONForMatrix(phs.C)
uvec = SymbolicPHS.getJSONForMatrix(phs.u)
usplit = SymbolicPHS.getJSONForMatrix(phs.usplit)
uspx = usplit["elements"]
for ix, y in enumerate(uspx):
if y == "0":
usplit["elements"][ix] = False
else:
usplit["elements"][ix] = True
parameters = dict()
for k, v in phs.parameters.items():
parameters[sympy.pretty(k)] = {
"value": sympy.pretty(v["value"]),
"units": v["units"],
}
statevalues = dict()
for k, v in phs.statevalues.items():
statevalues[sympy.pretty(k)] = {
"value": sympy.pretty(v["value"]),
"units": v["units"],
}
result = dict()
result["stateVector"] = states
result["state_values"] = statevalues
result["Hderivatives"] = {"rows": 0, "cols": 0, "elements": []}
result["hamiltonianLatex"] = hamexp
result["hamiltonian"] = hamitonian.replace("**", "^")
phsm = dict()
phsm["matR"] = matR
phsm["matJ"] = matJ
phsm["matB"] = matB
phsm["matQ"] = matQ
phsm["matE"] = matE
phsm["matBhat"] = matBhat
phsm["matC"] = matC
phsm["u"] = uvec
phsm["u_split"] = usplit
result["portHamiltonianMatrices"] = phsm
result["parameter_values"] = parameters
return result
@staticmethod
def loadPHSDefinition(phs,prefix=""):
"""
Load a PHS definition (json format)
"""
states = phs["stateVector"]
# hamexp = phs["hamiltonianLatex"]
hamexp = phs["hamiltonian"]
pmat = phs["portHamiltonianMatrices"]
matR = pmat["matR"]
matJ = pmat["matJ"]
matB = pmat["matB"]
matQ = pmat["matQ"]
matE = pmat["matE"]
uvec = pmat["u"]
usplit = pmat["u_split"]
if "matBhat" in pmat:
matBhat = pmat["matBhat"]
else:
matBhat = {"cols": 0, "elements": [], "rows": 2}
if "matC" in pmat:
matC = pmat["matC"]
else:
matC = {"cols": 0, "elements": [], "rows": 2}
# Get all variables for renaming
variables = set()
variables = variables.union(
SymbolicPHS.getVariables(states["elements"]))
variables = variables.union(SymbolicPHS.getVariables(hamexp))
variables = variables.union(SymbolicPHS.getVariables(matR["elements"]))
variables = variables.union(SymbolicPHS.getVariables(matJ["elements"]))
variables = variables.union(SymbolicPHS.getVariables(matB["elements"]))
variables = variables.union(SymbolicPHS.getVariables(matQ["elements"]))
variables = variables.union(SymbolicPHS.getVariables(matE["elements"]))
variables = variables.union(SymbolicPHS.getVariables(uvec["elements"]))
variables = variables.union(
SymbolicPHS.getVariables(matBhat["elements"]))
variables = variables.union(SymbolicPHS.getVariables(matC["elements"]))
#Get in the parameter names as well, some of them will be parameters to operators
pset = []
for k in phs["parameter_values"]:
pset.append(sympy.Symbol(k))
variables = variables.union(set(pset))
if prefix=="":
params = dict()
for k, v in phs["parameter_values"].items():
params[sympy.Symbol(k)] = {
"value": sympy.sympify(v["value"]),
"units": v["units"],
}
statevalues = dict()
for k, v in phs["state_values"].items():
statevalues[sympy.Symbol(k)] = {
"value": sympy.sympify(v["value"]),
"units": v["units"],
}
J = SymbolicPHS.getMatrix(matJ)
R = SymbolicPHS.getMatrix(matR)
B = SymbolicPHS.getMatrix(matB)
if J.rows != B.rows:
raise Exception(
"B does not have the same dimensions as the J matrix!!")
Q = SymbolicPHS.getMatrix(matQ)
E = SymbolicPHS.getMatrix(matE)
u = SymbolicPHS.getMatrix(uvec)
# if all elements are integers somethings break
usp = usplit["elements"]
for uix in range(len(usp)):
if usp[uix] is None:
usp[uix] = 0
us = Matrix(list(map(int, usp))).reshape(
int(usplit["rows"]), int(usplit["cols"])
)
Bhat = SymbolicPHS.getMatrix(matBhat)
C = SymbolicPHS.getMatrix(matC)
s = SymbolicPHS.getMatrix(states)
ham = sympy.parse_expr(hamexp)
else:
varsub = dict()
for v in variables:
varsub[v] = sympy.Symbol(f"{prefix}_{v}")
params = dict()
for k, v in phs["parameter_values"].items():
params[sympy.Symbol(f"{prefix}_{k}")] = {
"value": sympy.sympify(v["value"]).xreplace(varsub), #Make sure operators are updated as well
"units": v["units"],
}
statevalues = dict()
for k, v in phs["state_values"].items():
statevalues[sympy.Symbol(f"{prefix}_{k}")] = {
"value": sympy.sympify(v["value"]).xreplace(varsub), #Make sure operators are updated as well
"units": v["units"],
}
J = SymbolicPHS.getMatrix(matJ).xreplace(varsub)
R = SymbolicPHS.getMatrix(matR).xreplace(varsub)
B = SymbolicPHS.getMatrix(matB).xreplace(varsub)
if J.rows != B.rows:
raise Exception(
"B does not have the same dimensions as the J matrix!!")
Q = SymbolicPHS.getMatrix(matQ).xreplace(varsub)
E = SymbolicPHS.getMatrix(matE).xreplace(varsub)
u = SymbolicPHS.getMatrix(uvec).xreplace(varsub)
# if all elements are integers somethings break
usp = usplit["elements"]
for uix in range(len(usp)):
if usp[uix] is None:
usp[uix] = 0
us = Matrix(list(map(int, usp))).reshape(
int(usplit["rows"]), int(usplit["cols"])
)
Bhat = SymbolicPHS.getMatrix(matBhat).xreplace(varsub)
C = SymbolicPHS.getMatrix(matC)
s = SymbolicPHS.getMatrix(states).xreplace(varsub)
ham = sympy.parse_expr(hamexp).xreplace(varsub)
variables = set(varsub.values())
return SymbolicPHS(
J, R, B, Bhat, Q, E, C, ham, s, u, us, variables, params, statevalues
)
def instantiatePHS(self, postfix, substituteParameters=False):
"""Create a PHS with given postfix for its symbols
If substituteParameters is True, then symbols and expressions are evaluated with the cooresponding
numerical values and simplified.
Args:
postfix (string): Postfix for symbols
substituteParameters (bool, optional): Substitute numerical values in experessions and simplify. Defaults to False.
Returns:
SymbolicPHS: Instance with new postfix and substituted expressions if requested.
"""
vsubs = dict()
definedSymbols = []
for v in self.variables:
vsubs[v] = sympy.Symbol(str(v) + "_" + postfix)
definedSymbols.append(sympy.Symbol(str(v) + "_" + postfix))
J = deepcopy(self.J).xreplace(vsubs)
R = deepcopy(self.R).xreplace(vsubs)
B = deepcopy(self.B).xreplace(vsubs)
if self.Bhat is not None:
Bhat = deepcopy(self.Bhat).xreplace(vsubs)
else:
Bhat = sympy.zeros(0, 0)
Q = deepcopy(self.Q).xreplace(vsubs)
E = deepcopy(self.E).xreplace(vsubs)
if self.C is not None:
C = deepcopy(self.C).xreplace(vsubs)
else:
C = sympy.zeros(0, 0)
u = deepcopy(self.u).xreplace(vsubs)
s = deepcopy(self.states).xreplace(vsubs)
parms = dict()
for k, v in self.parameters.items():
nk = k.xreplace(vsubs)
parms[nk] = deepcopy(v)
parms[nk]["value"] = v["value"].xreplace(vsubs)
statevalues = dict()
for k, v in self.statevalues.items():
nk = k.xreplace(vsubs)
statevalues[nk] = deepcopy(v)
statevalues[nk]["value"] = v["value"].xreplace(vsubs)
us = deepcopy(self.usplit)
ham = deepcopy(self.hamiltonian).xreplace(vsubs)
if substituteParameters:
subs = dict()
for (k, v) in parms.items():
if not v["value"].free_symbols: # expression is numeric
subs[k] = v["value"]
J = J.xreplace(subs)
R = R.xreplace(subs)
B = B.xreplace(subs)
Bhat = Bhat.xreplace(subs)
Q = Q.xreplace(subs)
E = E.xreplace(subs)
C = C.xreplace(subs)
ham = ham.xreplace(subs)
return SymbolicPHS(
J, R, B, Bhat, Q, E, C, ham, s, u, us, definedSymbols, parms, statevalues
)
def __str__(self):
""" Convert to string"""
bbars = ""
if self.Bhat.shape[0] > 0:
bbars = f"Bhat Matrix\n {sympy.pretty(self.Bhat)}"
cmats = ""
if self.C.shape[0] > 0:
cmats = f"Bhat Matrix\n {sympy.pretty(self.C)}"
res = f""" Hamiltonian:\n {sympy.pretty(self.hamiltonian)}
State variables:\n {sympy.pretty(self.states)}\n
J Matrix\n {sympy.pretty(self.J)}
R Matrix\n {sympy.pretty(self.R)}
B Matrix\n {sympy.pretty(self.B)}
{bbars}
Q Matrix\n {sympy.pretty(self.Q)}
E Matrix\n {sympy.pretty(self.E)}
{cmats}
U Vector\n {sympy.pretty(self.u)}\n
Free variables : {sympy.pretty(self.variables)}
"""
return res
class Composer:
"""
Logic to compose a composite PHS, given the FTU graph, PHS information etc.
"""
def __init__(self) -> None:
self.nodeIndex = dict()
self.nodeName = dict()
self.nodeData = dict()
self.phsInstances = dict()
self.networkGraphs = dict()
self.dissipativeNets = dict()
self.boundaryinputs = dict()
self.nodeNetworks = dict()
self.networkNodes = dict()
self.networkGraphs = dict()
self.cellType = dict()
self.cellTypePHS = dict()
self.cellTypeUSplit = dict()
self.boundaryInputSelection = []
self.inodeIndexes = []
self.compositeJ: Matrix = None
self.compositeQ: Matrix = None
self.compositeR: Matrix = None
self.compositeE: Matrix = None
self.compositeB: Matrix = None
self.uyConnectionMatrix: Matrix = None
self.uyConnectionMatrixComputed = (
False # Will be set to true if it was computed by compose
)
self.composition = None #Store composition information if used to construct the composer
def setConnectivityGraph(self,graph:nx.Graph):
"""Set the base ftugraph from which the composition was created
Args:
graph (FTUGraph): Graph that stores the connectivity and edge
"""
self.ftugraph = graph
@staticmethod
def getMatrix(mjson: dict) -> Matrix:
"""Get Sympy matrix from json description"""
return SymbolicPHS.getMatrix(mjson)
@staticmethod
def getVariables(elem: list) -> set:
"""Convert from string to sympy varibales"""
return SymbolicPHS.getVariables(elem)
@staticmethod
def _elementwiseDiv(A: Matrix, B: Matrix):
"""Perform elementwise division of sympy given matrices"""
if A.shape[0] == B.shape[0] and A.shape[1] == B.shape[1]:
C = deepcopy(A)
for i in range(A.rows):
for j in range(B.rows):
C[i, j] = sympy.simplify(A[i, j] / B[i, j])
return C
else:
raise ("Matrix dimensions do not match!")
@staticmethod
def save(composition, filename):
"""Save the given composition as a pickle
Args:
composition (Composer): The composer instance to be saved
filename (string): Path of the pickle file
"""
if composerSerializationEnabled:
with open(filename, "wb") as ser:
cloudpickle.dump(composition, ser)
else:
raise (
"Serialization not supported on this platform. Failed to load module cloudpickle!"
)
@staticmethod
def load(filename):
"""Load the composition in a pickle
Args:
filename (string): Path of the pickle file
"""
if composerSerializationEnabled:
with open(filename, "rb") as ser:
composition = cloudpickle.load(ser)
return composition
else:
raise (
"Serialization not supported on this platform. Failed to load module cloudpickle!"
)
def loadPHSDefinition(self, mapid, phs,useprefix):
"""
Load a PHS definition (json format)
The PHS object is assigned the id `mapid` to be used by mapid based composition
"""
if useprefix:
self.phsInstances[mapid] = SymbolicPHS.loadPHSDefinition(phs,mapid)
else:
self.phsInstances[mapid] = SymbolicPHS.loadPHSDefinition(phs)
def loadComposition(self, composition: dict):
"""Load the FTU composition encoded in jsonable dict
Args:
composition (dict): FTU composition description
"""
self.inodeIndexes = []
self.nodeData = dict()
self.phsInstances = dict()
self.cellType = dict()
self.cellTypePHS = dict()
self.boundaryinputs = dict()
self.compositeparameters = dict()
# Load phs data
phsdata = composition["graph"]["phsdata"]
useprefixforPHS = len(phsdata) > 1
for k, v in phsdata.items():
self.loadPHSDefinition(k, v["phs"]["phs"],useprefixforPHS)
# Create a graph
gnodes = composition["graph"]["graph"]["nodes"]
# Edges use node id's which is different from node labels
# node labels may not be contigous, so iterate and find max node
labelmapid = dict()
# Structures to map inputs
nodeNetworks = dict()
networkNodes = (
dict()
) # Will link both src and target nodes,one of which will be on the boundary
maxlabel = 0
labelnodeindex = dict()
for nix, g in enumerate(gnodes):
id = int(f"{g['id']}")
label = int(f'{g["value"]["label"]}')
if maxlabel < label:
maxlabel = label
labelmapid[id] = label
if "phs" in g["value"]:
self.cellTypePHS[label] = g["value"]["phs"]
# Interior or boundary node
if g["value"]["type"] == "in":
self.cellType[label] = 1
self.inodeIndexes.append(label)
else:
self.cellType[label] = 0
labelnodeindex[label] = nix
self.inodeIndexes.sort()
# Load network data to help setup laplacian
dissipativeNets = dict()
networkDataS = composition["graph"]["networkdata"]
networkkeys = []
networkData = dict()
for k in networkDataS.keys():
networkkeys.append(int(k))
networkData[int(k)] = networkDataS[k]
networkkeys.sort()
networkkeys.reverse()
for k, v in networkData.items():
dissipativeNets[k] = False
if type(v) is str:
vj = json.loads(v)
if "isdissipative" in vj:
dissipativeNets[k] = vj["isdissipative"]
else:
if "isdissipative" in v:
dissipativeNets[k] = v["isdissipative"]
gedges = composition["graph"]["graph"]["edges"]
# For each network create a graph
networkGraphs = dict()
for networkNames, v in networkData.items():
networkName = int(f"{networkNames}")
ngraph = nx.DiGraph()
ngraph.add_nodes_from(list(range(maxlabel)))
networkNodes[networkName] = []
for g in gedges:
src = int(f"{g['source']}")
trg = int(f"{g['target']}")
weight = g["value"]["weight"]
for ks, vw in weight.items():
k = int(
f"{ks}"
) # Done this way as json serialisation changes keys to string
if k == networkName:
if src in nodeNetworks:
nodeNetworks[src][networkName] = vw
else:
nodeNetworks[src] = {networkName: vw}
if trg in nodeNetworks:
nodeNetworks[trg][networkName] = vw
else:
nodeNetworks[trg] = {networkName: vw}
networkNodes[networkName].append(src)
networkNodes[networkName].append(trg)
uniquenetworkNodes = set(networkNodes[networkName])
networkNodes[networkName] = list(uniquenetworkNodes)
if networkName in dissipativeNets:
if dissipativeNets[
networkName
]: # If dissipative add edge to compute laplacian
ngraph.add_edge(src, trg, weight=vw)
networkGraphs[networkName] = ngraph
networkBoundaryNodeMap = dict()
for l, v in self.cellType.items():
if v == 0:
nts = list(nodeNetworks[l].keys())
if len(nts) == 1:
networkBoundaryNodeMap[nts[0]] = l
else:
raise (
f"Boundary node {l} has been assigned more than one networks - {nts}!"
)
uVec = []
for k in networkkeys:
net = networkData[k]
if net["type"] == "boundary": # Should use boundary property
nname = k
if "input" in net:
input = net["input"]
phsc = self.phsInstances[input["phsclass"]]
comps = []
cindx = []
dindx = []
for i, v in enumerate(input["components"]):
if v:
# Encode the node from which input will be obtained. Note that laplacian and adjacency matrix will use different numbers than node label
# so map into labelnodeindex
# f"{phsc.u[i]}_{labelnodeindex[networkBoundaryNodeMap[f'{k}']]}" #f"{phsc.u[i]}{-k}" if k < 0 else f"{phsc.u[i]}{k}"
usym = f"{phsc.u[i]}_{k if k>0 else -k}"
uVec.append(Matrix([usym, i]))
comps.append(sympy.Symbol(usym))
cindx.append(i)
dindx.append(dissipativeNets[nname])
for nds in networkNodes[nname]:
if not nds in self.boundaryinputs:
self.boundaryinputs[nds] = [[], [], []]
self.boundaryinputs[nds][0].extend(comps)
self.boundaryinputs[nds][1].extend(cindx)
self.boundaryinputs[nds][2].extend(dindx)
uix = [
self.boundaryinputs[nds][0].index(x)
for x in set(self.boundaryinputs[nds][0])
]
ncmps = [self.boundaryinputs[nds][0][ix] for ix in uix]
ncidx = [self.boundaryinputs[nds][1][ix] for ix in uix]
ndidx = [self.boundaryinputs[nds][2][ix] for ix in uix]
self.boundaryinputs[nds][0] = ncmps
self.boundaryinputs[nds][1] = ncidx
self.boundaryinputs[nds][2] = ndidx
# Load Bcap information
bcapdata = composition["composition"]["Bcap"]
for k, v in bcapdata.items():
nl = int(k)
# Contains, bsplit, bbarcontrib, boundary nodes if any
self.nodeData[nl] = v
self.dissipativeNets = dissipativeNets
self.nodeNetworks = nodeNetworks
self.networkNodes = networkNodes
self.networkGraphs = networkGraphs
self.uVec = (
Matrix(uVec).reshape(len(uVec), 2).T
) # Row 1 are input symbols, row 2 are column indexes into B matrix
self.uyConnectionMatrixComputed = False
self.composition = composition
def getSourceComposition(self):
"""
Return the source composition json that was used to defined the composer
Returns None if json was not used
"""
return self.composition
def compose(self, substituteParameters=True):
"""
Create the composite PHS matrices for compostion description that has been loaded
Requires the phs for the different cell types to be loaded see loadPHSDefinition, loadCellTypePHSMap
Requires the phs interconnection to be loaded see loadCompositionFile
Ideally all interconnection u's and y's to be of the same size, if some phs have more u's,
then select the ones that need to be used in the interconnection see setCellTypeUSplit
"""
# calculate matrix dimensions
jmat = []
qmat = []
emat = []
rmat = []
bcapmat = []
nbcapmat = []
lashmat = []
bdasmat = []
lashzeroflag = []
jrsize = 0
jcsize = 0
brsize = 0
bcsize = 0
networkLap = dict()
networkAdj = dict()
for n, g in self.networkGraphs.items():
networkLap[n] = nx.laplacian_matrix(g.to_undirected()).todense()
# Construct node connectivity matrix, should be consistent with KCL
nadj = np.zeros((g.number_of_nodes(), g.number_of_nodes()))
for nd, nbrdict in g.adjacency():
nadj[
nd, nd
] = (
-1
) # -len(nbrdict) # src (-1) -> target (+1) , not using in-degree as src is associated with a quantity
for ni, wtd in nbrdict.items():
nadj[nd, ni] = +1
networkAdj[n] = nadj
hamiltonian = None
ucapVec = []
ycapVec = []
ucapVectm1 = [] # At t-1
ycapVectm1 = [] # At t-1
stateVec = []
rhsvec = []
nodePHS = dict()
statevalues = dict()
self.cellHamiltonians = OrderedDict() #Ensure insertion order is maintained
self.nodePHSData = dict()
for k in self.inodeIndexes:
v = self.nodeData[k]
phs = self.phsInstances[self.cellTypePHS[k]].instantiatePHS(
f"{k}", substituteParameters
)
self.nodePHSData[k] = phs #Used for generating input hooks
statevalues.update(phs.statevalues)
nodePHS[k] = phs
self.compositeparameters.update(phs.parameters)
r, c = phs.J.shape
jrsize += r
jcsize += c
r, c = phs.B.shape
brsize += r
bcsize += c
if hamiltonian is not None:
hamiltonian = sympy.Add(hamiltonian, phs.hamiltonian)
else:
hamiltonian = phs.hamiltonian
self.cellHamiltonians[k] = phs
jmat.append(phs.J)
qmat.append(phs.Q)
emat.append(phs.E)
rmat.append(phs.R)
for i in range(phs.u.rows):
stateVec.append(f"{phs.states[i,0]}")
# k in encoded in phs states
rhsvec.append(f"Del(H_{phs.states[i,0]})")
if not v["bsplit"][i]:
# k in encoded in u during instantiation
usym = f"{phs.u[i,0]}_{i}"
ysym = "y" + usym[1:]
ucapVec.append(sympy.Symbol(usym))
ycapVec.append(sympy.Symbol(ysym))
ucapVectm1.append(sympy.sympify(usym + "(t-1)"))
ycapVectm1.append(sympy.sympify(ysym + "(t-1)"))
else:
ucapVec.append(sympy.Symbol("0"))
ycapVec.append(sympy.Symbol("0"))
ucapVectm1.append(sympy.Symbol("0"))
ycapVectm1.append(sympy.Symbol("0"))
bcap, bdas = phs.split(v["bsplit"])
# Unlike the paper, C matrix is a real matrix and not connectivity matrix, therefore
# Metric contributions from bcap is determined by C matrix
# Only active/inactive contribution from component
# information is necessary - set all non zero entries in Bcap to 1
for ix in range(bcap.shape[0]):
for iy in range(bcap.shape[1]):
if bcap[ix, iy] != 0:
bcap[ix, iy] = 1 # sympy.Symbol("1")
# Include composite's Bhat to bcap
if (
phs.Bhat.shape[0] == bcap.shape[0]
and phs.Bhat.shape[1] == bcap.shape[1]
):
# Set the Bhat's nonzeros to bcap
for i in range(phs.Bhat.shape[0]):
for j in range(phs.Bhat.shape[1]):
if not sympy.is_zero(phs.Bhat[i, j]):
bcap[i, j] = phs.Bhat[i, j]
elif phs.Bhat.shape[0] != 0 and phs.Bhat.shape[1] != 0:
raise ("Composite PHS Bhat and Bcap are not of the same shape!")
bcapmat.append(
bcap
) # Since C is scaled by E, Bcap does not need to be scaled interior u = B C B^T Q x
nbcapmat.append((-bcap).T)
# The dimensions need to match the JMatrix as Bdash*udash is summed with (J-R) Q x
bash = sympy.zeros(phs.B.shape[0], self.uVec.shape[1])
lash = sympy.zeros(phs.B.shape[0], self.uVec.shape[1]) # laplacian
# boundaryinputs has the inputs that the nodes receives
# boundaryinputs[k][0] - component names
# boundaryinputs[k][1] - name index into u vector
# boundaryinputs[k][2] - network is dissipative or not
lashupdated = False
if k in self.boundaryinputs:
for (i, uin) in enumerate(self.boundaryinputs[k][0]):
comp = self.boundaryinputs[k][1][i]
# Subscript of uin contains the node to which k is connected
# prefix is given by phs.u[comp]
# if dissipative get the laplacian weight using k, uin_subscript
# us = Symbolics.variable(uin)
uix = -1
u_ix = -1 # Get the index in uVec
for j in range(self.uVec[0, :].cols):
if self.uVec[0, j] == uin:
uix = self.uVec[1, j]
u_ix = j
break
# uVec[1,:] has the names, uVec[2,:] has the component indexes
if self.boundaryinputs[k][2][i] == False:
bash[uix, u_ix] = phs.B[comp, comp]
else:
nid = f"{phs.usplit[comp]}"
if nid in self.dissipativeNets: # If dissipative
# uin is the node that provides the input - the suffix provides the node id and the index into the lapacian/adjacency matrix
ulc = phs.u[comp]
ulc = str(phs.u[comp]).find("_")
suffix = int(str(uin)[ulc + 1:])
wt = networkLap[nid][k, suffix]
lash[comp, u_ix] = wt
lashupdated = True
else: # Has input in bash
# Check uix and comp
bash[uix, u_ix] = phs.B[comp, comp]
bdasmat.append(bash)
lashmat.append(lash)
lashzeroflag.append(lashupdated)
# Set the vector elements in the correct order
if self.uVec.cols > 1:
self.uVecSymbols = self.uVec[0, self.uVec[1, :]]
else:
# When there is a single input symbol
self.uVecSymbols = Matrix([self.uVec[0]])
self.stateVec = stateVec
self.statevalues = statevalues
self.rhsVec = rhsvec
self.xVec = Matrix.vstack(
Matrix(stateVec), Matrix(ucapVec), Matrix(ycapVec))
self.rVec = Matrix.vstack(
Matrix(rhsvec), Matrix(ucapVectm1), Matrix(ycapVectm1)
)
self.hamiltonian = hamiltonian
"""
Create full connection matrix - get the asymmetric part for C and the other for R
Dissipative networks are expected to solve Reaction diffusion equations of the form
dx/dt = phs(x) + ∇x , where ∇x is the diffusive contributions computed from the weighted graph laplacian
When the PHS is of the form
E dx/dt = (J-R)Qx + Bu then the above equation requires a scaling factor for the ∇x term
E dx/dt = phs(x) + E ∇x
all terms of the lapacian matrix for the component are scaled by E
"""
Cx = sympy.zeros(brsize, bcsize)
roffset = 0
for (i, b) in enumerate(self.inodeIndexes):
# phs = self.phsInstances[self.cellTypePHS[b]]
phs = nodePHS[b]
# Emat = phs.E
usplit = phs.usplit
if phs.C.shape[0] != 0 and phs.C.shape[1] != 0:
# Scaling by compostite's E done at the time of construction
Cx[
roffset: roffset + phs.C.shape[0],
coffset: coffset + phs.C.shape[1],
] = phs.C
for (j, n) in enumerate(usplit):
nid = n
if (
nid in networkAdj
): # if u has zeros, networks for them will not be present
lap = networkAdj[nid]
if self.dissipativeNets[nid]:
lap = networkLap[nid]
coffset = 0
for (k, x) in enumerate(self.inodeIndexes):
phsx = nodePHS[x]
lc = phsx.B.shape[1]
if self.dissipativeNets[nid]:
try:
Cx[roffset + j, coffset + j] = lap[b, x]
except: # DomainError
continue
else:
# Setting up a symmetrix matrix for connection
if k > i:
try:
Cx[roffset + j, coffset + j] = lap[b, x]
Cx[coffset + j, roffset + j] = -lap[b, x]
except: # DomainError
continue
elif k == i:
try:
Cx[roffset + j, coffset + j] = lap[b, x]
except: # DomainError
continue
coffset += lc
roffset += phs.B.shape[0]
self.uyConnectionMatrix = Cx
sym = (Cx + Cx.T) / 2
skewsym = (Cx - Cx.T) / -2 # We need -C
self.uyConnectionMatrixComputed = True
# calculate the full matrix size
jr = 2 * jrsize + skewsym.shape[0]
jc = 2 * jcsize + skewsym.shape[1]
self.Jcap = sympy.zeros(jrsize, jcsize)
self.Rcap = sympy.zeros(jrsize, jcsize)
self.Ecap = sympy.zeros(jrsize, jcsize)
self.Qcap = sympy.zeros(jrsize, jcsize)
self.Bcap = sympy.zeros(jrsize, jcsize)
self.nBcapT = sympy.zeros(jrsize, jcsize)
self.Bdas = sympy.zeros(jrsize, self.uVec.shape[1])
self.Cmatrix = skewsym
self.Lmatrix = sym
jr, jc = 0, 0
for (i, jx) in enumerate(jmat):
self.Jcap[jr: jr + jx.shape[0], jc: jc + jx.shape[1]] = jx
self.Rcap[jr: jr + jx.shape[0], jc: jc + jx.shape[1]] = rmat[i]
self.Ecap[jr: jr + jx.shape[0], jc: jc + jx.shape[1]] = emat[i]
self.Qcap[jr: jr + jx.shape[0], jc: jc + jx.shape[1]] = qmat[i]
self.Bcap[jr: jr + jx.shape[0], jc: jc + jx.shape[1]] = bcapmat[i]
self.nBcapT[jr: jr + jx.shape[0],
jc: jc + jx.shape[1]] = nbcapmat[i]
# if laplacian is nonzero then Bdas should be lashmat
if not lashzeroflag[i]:
self.Bdas[jr: jr + bdasmat[i].shape[0], :] = bdasmat[i]
else:
self.Bdas[jr: jr + bdasmat[i].shape[0], :] = lashmat[i]
jr += jx.shape[0]
jc += jx.shape[1]
freevars = self.Jcap.free_symbols
freevars = freevars.union(self.Rcap.free_symbols)
freevars = freevars.union(self.Bcap.free_symbols)
freevars = freevars.union(self.Bdas.free_symbols)
freevars = freevars.union(self.Qcap.free_symbols)
freevars = freevars.union(self.hamiltonian.free_symbols)
freevars = freevars.union(self.uVecSymbols.free_symbols)
for k, v in self.compositeparameters.items():
freevars = freevars.union(k.free_symbols)
freevars = freevars.union(v["value"].free_symbols)
self.compositePHS = SymbolicPHS(
self.Jcap,
self.Rcap,
self.Bcap,
self.Bdas,
self.Qcap,
self.Ecap,
self.uyConnectionMatrix,
self.hamiltonian,
stateVec,
self.uVecSymbols,
sympy.zeros(self.uVec.shape[0], 1),
freevars,
self.compositeparameters,
self.statevalues,
)
def generateLatexReport(self):
"""Generate the latex describing the composite PHS
Returns:
string: HTML + Latex sting
"""
if len(self.stateVec) < 11:
return latexgenerationutils.generateLatex(self)
else:
return latexgenerationutils.generateImage(self)
def generatePythonIntermediates(self):
r"""Generate numerically solvable PHS
d/dx (Ex) = (J-R) Q x - \hat{B}\hat{C}\hat{B}^T \hat{u} + \bar{B} \bar{u}
\hat{y} = \hat{B}^T Q x
\bar{y} = \bar{B}^T Q x
"""
stateVec = Matrix(self.stateVec)
ucapVec = Matrix([f"u_{s}" for s in self.stateVec])
Ccap = self.uyConnectionMatrix
Delx = self.Qcap * stateVec # Potential
# Since E^-1 can be expensive, we will scale by the rate diagonal value of E for that component
Einv = sympy.eye(self.Ecap.shape[0])
for i in range(self.Ecap.shape[0]):
Einv[i, i] = 1 / self.Ecap[i, i]
JRQx = (self.Jcap - self.Rcap) * Delx
interioru = self.Bcap * Ccap * (self.Bcap.T) * ucapVec
exterioru = self.Bdas * Matrix(self.uVecSymbols).T
rhs = sympy.SparseMatrix(Einv * (JRQx - interioru + exterioru))
inputs = sympy.SparseMatrix(Einv * (-interioru + exterioru))
rhsfreesymbols = rhs.free_symbols
rhsnumericconstants = []
self.raw_rhs = deepcopy(rhs)
for elem in rhs:
if isinstance(elem, sympy.Expr):
for tm in elem.args:
rhsnumericconstants.extend(
[
term
for term in tm.args
if term not in rhsfreesymbols
and isinstance(term, sympy.Number)
and np.fabs(float(term)) != 1.0
]
)
elif isinstance(elem, sympy.Number):
if np.fabs(float(elem)) != 1.0:
rhsnumericconstants.append(elem)
# Constants in uCapVec
for i, s in enumerate(self.stateVec):
elem = interioru[i]
if isinstance(elem, sympy.Expr):
for tm in elem.args:
rhsnumericconstants.extend(
[
term
for term in tm.args
if term not in rhsfreesymbols
and isinstance(term, sympy.Number)
and np.fabs(float(term)) != 1.0
]
)
elif isinstance(elem, sympy.Number):
if np.fabs(float(elem)) != 1.0:
rhsnumericconstants.append(elem)
constantsubs = dict()
constCtr = 1
for c in set(rhsnumericconstants):
constantsubs[np.abs(c)] = f"c_{constCtr}"
constCtr += 1
# Remove constant entries that are same to given precision
constCtr = 1
constantstoprecision = dict()
newkeys = dict()
for k, v in constantsubs.items():
pk = f"{float(k):6f}"
if pk not in constantstoprecision:
constantstoprecision[pk] = sympy.Symbol(f"c_{constCtr}")
constCtr += 1
newkeys[k] = constantstoprecision[pk]
for k, v in newkeys.items():
constantsubs[k] = v
# Xreplace is faster than subs - no deep mathematical reasoning, ok for constant replacement
cleanrhs = rhs.xreplace(constantsubs)
cleaninputs = inputs.xreplace(constantsubs)
# Generate python
# Constants are contained in constantsubs, map and add all constants in compositeparameters that are used by functions in the composite parameters
nonlinearrhsterms = dict()
for c, t in self.compositeparameters.items():
fs = t["value"].free_symbols
cvdict = dict()
if len(fs) > 0:
# Load the values of composite parameter parameters
for f in fs:
if f in self.compositeparameters:
if self.compositeparameters[f]["value"] in constantsubs:
cvdict[f] = constantsubs[
self.compositeparameters[f]["value"]
]
elif (
np.fabs(
float(self.compositeparameters[f]["value"])) != 1.0
):
cvdict[f] = sympy.Symbol(f"c_{constCtr}")
constantsubs[self.compositeparameters[f]["value"]] = cvdict[
f
]
constCtr += 1
nonlinearrhsterms[c] = t["value"].xreplace(cvdict)
# Find all symbolic constants in nonlinearrhsterms
for k, v in nonlinearrhsterms.items():
fs = v.free_symbols
cvdict = dict()
for f in fs:
if f in self.compositeparameters:
if self.compositeparameters[f]["value"] in constantsubs:
cvdict[f] = constantsubs[self.compositeparameters[f]["value"]]
elif np.fabs(float(self.compositeparameters[f]["value"])) != 1.0:
cvdict[f] = sympy.Symbol(f"c_{constCtr}")
constantsubs[self.compositeparameters[f]
["value"]] = cvdict[f]
constCtr += 1
if len(cvdict) > 0:
v = v.xreplace(cvdict)
# Store all numeric ones inside constantsubs
if isinstance(v, sympy.Expr):
for tm in v.args:
xtn = [
term
for term in tm.args
if term not in fs and isinstance(term, sympy.Number)
]
for c in xtn:
if np.abs(c) not in constantsubs and np.fabs(float(c)) != 1.0:
constantsubs[np.abs(c)] = sympy.Symbol(
f"c_{constCtr}")
constCtr += 1
elif isinstance(v, sympy.Number):
if np.abs(v) not in constantsubs and np.fabs(float(v)) != 1.0:
constantsubs[np.abs(v)] = f"c_{constCtr}"
constCtr += 1
# Remove constant entries that are same to given precision
constCtr = 1
constantstoprecision = dict()
newkeys = dict()
skippedkeys = dict()
for k, v in constantsubs.items():
pk = f"{float(k):6f}"
if pk not in constantstoprecision:
constantstoprecision[pk] = sympy.Symbol(f"c_{constCtr}")
constCtr += 1
if v != constantstoprecision[pk]:
skippedkeys[v] = constantstoprecision[pk]
newkeys[k] = constantstoprecision[pk]
for k, v in newkeys.items():
constantsubs[k] = v
# Handle elements that are functions, the multiplication operation with a state should be composition
cleanedrhs = []
for elem in cleanrhs:
newelem = 0
# Logic works for Add expression
if not isinstance(elem, sympy.Add):
fs = elem.free_symbols
nterm = None
state = None
for f in fs:
if f in nonlinearrhsterms:
nterm = nonlinearrhsterms[f]
break
if nterm is not None:
# #Get the current state for the term
states = []
for f in fs:
if f in stateVec.free_symbols:
states.append(f)
# If the state in term appears in nterm, divide
for st in states:
if st in nterm.free_symbols:
state = st
# handles just one!
break
if nterm is not None and state is not None:
newelem = elem / state
else:
newelem = term
cleanedrhs.append(sympy.simplify(newelem))
else:
for term in elem.args:
fs = term.free_symbols
nterm = None
state = None
for f in fs:
if f in nonlinearrhsterms:
nterm = nonlinearrhsterms[f]
break
if nterm is not None:
# #Get the current state for the term
states = []
for f in fs:
if f in stateVec.free_symbols:
states.append(f)
# break
# If the state in term appears in nterm, divide
for st in states:
if st in nterm.free_symbols:
state = st
# handles just one!
break
if nterm is not None and state is not None:
nterm = term / state
newelem += nterm
else:
newelem += term
cleanedrhs.append(sympy.simplify(newelem))
# Constants also contain u vector, however they are updated after each step
# Do the update in compute_variables method, and initialise them in initialise_variables method
# Compute rhs contains, nonlinearrhsterms and cleanedrhs
# All parameters are in compositeparameters
# Translate to use constants and states arrays
arraymapping = OrderedDict()
invarraymapping = OrderedDict()
arraysubs = dict()
for i, s in enumerate(self.stateVec):
arraysubs[sympy.Symbol(s)] = sympy.Symbol(f"states[{i}]")
arraymapping[s] = f"states[{i}]"
invarraymapping[f"states[{i}]"] = s
numconstants = 0
# Do ubar first as numconstants change due to precision selection
# ubar entries
ubaridxmap = dict()
for s in self.uVecSymbols:
arraysubs[s] = sympy.Symbol(f"variables[{numconstants}]")
arraymapping[s.name] = f"variables[{numconstants}]"
invarraymapping[f"variables[{numconstants}]"] = s.name
ubaridxmap[s.name] = f"variables[{numconstants}]"
numconstants += 1
# Multiple k's will have same v due to defined precision
definedConstants = []
for k, v in constantsubs.items():
if v not in definedConstants:
arraysubs[v] = sympy.Symbol(f"variables[{numconstants}]")
arraymapping[str(v)] = f"variables[{numconstants}]"
invarraymapping[f"variables[{numconstants}]"] = str(v)
numconstants += 1
definedConstants.append(v)
# uCap entries
for s in self.stateVec:
arraysubs[sympy.Symbol(f"u_{s}")] = sympy.Symbol(
f"variables[{numconstants}]"
)
arraymapping[f"u_{s}"] = f"variables[{numconstants}]"
invarraymapping[f"variables[{numconstants}]"] = fr"\hat{{u}}_{s}"
numconstants += 1
# Non linear rhs terms
for s, v in nonlinearrhsterms.items():
arraysubs[s] = sympy.Symbol(f"variables[{numconstants}]")
arraymapping[s.name] = f"variables[{numconstants}]"
invarraymapping[f"variables[{numconstants}]"] = s.name
numconstants += 1
uCapterms = dict()
ucapdescriptive = dict()
for i, s in enumerate(self.stateVec):
consu = Delx[i].xreplace(skippedkeys).xreplace(constantsubs)
res = consu.xreplace(arraysubs)
uCapterms[arraymapping[f"u_{s}"]] = res
# Done this was as sympy printing changes the order of printed expr
ucapdescriptive[
arraymapping[f"u_{s}"]
] = fr"\hat{{u}}_{s} = {codegenerationutils._stringsubs(res.__str__(),invarraymapping)}"
nonlineararrayedrhsterms = dict()
nonlinearrhstermsdescriptive = dict()
for s, v in nonlinearrhsterms.items():
consv = v.xreplace(skippedkeys).xreplace(constantsubs)
res = consv.xreplace(arraysubs)
nonlineararrayedrhsterms[arraymapping[s.name]] = res
# Done this was as sympy printing changes the order of printed expr
nonlinearrhstermsdescriptive[
arraymapping[s.name]
] = f"{s} = {codegenerationutils._stringsubs(res.__str__(),invarraymapping)}"
arrayedrhs = []
arrayedinputs = []
# Use cleanedrhs and not cleanrhs - nonlinear terms with functions are transformed to compositions and not multiplication
for elem in cleanedrhs:
arrayedrhs.append(elem.xreplace(arraysubs))
for elem in cleaninputs:
arrayedinputs.append(elem.xreplace(arraysubs))
return numconstants,constantsubs,nonlinearrhsterms,inputs,arrayedinputs,arraymapping,uCapterms,ucapdescriptive,nonlineararrayedrhsterms,nonlinearrhstermsdescriptive,arrayedrhs,invarraymapping,rhs,ubaridxmap,cleaninputs
def exportAsPython(self):
"""Export composed FTU as python code similar to OpenCOR export"""
return codegenerationutils.exportAsPython(self)
def exportAsODEStepper(self,modelName="FTUStepper"):
r"""Generate numerically solvable PHS
d/dx (Ex) = (J-R) Q x - \hat{B}\hat{C}\hat{B}^T \hat{u} + \bar{B} \bar{u}
\hat{y} = \hat{B}^T Q x
\bar{y} = \bar{B}^T Q x
Setup the code as a Python class, with the ability to step through time and
set inputs
"""
return codegenerationutils.exportAsODEStepper(self,modelName)
def boundaryOperator(self):
"""Determine the boundary operator for the input graph
Returns:
numpy.array : 2D numpy array of size |internal E|x|internal V|
"""
graph = self.ftugraph.to_undirected()
#Handle boundary nodes seperately - encoded in node type attribute
# Discrete operator requires a node for each potential - in case of FTU's
# the boundary node provides fluxes, therefore create a node for each connection
# set the nodes's potential to be that of head node + flux
ntype = nx.get_node_attributes(graph,'type')
nodes = [n for n in graph.nodes() if ntype[n] == "in" ]
edges = [ed for ed in graph.edges() if ed[0] in nodes and ed[1] in nodes]
boundaryedges = [ed for ed in graph.edges() if ed[0] not in edges]
nodes.sort() #Ensure consistancy
boundaryedges.sort()
nidx = dict() #Node label to incidence matrix index map
nid = 0
for nd in nodes:
nidx[nd] = nid
nid +=1
numEdges = len(edges)
adm = np.zeros((numEdges,len(nodes)))
#Edge Ordering could be handled
for ei,ed in enumerate(edges):
adm[ei,nidx[ed[0]]] = -1
adm[ei,nidx[ed[1]]] = +1
return adm
def ddecSetupOperators(self,weight='weight'):
"""
These operators are used to setup training data for DDEC operators
Steps to use:
Given Node potentials (u0) and energy that is input at each node (f), where |u0| = |f| (as done by exported python code for simulating FTU)
Find f0 from u0
Since f0 - weighted Grad(u0) = 0;
f0 is determined as
f0 = weighted Grad (u0)
the rhs f vector is obtained as
f1 = rhs_f_vector_map*f
Then the problem for DDEC can be setup as
-Gradstarh*u^f_0 + f0 = 0
Div_h*f0 = f1
Args:
weight (string): Name of edge weight that will be used. default = 'weight'
Returns:
numpy.array : Weighted Gradient Operator 2D numpy array of size |all edges| x |V|
"""
graph = self.ftugraph.to_undirected()
#Handle boundary nodes seperately - encoded in node type attribute
# Discrete operator requires a node for each potential - in case of FTU's
# the boundary node provides fluxes, therefore create a node for each connection
# set the nodes's potential to be that of head node + flux
ntype = nx.get_node_attributes(graph,'type')
nodes = [n for n in graph.nodes() if ntype[n] == "in" ]
edges = [ed for ed in graph.edges() if ed[0] in nodes and ed[1] in nodes]
boundaryedges = [ed for ed in graph.edges() if ed[0] not in edges]
nodes.sort() #Ensure consistancy
boundaryedges.sort()
nidx = dict() #Node label to incidence matrix index map
nid = 0
for nd in nodes:
nidx[nd] = nid
nid +=1
numNodes = len(nodes)
numEdges = len(edges)
adm = np.zeros((numEdges,numNodes))
edgeWeights = []
#Edge Ordering could be handled
#When loading from a composition Graph is a multigraph - data is stored as dict of dicts
if isinstance(self.ftugraph,nx.MultiGraph):
for ei,ed in enumerate(edges):
ews = self.ftugraph.get_edge_data(ed[0],ed[1])
ew = 1.0
for k1,v1 in ews.items():
if weight in v1:
ew = v1[weight]
break
edgeWeights.append(ew)
sew = np.sqrt(ew)
adm[ei,nidx[ed[0]]] = -sew
adm[ei,nidx[ed[1]]] = +sew
else:
for ei,ed in enumerate(edges):
ew = 1.0
ews = self.ftugraph.get_edge_data(ed[0],ed[1])
if weight in ews:
ew = ews[weight]
edgeWeights.append(ew)
sew = np.sqrt(ew)
adm[ei,nidx[ed[0]]] = -sew
adm[ei,nidx[ed[1]]] = +sew
return adm,edgeWeights
def saveDiscreteExteriorCalculusOperators(self,filename,weight='weight'):
"""Save the boundary, edgeWeight and weighted gradient operators to file
Note that diag(sqrt(edgeWeight))* boudary = weighted gradient
Args:
filename (string): Absolute path of the destination numpy file to store the operators
weight (str, optional): The FTUgraph edge attribute that defines the weight of connections. Defaults to 'weight'.
Raises:
Exception: If the source ftugraph is not bound to the composer, exception is raised
"""
if self.ftugraph is not None:
boundaryOp = self.boundaryOperator()
adm,edgeWeights = self.ddecSetupOperators(weight)
with open(filename,'wb') as ops:
np.save(ops,boundaryOp)
np.save(ops,edgeWeights)
np.save(ops,adm)
else:
raise Exception("Connectivity graph not available!!")
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day 2 Exercise 4</title>
</head>
<body>
<h1>Exercise 4</h1>
<select id="car-selector">
</select>
<h2>Selected Brand</h2>
<h4 id="car-make"></h4>
<h3>Reflections</h3>
<div style="border: 1px solid black; border-radius: 5px;padding: 1em;">
For the UX a drop-down menu isn't great if you have too many options. 10 might be a nice max but lots of places seem to use it for stuff like countries where there's a lot more.<br>
To make this drop-down (select html element) we iterate through the cars array with the forEach method. On each array element we first use the DOM method createElement() to create a new option element <br>
Then we assign the option the value of the array element and uppercase the text to show up in the dropdown. Lastly but most importantly we use appendChild() from the selector element to add the new html-element, the option, as a child of the "car-selector" element. <br>
After the forEach() has run its arrow function on each element in the array we add an event listener to to the select element that reacts to change events by outputting the value of the currently selected option to the "car-make" div.
</div>
<a href="/">GO BACK</a>
<script>
const cars = ["Ford", "WW", "Toyota", "Volvo"];
const selector = document.getElementById("car-selector");
cars.forEach(make => {
const opt = document.createElement('option');
opt.value = make;
opt.textContent = make.toUpperCase();
selector.appendChild(opt);
});
selector.addEventListener('change', (event) => {
document.getElementById("car-make").innerText = event.target.value
});
</script>
</body>
</html>
|
package com.example.appyoutube.utils.extention
import android.view.View
import androidx.core.view.isVisible
fun View.visible() = if (!this.isVisible) this.visibility = View.VISIBLE else {
}
fun View.gone() {
if (this.isVisible) this.visibility = View.GONE
}
fun View.invisible() = if (this.isVisible) this.visibility = View.INVISIBLE else {
}
fun View.setOnSafeClick(defaultInterval: Int = 600, onSafeClick: (View) -> Unit) {
val safeClickListener = SafeClickListener(defaultInterval) {
onSafeClick(it)
}
setOnClickListener(safeClickListener)
}
class SafeClickListener(
private var defaultInterval: Int = 600,
private val onSafeCLick: (View) -> Unit
) : View.OnClickListener {
private var lastTimeClicked: Long = 0
override fun onClick(v: View) {
if (System.currentTimeMillis() - lastTimeClicked < defaultInterval) {
return
}
lastTimeClicked = System.currentTimeMillis()
runCatching {
onSafeCLick(v)
}.onFailure { it.printStackTrace() }
}
}
|
<template>
<div ref='editor'></div>
<button @click='syncHTML'>同步内容</button>
<button @click="saveToDB">保存至数据库</button>
<div :innerHTML='content.html'></div>
</template>
<script>
import { onMounted, onBeforeUnmount, ref, reactive } from 'vue';
import WangEditor from 'wangeditor';
import axios from 'axios'
import {Base64} from "js-base64";
export default {
name: 'app',
setup() {
const editor = ref();
const content = reactive({
html: '',
text: '',
});
let instance;
onMounted(() => {
instance = new WangEditor(editor.value);
const data = new FormData()
data.append("id", "1455445303942975488")
axios({
url: "/api/wangEditor/issue/findById",
method: 'post',
data: data
}).then(res => {
content.html = Base64.decode(res.data.data.description)
instance.txt.html(content.html)
}).catch(res => {
console.log(res)
})
Object.assign(instance.config, {
onchange() {
console.log(instance.txt.html())
console.log(instance.txt.getJSON())
},
});
instance.config.customUploadImg = function (resultFiles, insertImgFn) {
const data = new FormData()
for (let i = 0; i< resultFiles.length; i++) {
data.append("files", resultFiles[i])
}
data.append("issueId", 1);
axios({
url: "/api/wangEditor/attachment/upload",
method: 'post',
headers: {
'Content-Type': 'multipart/form-data;charset=UTF-8'
},
data: data
}).then(res => {
res.data.data.forEach(attachment => {
insertImgFn(attachment.url)
})
}).catch(res => {
console.log(res)
})
}
instance.create();
});
onBeforeUnmount(() => {
instance.destroy();
instance = null;
});
const syncHTML = () => {
content.html = instance.txt.html();
};
const saveToDB = () => {
const data = new FormData()
data.append("description", instance.txt.html())
console.log(data)
axios({
url: '/api/wangEditor/issue/save',
method: 'post',
data
}).then(res => {
if (res.data.code == 200) {
console.log("保存成功")
}
}).catch(res => {
console.log(res)
})
}
return {
syncHTML,
editor,
content,
saveToDB
};
},
};
</script>
|
<?php
namespace Drupal\quanthub_core\Plugin\Action;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\Entity\Node;
use Drupal\quanthub_core\QuanthubWorkflowInterface;
use Drupal\views_bulk_operations\Action\ViewsBulkOperationsActionBase;
/**
* Content moderation archive node.
*
* @Action(
* id = "quanthub_workflow_archive_action",
* label = @Translation("Archive node (quanthub moderation_state)"),
* type = "node",
* confirm = TRUE
* )
*/
class QuanthubArchive extends ViewsBulkOperationsActionBase {
/**
* {@inheritdoc}
*/
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
if ($object instanceof Node) {
$can_update = $object->access('update', $account, TRUE);
$can_edit = $object->access('edit', $account, TRUE);
$access = $can_edit->andIf($can_update);
return $return_as_object ? $access : $access->isAllowed();
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function execute(ContentEntityInterface $entity = NULL) {
if (!$state = $entity->get('moderation_state')->getString()) {
return $this->t(":title - can't change state",
[
':title' => $entity->getTitle(),
]
);
}
// Nothing do here for draft and archived.
// We move only published to archive.
if ($state == QuanthubWorkflowInterface::PUBLISHED_STATE) {
$entity->set('moderation_state', QuanthubWorkflowInterface::ARCHIVED_STATE);
$entity->save();
}
return $this->t(':title state changed to :state',
[
':title' => $entity->getTitle(),
':state' => $entity->get('moderation_state')->getString(),
]
);
}
}
|
#include <Arduino.h> //don't need to add this one...already included in arduino
#include <WiFi.h>
#include <HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "DHT.h"
#define DHTPIN 32
#define oneWireBus 33
#define DHTTYPE DHT22
#define moistPin 35
#define LDRPin 34
DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
const char* ssid = "SSID";
const char* password = "password";
float soilTemperature, h, t, lightIntensity, soilMoisture;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
sensors.begin(); //starts ds18b20
dht.begin(); //give 2 second delay to all sensors
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP Address");
Serial.println(WiFi.localIP());
}
void loop() {
HTTPClient http;
http.begin("https://finalyearprojectnuml.000webhostapp.com/fyp.php");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String Data = "humidity= " + String(h);
Data += "&air_temp= " + String(t);
Data += "&humidity= " + String(h);
Data += "&temp=" + String(soilTemperature); //change the order of data if you want. just keep the format similar
Data += "&soil_moisture=" + String(soilMoisture);
Data += "&light_intensity=" + String(lightIntensity);
int httpResponseCode = http.POST(Data);
if (httpResponseCode > 0) {
String response = http.getString(); //once you upload the code open serial monitor to show response code sent from website
Serial.println(httpResponseCode);
Serial.println(response);
}
else {
Serial.print("Error on sending post");
Serial.println(httpResponseCode);
}
http.end();
delay(2000);
}
void getSensorValues() {
sensors.requestTemperatures();
float soilTemp = sensors.getTempCByIndex(0);
float h = dht.readHumidity();
t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!")); //print to server
return;
}
lightIntensity = analogRead(LDRPin); // read the value from the LDR
soilMoisture = analogRead(moistPin);
}
|
package coded.alchemy.qoutable.database.data
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Unit test for the [Quote] class.
*
* @author Taji Abdullah
*/
class QuoteTest {
@Test
fun testQuoteProperties() {
// Arrange
val id = "123"
val author = "John Doe"
val content = "This is a sample quote."
val tags = listOf("tag1", "tag2")
val authorSlug = "john-doe"
val length = 42
val dateAdded = "2023-01-15"
val dateModified = "2023-01-20"
// Act
val quote = Quote(id, author, content, tags, authorSlug, length, dateAdded, dateModified)
// Assert
assertEquals(id, quote._id)
assertEquals(author, quote.author)
assertEquals(content, quote.content)
assertEquals(tags, quote.tags)
assertEquals(authorSlug, quote.authorSlug)
assertEquals(length, quote.length)
assertEquals(dateAdded, quote.dateAdded)
assertEquals(dateModified, quote.dateModified)
}
}
|
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ConfigurationPlayground._8.LazyLoading;
public static partial class ServiceCollectionExtensions
{
public static IServiceCollection AddLazyOptions(this IServiceCollection services, IConfiguration configuration, Action<string> addJsonFile)
{
services.AddOptions<LazyOptions>()
.BindConfiguration(LazyOptions.SectionName)
.Configure(options =>
{
options.GuessMyValue = "From configure";
});
return services;
}
/// <summary>
/// You should avoid using the IConfiguration or IOption before they are completely configured.
/// The way to do it is:
/// - Receive an IOption in the ctor of your services
/// - Use the factory pattern when adding services to the DI
/// </summary>
// public static IServiceCollection AddLazyOptions(this IServiceCollection services, IConfiguration configuration, Action<string> addJsonFile)
// {
// services.AddOptions<LazyOptions>()
// .BindConfiguration(LazyOptions.SectionName)
// .Configure(options =>
// {
// options.GuessMyValue = $"Now: From configure #1, Previously: {options.GuessMyValue}";
// });
//
// var fromCapturedConfiguration = configuration.GetSection(LazyOptions.SectionName).Get<LazyOptions>().GuessMyValue;
//
// // Nono! Don't do this!
// using var sp = services.BuildServiceProvider();
//
// addJsonFile("other.json");
//
// services.Configure<LazyOptions>(options =>
// {
// options.GuessMyValue = "From configure #2";
// });
//
// // Why take into account other.json?
// var fromPrematureOption = sp.GetRequiredService<IOptionsMonitor<LazyOptions>>().CurrentValue.GuessMyValue;
//
// services.AddScoped<EmptyClass>(_ =>
// {
// return new EmptyClass("From captured configuration",fromCapturedConfiguration);
// });
//
// services.AddScoped<EmptyClass>(_ =>
// {
// return new EmptyClass("From premature options",fromPrematureOption);
// });
//
// services.AddScoped<EmptyClass>((services) =>
// {
// var lazyConfiguration2 = services.GetRequiredService<IConfiguration>().GetSection(LazyOptions.SectionName).Get<LazyOptions>().GuessMyValue;
// return new EmptyClass("From options in factory", lazyConfiguration2);
// });
//
// services.AddScoped<EmptyClass>(services =>
// {
// var lazyOptions2 = services.GetRequiredService<IOptions<LazyOptions>>().Value.GuessMyValue;
// return new EmptyClass("From options in factory", lazyOptions2);
// });
//
// services.Configure<LazyOptions>(options =>
// {
// options.GuessMyValue = "From configure #3";
// });
//
//
// return services;
// }
// public static IServiceCollection AddLazyOptions(this IServiceCollection services, IConfiguration configuration, Action<string> addJsonFile)
// {
// services.AddOptions<LazyOptions>()
// .BindConfiguration(LazyOptions.SectionName);
//
// var lazyConfiguration = configuration.GetSection(LazyOptions.SectionName).Get<LazyOptions>().GuessMyValue;
//
// // Nono! Don't do this!
// using var sp = services.BuildServiceProvider();
// var prematureLazyConfiguration1 = sp.GetRequiredService<IOptions<LazyOptions>>().Value.GuessMyValue;
//
// services.Configure<LazyOptions>(options =>
// {
// options.GuessMyValue = "From configure #1";
// });
//
// using var sp2 = services.BuildServiceProvider();
// var prematureLazyConfiguration2 = sp2.GetRequiredService<IOptions<LazyOptions>>().Value.GuessMyValue;
//
// addJsonFile("other.json");
// var lazyConfigurationPostJson = configuration.GetSection(LazyOptions.SectionName).Get<LazyOptions>().GuessMyValue;
//
// services.AddScoped<EmptyClass>(services =>
// {
// return new EmptyClass("From captured configuration before json",lazyConfiguration);
// });
//
// services.AddScoped<EmptyClass>(services =>
// {
// return new EmptyClass("From premature options before configure",prematureLazyConfiguration1);
// });
//
// services.AddScoped<EmptyClass>(services =>
// {
// return new EmptyClass("From premature options after configure",prematureLazyConfiguration2);
// });
//
// services.AddScoped<EmptyClass>(services =>
// {
// return new EmptyClass("From captured configuration after json",lazyConfigurationPostJson);
// });
//
// services.AddScoped<EmptyClass>((services) =>
// {
// var lazyConfiguration2 = services.GetRequiredService<IConfiguration>().GetSection(LazyOptions.SectionName).Get<LazyOptions>().GuessMyValue;
// return new EmptyClass("From options in factory", lazyConfiguration2);
// });
//
// services.AddScoped<EmptyClass>(services =>
// {
// var lazyOptions2 = services.GetRequiredService<IOptions<LazyOptions>>().Value.GuessMyValue;
// return new EmptyClass("From options in factory", lazyOptions2);
// });
//
// services.Configure<LazyOptions>(options =>
// {
// options.GuessMyValue = "From configure #2";
// });
//
//
// return services;
// }
}
|
<script lang="ts" setup>
import { Link, usePage } from "@inertiajs/vue3";
import { computed, ref } from "vue";
import WrappedLink from "@/Components/WrappedLink.vue";
const burgerOpen = ref(false);
type User = {
id: number;
name: string;
email: string;
email_verified_at: string;
current_team_id: number;
profile_photo_path: string;
created_at: string;
updated_at: string;
is_admin: boolean;
two_factor_enabled: boolean;
two_factor_confirmed_at: string;
profile_photo_url: string;
};
const { props } = usePage() as { props: { auth: { user: User | null } } };
const isLoggedIn = computed(() => !!props.auth.user);
const isAdmin = computed(() => props.auth.user?.is_admin ?? false);
</script>
<template>
<div class="flex flex-col flex-nowrap min-h-[100vh] font-montserrat">
<header class="fixed z-50 w-full h-24 px-4">
<div
class="mx-auto max-w-5xl flex flex-nowrap gap-4 items-center py-4"
>
<Link
href="/"
class="h-14 w-14 rounded-[15%] overflow-hidden shrink-0"
>
<img
class="scale-[105%]"
src="/images/logos/minimal.png"
alt="Green Mindful Coach"
/>
</Link>
<div class="grow grid place-content-center">
<ul
class="hidden md:flex flex-nowrap place-content-center text-center rounded-full bg-white shadow-xl"
>
<WrappedLink
routeName="home"
class="w-24 py-2 hover:font-bold cursor-pointer transition-all"
/>
<WrappedLink
routeName="services"
class="w-24 py-2 hover:font-bold cursor-pointer transition-all"
/>
<WrappedLink
routeName="blogs"
class="w-24 py-2 hover:font-bold cursor-pointer transition-all"
/>
</ul>
</div>
<div class="shrink-0 relative">
<div class="bg-white h-8 relative">
<ul
v-if="burgerOpen"
class="absolute grid w-48 -top-2 -right-2 bg-white rounded-lg shadow-xl border-2 [&>*:first-child]:mr-12"
>
<Link
href="/"
class="p-3 hover:font-bold cursor-pointer"
>
Home
</Link>
<Link
href="/#services"
class="p-3 hover:font-bold cursor-pointer"
>
Services
</Link>
<Link
href="/blogs"
class="border-b p-3 hover:font-bold cursor-pointer"
>
Blogs
</Link>
<Link
v-if="isAdmin"
href="/nova"
class="p-3 hover:font-bold cursor-pointer"
>
Admin panel
</Link>
<Link
v-if="isLoggedIn"
href="/logout"
class="p-3 hover:font-bold cursor-pointer"
>
Log out
</Link>
<template v-if="!isLoggedIn">
<Link
href="/login"
class="p-3 hover:font-bold cursor-pointer"
>
Log in
</Link>
<Link
href="/register"
class="p-3 hover:font-bold cursor-pointer"
>
Sign up
</Link>
</template>
</ul>
<div
@click="burgerOpen = !burgerOpen"
class="absolute right-0 h-8 w-8 bg-[#484f52] border rounded-full grid place-content-center gap-1 group cursor-pointer transition-all"
:class="[burgerOpen ? 'hover:scale-110' : '']"
>
<div
class="h-[2px] w-5 rounded-md bg-white transition-all"
:class="[
burgerOpen
? 'translate-y-[6px] rotate-[45deg]'
: 'rotate-0',
]"
/>
<div
class="h-[2px] w-5 rounded-md bg-white transition-all"
:class="[
burgerOpen ? 'opacity-0' : 'opacity-100',
]"
/>
<div
class="h-[2px] w-5 rounded-md bg-white transition-all"
:class="[
burgerOpen
? 'translate-y-[-6px] rotate-[-45deg]'
: 'rotate-0',
]"
/>
</div>
</div>
</div>
</div>
</header>
<div class="grow relative mt-24">
<div class="max-w-7xl mx-auto">
<slot />
</div>
</div>
<footer
class="grid items-center text-center p-3 py-6 bg-gray-100 border-t"
>
<h2 class="text-3xl font-bold">Get in Touch</h2>
<p class="mt-4">Ready to start your journey to better health?</p>
<p class="flex flex-col md:flex-row gap-1 mx-auto">
<a href="mailto:celeste@greenmindfulcoach.com">
celeste@greenmindfulcoach.com
</a>
<span class="hidden md:inline">|</span>
<a href="tel:7735468672">(773) 546-8672</a>
</p>
</footer>
</div>
</template>
<style lang="scss" scoped>
footer a {
@apply text-brand-2 underline;
}
</style>
|
const express = require('express');
const bcrypt = require('bcrypt');
const users = require('../Models/userModel');
const jwt = require("jsonwebtoken");
const router = express.Router();
router.get('/',(req,res)=>{
res.status(200).send("Welcome to Users Route !")
})
router.post('/register',async(req,res)=>{
try {
const {email,password} = req.body;
const checkUser = await users.findOne({email});
if(checkUser){
return res.status(400).send('User Already Exists !')
}
const newPass = await bcrypt.hash(password, 10);
const newUser = await users.create({...req.body, password : newPass})
res.status(200).send({msg : "New user Registered !", newUser})
// const
} catch (error) {
res.status(500).send(error)
}
})
router.post("/login",async(req,res)=>{
try {
const {email,password} = req.body;
const userCheck = await users.findOne({email});
if( !userCheck){
return res.status(400).send("User Doesn't exist ...")
}
const verify = await bcrypt.compare(password, userCheck.password)
if(!verify){
return res.status(400).send("Wrong Password !")
}
const token = jwt.sign({userID : userCheck._id, email : userCheck.email},'123',{expiresIn : '5d'});
res.status(200).send({msg : "Login Successful", token});
} catch (error) {
res.status(500).send(error)
}
})
module.exports = router;
|
import argparse
import os
import json
import torch
from datetime import datetime
def get_parser():
"""
Function to obtain the config-dictionary with all parameters to be used in training/testing
:return: config - dictionary with all parameters to be used
"""
parser = argparse.ArgumentParser(description='Graph Autoregressive Diffusion Model',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# If config file should be used
parser.add_argument("--config", type=str, help="Config file to read run config from")
# General
parser.add_argument("--seed", type=int, default=42,
help="Seed for random number generator")
parser.add_argument("--mode", type=str.lower,
help="What mode to run in (train_ardm, train_discriminator, evaluate, generate)")
parser.add_argument("--load", type=str.lower,
help="Load parameters from pre-trained model (generator)")
parser.add_argument("--load_discriminator", type=str.lower,
help="Load parameters of discriminator")
parser.add_argument('--disable_cuda', action='store_true',
help='Whether to disable cuda, even if available')
parser.add_argument("--task", type=str.lower,
help="What task to perform (qm9, qm9_no_h, moses")
parser.add_argument("--num_samples", type=int, default=1000,
help="Number of samples to evaluate on")
parser.add_argument("--logger", type=str.lower,
help="Logger type (none or wandb)")
# Model related
parser.add_argument("--n_hidden_layers", type=int, default=3,
help="Number of hidden layers in MLP")
parser.add_argument("--activation_function", type=str.lower, default='relu',
help="MLP activation function")
parser.add_argument("--hidden_dim", type=int, default=256,
help="Dimension for hidden layers")
parser.add_argument("--batch_norm", type=int, default=0,
help="Use batch norm in MLP")
# Graph Transformer
parser.add_argument("--hidden_mlp_dim_x", type=int, default=256,
help="Hidden mlp dim for nodes")
parser.add_argument("--hidden_mlp_dim_e", type=int, default=128,
help="Hidden mlp dim for edges")
parser.add_argument("--hidden_mlp_dim_y", type=int, default=1,
help="Hidden mlp dim for y. Not used, and hence should be 1 for speed")
parser.add_argument("--hidden_dim_dx", type=int, default=256,
help="Hidden dim for dx")
parser.add_argument("--hidden_dim_de", type=int, default=64,
help="Hidden mlp dim for de")
parser.add_argument("--hidden_dim_dy", type=int, default=1,
help="Hidden mlp dim for dy. Not used, and hence should be 1 for speed")
parser.add_argument("--dim_ffX", type=int, default=256,
help="Feedforward dim, nodes")
parser.add_argument("--dim_ffE", type=int, default=128,
help="Feedforward dim, edges")
parser.add_argument("--dim_ffy", type=int, default=1,
help="Feedforward dim, y. Not used, and hence should be 1 for speed")
parser.add_argument("--n_head", type=int, default=8,
help="Number of Transformer heads")
parser.add_argument("--node_lambda", type=float,
help="Node lambda", default=1.0)
parser.add_argument("--edge_lambda", type=float,
help="Edge lambda", default=1.0)
parser.add_argument("--node_next_odds", type=float,
help="For NEsN, uppweighing the probability of sampling a node next (or, mask 0 edges)",
default=1.0)
parser.add_argument("--graph_kernel", type=str.lower, choices=['autoreg', 'nen', 'ne', 'partialautoreg'],
help="Which graph kernel to use", default='autoreg')
# Data related
parser.add_argument("--train_ratio", type=float, default=0.8,
help="Train set ratio, if dataset is not already split")
parser.add_argument("--val_ratio", type=float, default=0.2,
help="Validation set ratio, if dataset is not already split")
parser.add_argument("--filter", type=int, default=1,
help="If filtering dataset")
# Training
parser.add_argument("--epochs", type=int,
help="How many epochs to train for", default=100)
parser.add_argument("--val_interval", type=int,
help="How often to evalute on validation set (number of gradient steps)", default=10000)
parser.add_argument("--print_interval", type=int,
help="How often to print (number of epochs)", default=1)
parser.add_argument("--l2_reg", type=float, default=0,
help="L2-regularization added to cost function (aka weight decay)")
parser.add_argument("--batch_size", type=int,
help="Batch size for training", default=32)
parser.add_argument("--lr", type=float,
help="Learning rate", default=1e-3)
parser.add_argument("--optimizer", type=str.lower,
help="Optimizer to use for training", default="adam")
parser.add_argument("--scheduler", type=int,
help="If to use Cosine annealing")
parser.add_argument("--lr_min", type=float, default=0,
help="eta_min if using cosine scheduler")
# Discriminator
parser.add_argument("--discriminator", type=str.lower, default="transformer",
help="Which architecture for the discriminator")
parser.add_argument("--guidance_mode", type=str.lower,
help="Which mode to run the discriminator guidance (ardg, fadg, bsdg)")
parser.add_argument("--max_masked_percentage", type=float, default=1.0,
help="Maximum percentage of elements that should be masked")
parser.add_argument("--gradual_max_masked_percentage", type=int, default=0,
help="Have a gradual increase in max percentage of masked elements")
parser.add_argument("--increase_masked_percentage_every", type=int, default=7500,
help="Number of steps between increasing masked percentage")
parser.add_argument("--pool_only_unmasked", type=float, default=0,
help="Pool only unmasked representations")
parser.add_argument("--discriminator_tempering", type=int, default=0,
help="Temper discriminator")
parser.add_argument("--discriminator_temp_constant", type=float, default=1.0,
help="Discriminator temp constant if using tempering")
parser.add_argument("--encode_time", type=int, default=0,
help="Encode timestep")
parser.add_argument("--gen_data_path", type=str.lower,
help="Path to generated data")
# Particle filter
parser.add_argument("--pf_resampling", type=str.lower, default="systematic",
help="type of resampling in particle filter")
parser.add_argument("--ess_ratio", type=float, default=0.7,
help="ESS ratio for resampling (i.e, the number N_thresh/N")
parser.add_argument("--debug_pf", type=int, default=0,
help="Run PF in debug mode")
parser.add_argument("--same_order", type=int, default=1,
help="Same order for all particles")
parser.add_argument("--num_particles", type=int, default=10,
help="Number of particles per sample. -1 if using a full batch with particles")
return parser
def get_included_config(file_path):
with open(file_path, "r") as json_file:
config = json.load(json_file)
if "include" in config:
included_config = get_included_config(config["include"])
assert "include" not in included_config
included_config.update(config)
del included_config["include"]
config = included_config.copy()
return config
def get_config():
# First parse, and include default values
default_parser = get_parser()
default_args = default_parser.parse_args()
config = vars(default_args)
# Now update with arguments from config file
if default_args.config:
assert os.path.exists(default_args.config), f"No config file: {default_args}"
with open(default_args.config) as json_file:
config_from_file = json.load(json_file)
if "include" in config_from_file: # ability to include another json to avoid having to specify multiple things
included_config = get_included_config(config_from_file["include"])
included_config.update(config_from_file)
config_from_file = included_config.copy()
del config_from_file["include"]
unknown_options = set(config_from_file.keys()).difference(set(config.keys()))
unknown_error = "\n".join(["Unknown option in config file: {}".format(opt)
for opt in unknown_options])
assert (not unknown_options), unknown_error
config.update(config_from_file)
# Now parse again, but without any default values
command_line_parser = argparse.ArgumentParser(parents=[default_parser], add_help=False)
command_line_parser.set_defaults(**{key: None for key in config.keys()})
command_line_args = command_line_parser.parse_args()
# now overwrite values in config with those from command line
flags_from_command_line = []
config_from_command_line = vars(command_line_args)
for key, value in config_from_command_line.items():
if value is not None:
if key == "config":
value = str(value)
value = os.path.splitext(value)[0]
value = "-".join(os.path.normpath(value).split(os.path.sep))
if key != "logger":
flags_from_command_line.append(f'{key}={value}' if key != 'config' else str(value))
config[key] = value
config['cuda'] = not config['disable_cuda'] and torch.cuda.is_available()
dt_string = datetime.now().strftime("%d-%m-%Y-%H-%M-%S")
config['run_name'] = '_'.join([dt_string] + flags_from_command_line)
if not config["mode"].startswith("train"):
config["logger"] = "none"
print("Not running any training, therefore using no-op logger")
return config
if __name__ == '__main__':
print(get_config())
|
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:payment_ui/utils/app_colors.dart';
import 'package:payment_ui/utils/app_sizes.dart';
import 'package:payment_ui/utils/custom_textstyle.dart';
import 'package:payment_ui/widgets/white_box.dart';
class IncomeWidget extends StatelessWidget {
const IncomeWidget({
super.key,
required this.title,
required this.subtitle,
required this.icon,
});
final String title, subtitle, icon;
@override
Widget build(BuildContext context) {
return Expanded(
child: WhiteBox(
padding: EdgeInsets.all(12.w),
borderRadius: 16,
boxBorder: Border.all(color: AppColors.grey300),
child: Row(
children: [
WhiteBox(
height: 40,
color: const Color(0xffF9FAFB),
padding: const EdgeInsets.all(10),
borderRadius: 12,
width: 40,
child: SvgPicture.asset(icon)),
gapW12,
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: CustomTextStyle.t12400(color: AppColors.grey200),
),
gapH4,
Text(
subtitle,
style: CustomTextStyle.t14600(color: AppColors.blue100),
)
],
),
],
)),
);
}
}
|
import sqlite3
from services.db.db_dialogue_data import load_data_from_db
from services.db.db_rule import query_rule
from utils.data_utils import list_to_text
from utils.global_utils import SCHEME_DB_PATH, TASK_DB_PATH, RULE_DB_PATH
# scheme类,多个rule组成一个scheme
class Scheme:
def __init__(self, scheme_name, description):
self.scheme_name = scheme_name
self.description = description
self.rules = [] # 存储与此方案相关联的规则对象
def append(self, rule):
if rule not in self.rules:
self.rules.append(rule)
def remove_rule(self, rule):
self.rules.remove(rule)
def save(self):
conn = sqlite3.connect(SCHEME_DB_PATH)
cursor = conn.cursor()
# 检查方案是否已存在
cursor.execute("SELECT scheme_name FROM Schemes WHERE scheme_name = ?", (self.scheme_name,))
scheme_exists = cursor.fetchone()
if scheme_exists:
# 如果方案已存在,更新描述
cursor.execute("UPDATE Schemes SET description = ? WHERE scheme_name = ?",
(self.description, self.scheme_name))
else:
# 否则,插入新方案
cursor.execute("INSERT INTO Schemes (scheme_name, description) VALUES (?, ?)",
(self.scheme_name, self.description))
# 更新方案和规则的关联
# 首先,删除旧的关联
cursor.execute("DELETE FROM Scheme_Rule_Relationship WHERE scheme_name = ?", (self.scheme_name,))
# 然后,为方案添加新的规则关联
for rule in self.rules:
# 确保规则已经存在于 Rules 表中
cursor.execute("INSERT INTO Scheme_Rule_Relationship (scheme_name, rule_name) VALUES (?, ?)",
(self.scheme_name, rule))
conn.commit() # 提交事务
conn.close() # 关闭数据库连接
print(f"方案 '{self.scheme_name}' 已保存到数据库。")
def update(self, new_scheme_name, new_description):
conn = sqlite3.connect(SCHEME_DB_PATH)
cursor = conn.cursor()
cursor.execute("UPDATE Schemes SET scheme_name = ?, description = ? WHERE scheme_name = ?",
(new_scheme_name, new_description, self.scheme_name))
cursor.execute("UPDATE Scheme_Rule_Relationship SET scheme_name = ? WHERE scheme_name = ?",
(new_scheme_name, self.scheme_name))
conn.commit()
conn.close()
print(f"方案 '{self.scheme_name}' 已更新。")
def scheme_evaluate(self, task_id, dialogue_id, dialogue_df, manually_check):
conn = sqlite3.connect(TASK_DB_PATH)
cursor = conn.cursor()
base_score = 100 # 基础分
hit_rules = [] # 用于存储命中的规则及其影响
print(f"1")
for rule in self.rules:
print(rule)
evaluation_result = query_rule(rule).evaluate(dialogue_df)
if not evaluation_result:
continue # 规则未命中
print(f"3")
if isinstance(evaluation_result, tuple):
score_type, score_value = evaluation_result
print(f"4")
# 记录命中的规则及其影响
hit_rules.append((rule, score_value))
if score_type == "0":
# 一次性评分, 直接返回该得分并结束评估
base_score = score_value
break
elif score_type == "1":
# 加减分
base_score += score_value
# 将评分结果保存到数据库
cursor.execute('''
INSERT INTO evaluation_results (task_id, dialogue_id, score,manually_check)
VALUES (?, ?, ?, ?)
''', (task_id, dialogue_id, base_score, manually_check))
# 获取最新插入评分结果的ID
result_id = cursor.lastrowid
load_data_from_db("测试数据1")
# 将命中的规则详情保存到数据库
for rule, impact in hit_rules:
cursor.execute('''
INSERT INTO hit_rules_details (task_id, dialogue_id, rule_name, impact)
VALUES (?, ?, ?, ?)
''', (task_id, dialogue_id, rule, impact))
conn.commit()
conn.close()
return base_score
def update_score_by_HitRulesList(task_id, dialogue_id, hit_rules):
"""
更新数据库中的评分记录
:param task_id: 任务ID
:param dialogue_id: 对话ID
:param hit_rules: 命中的规则列表,储存名称
:return: base_score
"""
# 基础分数设置为 100,或者你可以从数据库读取初始分数
base_score = 100
conn_rule = sqlite3.connect(RULE_DB_PATH)
cursor_rule = conn_rule.cursor()
# 遍历每个命中的规则名称
for rule_name in hit_rules:
# 从 score_rules 表中获取评分类型和影响分值
cursor_rule.execute('''
SELECT score_type, score_value FROM score_rules
WHERE rule_name = ?
''', (rule_name,))
rule_info = cursor_rule.fetchone()
if rule_info:
score_type, score_value = rule_info
if score_type == "0":
# 一次性评分, 直接设置分数并结束循环
base_score = int(score_value)
break
elif score_type == "1":
# 加减分, 在基础分上进行加减
base_score += int(score_value)
conn_rule.close() # 关闭规则数据库连接
conn_task = sqlite3.connect(TASK_DB_PATH)
cursor_task = conn_task.cursor()
# 更新数据库中的评分记录
cursor_task.execute('''
UPDATE evaluation_results
SET score = ?
WHERE task_id = ? AND dialogue_id = ?
''', (base_score, task_id, dialogue_id))
conn_task.commit()
conn_task.close() # 关闭任务数据库连接
print(f"Task ID: {task_id}, Dialogue ID: {dialogue_id} score has been updated to {base_score}.")
return base_score
def query_scheme(scheme_name):
# 从数据库中查询方案,构建一个方案对象,然后返回
conn = sqlite3.connect(SCHEME_DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT description FROM Schemes WHERE scheme_name = ?", (scheme_name,))
scheme_data = cursor.fetchone()
cursor.execute("SELECT rule_name FROM Scheme_Rule_Relationship WHERE scheme_name = ?", (scheme_name,))
rule_data = cursor.fetchall()
conn.close()
if scheme_data:
scheme = Scheme(scheme_name, scheme_data[0])
for rule in rule_data:
scheme.append(rule[0])
return scheme
else:
return None
def delete_scheme(scheme_name):
conn = sqlite3.connect(SCHEME_DB_PATH)
cursor = conn.cursor()
cursor.execute("DELETE FROM Schemes WHERE scheme_name = ?", (scheme_name,))
conn.commit()
conn.close()
print(f"方案 '{scheme_name}' 已从数据库中删除。")
# 通过规则名,获取所属方案,返回唯一方案名字符串
def get_scheme_by_rule_name(rule_name):
"""
通过规则名,获取所属方案
:param rule_name:
:return: 一个字符串,包含所有包含该规则的方案名,用空格分隔
"""
conn = sqlite3.connect(SCHEME_DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT scheme_name FROM Scheme_Rule_Relationship WHERE rule_name = ?", (rule_name,))
scheme_data = cursor.fetchall()
conn.close()
scheme_names = [item[0] for item in scheme_data]
scheme_str = list_to_text(scheme_names)
return scheme_str
# 假设的辅助函数,根据方案name从数据库获取规则
def get_rules_by_scheme_name(scheme_name):
conn = sqlite3.connect(SCHEME_DB_PATH)
cursor = conn.cursor()
# 只选择与scheme_name相关联的规则名称
cursor.execute("SELECT rule_name FROM Scheme_Rule_Relationship WHERE scheme_name = ?", (scheme_name,))
rules_data = cursor.fetchall()
# 从查询结果中提取规则名称,并构建规则名称列表
rule_list = [rule_name[0] for rule_name in rules_data]
print(rule_list)
conn.close()
return rule_list
|
<template>
<div v-if="config">
<section class="p-6 bg-primary text-white">
<h1 dir="auto">{{ config.name }}</h1>
<p dir="auto">{{ config.description }}</p>
</section>
<section
class="px-2 flex flex-wrap gap-2 contact-statistics"
v-if="statistics"
>
<div class="statistics flex-1 min-w-[20rem]">
<i18n-t tag="p" keypath="Home to {number} users">
<template #number>
<strong>{{ statistics.numberOfUsers }}</strong>
</template>
</i18n-t>
<i18n-t tag="p" keypath="and {number} groups">
<template #number>
<strong>{{ statistics.numberOfLocalGroups }}</strong>
</template>
</i18n-t>
<i18n-t tag="p" keypath="Who published {number} events">
<template #number>
<strong>{{ statistics.numberOfLocalEvents }}</strong>
</template>
</i18n-t>
<i18n-t tag="p" keypath="And {number} comments">
<template #number>
<strong>{{ statistics.numberOfLocalComments }}</strong>
</template>
</i18n-t>
</div>
<div class="">
<p class="font-bold">{{ t("Contact") }}</p>
<instance-contact-link
v-if="config && config.contact"
:contact="config.contact"
/>
<p v-else>{{ t("No information") }}</p>
</div>
</section>
<hr role="presentation" v-if="config.longDescription" />
<section class="long-description content">
<div v-html="config.longDescription" />
</section>
<hr role="presentation" />
<section class="px-3">
<h2 class="text-xl">{{ t("Instance configuration") }}</h2>
<table class="border-collapse table-auto w-full">
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td>{{ t("Instance languages") }}</td>
<td
v-if="config.languages.length > 0"
:title="config.languages.join(', ') ?? ''"
>
{{ formattedLanguageList }}
</td>
<td v-else>{{ t("No information") }}</td>
</tr>
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td>{{ t("Mobilizon version") }}</td>
<td>{{ config.version }}</td>
</tr>
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td>{{ t("Registrations") }}</td>
<td v-if="config.registrationsOpen && config.registrationsAllowlist">
{{ t("Restricted") }}
</td>
<td v-if="config.registrationsOpen && !config.registrationsAllowlist">
{{ t("Open") }}
</td>
<td v-else>{{ t("Closed") }}</td>
</tr>
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td>{{ t("Federation") }}</td>
<td v-if="config.federating">{{ t("Enabled") }}</td>
<td v-else>{{ t("Disabled") }}</td>
</tr>
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td>{{ t("Anonymous participations") }}</td>
<td v-if="config.anonymous.participation.allowed">
{{ t("If allowed by organizer") }}
</td>
<td v-else>{{ t("Disabled") }}</td>
</tr>
<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td>{{ t("Instance feeds") }}</td>
<td v-if="config.instanceFeeds.enabled" class="flex gap-2">
<o-button
tag="a"
size="small"
icon-left="rss"
href="/feed/instance/atom"
target="_blank"
>{{ t("RSS/Atom Feed") }}</o-button
>
<o-button
tag="a"
size="small"
icon-left="calendar-sync"
href="/feed/instance/ics"
target="_blank"
>{{ t("ICS/WebCal Feed") }}</o-button
>
</td>
<td v-else>{{ t("Disabled") }}</td>
</tr>
</table>
</section>
</div>
</template>
<script lang="ts" setup>
import { formatList } from "@/utils/i18n";
import InstanceContactLink from "@/components/About/InstanceContactLink.vue";
import { LANGUAGES_CODES } from "@/graphql/admin";
import { ILanguage } from "@/types/admin.model";
import { ABOUT } from "../../graphql/config";
import { STATISTICS } from "../../graphql/statistics";
import { IConfig } from "../../types/config.model";
import { IStatistics } from "../../types/statistics.model";
import { useQuery } from "@vue/apollo-composable";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useHead } from "@vueuse/head";
const { result: configResult } = useQuery<{ config: IConfig }>(ABOUT);
const config = computed(() => configResult.value?.config);
const { result: statisticsResult } = useQuery<{ statistics: IStatistics }>(
STATISTICS
);
const statistics = computed(() => statisticsResult.value?.statistics);
const { result: languagesResult } = useQuery<{ languages: ILanguage[] }>(
LANGUAGES_CODES,
() => ({
codes: config.value?.languages,
}),
() => ({
enabled: config.value?.languages !== undefined,
})
);
const languages = computed(() => languagesResult.value?.languages);
const formattedLanguageList = computed((): string => {
if (languages.value) {
const list = languages.value?.map(({ name }) => name) ?? [];
return formatList(list);
}
return "";
});
const { t } = useI18n({ useScope: "global" });
useHead({
title: t("About {instance}", { instance: config.value?.name }),
});
</script>
<style lang="scss" scoped>
section {
&:not(:first-child) {
margin: 2rem auto;
}
&.hero {
h1.title {
margin: auto;
}
}
&.contact-statistics {
margin: 2px auto;
.statistics {
display: grid;
grid-template-columns: repeat(auto-fit, 150px);
gap: 2rem 0;
p {
text-align: right;
padding: 0 15px;
& > * {
display: block;
}
strong {
font-weight: 500;
font-size: 32px;
line-height: 48px;
}
}
}
}
tr.instance-feeds {
height: 3rem;
td:first-child {
vertical-align: middle;
}
td:last-child {
height: 3rem;
}
}
}
</style>
|
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import Fab from '@material-ui/core/Fab';
import AddIcon from '@material-ui/icons/Add';
import Major from './Major';
import MajorForm from './MajorForm';
const URL = 'http://localhost:8080';
const styles = theme => ({
fab: {
position: 'absolute',
bottom: theme.spacing.unit * 2,
right: theme.spacing.unit * 2,
},
extendedIcon: {
marginRight: theme.spacing.unit,
},
});
class MajorList extends Component {
constructor(props){
super(props);
this.state = {
open: false,
code:'',
title:'',
description: '',
period: '',
duration:'',
registrationNumber:'',
majors:[],
courses:[]
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleClickOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
handleSubmit = () => {
this.handleClose();
const major = {}
major.code = this.state.code
major.title = this.state.title
major.description = this.state.description
major.period = this.state.period
major.duration = this.state.duration
major.registrationNumber = this.state.registrationNumber
fetch(URL + '/majors', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(major)
})
.then(response => response.json())
.then(response => {
this.refreshMajors();
})
}
handleUpdate = (selectedMajor) => {
fetch(URL + '/majors', {
headers: {
'Content-Type': 'application/json'
},
method: 'PUT',
body: JSON.stringify(selectedMajor)
})
.then(response => response.json())
.then(response => {
this.refreshMajors();
})
}
handleRemove = (id) => {
fetch(URL + '/majors/' + id, {
headers: {
'Content-Type': 'application/json'
},
method: 'DELETE'
})
.then(response => response.json())
.then(response => {
this.refreshMajors();
})
}
handleChange = name => event => {
this.setState({ ...this.state, [name]: event.target.value });
};
cleanForm = () => {
this.setState({...this.state.code, code:''});
this.setState({...this.state.title, title:''});
this.setState({...this.state.description, description: ''});
this.setState({...this.state.period, period: ''});
this.setState({...this.state.duration, duration:''});
this.setState({...this.state.registrationNumber, registrationNumber:''});
}
refreshMajors(){
this.cleanForm()
fetch(URL + '/majors', {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(response => {
this.setState({...this.state, majors: response.data.content});
})
}
refreshCourses(){
fetch(URL + '/courses', {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(response => {
this.setState({...this.state, courses: response.data.content});
})
}
componentWillMount = () => {
this.refreshMajors();
}
componentDidMount = () => {
this.refreshCourses();
}
render(){
const { classes } = this.props;
return (
<div>
{
localStorage.getItem('user') ? <Fab color="primary" aria-label="Add" className={classes.fab} onClick={() => this.handleClickOpen()}>
<AddIcon />
</Fab> : null
}
{this.state.majors.map(major => (<Major handleSubmit={this.handleUpdate} courses={this.state.courses} key={major.id} major={major} handleRemove={this.handleRemove}/>))}
<MajorForm
open={this.state.open}
code={this.state.code}
title={this.state.title}
description={this.state.description}
period={this.state.period}
duration={this.state.duration}
registrationNumber={this.state.registrationNumber}
handleSubmit={this.handleSubmit}
handleClose={this.handleClose}
handleChange={this.handleChange}
/>
</div>
);
}
}
export default withStyles(styles)(MajorList);
|
@extends('template')
@section('title')
Bibliothèque principale
@endsection
@section('content')
<div class="row d-flex justify-content-center">
<h3>Bibliothèque principale</h3>
</div>
<div class="container p-3 mb-2 bg-light text-dark">
<form class="form" action="{{ route('bibliotheque.principale.tri') }}" method="post">
@csrf
<div class="row">
<div class="form-group col">
<label for="isbn">ISBN</label>
<input type="text" name="isbn" class="form-control" value="{{ $data['isbn'] ?? '' }}">
</div>
<div class="form-group col">
<label for="title">Titre</label>
<input type="text" name="title" class="form-control" value="{{ $data['title'] ?? '' }}">
</div>
</div>
<div class="row">
<div class="form-group col">
<label for="authors">Auteur</label>
<input type="text" name="authors" class="form-control" value="{{ $data['authors'] ?? '' }}">
</div>
<div class="form-group col">
<label for="editor">Éditeur</label>
<input type="text" name="editor" class="form-control" value="{{ $data['editor'] ?? '' }}">
</div>
</div>
<div class="row">
<div class="form-group col">
<label for="category">Catégorie</label>
<select name="category" class="form-control">
<option value=""></option>
@foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->label }}</option>
@endforeach
</select>
</div>
</div>
<div class="row d-flex justify-content-center">
<input type="submit" name="submit" class="btn btn-info btn-md" value="Trier"/>
</div>
</form>
</div>
<div class="d-flex justify-content-center">
{{ $books->links() }}
</div>
@if(!$books->isEmpty())
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">ISBN</th>
<th scope="col">Titre</th>
<th scope="col">Auteur</th>
<th scope="col">Éditeur</th>
<th scope="col">Catégorie</th>
<th scope="col">Opérations</th>
</tr>
</thead>
<tbody>
@foreach($books as $book)
<tr>
<td scope="row">{{ $book->id }}</td>
<td scope="row">{{ $book->isbn }}</td>
<td scope="row">{{ $book->title }}</td>
<td scope="row">{{ $book->authors }}</td>
<td scope="row">{{ $book->editor }}</td>
<td scope="row">{{ $book->category->label }}</td>
<td scope="row">
<a href="{{ url('livre/consulter/' . $book->id) }}" class="row">Consulter</a>
@foreach($writed_books as $writed)
@if($writed->id == $book->id)
<a href="{{ url('livre/editer/' . $book->id) }}" class="row">Éditer</a>
@endif
@endforeach
<?php $verif = false; ?>
@foreach($owned_books as $owned)
@if($owned->id == $book->id)
<?php $verif = true; ?>
@endif
@endforeach
<?php
if($verif){
?>
<a href="{{ url('livre/retirer/' . $book->id) }}" class="row">Retirer</a>
<form action="{{ route('livre.noter') }}" method="post" class="row">
@csrf
<a href="javascript:;" onclick="parentNode.submit();">Noter</a>
<input type="hidden" name="id" value="{{ $book->id }}"/>
</form>
<?php
}
else{
?>
@if($ajoutPossible)
<a href="{{ url('livre/ajouter/' . $book->id) }}" class="row">Ajouter</a>
@endif
<?php
}
?>
</td>
</tr>
@endforeach
</tbody>
</table>
@else
<div class="container">
Désolé, aucun livre n'a été trouvé.
</div>
@endif
<div class="d-flex justify-content-center">
{{ $books->links() }}
</div>
@endsection
|
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
//
// SPDX-License-Identifier: Apache-2.0
package access
import (
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/marketplaceordering/armmarketplaceordering"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcegraph/armresourcegraph"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
)
// ConnectConfig is the configuration required to connect to azure provider.
type ConnectConfig struct {
// SubscriptionID is a unique ID identifying a subscription.
SubscriptionID string
// TenantID is a unique identifier for an active directory tenant.
TenantID string
// ClientID is a unique identity assigned by azure active directory to an application.
ClientID string
// ClientSecret is a certificate issues for the ClientID.
ClientSecret string
}
// Factory is an access factory providing methods to get facade/access for different resources.
// Azure SDK provides clients for resources, these clients are actually just facades which internally uses another client.
type Factory interface {
// GetResourceGroupsAccess creates and returns a new instance of armresources.ResourceGroupsClient.
GetResourceGroupsAccess(connectConfig ConnectConfig) (*armresources.ResourceGroupsClient, error)
// GetVirtualMachinesAccess creates and returns a new instance of armcompute.VirtualMachinesClient.
GetVirtualMachinesAccess(connectConfig ConnectConfig) (*armcompute.VirtualMachinesClient, error)
// GetNetworkInterfacesAccess creates and returns a new instance of armnetwork.InterfacesClient.
GetNetworkInterfacesAccess(connectConfig ConnectConfig) (*armnetwork.InterfacesClient, error)
// GetSubnetAccess creates and returns a new instance of armnetwork.SubnetsClient.
GetSubnetAccess(connectConfig ConnectConfig) (*armnetwork.SubnetsClient, error)
// GetDisksAccess creates and returns a new instance of armcompute.DisksClient.
GetDisksAccess(connectConfig ConnectConfig) (*armcompute.DisksClient, error)
// GetResourceGraphAccess creates and returns a new instance of armresourcegraph.Client.
GetResourceGraphAccess(connectConfig ConnectConfig) (*armresourcegraph.Client, error)
// GetVirtualMachineImagesAccess creates and returns a new instance of armcompute.VirtualMachineImagesClient.
GetVirtualMachineImagesAccess(connectConfig ConnectConfig) (*armcompute.VirtualMachineImagesClient, error)
// GetMarketPlaceAgreementsAccess creates and returns a new instance of armmarketplaceordering.MarketplaceAgreementsClient.
GetMarketPlaceAgreementsAccess(connectConfig ConnectConfig) (*armmarketplaceordering.MarketplaceAgreementsClient, error)
}
|
# Windows Dynamic DNS Registration Fails
## Related Issue - Azure Information Protection Conditional Access
I believe that the Azure Information Protection Conditional-Access machine registration / access token was being partially reset on every reboot of these impacted systems due to the behavior mimicking a computer name-change / domain-join operation.
## Dynamic DNS Registration Overview
During normal operation a computer will automatically register its DNS record(s) at boot, on a regular refresh interval, and any time the computer IP Address changes.
If a computer has more than one IP Address (like wifi and wired), the dynamic dns registration results may be unreliable.
Active-Directory integrated DNS records replicate with the rest of the LDAP directory partitions. New or changed records will take the replication interval before they resolve in other sites or domain-controllers.
Recent versions of Windows also dynamically register reverse-dns IP-to-Name records when possible. These reverse records are Highly Unreliable because a reverse record created by one computer will be "owned" by the first computer with that reverse-record. Other computers using an ip-address previously registered by another computer will be unable to delete or change the reverse-record because the record is "owned" by the previous computer. DNS Stale-Record Scavenging can be enabled if desired to attempt to clear out old inaccurate reverse-dns records but BEWARE that some dynamically-registered server dns-records may be automatically-deleted in the process of scavenging stale client reverse-dns records. BACKUP a copy of all dns-records to CSV using powershell BEFORE enabling DNS Stale-Record Scavenging to have a record of any reverse entries to add back as static for servers.
Non-Microsoft systems like NAS devices or Linux hosts might have the problem of creating dynamic dns records but never refreshing the records after creation. These are the most likely types of dynamic-dns records to go "missing" after DNS-Scavenging is enabled. For these types of systems, Static-IP and Static-DNS records are recommended.
## Test Commands with Error Messages
Command-prompt and PowerShell test commands with associated error messages and comments. These commands require UAC Privilege Elevation (run-as-administrator).
* `ipconfig /registerdns`
* ERROR: `Registration of DNS records failed: The service has not been started.`
* Review of the `dnscache` (DNS Client) service shows that it is running.
* The error message was inaccurate in our case.
* `Register-DnsClient -Verbose`
* ERROR: `A general error occurred that is not covered by a more specific error code.`
* Attempts to enable logging on the DNS Client in Event Viewer failed to show the cause for our environment.
## Pending Computer-Name Change or Domain Join
In our environment the cause of this issue was a pending computer-name change or domain join which normally would just require a system reboot to resolve.
Unfortunately, in our environment a team-member had created a desired-state-configuration to automate domain-join
to our old-domain which was triggered by a scheduled task during every startup or user logon.
The legacy-doman join was failing, but the system was still acting as if a name-change or domain-join was in-process and pending-reboot.
In order to resolve the issue we were able to disable or unregister the scheduled task and remove the DSC (no longer needed).
## Disabling or Removing a Problem Scheduled Task
Commands to review and disable or remove a named scheduled task with comments.
* `Get-ScheduledTask -TaskName 'YourProblemTaskName' -Verbose`
* This will fail if a task with the matching name is missing.
* `Get-ScheduledTask -TaskPath '\'`
* List all root-level scheduled tasks for the computer
* `(Get-ScheduledTask -TaskPath '\' | Where TaskName -eq 'YourProblemTaskName') -ne $null`
* Returns `$true` if the TaskName is present
* Returns `$false` if the TaskName is missing
* `Disable-ScheduledTask -TaskName 'YourProblemTaskName' -Verbose`
* Disable the named scheduled task (without deleting)
* `Unregister-ScheduledTask -TaskName 'YourProblemTaskName' -Confirm:$false -Verbose`
* Remove the named scheduled task (delete)
## Remove Desired State Configuration (DSC)
Commands to review and remove desired state configuration document(s) with comments.
* BACKUP a copy of the system DSC configuration directory `"$env:SystemRoot\System32\Configuration"`
* This is just in case you need to restore something from the old DSC later.
* `Remove-DscConfigurationDocument -Stage Current -Verbose`
* Removes the `Current` DSC configuration. You can also specify `Previous` or `Pending` for -Stage.
* `Get-DscConfigurationStatus`
* This will return `$null` if the DscConfigurationDocument(s) have been removed.
|
// FoodResults.js
import React, { useState } from 'react';
import MealDialog from './MealDialog';
/**
* Component to display search results for food/meals.
* @param {Object} props - React component properties.
* @param {Array} props.searchResults - Array of meal objects representing search results.
* @returns {JSX.Element} - FoodResults component.
*/
const FoodResults = (props) => {
// Destructuring props to get searchResults
const { searchResults } = props;
// State to manage the selected meal for modal
const [selectedMeal, setSelectedMeal] = useState(null);
/**
* Function to open the modal and set the selected meal.
* @param {Object} meal - Selected meal object.
*/
const openModal = (meal) => setSelectedMeal(meal);
const closeModal = () => setSelectedMeal(null);
return (
<>
<div className="food-results" >
{/* Mapping through search results to display each meal */}
{searchResults.map((meal) => (
<div key={meal.idMeal}>
<h3 onClick={() => openModal(meal)}>{meal.strMeal}</h3>
<img onClick={() => openModal(meal)} src={meal.strMealThumb} alt={meal.strMeal} />
</div>
))}
</div>
{/* Modal component to display detailed information about the selected meal */}
<MealDialog meal={selectedMeal} onClose={closeModal} />
</>
);
};
export default FoodResults;
|
<?php
namespace App\Imports;
use App\ChiTietLopHocPhan;
use App\HocPhan;
use App\Khoa;
use App\Lop;
use App\LopHocPhan;
use App\SinhVien;
use App\SinhvienLop;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
class ChiTietLopHocPhanImport implements ToModel, SkipsEmptyRows, WithHeadingRow
{
public function model(array $row)
{
//Sinh viên
$masv = $row['ma_sv'];
$tensv = $row['ho_lot'] . ' ' . $row['ten'];
$ngaysinh = (isset($row['ngay_sinh']) && $row['ngay_sinh'] != '') ? $row['ngay_sinh'] : '';
//Khoa
$tenkhoa = (isset($row['thuoc_khoa']) && $row['thuoc_khoa'] != '') ? $row['thuoc_khoa'] : 0;
//Lớp
$lops = (isset($row['ma_lop']) && $row['ma_lop'] != '') ? $row['ma_lop'] : 0;
$lops = explode(',', $lops);
// Lớp học phần
$malhp = (isset($row['ma_lhp'])) ? $row['ma_lhp'] : '0';
$mahp = ($malhp == '0') ? '0' : substr($malhp, 3);
$tenhp = (isset($row['ten_hp'])) ? $row['ten_hp'] : '';
$loaihp = (isset($row['loai_hp'])) ? $row['loai_hp'] : '';
$sotc = (isset($row['so_tc'])) ? $row['so_tc'] : '0';
$ngaydk = (isset($row['ngay_dk'])) ? $row['ngay_dk'] : '';
//Check xem sinh viên đã đăng ký mã học phần này, và trong lớp học phần này chưa nếu có thì dừng
$checkValid = ChiTietLopHocPhan::where('malhp', $malhp)->where('mahp', $mahp)->where('masv', $masv)->get();
if (count($checkValid) != 0) {
DB::rollBack();
throw new ModelNotFoundException('dữ liệu bị trùng - MSSV: ' . $masv . ' đã đăng ký HP: ' . $mahp . ' với LHP: ' . $malhp);
}
//Check khoa đã tồn tại chưa
$khoa = Khoa::where('tenkhoa', $tenkhoa)->get();
if (count($khoa) == 0) {
$khoanew = Khoa::create([
'tenkhoa' => $tenkhoa,
'makhoa'=> substr($malhp,3,2)
]);
$makhoa = $khoanew->id;
} else {
$makhoa = $khoa[0]->id;
}
foreach ($lops as $lop) {
$lop = trim($lop);
//Check lop da co chua khong thi tao
$llop = Lop::where('malop', $lop)->get();
if (count($llop) == 0) {
Lop::create([
'malop' => $lop,
'makhoa' => $makhoa,
'magvcn' => 0,
]);
}
//Them lop cho sinh vien
$sinhvienlop = SinhvienLop::where('masv', $masv)->where('malop', $lop)->get();
if (count($sinhvienlop) == 0) {
SinhvienLop::create([
'masv' => $masv,
'malop' => $lop
]);
//Sinh viên chưa có trong lớp mới + 1 cho lớp, nếu có thì không cần +
$lop = Lop::where('malop', $lop)->get();
$sisonew = $lop[0]->siso + 1;
Lop::where('malop', $lop[0]->malop)->update([
'siso' => $sisonew
]);
}
}
//Thêm lớp học phần
$lophocphan = LopHocPhan::where('malhp', $malhp)->get();
if (count($lophocphan) == 0) {
$lophocphannew = LopHocPhan::create([
'malhp' => $malhp,
'namhoc' => '20' . substr($malhp, 0, 2). '-20'.strval(intval(substr($malhp, 0, 2)) + 1),
'hocky' => substr($malhp, 2, 1),
]);
$malhpnew = $lophocphannew->malhp;
} else {
$malhpnew = $malhp;
}
//Thêm học phần
$hocphan = HocPhan::where('mahp', $mahp)->get();
if (count($hocphan) == 0) {
$hocphannew = HocPhan::create([
'mahp' => $mahp,
'tenhp' => $tenhp,
'loai' => $loaihp,
'stc' => $sotc
]);
$mahpnew = $hocphannew->mahp;
} else {
$mahpnew = $mahp;
}
//Thêm sinh viên
$sinhvien = SinhVien::where('masv', $masv)->get();
if (count($sinhvien) == 0) {
$sinhviennew = SinhVien::create([
'masv' => $masv,
'tensv' => $tensv,
]);
$masvnew = $sinhviennew->masv;
} else {
$masvnew = $masv;
}
if ($ngaysinh != '') {
$sinhviennew->update([
'ngaysinh' => $ngaysinh,
]);
}
//Thêm chi tiết lớp học phần
$chitietlophocphan = array(
'malhp' => $malhpnew,
'masv' => sprintf($masv),
'mahp' => $mahpnew,
);
if ($ngaydk != '') {
$chitietlophocphan = array(
'malhp' => $malhpnew,
'masv' => sprintf($masvnew),
'mahp' => $mahpnew,
'ngaydk' => $ngaydk
);
}
return new ChiTietLopHocPhan($chitietlophocphan);
}
}
|
export {};
//* Flyweight Design Pattern
// Fly in the term Flyweight means light/not heavy.
// interface IFlyweight {
// code: number;
// }
// class Flyweight implements IFlyweight {
// // The Concrete Flyweight
// code: number;
// constructor(code: number) {
// this.code = code;
// }
// }
// class FlyweightFactory {
// // Creating the FlyweightFactory as a static class
// static flyweights: { [id: number]: Flyweight } = {};
// static getFlyweight(code: number): Flyweight {
// // A static method to get a flyweight based on a code
// if (!(code in FlyweightFactory.flyweights)) {
// FlyweightFactory.flyweights[code] = new Flyweight(code);
// }
// return FlyweightFactory.flyweights[code];
// }
// static getCount(): number {
// // Return the number of flyweights in the cache
// return Object.keys(FlyweightFactory.flyweights).length;
// }
// }
// class AppContext {
// // An example context that holds references to the flyweights in a
// // particular order and converts the code to an ascii letter
// private codes: number[] = [];
// constructor(codes: string) {
// for (let i = 0; i < codes.length; i++) {
// this.codes.push(codes.charCodeAt(i));
// }
// }
// output() {
// // The context specific output that uses flyweights
// let ret = "";
// this.codes.forEach((c) => {
// ret = ret + String.fromCharCode(FlyweightFactory.getFlyweight(c).code);
// });
// return ret;
// }
// }
// // The Client
// const APP_CONTEXT = new AppContext("abracadabra");
// // use flyweights in a context
// console.log("");
// console.log(`abracadabra has ${"abracadabra".length} letters`);
// console.log(`FlyweightFactory has ${FlyweightFactory.getCount()} flyweights`);
//* The Flyweight Use Case Example
class Column {
// The columns are the contexts.
// They will share the Flyweights via the FlyweightsFactory.
// `data`, `width` and `justify` are extrinsic values. They are outside
// of the flyweights.
data = "";
width = 10;
justify = 0;
getData(): string {
// Get the flyweight value from the factory, and apply the extrinsic values
const codes = [];
for (let i = 0; i < this.data.length; i++) {
codes.push(this.data.charCodeAt(i));
}
let ret = "";
Array.from(codes).forEach((c) => {
ret = ret + String.fromCharCode(FlyweightFactory.getFlyweight(c).code);
});
switch (this.justify) {
case 1:
ret = this.leftAlign(this.width, ret, " ");
break;
case 2:
ret = this.rightAlign(this.width, ret, " ");
break;
default:
ret = this.center(this.width, ret, " ");
}
return ret;
}
center(width: number, string: string, padding: string): string {
return width <= string.length ? string : this.centerAlternate(width, padding + string, padding);
}
centerAlternate(width: number, string: string, padding: string): string {
return width <= string.length ? string : this.center(width, string + padding, padding);
}
leftAlign(width: number, string: string, padding: string): string {
return width <= string.length ? string : this.leftAlign(width, string + padding, padding);
}
rightAlign(width: number, string: string, padding: string): string {
return width <= string.length ? string : this.rightAlign(width, padding + string, padding);
}
}
class Row {
columns: Column[];
constructor(column_count: number) {
this.columns = [];
for (let i = 0; i < column_count; i++) {
this.columns.push(new Column());
}
}
getData(): string {
// Format the row before returning it to the table
let ret = "";
this.columns.forEach((column) => {
ret = `${ret}${column.getData()}|`;
});
return ret;
}
}
class Table {
rows: Row[];
constructor(row_count: number, column_count: number) {
this.rows = [];
for (let i = 0; i < row_count; i++) {
this.rows.push(new Row(column_count));
}
}
draw(): void {
// Draws the table formatted in the console
let maxRowLength = 0;
const rows: string[] = [];
this.rows.forEach((row) => {
const rowData = row.getData();
rows.push(`|${rowData}`);
const rowLength = rowData.length + 1;
if (maxRowLength < rowLength) {
maxRowLength = rowLength;
}
});
console.log("-".repeat(maxRowLength)) + "<br />";
rows.forEach((row) => {
console.log(row);
});
console.log("-".repeat(maxRowLength));
}
}
class FlyweightFactory {
// Creating the FlyweightFactory as a static class
static flyweights: { [id: number]: Flyweight } = {};
static getFlyweight(code: number): Flyweight {
// A static method to get a flyweight based on a code
if (!(code in FlyweightFactory.flyweights)) {
FlyweightFactory.flyweights[code] = new Flyweight(code);
}
return FlyweightFactory.flyweights[code];
}
static getCount(): number {
// Return the number of flyweights in the cache
return Object.keys(FlyweightFactory.flyweights).length;
}
}
class Flyweight {
// The Concrete Flyweight
code: number;
constructor(code: number) {
this.code = code;
}
}
const TABLE = new Table(3, 3);
TABLE.rows[0].columns[0].data = "abra";
TABLE.rows[0].columns[1].data = "112233";
TABLE.rows[0].columns[2].data = "cadabra";
TABLE.rows[1].columns[0].data = "racadab";
TABLE.rows[1].columns[1].data = "12345";
TABLE.rows[1].columns[2].data = "332211";
TABLE.rows[2].columns[0].data = "cadabra";
TABLE.rows[2].columns[1].data = "445566";
TABLE.rows[2].columns[2].data = "aa 22 bb";
TABLE.rows[0].columns[0].justify = 1;
TABLE.rows[1].columns[0].justify = 1;
TABLE.rows[2].columns[0].justify = 1;
TABLE.rows[0].columns[2].justify = 2;
TABLE.rows[1].columns[2].justify = 2;
TABLE.rows[2].columns[2].justify = 2;
TABLE.rows[0].columns[1].width = 15;
TABLE.rows[1].columns[1].width = 15;
TABLE.rows[2].columns[1].width = 15;
TABLE.draw();
console.log(`FlyweightFactory has ${FlyweightFactory.getCount()} flyweights`);
|
## stratum areas
library(rvest)
library(dplyr)
st_tab <- read_html("https://www.pwrc.usgs.gov/bbs/stratanames/index.html") %>%
html_node("#Table2") %>%
html_table(header = TRUE)
strat_areas <- rbind.data.frame(st_tab[,1:3], st_tab[,5:7]) %>%
dplyr::filter(!is.na(Stratum)) %>%
setNames(c("stratum", "stratum_name", "stratum_area")) %>%
dplyr::select(-stratum_name)
## filenames and common names for stateprovs in 10-stop data (States/)
# 10-stop files (by stateprov)
ts <- 'ftp://ftpext.usgs.gov/pub/er/md/laurel/BBS/DataFiles/States/'
ts_lines <- readLines(ts)
ts_lines_split <- strsplit(ts_lines, '[[:space:]]+')
ts_files <- vapply(ts_lines_split, function(x) x[length(x)], character(1))
ts_files <- ts_files[grep('\\.txt$|\\.pdf$|\\.zip$', ts_files)]
# write csv with file names and manually add in common names, abbreviations,
# and 50-state zip files
df <- data.frame(file = ts_files, stringsAsFactors = F)
# write.csv(df, 'data-raw/ten-stop-files.csv', row.names = F)
# write to sysdata
library(readr)
df_zip <- read_csv('data-raw/zip-files.csv')
usethis::use_data(strat_areas, df_zip, overwrite = TRUE, internal = TRUE)
## subset weather data for tests
bbs_dir <- '~/bbs_data/'
wx <- bbs_meta_weather(bbs_dir = bbs_dir)
regions <- bbs_meta_regions(bbs_dir = bbs_dir)
regions[regions$country_name == 'Canada',]
# subset to Nunavut and NWT
wx <- wx[wx$state_num %in% c(43, 62),]
setwd('inst/testdata/')
write.csv(wx, 'weather.csv', row.names = FALSE)
zip('Weather.zip', 'weather.csv')
file.remove('weather.csv')
setwd('../../')
## subset 50-stop zip file to Nunavut for tests
nunavut_zip <- '~/bbs_data/50-StopData/1997ToPresent_SurveyWide/Fifty7.zip'
temp <- tempdir()
unzip(nunavut_zip, exdir = temp)
bbs_50 <- read.csv(paste(temp, 'fifty7.csv', sep = '/'))
bbs_50 <- subset(bbs_50, statenum == 62) # subset to Nunavut
dir.create('inst/testdata/50-StopData/1997ToPresent_SurveyWide/', recursive = TRUE)
setwd('inst/testdata/50-StopData/1997ToPresent_SurveyWide/')
write.csv(bbs_50, 'fifty7.csv', row.names = FALSE)
zip('Fifty7.zip', 'fifty7.csv')
file.remove('fifty7.csv')
setwd('~/rBBS')
|
import { MarkdownPostProcessorContext } from 'obsidian';
import { CLASS_ME_MENTION, CLASS_MENTION } from './Constants';
import { isFilePathInIgnoredDirectories } from './IgnoreHelper';
import { getMeMentionOrMentionRegex } from './RegExp';
import { MentionSettings } from './Settings';
export class MentionPostProcessor {
private subscribers: ((text: string) => void)[] = [];
private meMentionOrMentionRegex: RegExp = undefined;
constructor(private element: HTMLElement, private settings: MentionSettings, private ctx: MarkdownPostProcessorContext) {
// It is OK to set this regular expression here. As for now, the updates of the settings is not supported
// TODO (IMPROVEMENT): Add a function to update a new RegExp after setting a new TriggerPhrase / new MeMentionName
this.meMentionOrMentionRegex = getMeMentionOrMentionRegex(this.settings.mentionTriggerPhrase, this.settings.meMentionName);
}
public subscribeToMentionClick(fn: (text: string) => void): void {
this.subscribers.push(fn);
}
public addPreviewMentionStyle(): void {
if (isFilePathInIgnoredDirectories(this.ctx.sourcePath, this.settings)) return;
if (this.element.firstChild instanceof Node) {
const nodes = this.getChildNodes(this.element);
for (let node of nodes) {
if (node.parentElement.tagName === 'CODE') continue;
let replacementNodes = this.getReplacementNodesOrNull(node.textContent, this.meMentionOrMentionRegex);
if (replacementNodes) {
node.replaceWith(...replacementNodes);
}
}
}
}
private getChildNodes(element: HTMLElement): ChildNode[] {
const walker = document.createTreeWalker(element.firstChild, NodeFilter.SHOW_TEXT, null);
const nodes: ChildNode[] = [];
let node: Node;
while ((node = walker.nextNode())) {
nodes.push(node as ChildNode);
}
return nodes;
}
private getReplacementNodesOrNull(text: string, regExp: RegExp): (string | Node)[] {
const matches = [...text.matchAll(regExp)];
if (matches.length > 0) {
const parts: (string | Node)[] = [];
// The part before the mention
const textBeforFirstMention = text.substring(0, matches[0].index);
parts.push(textBeforFirstMention);
matches.forEach((m, i) => {
// The mention it self
const cls = m[1] != null ? CLASS_ME_MENTION : m[2] != null ? CLASS_MENTION : '';
const anchorNode = this.surroundWithAnchorTag(m[0], cls);
parts.push(anchorNode);
// The part after the mention
const indexEndTextAfterMention = matches[i + 1] == undefined ? text.length : matches[i + 1].index;
const indexStartTextAfterMention = m.index + m[0].length;
const textAfterMention = text.substring(indexStartTextAfterMention, indexEndTextAfterMention);
parts.push(textAfterMention);
});
return parts;
}
return null;
}
private surroundWithAnchorTag(text: string, className: string): HTMLAnchorElement {
const anchor = document.createElement('a');
anchor.addClass(className, 'preview');
anchor.textContent = text;
anchor.onClickEvent((_) => {
this.subscribers.forEach((s) => s(text));
});
return anchor;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Sharp"
rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Dasbord</title>
</head>
<body>
<nav>
<div class="container">
<img src="./img/logo.png" alt="logo" class="logo">
<div class="search-bar">
<span class="material-icons-sharp" >search</span>
<input type="search" placeholder="Search">
</div>
<div class="profile-area">
<div class="theme-btn">
<span class="material-icons-sharp active">light_mode</span>
<span class="material-icons-sharp">dark_mode</span>
</div>
<div class="profile">
<div class="profile-photo">
<img src="./img/profile-1.jpg" alt="">
</div>
<h5>Benn O`gain</h5>
<span class="material-icons-sharp">expand_more</span>
</div>
<button id="menu-btn" >
<span class="material-icons-sharp">menu</span>
</button>
</div>
</div>
</nav>
<!-- end of navbar -->
<main>
<aside>
<button id="close-btn" >
<span class="material-icons-sharp">close</span>
</button>
<div class="sidebar">
<a href="#" class="active">
<span class="material-icons-sharp ">dashboard</span>
<h4>Dashboard</h4>
</a>
<a href="#">
<span class="material-icons-sharp">currency_exchange</span>
<h4>Exchange</h4>
</a>
<a href="#">
<span class="material-icons-sharp">account_balance_wallet</span>
<h4>Wallet</h4>
</a>
<a href="#">
<span class="material-icons-sharp">payment</span>
<h4>Trasactions</h4>
</a>
<a href="#">
<span class="material-icons-sharp">pie_chart</span>
<h4>Analytics</h4>
</a>
<a href="#">
<span class="material-icons-sharp">message</span>
<h4>Messages</h4>
</a>
<a href="#">
<span class="material-icons-sharp">help_center</span>
<h4>Help Center</h4>
</a> <a href="#">
<span class="material-icons-sharp">settings</span>
<h4>Settings</h4>
</a>
</div>
<!-- end of sidebar -->
<div class="updates">
<span class="material-icons-sharp">update</span>
<h4>Updates Avaolable</h4>
<small>Security Updates</small>
<small>General Updates</small>
<a href="#">Update Now</a>
</div>
</aside>
<!-- end of aside -->
<section class="middle">
<div class="header">
<h1>Overview</h1>
<input type="date">
</div>
<div class="cards">
<!-- start of CARD 1 -->
<div class="card">
<div class="top">
<div class="left">
<img src="./img/BTC.png" alt="BTC">
<h2>BTC</h2>
</div>
<img class="right" src="./img/visa.png" alt="visa">
</div>
<div class="middle">
<h1>$827,199</h1>
<div class="chip">
<img src="./img/card chip.png" alt="card chip">
</div>
</div>
<div class="bottom">
<div class="left">
<small>Card Holder</small>
<h5>JOHN DOE</h5>
</div>
<div class="right">
<div class="expiry">
<small>Expiry</small>
<h5>08/23</h5>
</div>
<div class="cvv">
<small>CVV</small>
<h5>123</h5>
</div>
</div>
</div>
</div>
<!-- end of CARD 1 -->
<!-- start of CARD 2 -->
<div class="card">
<div class="top">
<div class="left">
<img src="./img/ETH.png" alt="EHT">
<h2>EHT</h2>
</div>
<img class="right" src="./img/master card.png" alt="master card">
</div>
<div class="middle">
<h1>$96,9</h1>
<div class="chip">
<img src="./img/card chip.png" alt="card chip">
</div>
</div>
<div class="bottom">
<div class="left">
<small>Card Holder</small>
<h5>JOHN DOE</h5>
</div>
<div class="right">
<div class="expiry">
<small>Expiry</small>
<h5>08/23</h5>
</div>
<div class="cvv">
<small>CVV</small>
<h5>123</h5>
</div>
</div>
</div>
</div>
<!-- end of CARD 2 -->
<!-- start of CARD 3 -->
<div class="card">
<div class="top">
<div class="left">
<img src="./img/EURO.png" alt="EURO">
<h2>EURO</h2>
</div>
<img class="right" src="./img/master card.png" alt="master card">
</div>
<div class="middle">
<h1>$74,129</h1>
<div class="chip">
<img src="./img/card chip.png" alt="card chip">
</div>
</div>
<div class="bottom">
<div class="left">
<small>Card Holder</small>
<h5>JOHN DOE</h5>
</div>
<div class="right">
<div class="expiry">
<small>Expiry</small>
<h5>08/24</h5>
</div>
<div class="cvv">
<small>CVV</small>
<h5>223</h5>
</div>
</div>
</div>
</div>
<!-- end of CARD 3 -->
</div>
<!-- end of CARDS -->
<div class="mountly-report">
<div class="report">
<h3>Income</h3>
<details>
<h1>$29,023</h1>
<h6 class="success">+3.5%</h6>
</details>
<p class="text-muted">Compared to 26,938 last mounth</p>
</div>
<!-- end of income report -->
<div class="report">
<h3>Expenses</h3>
<details>
<h1>$9,005</h1>
<h6 class="danger">-6.5%</h6>
</details>
<p class="text-muted">Compared to 11,938 last mounth</p>
</div>
<!-- end of Expenses report -->
<div class="report">
<h3>Cashback</h3>
<details>
<h1>$4,7004</h1>
<h6 class="success">+7.1%</h6>
</details>
<p class="text-muted">Compared to 3,938 last mounth</p>
</div>
<!-- end of Cashback report -->
<div class="report">
<h3>Turnover</h3>
<details>
<h1>$118,900</h1>
<h6 class="danger">-17.8%</h6>
</details>
<p class="text-muted">Compared to 136,981 last mounth</p>
</div>
<!-- end of Turnover report -->
</div>
<!-- end of monyly report -->
<div class="fast-payment">
<h2>Fast Payment</h2>
<div class="badges">
<div class="badge">
<span class="material-icons-sharp" >add</span>
</div>
<div class="badge">
<span class="bg-primary"></span>
<div>
<h5>Training</h5>
<h4>$50</h4>
</div>
</div>
<div class="badge">
<span class="bg-success"></span>
<div>
<h5>Internet</h5>
<h4>$40</h4>
</div>
</div>
<div class="badge">
<span class="bg-primary"></span>
<div>
<h5>Gas</h5>
<h4>$190</h4>
</div>
</div>
<div class="badge">
<span class="bg-success"></span>
<div>
<h5>Movies</h5>
<h4>$35</h4>
</div>
</div>
<div class="badge">
<span class="bg-success"></span>
<div>
<h5>Education</h5>
<h4>$999</h4>
</div>
</div>
<div class="badge">
<span class="bg-primary"></span>
<div>
<h5>Electricity</h5>
<h4>$109</h4>
</div>
</div>
<div class="badge">
<span class="bg-success"></span>
<div>
<h5>Food</h5>
<h4>$399</h4>
</div>
</div>
</div>
</div>
<!-- end of fast-payment -->
<canvas id="chart"></canvas>
</section>
<!-- end of section middle -->
<section class="right">
<div class="investments">
<div class="header">
<h2>Investments</h2>
<a href="#">More <span class="material-icons-sharp">chevron_right</span></a>
</div>
<!-- start of investment -->
<div class="investment">
<img src="./img/uniliver.png" alt="">
<h4>Oniliver</h4>
<div class="data-time">
<p>7 Nov, 2022</p>
<small class="text-muted">9:14pm</small>
</div>
<div class="bonds">
<p>1402</p>
<small class="text-muted">Bonds</small>
</div>
<div class="amount">
<h4>$20,033</h4>
<small class="danger">-4.27%</small>
</div>
</div>
<!-- end of investment -->
<!-- start of investment -->
<div class="investment">
<img src="./img/tesla.png" alt="">
<h4>Tesla</h4>
<div class="data-time">
<p>1 Dec, 2022</p>
<small class="text-muted">11:54pm</small>
</div>
<div class="bonds">
<p>5377</p>
<small class="text-muted">Bonds</small>
</div>
<div class="amount">
<h4>$720,110</h4>
<small class="success">+38.27%</small>
</div>
</div>
<!-- end of investment -->
<!-- start of investment -->
<div class="investment">
<img src="./img/monster.png" alt="">
<h4>Monster</h4>
<div class="data-time">
<p>1 Dec, 2022</p>
<small class="text-muted">4:04pm</small>
</div>
<div class="bonds">
<p>700</p>
<small class="text-muted">Bonds</small>
</div>
<div class="amount">
<h4>$13,110</h4>
<small class="success">+7.27%</small>
</div>
</div>
<!-- end of investment -->
<!-- start of investment -->
<div class="investment">
<img src="./img/mcdonalds.png" alt="">
<h4>McDonalds</h4>
<div class="data-time">
<p>3 Dec, 2022</p>
<small class="text-muted">8:14pm</small>
</div>
<div class="bonds">
<p>5200</p>
<small class="text-muted">Bonds</small>
</div>
<div class="amount">
<h4>$78,033</h4>
<small class="danger">-1.02%</small>
</div>
</div>
<!-- end of investment -->
</div>
<!-- end of investments -->
<div class="recent-transactions">
<div class="header">
<h2>Recent Trasactions</h2>
<a href="#">More <span class="material-icons-sharp" >chevron_right</span> </a>
</div>
<!-- start transaction -->
<div class="transaction">
<div class="service">
<div class="icon bg-purple-light">
<span class="material-icons-sharp purple">headphones</span>
</div>
<div class="details">
<h4>Music</h4>
<p>20.11.2022</p>
</div>
</div>
<div class="card-details">
<div class="card bg-danger">
<img src="./img/visa.png" alt="visa">
</div>
<div class="details">
<p>*2757</p>
<small class="text-muted" >Credit Card</small>
</div>
</div>
<h4>-$20</h4>
</div>
<!-- end transaction -->
<!-- start transaction -->
<div class="transaction">
<div class="service">
<div class="icon bg-purple-light">
<span class="material-icons-sharp purple">shopping_bag</span>
</div>
<div class="details">
<h4>Shopping</h4>
<p>19.11.2022</p>
</div>
</div>
<div class="card-details">
<div class="card bg-primary">
<img src="./img/visa.png" alt="visa">
</div>
<div class="details">
<p>*2757</p>
<small class="text-muted" >Credit Card</small>
</div>
</div>
<h4>-$120</h4>
</div>
<!-- end transaction -->
<!-- start transaction -->
<div class="transaction">
<div class="service">
<div class="icon bg-purple-light">
<span class="material-icons-sharp success">restaurant</span>
</div>
<div class="details">
<h4>Restaurant</h4>
<p>19.11.2022</p>
</div>
</div>
<div class="card-details">
<div class="card bg-dark">
<img src="./img/master card.png" alt="master card">
</div>
<div class="details">
<p>*2757</p>
<small class="text-muted" >Master card</small>
</div>
</div>
<h4>-$50</h4>
</div>
<!-- end transaction -->
<!-- start transaction -->
<div class="transaction">
<div class="service">
<div class="icon bg-danger-light">
<span class="material-icons-sharp danger">sports</span>
</div>
<div class="details">
<h4>Games</h4>
<p>18.11.2022</p>
</div>
</div>
<div class="card-details">
<div class="card bg-danger">
<img src="./img/visa.png" alt="visa">
</div>
<div class="details">
<p>*2757</p>
<small class="text-muted" >Credit card</small>
</div>
</div>
<h4>-$46</h4>
</div>
<!-- end transaction -->
<!-- start transaction -->
<div class="transaction">
<div class="service">
<div class="icon bg-danger-light">
<span class="material-icons-sharp success">medication</span>
</div>
<div class="details">
<h4>Pharmacy</h4>
<p>15.11.2022</p>
</div>
</div>
<div class="card-details">
<div class="card bg-primary">
<img src="./img/visa.png" alt="visa">
</div>
<div class="details">
<p>*2757</p>
<small class="text-muted" >Credit card</small>
</div>
</div>
<h4>-$500</h4>
</div>
<!-- end transaction -->
</div>
<!-- end transactions -->
</section>
<!-- end of section right -->
</main>
<!-- end of maine -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js" integrity="sha512-GMGzUEevhWh8Tc/njS0bDpwgxdCJLQBWG3Z2Ct+JGOpVnEmjvNx6ts4v6A2XJf1HOrtOsfhv3hBKpK9kE5z8AQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="./index.js" ></script>
</body>
</html>
|
import React, { ReactNode, CSSProperties } from "react";
import { clamp, getCircularArcPathD, TWO_PI } from "./utils";
/**
* Renders an SVG arc showing current "fullness" for a `value` between `from` and `to`.
*/
export const Gauge = ({
from,
to,
value,
fgColor = "salmon",
bgColor = "#dddddd",
strokeWidth = 16,
getCenterLabel,
style,
size = 300,
}: {
from: number;
to: number;
value: number;
fgColor?: string;
bgColor?: string;
strokeWidth?: number;
getCenterLabel?: (size: number) => ReactNode;
style?: CSSProperties;
size: number;
}) => {
const innerStrokeWidth = strokeWidth;
const outerStrokeWidth = innerStrokeWidth + 6;
const center = size / 2;
const arcRadius = size / 2 - outerStrokeWidth / 2;
const progress = clamp((value - from) / (to - from), 0.00001, 0.99999);
const startTheta = Math.PI / 2;
const endTheta = startTheta + TWO_PI * progress;
const fgD = getCircularArcPathD({
center: { x: center, y: center },
startTheta,
endTheta,
radius: arcRadius,
});
const bgD = getCircularArcPathD({
center: { x: center, y: center },
startTheta,
endTheta: startTheta + TWO_PI * 0.999,
radius: arcRadius,
});
return (
<div style={style}>
<div
style={{
width: size,
height: size,
display: "flex",
justifyContent: "center",
alignItems: "center",
position: "relative",
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox={`0 0 ${size} ${size}`}
style={{
width: size,
height: size,
position: "absolute",
left: 0,
top: 0,
}}
>
<path
strokeLinecap="round"
stroke={bgColor}
strokeWidth={outerStrokeWidth}
fill="none"
d={bgD}
/>
{progress > 0 && (
<path
strokeLinecap="round"
stroke={fgColor}
strokeWidth={innerStrokeWidth}
fill="none"
d={fgD}
/>
)}
</svg>
{getCenterLabel ? getCenterLabel(size) : null}
</div>
</div>
);
};
|
package common
import (
"context"
"net/http"
"github.com/PlayEconomy37/Play.Common/database"
)
// Define a custom contextKey type with the underlying type string
type contextKey string
// Convert the string "user" to a contextKey type and assign it to the userContextKey
// constant. We'll use this constant as the key for getting and setting user information
// in the request context.
const userContextKey = contextKey("user")
// ContextSetUser returns a new copy of the request with the provided
// User struct added to the context
func (app *App) ContextSetUser(r *http.Request, user database.User) *http.Request {
ctx := context.WithValue(r.Context(), userContextKey, user)
return r.WithContext(ctx)
}
// ContextGetUser retrieves the User struct from the request context. The only
// time that we'll use this helper is when we logically expect there to be User struct
// value in the context, and if it doesn't exist it will firmly be an 'unexpected' error.
func (app *App) ContextGetUser(r *http.Request) database.User {
user, ok := r.Context().Value(userContextKey).(database.User)
if !ok {
panic("missing user value in request context")
}
return user
}
|
import React, { useEffect } from "react";
import { ThemeProvider, makeStyles } from "@mui/styles";
import axios from "axios";
import { Box, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import theme from "../../theme";
import ViewAssessments from "../assessment/ViewAssessments";
import PartnerLink from "./PartnerLink";
import AddSlug from "./AddSlug";
import CreateAssessment from "../assessment/CreateAssessment";
import AddMerakiLink from "../smallComponents/AddMerakiLink";
import EditPartner from "./EditPartner";
import MainLayout from "../muiTables/MainLayout";
import ReportSend from "./ReportSend";
import ToolbarAddButton from "../admin/ToolbarAddButton";
import SelectReact from "../smallComponents/SelectReact";
const baseUrl = import.meta.env.VITE_API_URL;
const useStyles = makeStyles(() => ({
innerTable: {
marginLeft: "3vw",
marginRight: "3vw",
width: "94vw",
marginTop: "5",
marginBottom: "5",
[theme.breakpoints.up("md")]: {
margin: "auto",
marginTop: 5,
marginBottom: 5,
},
},
buttons: {
display: "flex",
gap: theme.spacing(2),
margin: theme.spacing(2),
},
}));
const getColumns = (partnerList) => [
{
name: "id",
label: "Edit Partner Details",
options: {
filter: false,
sort: true,
customBodyRender: (value) => <EditPartner value={value} />,
},
},
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
filterType: "custom",
filterOptions: {
logic: (location, filters) =>
filters[0] === "All" || filters[0] === undefined
? false
: !filters.includes(location),
display: (filterlist, onChange, index, column) => (
<>
<Typography variant="caption">Name</Typography>
<SelectReact
options={[{ name: "All" }, ...partnerList].map(({ name }) => ({
value: name,
label: name,
}))}
filterList={filterlist}
onChange={onChange}
index={index}
column={column}
value={filterlist[index].length === 0 ? "All" : filterlist[index]}
/>
</>
),
fullWidth: true,
},
customBodyRender: (value, rowMeta) => {
const id = rowMeta.rowData[0];
return <PartnerLink url={`/partner/${id}`} text={value} name={value} />;
},
},
},
{
name: "notes",
label: "View Assessments",
options: {
filter: false,
sort: false,
customBodyRender: (value, rowMeta) => (
<ViewAssessments partnerId={rowMeta.rowData[0]} />
),
},
},
{
name: "name",
label: "Create Assessment",
options: {
filter: false,
sort: false,
customBodyRender: (rowData, rowMeta) => (
<CreateAssessment
partnerId={rowMeta.rowData[0]}
partnerName={rowData}
/>
),
},
},
{
name: "id",
label: "Joined Students Progress",
options: {
filter: false,
sort: false,
customBodyRender: (value, rowMeta) => {
const name = rowMeta.rowData[3];
return (
<PartnerLink
url={`/partner/${value}/progress`}
text="Get Information"
name={name}
/>
);
},
},
},
{
name: "slug",
label: "Online Test For Partner",
options: {
filter: false,
sort: false,
customBodyRender: (value, rowMeta, updateValue) => {
if (value) {
const url = `/partnerLanding/${value}`;
return (
<div>
<a
href={url}
target="_blank"
rel="noreferrer noopener"
style={{ color: "#f05f40" }}
>
Go for test
</a>
</div>
);
}
return (
<AddSlug
columnIndex={rowMeta.columnIndex}
partnerId={rowMeta.rowData[0]}
name={rowMeta.rowData[3]}
notes={rowMeta.rowData[2]}
change={(event) => updateValue(event)}
/>
);
},
},
},
{
name: "meraki_link",
label: "Meraki Link",
options: {
filter: false,
sort: false,
customBodyRender: (value, rowMeta, updateValue) => (
<AddMerakiLink
isValue={value}
studentId={rowMeta.rowData[0]}
updateValue={updateValue}
/>
),
},
},
{
name: "id",
label: "Send Report",
options: {
filter: false,
sort: false,
customBodyRender: (value) => <ReportSend partnerId={value} />,
},
},
];
const PartnerList = () => {
const classes = useStyles();
const { privileges } = useSelector((state) => state.auth);
const navigate = useNavigate();
const [loading, setLoading] = React.useState(true);
const [partnerList, setPartnerList] = React.useState([]);
const dataSetup = (data) => {
setPartnerList(data);
};
const fetchPartners = async () => {
try {
const dataURL = `${baseUrl}partners`;
const response = await axios.get(dataURL, {
headers: { Authorization: `Bearer ${localStorage.getItem("jwt")}` },
});
dataSetup(response.data.data);
} catch (e) {
console.error(e);
}
};
useEffect(() => {
(async () => {
setLoading(true);
await fetchPartners();
setLoading(false);
})();
}, []);
const options = {
customToolbar: React.useCallback(
() => (
<ToolbarAddButton
handleOpen={() => navigate("/partner/add")}
disabled={!privileges.some((priv) => priv.privilege === "AddPartner")}
/>
),
[]
),
};
return (
<Box>
<ThemeProvider theme={theme}>
<div className={classes.innerTable}>
<MainLayout
title="Partners"
columns={getColumns(partnerList)}
data={partnerList}
options={options}
tableBodyMaxHeight="74vh"
showLoader={loading}
/>
</div>
</ThemeProvider>
</Box>
);
};
export default PartnerList;
|
# installed.packages()
# decreasing: FALSE, TRUE, NULL
#' @param which `"loaded"`, `"installed"`)
#' @param decreasing `FALSE`, `TRUE`, `NULL`
#' @param ... Arguments passed to [stringr::str_sort()]
#'
#' @md
#' @noRd
#' @keywords internal
#' @examples
#' list_packages()
#' list_packages("installed")
#'
list_packages <- function(which = c("loaded", "installed"), decreasing = FALSE, ...) {
which <- match.arg(which, several.ok = FALSE)
pkgs <- switch(
which,
"loaded" = (.packages(all.available = FALSE)),
"installed" = (.packages(all.available = TRUE)),
stop("Unknown option of `which` (type of packages): ", which)
)
if (!is.null(decreasing)) {
str_sort(pkgs, decreasing = decreasing, ...)
} else {
pkgs
}
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' Get number of datasets in a package
#'
#' @param package String with valid name of inst6alled package
#'
#' @return Number with number of datasets in a package
#'
#' @md
#' @noRd
#'
#' @examples
#' get_n_datasets("datasets")
#' get_n_datasets("purrr")
get_n_datasets <- function(package) {
ds_in_pkg <- data(package = package)$results
nrow(ds_in_pkg)
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' Get either dimensions or length of a dataset
#'
#' @param obj An R object (dataset).
#'
#' @return A string wiht dimensions of matrix-like or array-like oblect and
#' length of other objects.
#' @md
#' @noRd
#'
#' @examples
#' get_obj_dims(iris)
#'
get_obj_dims <- function(obj, x_symbol = " \u00D7 ") {
dim_obj <- dim(obj)
if (is.null(dim_obj)) {
as.character(length(obj))
} else {
stringr::str_c(dim_obj, collapse = x_symbol) # "\u00D7" - times symbol
}
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' Get information about dataset
#'
#' @param str sting with datasets name, e.g, "datasets::iris"
#'
#' @return Dataframe with size, class and some other information about a dataset.
#'
#' @md
#' @noRd
#'
#' @examples
#' get_ds_info("datasets::iris")
get_ds_info <- function(str) {
# ds <- eval(parse(text = str))
ds <- get_ds_data(str)
data.frame(
size = get_obj_dims(ds),
is_df = is.data.frame(ds),
is_matrix = is.matrix(ds),
is_list = is.list(ds),
class = str_c(class(ds), collapse = ", "),
stringsAsFactors = FALSE
)
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' Get data of a dataset in R package
#'
#' @param str sting with datasets name, e.g,
#' `"iris"` (if package with data is loaded) or `"datasets::iris"`.
#'
#' @return The contents of the dataset.
#'
#' @md
#' @noRd
#'
#' @examples
#' get_ds_data("datasets::BOD")
#'
#' get_ds_data("BOD")
#'
#' str <- "datasets::BOD"
#' get_ds_data(str)
get_ds_data <- function(str) {
ds <- try(eval(parse(text = str)), silent = TRUE)
# If dataset is not experted
if (inherits(ds, "try-error")) {
tmp_envir <- new.env()
if (isTRUE(stringr::str_detect(str, ":{2,3}"))) {
names <- stringr::str_split(str, ":{2,3}", 2)[[1]]
ds_name <- data(list = names[2], package = names[1], envir = tmp_envir)
} else {
ds_name <- data(list = str, envir = tmp_envir)
}
ds <- tmp_envir[[ds_name]]
}
# Return:
ds
}
#' Get information about dataset and its variables
#'
#' @param str sting with datasets name, e.g, "datasets::iris"
#'
#' @return Dataframe with size and variable type frequency
#'
#' @md
#' @noRd
#'
#' @examples
#' str <- "datasets::iris"
#' get_ds_info_2("datasets::iris")
#' get_ds_info_2("BOD")
#'
get_ds_info_2 <- function(str) {
ds <- get_ds_data(str)
ds_size <- get_obj_dims(ds)
if (is.data.frame(ds)) {
n_variables <- ncol(ds)
n_numeric <- sum(purrr::map_int(ds, is.numeric))
n_factor <- sum(purrr::map_int(ds, is.factor))
n_logical <- sum(purrr::map_int(ds, is.logical))
n_character <- sum(purrr::map_int(ds, is.character))
n_other <- n_variables - n_character - n_logical - n_factor - n_numeric
} else {
n_variables <- n_numeric <- n_factor <- n_logical <- n_character <-
n_other <- n_variables <- NA
}
tibble::tibble(
size = ds_size,
is_data_frame = is.data.frame(ds),
# n_vars = n_variables,
n_num = n_numeric,
n_fct = n_factor,
n_lgl = n_logical,
n_chr = n_character,
n_other = n_other,
class = str_c(class(ds), collapse = ", ")
)
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' @param package
#'
#' @md
#' @noRd
#'
#' @examples
#' get_info_about_datasets("ggplot2")
get_info_about_datasets <- function(package = NULL) {
# library(tidyverse)
#
# package <- "ggplot2"
# all_pkgs <- FALSE
#
# pkgs <- setdiff(.packages(all.available = all_pkgs), c("base", "stats"))
# package <- pkgs
#
# # package <- "purrr"
# package <- "ggplot2"
res <-
package %>%
purrr::map_dfr(~ tibble::as_tibble(data(package = .)$results)) %>%
dplyr::select(-LibPath) %>%
dplyr::mutate(
# removes unnecessary information
Item = stringr::str_trim(stringr::str_replace(Item, " .*$", "")),
pkg_ds = stringr::str_c(Package, "::", Item),
code_to_load = stringr::str_glue('data({Item}, package = "{Package}")'),
info = purrr::map(pkg_ds, ~ purrr::safely(get_ds_info_2)(.)$result)
) %>%
tidyr::unnest(info) %>%
dplyr::rename(Dataset = Item) %>%
dplyr::select(-pkg_ds, -code_to_load, dplyr::everything(), code_to_load) %>%
dplyr::arrange(Package, Dataset)
# If no datasets are present
if (nrow(res) < 1) {
res <- tibble::tibble(
"Package" = character(),
"Dataset" = character(),
"Title" = character(),
"size" = character(),
"is_data_frame" = logical(),
"n_num" = integer(),
"n_fct" = integer(),
"n_lgl" = integer(),
"n_chr" = integer(),
"n_other" = integer(),
"class" = character(),
# "pkg_ds" = character(),
"code_to_load" = character()
)
}
res
# View(res)
# Issue:
# (data(BJsales.lead, package = "datasets"))
}
list_datasets_in_package <- function(package) {
data(package = package)$results[, "Item"]
}
get_ds_info_as_sring <- function(str) {
str %>%
get_ds_info_2() %>%
knitr::kable(format = "pandoc") %>%
str_c(collapse = "\n")
}
# pkgs <- c( "sandwich", "datasets")
# get_ds_list(pkgs)
get_ds_list <- function(pkgs) {
pkgs %>%
purrr::map_dfr(~ tibble::as_tibble(data(package = .)$results)) %>%
dplyr::mutate(Item = stringr::str_trim(stringr::str_replace(Item, " .*$", ""))) %>%
dplyr::pull(Item)
}
|
/****************************************************************************
* GOTV-Qt - Qt and libgotvptop connector library
* Copyright (C) 2012 Tadej Novak <tadej@tano.si>
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef GOTVQT_MEDIALIST_H_
#define GOTVQT_MEDIALIST_H_
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QUrl>
#include "Enums.h"
#include "SharedExportCore.h"
class GoTvPtoPInstance;
class GoTvPtoPMedia;
struct libgotvptop_event_t;
struct libgotvptop_event_manager_t;
struct libgotvptop_media_t;
struct libgotvptop_media_list_t;
/*!
\class GoTvPtoPMediaList MediaList.h core/MediaList.h
\ingroup GOTVQtCore
\brief Media list item
GoTvPtoPMediaList holds multiple GoTvPtoPMedia items to play in sequence.
*/
class GOTVQT_CORE_EXPORT GoTvPtoPMediaList : public QObject
{
Q_OBJECT
public:
/*!
\brief GoTvPtoPMediaList constructor.
This constructor creates a new media list instance.
\param instance main libgotvptop instance
*/
explicit GoTvPtoPMediaList(GoTvPtoPInstance *instance);
/*!
\brief GoTvPtoPMediaList destructor
*/
~GoTvPtoPMediaList();
/*!
\brief libgotvptop media list item
\return libgotvptop media list item (libgotvptop_media_list_t *)
*/
libgotvptop_media_list_t *core();
/*!
\brief Add media item to the list
\param media media item
*/
void addMedia(GoTvPtoPMedia *media);
/*!
\brief Get media item at selected index
\param index item position
\return media item (GoTvPtoPMedia)
*/
GoTvPtoPMedia *at(int index);
/*!
\brief libgotvptop media list item
\return items count (int)
*/
int count();
/*!
\brief Index of media item
\param media media item
\return media item index (int)
*/
int indexOf(GoTvPtoPMedia *media);
/*!
\brief Index of media item (core)
\param media media item
\return media item index (int)
*/
int indexOf(libgotvptop_media_t *media);
/*!
\brief Insert media item at the specific position of the list.
\param media media item
\param index item position
*/
void insertMedia(GoTvPtoPMedia *media,
int index);
/*!
\brief Remove media item from the specific position of the list.
\param index item position
*/
void removeMedia(int index);
signals:
/*!
\brief Signal sent on item added
\param item item that was added
\param index index of item
*/
void itemAdded(libgotvptop_media_t *item,
int index);
/*!
\brief Signal sent when item will be added
\param item item that will be added
\param index index of item
*/
void willAddItem(libgotvptop_media_t *item,
int index);
/*!
\brief Signal sent on item deleted
\param item item that was added
\param index index of item
*/
void itemDeleted(libgotvptop_media_t *item,
int index);
/*!
\brief Signal sent when item will be deleted
\param item item that will be deleted
\param index index of item
*/
void willDeleteItem(libgotvptop_media_t *item,
int index);
private:
void lock();
void unlock();
static void libgotvptop_callback(const libgotvptop_event_t *event,
void *data);
void createCoreConnections();
void removeCoreConnections();
libgotvptop_media_list_t *_gotvptopMediaList;
libgotvptop_event_manager_t *_gotvptopEvents;
QList<GoTvPtoPMedia *> _list;
};
#endif // GOTVQT_MEDIALIST_H_
|
import { useEffect, useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import Loader from "../components/Loader";
import useDisplay from "../hooks/useDisplay";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
// Definición de los tipos de entrada para el formulario
type IDisplayInputs = {
name: string;
description: string;
price_per_day: number;
resolution_height: number;
resolution_width: number;
type: string;
};
// Enumeración de los posibles estados del formulario
const FORM_STATUS = {
IDLE: "idle",
UPLOADING: "uploading",
ERROR: "error",
} as const;
// Definición del tipo de datos para el estado del formulario
type StatusType = (typeof FORM_STATUS)[keyof typeof FORM_STATUS];
function FormDisplayPage() {
// Estado del formulario y funciones para manejarlo
const [formStatus, setFormStatus] = useState<StatusType>(FORM_STATUS.IDLE);
const {
register,
handleSubmit,
formState: { errors },
setValue,
} = useForm<IDisplayInputs>();
const { createDisplay, isCreated, getDisplayBy, updateDisplay, isUpdated } = useDisplay();
const navigate = useNavigate();
const params = useParams();
// Efecto para cargar los datos de visualización si se está editando
useEffect(() => {
async function loadDisplay() {
setFormStatus(FORM_STATUS.UPLOADING);
if (params.id) {
const dis: any = await getDisplayBy(Number(params.id));
setValue("name", dis.name);
setValue("description", dis.description);
setValue("price_per_day", dis.price_per_day);
setValue("resolution_height", dis.resolution_height);
setValue("resolution_width", dis.resolution_width);
setValue("type", dis.type);
}
setFormStatus(FORM_STATUS.IDLE);
}
loadDisplay();
}, []);
// Efectos para redirigir después de crear o actualizar una visualización
useEffect(() => {
if (isCreated || isUpdated) {
navigate("/display");
toast.success(`La pantalla fue ${isCreated ? 'creada' : 'actualizada'}`);
}
}, [isCreated, isUpdated]);
// Función de envío del formulario
const onSubmit: SubmitHandler<IDisplayInputs> = async (values) => {
setFormStatus(FORM_STATUS.UPLOADING);
if (params.id) {
await updateDisplay(values, Number(params.id))
} else {
await createDisplay(values);
}
};
return (
<div className="flex flex-col items-center justify-center p-6 h-[calc(100vh-5.1rem)]">
<div className="flex justify-between relative bg-neutral-100 rounded-xl w-96 max-w-full px-6 py-2 shadow-lg">
{/* Formulario */}
<form
onSubmit={handleSubmit(onSubmit)}
className="flex flex-col gap-4 w-full p-2"
>
<h3 className="text-xl text-sky-700 text-center font-bold">
Añadir Pantalla
</h3>
{/* Campos del formulario - Nombre */}
<label className="relative border border-sky-600 rounded">
<span className="absolute left-2 -translate-y-1/2 pointer-events-none rounded px-1 bg-sky-600 shadow text-neutral-100">
Nombre
</span>
<input
{...register("name", { required: true })}
id="name-display"
placeholder="Nombre de la pantalla"
type="text"
className="w-full border-0 bg-neutral-100 rounded text-sky-800 p-3 focus:outline-0 placeholder:text-sky-400"
/>
</label>
{errors.name && (
<p className="text-xs text-center text-red-500 -mt-4">
*Debe ingresar un nombre para la pantalla
</p>
)}
{/* Campos del formulario - Descripcion */}
<label className="relative border border-sky-600 rounded">
<span className="absolute left-2 -translate-y-1/2 pointer-events-none rounded px-1 bg-sky-600 shadow text-neutral-100">
Descripción
</span>
<textarea
{...register("description", { required: true })}
id="description-display"
placeholder="Descripción de la pantalla"
className="w-full border-0 bg-neutral-100 rounded text-sky-800 p-3 focus:outline-0 placeholder:text-sky-400"
/>
</label>
{errors.description && (
<p className="text-xs text-center text-red-500 -mt-4">
*Debe ingresar una descripción para la pantalla
</p>
)}
{/* Campos del formulario - Precio y tipo */}
<div className="flex flex-col md:flex-row gap-4 md:gap-2">
<label className="relative border border-sky-600 rounded w-full md:w-1/2">
<span className="absolute left-2 -translate-y-1/2 pointer-events-none rounded px-1 bg-sky-600 shadow text-neutral-100">
Precio
</span>
<input
{...register("price_per_day", { required: true })}
id="price-per-day-display"
placeholder="Precio por día"
type="number"
min="0"
className="w-full border-0 bg-neutral-100 rounded text-sky-800 p-3 focus:outline-0 placeholder:text-sky-400"
/>
</label>
{errors.price_per_day && (
<p className="text-xs text-center text-red-500 -mt-4 block md:hidden">
*Debe ingresar un precio por día
</p>
)}
<label className="relative border border-sky-600 rounded w-full md:w-1/2">
<span className="absolute left-2 -translate-y-1/2 pointer-events-none rounded px-1 bg-sky-600 shadow text-neutral-100">
Tipo
</span>
<select
{...register("type", { required: true })}
id="type-display"
className="w-full border-0 bg-neutral-100 rounded text-sky-800 p-3 focus:outline-0 placeholder:text-sky-400"
>
<option disabled hidden selected value="">
Seleccionar Tipo
</option>
<option value="indoor">Interior</option>
<option value="outdoor">Exterior</option>
</select>
</label>
</div>
{errors.price_per_day && (
<p className="text-xs text-center text-red-500 -mt-4 hidden md:block">
*Debe ingresar un precio por día en números enteros
</p>
)}
{errors.type && (
<p className="text-xs text-center text-red-500 -mt-4">
*Debe ingresar un tipo para la pantalla
</p>
)}
{/* Campos del formulario - Resolucion en alto y ancho */}
<div className="flex gap-2">
<label className="relative border border-sky-600 rounded">
<span className="absolute left-2 -translate-y-1/2 pointer-events-none rounded px-1 bg-sky-600 shadow text-neutral-100">
Alto
</span>
<input
{...register("resolution_height", { required: true })}
id="resolution-height-display"
placeholder="Alto de resolución"
type="number"
className="w-full border-0 bg-neutral-100 rounded text-sky-800 p-3 focus:outline-0 placeholder:text-sky-400"
/>
</label>
<label className="relative border border-sky-600 rounded">
<span className="absolute left-2 -translate-y-1/2 pointer-events-none rounded px-1 shadow bg-sky-600 text-neutral-100">
Ancho
</span>
<input
{...register("resolution_width", { required: true })}
id="resolution-width-display"
placeholder="Ancho de resolución"
type="number"
className="w-full border-0 bg-neutral-100 rounded text-sky-800 p-3 focus:outline-0 placeholder:text-sky-400"
/>
</label>
</div>
{(errors.resolution_height || errors.resolution_width) && (
<p className="text-xs text-center text-red-500 -mt-4">
*Debe ingresar la resolución en ancho y alto para la pantalla
</p>
)}
{/* Botón de envío */}
{formStatus === FORM_STATUS.IDLE && (
<button
type="submit"
className="flex text-neutral-100 bg-sky-700 font-bold uppercase rounded py-3 justify-center shadow-lg"
>
{params.id ? "Actualizar" : "Añadir"}
</button>
)}
{/* Indicador de carga */}
{formStatus === FORM_STATUS.UPLOADING && <Loader />}
</form>
</div>
</div>
);
}
export default FormDisplayPage;
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
body {
font-size: 12px;
margin: 20px;
}
.p1 {
/*em相对于父元素字体大小而改变*/
width: 300px;
font-size: 16px;
text-indent: 2em;
/*两端对齐,仅限于多行时*/
text-align: justify;
/*文字溢出*/
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
/*text-shadow: 4px 4px 4px #D30408,
4px 4px 4px #0000FF;*/
}
/*多行溢出*/
.p2 {
overflow: hidden;
/*条件1:超出部分隐藏*/
text-overflow: ellipsis;
/*条件2:超出部分显示。。。*/
display: -webkit-box;
/*条件3:设置为伸缩盒*/
-webkit-line-clamp: 2;
/*这是要显示的行数*/
-webkit-box-orient: vertical;
/*设置排版方向为从上到下*/
width: 300px;
}
.box {
width: 100px;
height: 100px;
background: red;
box-shadow: 0 0 10px #017FCB;
}
/*画一朵云*/
.box1 {
margin: 60px;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: #ccc;
box-shadow: -11px -18px 0 #ccc,
20px -2px 0 #ccc,
17px -20px 0 #c52d2d;
}
</style>
</head>
<body>
<!--
1、段落缩进: text-indent
2、段落对齐: text-align : left | right | center | justify
3、文字溢出
- 单行溢出:
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
-->
<p class="p1">
北京时间25日凌晨,国际足联年度颁奖典礼在英国伦敦举行。在最后的压轴大戏中,莫德里奇击败C罗和萨拉赫,荣膺本年度世界足球先生!这是克罗地亚人首次获得世界足球先生称号。此外,莫德里奇的当选也打破了梅罗对此奖项长达10年的统治。
</p>
<p class="p2">
正所谓“所有的成功都不是偶然的”,真的需要千锤百炼的磨砺。资质平庸的人想获得巨大的成功,则更需要通过严酷的环境去磨砺,让我们平庸的身体能够得到蜕变。而这样的蜕变也让大器晚成的莫德里奇率领着克罗地亚国家队以黑马的姿态一举杀到了世界杯决赛的赛场,也最终让这位克罗地亚球星在33岁这样的年纪拿到了FIFA世界足球先生这样的殊荣。在此,搜狐体育也为您带来了关于莫德里奇的成长之路,我们一起来看看这位球星是如何从战争的炮火中一步步走来的。
</p>
<div class="box">
</div>
<div class="box1">
</div>
</body>
</html>
|
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const morgan = require('koa-morgan')
var path = require('path')
var fs = require('fs')
const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const { REDIS_CONF } = require('./conf/db')
const index = require('./routes/index')
const users = require('./routes/users')
const user = require('./routes/user')
const blog = require('./routes/blog')
// error handler
onerror(app)
const ENV = process.env.NODE_ENV
// app.use(
// logger('dev', {
// stream: process.stdout,
// })
// )
if (ENV !== 'production') {
// 开发、测试环境
app.use(morgan('dev'))
} else {
// 线上环境
const logFileName = path.join(__dirname, 'logs', 'access.log')
const wirteStream = fs.createWriteStream(logFileName, {
flags: 'a',
})
app.use(
morgan('combined', {
stream: wirteStream,
})
)
}
// middlewares
app.use(
bodyparser({
enableTypes: ['json', 'form', 'text'],
})
)
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(
views(__dirname + '/views', {
extension: 'pug',
})
)
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.keys = ['weh343#_343']
app.use(
session({
// 配置cookie
cookie: {
path: '/',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000,
},
//配置redis
store: redisStore({
// all: '127.0.0.1:6379', // 写死本地redis
all: `${REDIS_CONF.host}:${REDIS_CONF.port}`,
}),
})
)
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(user.routes(), user.allowedMethods())
app.use(blog.routes(), blog.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
})
module.exports = app
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.