text
stringlengths 184
4.48M
|
---|
1. Produce an STL decomposition as follows
```r
us_construction <- us_employment |>
filter(Title == "Construction", year(Month) > 1980)
dcmp <- us_construction |>
model(stl = STL(Employed ~ trend(window = 9) + season(window = 11)))
dcmp |> components() |> autoplot()
```
2. What happens as you change the values of the two `window` arguments?
3. How does the seasonal shape change over time? *[Hint: Try plotting the seasonal component using `gg_season`.]*
4. Can you produce a plausible seasonally adjusted series? *[Hint: `season_adjust` is returned by `components()`.]*
|
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>HTML5 Inputs</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
#fillall{
background-color: aqua;
}
#rtl, #ltr,#paragrafo1,#sim{
background-color: blue;
color:white;
}
#hidden-true,#hidden-false,#paragrafo2,#nao{
background-color: red;
color:white;
}
#spellcheck-true,#spellcheck-false,#paragrafo3{
background-color: green;
color:white;
}
#tecla-aviso{
font-weight: 900;
background-color: black;
color:whitesmoke;
font-size: 20px;
}
#bloco{
background-color: darkgray;
}
</style>
</head>
<body contextmenu="share"> <!-- o valor do contextmenu, deve bater com o ID do menu. -->
<!--
O menu de contexto esta obsoleto e deixando de ser usando nos navegadores
mais novos, entao pode nao funcionar da maneira almejada.
-->
<menu type="context" id="share"> <!-- repare que o ID bate com o atributo contextmenu do body.-->
<menu label="share">
<menuitem label="MenuExemplo1" valor="1"></menuitem>
<menuitem label="MenuExemplo2" valor="2"></menuitem>
</menu>
</menu>
<div id="fillall">
<span id="tecla-aviso">Pressione a Tecla "ALT+Q" para que o input tenha foco.</span> <br />
<!--
Aqui temos um exemplo de como funciona os atributos do campo input.
dir => se "ltr" (Padrão, texto da esquerda para a direita).
dir => se "rtl" (texto da direita para a esquerda).
hidden => (true) => oculta o elemento, (false, padrão) => exibe o elemento.
spellcheck => (true ou false) => Habilita e desabilita corretor ortografico,
esse corretor ortografico faz a verificacao quando o usuario digita o valor
do input nesse exemplo de input.
accesskey => aqui voce informa o caracter que o usuario deve usar para que
esse elemento tenha foco, no caso do input abaixo, isso acontece quando
pressionado a tecla "ALT+Q", porem apenas o q eh informado, ficando subentendido
assim que voce precisa pressiona-lo na compania do "ALT".
-->
<input type="text" dir="ltr" id="inputExemplo" placeholder="Exemplo de Texto"
spellcheck="true" accesskey="q"
/>
<input id="rtl" type="button" onclick="IsSettingRtl(true,input)"/ value="DIR = 'RTL'" title="Ao clicar o texto do input sera alinhado a direita">
<input id="ltr" type="button" onclick="IsSettingRtl(false,input)" value="DIR = 'LTR'" title="Ao clicar o texto do input sera alinhado a esquerda">
<input id="hidden-true" type="button" onclick="Ishidden(true,input)" value="HIDDEN = 'TRUE'" title="Ao clicar o elemento sera ocultado">
<input id="hidden-false" type="button" onclick="Ishidden(false,input)" value="HIDDEN = 'FALSE'" title="Ao clicar o elemento sera revelado">
<input id="spellcheck-true" type="button" onclick="IsSpellcheck(true,input)" value="SPELLCHECK = 'TRUE'" title="Habilita o corretor ortografico do input">
<input id="spellcheck-false" type="button" onclick="IsSpellcheck(false,input)" value="SPELLCHECK = 'FALSE'" title="Desabilita o corretor ortografico do input">
</div>
<div id="bloco">
<!--
contenteditable pode aceitar 3 valores: true, false ou inherit, se true,
permite que o usuario consiga editar o texto no navegador, se false, desabilita.
ja "inherit" habilita ou desabilita de acordo com o valor contenteditable do atributo
pai. Se o atributo pai tiver true ele assume verdadeiro, caso contrario false, tudo
depende do valor do no pai.
-->
<p contenteditable="true" id="paragrafo1">ELEMENTO 1 PODE SER EDITADO SEMPRE (DUPLO CLIQUE PARA EDITAR)</p>
<p contenteditable="false" id="paragrafo2">ELEMENTO 2 NÃO PODE SER EDITADO (TENTE DAR O DUPLO CLIQUE E VEJA)</p>
<p contenteditable="inherit" id="paragrafo3">ELEMENTO 3 PODE SER EDITADO DEPENDENDO DA DIV PAI (DEPENDE DO BOTAO QUE VOCE APERTAR, COM O SIM EDITE VOCE CONSEGUE EDITAR)</p>
<input type="button" value="SIM EDITE!" id="sim" onclick="contentEditabe(true)"/>
<input type="button" value="NAO EDITE!" id="nao" onclick="contentEditabe(false)"/>
</div>
<script>
//Bloco do input
const input = document.getElementById("inputExemplo");
/*
Uma vez que voce tenha pego o elemento, "via getElment"
ou "getElements" voce podera por os atributos direto no
elmento, por exemplo, aqui pegamos um "input" e colocamos
na variavel "input" via javascript, nesse caso por exemplo:
"input.dir = 'rtl ou ltr'" ou "input.hidden = 'true ou false'"
*/
function IsSettingRtl(isTrue,element){
//Aqui colocaremos um atributo no dir de acordo com o botao apertado.
if(isTrue){
element.dir = "rtl";
}else{
element.dir = "ltr";
}
}
function Ishidden(isTrue,element){
//Aqui deixamos o hidden verdadeiro ou falso. Nao use o hidden se quiser
//que o elemento seja exibido.
if(isTrue){
element.hidden = true;
}else{
element.hidden = false;
}
}
function IsSpellcheck(isTrue,element){
//Aqui deixamos o spellcheck verdadeiro ou falso. Nao use o hidden se quiser
if(isTrue){
element.spellcheck = true;
}else{
element.spellcheck = false;
}
}
function contentEditabe(isTrue){
const bloco = document.getElementById("bloco");
if(isTrue){
bloco.contentEditable = "true";
}else{
bloco.contentEditable = "false";
}
}
</script>
</body>
</html>
|
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const APIKEY = process.env.REACT_APP_API_KEY;
export const TopSeriesAPIFUNC = createAsyncThunk(
"TopSeriesInitialState/GetTopSeries",
async function (Paggination) {
const response = await axios.get(
`https://api.themoviedb.org/3/tv/top_rated?${APIKEY}&include_adult=false&language=en-US&page=${Paggination}`
);
console.log(response);
return response;
}
);
const TopSeriesSlice = createSlice({
name: "TopSeriesInitialState",
initialState: {
APIDATA: [],
isLoading: true,
},
/// Third Phase =>(ExtraReducers)<= for Login Handling ///////
/// with 3 condetions to handle =>(Fulfilled , rejected ,Pending)////
extraReducers: function (builder) {
builder.addCase(TopSeriesAPIFUNC.pending, function (PrevState, Action) {
PrevState.isLoading = true;
});
builder.addCase(TopSeriesAPIFUNC.fulfilled, function (prevstate, Action) {
prevstate.isLoading = false;
prevstate.APIDATA = Action.payload.data;
console.log(Action.payload.data.results);
});
},
});
export const TopSeriresReducer = TopSeriesSlice.reducer;
|
@if (data(); as data) {
<app-card-simple icon="location_on" [title]="title()">
@if(imgUrl(); as img) {
<img priority class="-ml-8" [ngSrc]="img" alt="image" width="150" height="150">
}
<p class="font-normal text-4xl text-slate-500 dark:text-white">{{ data?.main?.temp | number: '1.1-1' }}
<span>°C</span>
</p>
<p class="font-normal capitalize text-slate-500 dark:text-white">
{{ data?.weather?.description }}
</p>
<hr class="h-px my-8 bg-gray-200 border-0 dark:bg-gray-200">
<div class="flex space-y-2 flex-col lg:space-y-4">
<div class="flex items-center space-x-1 lg:space-y-2">
<mat-icon aria-hidden="false" aria-label="Example home icon"
class="text-slate-900 dark:text-slate-500">device_thermostat</mat-icon>
<p class=" font-light tracking-tight text-slate-900 dark:text-white text-sm lg:text-base">Feels like {{ data.main.feels_like | number:
'1.1-1' }} <span>°C</span></p>
</div>
<div class="flex items-center space-x-2">
<mat-icon aria-hidden="false" aria-label="Example home icon"
class="text-slate-900 dark:text-slate-500">local_fire_department</mat-icon>
<p class=" font-light tracking-tight text-slate-900 dark:text-white text-sm lg:text-base">Max Temp {{ data.main.temp_max | number:
'1.1-1' }} <span>°C</span></p>
</div>
<div class="flex items-center space-x-2">
<mat-icon aria-hidden="false" aria-label="Example home icon"
class="text-slate-900 dark:text-slate-500">ac_unit</mat-icon>
<p class=" font-light tracking-tight text-slate-900 dark:text-white text-sm lg:text-base">Min Temp {{ data.main.temp_min | number:
'1.1-1' }} <span>°C</span></p>
</div>
<div class="flex items-center space-x-2">
<mat-icon aria-hidden="false" aria-label="Example home icon"
class="text-slate-900 dark:text-slate-500">today</mat-icon>
<p class=" font-light tracking-tight text-slate-900 dark:text-white text-sm lg:text-base">{{ today() | date }}</p>
</div>
<div class="flex items-center space-x-2">
<mat-icon aria-hidden="false" aria-label="Example home icon"
class="text-slate-900 dark:text-slate-500">schedule</mat-icon>
<p class=" font-light tracking-tight text-slate-900 dark:text-white text-sm lg:text-base">{{ today()| date:'shortTime' }}</p>
</div>
</div>
</app-card-simple>
}
|
part of 'paged_datatable.dart';
/// A Row renderer that uses two lists for two directional scrolling
class _DoubleListRows<K extends Comparable<K>, T> extends StatefulWidget {
final List<ReadOnlyTableColumn> columns;
final ScrollController horizontalController;
final int fixedColumnCount;
final PagedDataTableController<K, T> controller;
final PagedDataTableConfiguration configuration;
final List<double> sizes;
final Widget? prototypeItem;
final double? cacheExtent;
const _DoubleListRows({
required this.columns,
required this.fixedColumnCount,
required this.horizontalController,
required this.controller,
required this.configuration,
required this.sizes,
this.prototypeItem,
this.cacheExtent,
});
@override
State<StatefulWidget> createState() => _DoubleListRowsState<K, T>();
}
class _DoubleListRowsState<K extends Comparable<K>, T>
extends State<_DoubleListRows<K, T>> {
final scrollControllerGroup = LinkedScrollControllerGroup();
late final fixedController = scrollControllerGroup.addAndGet();
late final normalController = scrollControllerGroup.addAndGet();
late _TableState state;
@override
void initState() {
super.initState();
state = widget.controller._state;
widget.controller.addListener(() {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
final theme = PagedDataTableTheme.of(context);
return DefaultTextStyle(
style: theme.cellTextStyle,
child: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: Opacity(
opacity: widget.controller._state == _TableState.idle ? 1 : 0.5,
child: Scrollbar(
thumbVisibility: theme.verticalScrollbarVisibility,
controller: normalController,
child: Row(
children: [
SizedBox(
width: widget.sizes
.take(widget.fixedColumnCount)
.fold(0.0, (a, b) => a! + b),
child: ListView.builder(
primary: false,
controller: fixedController,
itemCount: widget.controller._totalItems,
prototypeItem: widget.prototypeItem ??
(widget.controller._totalItems > 0
? _FixedPartRow<K, T>(
index: 0,
fixedColumnCount: widget.fixedColumnCount,
sizes: widget.sizes,
columns: widget.columns,
)
: null),
cacheExtent: widget.cacheExtent,
itemBuilder: (context, index) => _FixedPartRow<K, T>(
index: index,
fixedColumnCount: widget.fixedColumnCount,
sizes: widget.sizes,
columns: widget.columns,
),
),
),
Expanded(
child: Scrollbar(
thumbVisibility: theme.horizontalScrollbarVisibility,
controller: widget.horizontalController,
child: ListView(
controller: widget.horizontalController,
scrollDirection: Axis.horizontal,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: widget.sizes
.skip(widget.fixedColumnCount)
.fold(0.0, (a, b) => a + b),
),
child: ListView.builder(
controller: normalController,
itemCount: widget.controller._totalItems,
prototypeItem: widget.prototypeItem ??
(widget.controller._totalItems > 0
? _VariablePartRow<K, T>(
sizes: widget.sizes,
index: 0,
fixedColumnCount:
widget.fixedColumnCount,
columns: widget.columns,
)
: null),
cacheExtent: widget.cacheExtent,
itemBuilder: (context, index) =>
_VariablePartRow<K, T>(
sizes: widget.sizes,
index: index,
fixedColumnCount: widget.fixedColumnCount,
columns: widget.columns,
),
),
),
],
),
),
),
],
),
),
),
),
);
}
@override
void dispose() {
super.dispose();
normalController.dispose();
fixedController.dispose();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class TrackCheckpoints : MonoBehaviour
{
[Tooltip("List of player transforms. This is used to track what checkpoints players go through.")]
[SerializeField] private List<Transform> racerTransformList;
[Header("Laps to Complete")]
public int lapsToComplete = 4;
[Header("Player Laps Reference")]
[SerializeField] private Laps playerOneLaps;
[SerializeField] private Laps playerTwoLaps;
[Header("Unity Event")]
[SerializeField] private UnityEvent SpawnFinishLine;
private List<CheckpointSingle> checkpointSingleList;
private List<int> nextCheckpointSingleIndexList;
private void Awake()
{
// finding the container object with the checkpoints inside of it
Transform checkpointsTransform = transform.Find("Checkpoints");
checkpointSingleList = new List<CheckpointSingle>();
foreach (Transform checkpointSingleTransform in checkpointsTransform)
{
// grabbing the component
CheckpointSingle checkpointSingle = checkpointSingleTransform.GetComponent<CheckpointSingle>();
// calling a function SetTrackCheckpoints and calling this script
checkpointSingle.SetTrackCheckpoints(this);
// adding all the checkpoint to the list
checkpointSingleList.Add(checkpointSingle);
}
nextCheckpointSingleIndexList = new List<int>();
foreach (Transform racerTransfrom in racerTransformList)
{
nextCheckpointSingleIndexList.Add(0);
}
}
// grabbing the checkpoint the player goes through
public void RacerThroughCheckpoint(CheckpointSingle checkpointSingle, Transform racerTransform)
{
int nextCheckpointSingleIndex = nextCheckpointSingleIndexList[racerTransformList.IndexOf(racerTransform)];
// checking if the index of the list is equal to the next checkpoint, EX: index 0 == 0, index 1 == 1
if (checkpointSingleList.IndexOf(checkpointSingle) == nextCheckpointSingleIndex)
{
// correct checkpoint
// % returns the remainder of the divsison
// next checkpoint is equal to the index plus 1 and the remainder of the list of checkpoints
// loops back to zero after going through all the checkpoints
nextCheckpointSingleIndexList[racerTransformList.IndexOf(racerTransform)] = (nextCheckpointSingleIndex + 1) % checkpointSingleList.Count;
// last checkpoint in the list
if (nextCheckpointSingleIndex == checkpointSingleList.Count - 1)
{
if(racerTransform.name == "PlayerOne")
{
playerOneLaps.laps++;
}
if (racerTransform.name == "PlayerTwo")
{
playerTwoLaps.laps++;
}
// either player have complete the total amount of laps, spawn the finishline
if (playerOneLaps.laps == lapsToComplete || playerTwoLaps.laps == lapsToComplete)
SpawnFinishLine.Invoke();
}
Debug.Log("Correct: " + racerTransform);
}
else
{
// wrong checkpoint
Debug.Log("Wrong");
}
}
}
|
import { useState, useEffect } from 'react'
import axios from 'axios'
import Filter from './components/Filter'
import Form from './components/Form'
import Persons from './components/Persons'
import Notification from './components/Notification'
import personService from './services/persons'
const App = () => {
const [persons, setPersons] = useState([])
const [newName, setNewName] = useState('')
const [newNumber, setNewNumber] = useState('')
const [filter, setFilter] = useState('')
const [successMessage, setSuccessMessage] = useState(null)
const [errorMessage, setErrorMessage] = useState(null)
useEffect(() => {
console.log('effect')
personService
.getAll()
.then(initialPersons => {
setPersons(initialPersons)
})
}, [])
const addName = (event) => {
event.preventDefault()
const personObject = {
name: newName,
number: newNumber
}
const allNames = persons.map(person => person.name)
if(allNames.includes(newName)) {
if (window.confirm(`${newName} is already added to phonebook, replace the old number with a new one?`)) {
const person = persons.find(n => n.name === newName)
const changedPerson = { ...person, number: newNumber }
personService
.update(person.id, changedPerson)
.then(returnedPerson => {
setPersons(persons.map(person => person.id !== changedPerson.id ? person : returnedPerson))
setNewName('')
setNewNumber('')
setSuccessMessage(
`${changedPerson.name}'s number changed`
)
setTimeout(() => {
setSuccessMessage(null)
}, 5000)
})
.catch(() => {
setErrorMessage(
`Information of ${changedPerson.name} has already been removed from the server`
)
setTimeout(() => {
setErrorMessage(null)
}, 5000)
})
}
return
}
personService
.create(personObject)
.then(returnedPerson => {
setPersons(persons.concat(returnedPerson))
setNewName('')
setNewNumber('')
setSuccessMessage(
`Added ${returnedPerson.name}`
)
setTimeout(() => {
setSuccessMessage(null)
}, 5000)
})
}
const handleNameChange = (event) => {
console.log(event.target.value)
setNewName(event.target.value)
}
const handleNumberChange = (event) => {
console.log(event.target.value)
setNewNumber(event.target.value)
}
const handleFilterChange = (event) => {
console.log(event.target.value)
setFilter(event.target.value)
}
const toggleDeletionOf = person => {
if (window.confirm(`Delete ${person.name} ?`)){
personService
.remove(person.id)
.then(response => {
console.log(response)
setPersons(persons.filter(n => n.id !== person.id))
})
.catch (error => {
console.log(error)
})
}
}
const personsToShow = filter === ''
? persons
: persons.filter(person =>
person.name.toLowerCase().includes(filter.toLowerCase()))
return (
<div>
<h2>Phonebook</h2>
<Notification message={successMessage} className={'success'}/>
<Notification message={errorMessage} className={'error'}/>
<Filter value={filter} onChange={handleFilterChange}/>
<h3>add a new</h3>
<Form onSubmit={addName} nameValue ={newName} nameChange={handleNameChange} numberValue={newNumber} numberChange={handleNumberChange}/>
<h3>Numbers</h3>
<Persons persons={personsToShow} toggle={toggleDeletionOf}/>
</div>
)
}
export default App
|
<template>
<div class="designiy-image-sticker">
<div class="designiy-image-sticker-header">
<el-input v-model="input" placeholder="搜索贴纸">
<template #prefix>
<el-icon><Search /></el-icon>
</template>
<template #suffix>
<el-icon><Operation /></el-icon>
</template>
</el-input>
</div>
<div
class="designiy-image-sticker-content"
v-infinite-scroll="scroll"
:infinite-scroll-distance="150"
:infinite-scroll-disabled="disabled || loading"
>
<div class="item" title="拖动来进行贴图" v-for="i in list" draggable="false">
<el-image
@load="load($event, i)"
:src="i.preview_img"
style="width: 100%; height: 100%"
fit="contain"
lazy
>
<template #placeholder>
<div class="item_loading"></div>
</template>
<template #error>
<div class="item_error">
<el-icon style="color: #888"><Picture /></el-icon>
</div>
</template>
</el-image>
</div>
</div>
<div class="designiy-image-sticker-footer">
<el-button type="pirmary" @click="showImageUplaod = true"> 上传图片 </el-button>
</div>
</div>
</template>
<script setup>
import { onMounted, ref, computed } from "vue";
import {
currentController,
} from "../../store";
import {
Picture,
FolderOpened,
Search,
Operation,
} from "@element-plus/icons-vue";
import { getImage } from "@/api/index";
import { initDraggableElement } from "../../utils/draggable";
import { showImageUplaod, showDecalControl } from "../../store";
import {
imgToFile,
createImgObjectURL,
imgToBase64,
} from "@/common/transform/index";
const input = ref()
const list = ref([]);
// image load success
function load(e, info) {
const img = e.target;
initDraggableElement(
img,
() => {
const src = createImgObjectURL(img);
const base64 = imgToBase64(img);
currentController.value.stickToMousePosition({
img: img,
type: "image",
local: false,
src: src,
...info,
base64: base64,
});
showDecalControl.value = true;
}
);
}
const page = ref(1);
const disabled = ref(false);
const pages = ref();
const loading = ref(false);
async function scroll() {
if (page.value > pages.value) {
return;
}
loading.value = true;
const res = await getImage({
page: page.value++,
});
if (!res.list.length) {
disabled.value = true;
return false;
}
pages.value = res.pages;
list.value = list.value.concat(res.list);
loading.value = false;
}
</script>
<style lang="less">
.designiy-image-sticker {
width: 300px;
height: 100%;
display: flex;
flex-direction: column;
}
.designiy-image-sticker-header {
padding: 10px;
display: flex;
flex-direction: column;
row-gap: 10px;
.el-input__wrapper {
box-shadow: none;
background-color: #f6f6f6;
font-size: 12px;
}
.el-cascader {
width: 100%;
}
}
.designiy-image-sticker-content {
flex: 1;
display: flex;
flex-wrap: wrap;
overflow: auto;
justify-content: space-between;
padding:10px;
column-gap: 4px;
row-gap: 4px;
.el-image {
display: block;
}
}
.designiy-image-sticker-footer {
width: 100%;
padding: 10px;
button {
width: 100%;
}
}
.item {
width: calc(50% - 2px);
height: 100px;
background-color: var(--1s-image-sticker-image-background-color);
border-radius: 4px;
overflow: hidden;
cursor: pointer;
&_loading {
width: 100%;
height: 100%;
list-style: none;
background-image: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
background-size: 400% 100%;
background-position: 100% 50%;
animation: skeleton-loading 1.4s ease infinite;
}
&_error {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
}
@keyframes skeleton-loading {
0% {
background-position: 100% 50%;
}
100% {
background-position: 0 50%;
}
}
@keyframes rolling {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
|
package main
import (
"encoding/json"
"flag"
"log"
"os"
"os/exec"
"regexp"
"strings"
)
type file struct {
Path string
TargetPath string
}
type config struct {
Files []file
VariableRegex string
RegexGroup int
ForceOverwrite bool
UpdateUID bool
User string
UIDVariable string
UpdateGID bool
Group string
GIDVariable string
RunBefore [][]string
}
const defaultVariableRegex = `\$\{([a-zA-Z0-9_-]+)\}`
const defaultUIDVariable = "UID"
const defaultGIDVariable = "GID"
func loadConfig(path string) (*config, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var config config
err = json.Unmarshal(raw, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func filterFile(file file, regex regexp.Regexp, regexGroup int) error {
data, err := os.ReadFile(file.Path)
if err != nil {
return err
}
stat, err := os.Stat(file.Path)
if err != nil {
return err
}
text := string(data)
text = regex.ReplaceAllStringFunc(text, func(s string) string {
matches := regex.FindStringSubmatch(text)
return os.Getenv(matches[regexGroup])
})
err = os.WriteFile(file.TargetPath, []byte(text), stat.Mode())
if err != nil {
return err
}
return nil
}
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func filterFiles(config config) error {
var regexString string
if len(config.VariableRegex) == 0 {
regexString = defaultVariableRegex
} else {
regexString = config.VariableRegex
}
var regexGroup int
if config.RegexGroup == 0 {
regexGroup = 1
} else {
regexGroup = config.RegexGroup
}
log.Println("Regex is:", regexString)
regex, err := regexp.Compile(regexString)
if err != nil {
return err
}
for _, file := range config.Files {
if !config.ForceOverwrite {
exists, err := fileExists(file.TargetPath)
if err != nil {
return err
}
if exists {
log.Println("Skipping file:", file.Path, "->", file.TargetPath, "(already exists)")
continue
}
}
log.Println("Filtering file:", file.Path, "->", file.TargetPath)
err := filterFile(file, *regex, regexGroup)
if err != nil {
return err
}
}
return nil
}
func updateUID(config config) error {
uidVariable := config.UIDVariable
if len(uidVariable) == 0 {
uidVariable = defaultUIDVariable
}
newUID := os.Getenv(uidVariable)
if len(newUID) == 0 {
log.Println("UID variable is not set. Not updating UID")
return nil
}
log.Println("Updating UID of user", config.User)
cmd := exec.Command("usermod", "-u", newUID, config.User)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
return nil
}
func updateGID(config config) error {
gidVariable := config.GIDVariable
if len(gidVariable) == 0 {
gidVariable = defaultGIDVariable
}
newGID := os.Getenv(gidVariable)
if len(newGID) == 0 {
log.Println("GID variable is not set. Not updating GID")
return nil
}
log.Println("Updating GID of group", config.Group)
cmd := exec.Command("groupmod", "-g", newGID, config.Group)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
return nil
}
func main() {
configPath := flag.String("config", "config.json", "Path to config file")
force := flag.Bool("force", false, "Forcibly overwrite existing files (equivalent to setting forceOverwrite to true in the config)")
flag.Parse()
if flag.NArg() == 0 {
log.Fatal("Missing command")
}
config, err := loadConfig(*configPath)
if err != nil {
log.Fatalln("Failed to load config:", err)
}
config.ForceOverwrite = config.ForceOverwrite || *force
err = filterFiles(*config)
if err != nil {
log.Fatalln(err)
}
if config.UpdateUID {
err = updateUID(*config)
if err != nil {
log.Fatalln(err)
}
}
if config.UpdateGID {
err = updateGID(*config)
if err != nil {
log.Fatalln(err)
}
}
for _, command := range config.RunBefore {
log.Println(">", strings.Join(command, " "))
cmd := exec.Command(command[0], command[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
log.Fatalln(err)
}
}
command := flag.Args()
log.Println(">", strings.Join(command, " "))
cmd := exec.Command(command[0], command[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
log.Fatal("Error: ", err)
}
}
|
/// <reference types="Cypress" />
describe('Upload Page', () => {
it('successfully uploads a file', () => {
cy.intercept(
{
method: 'POST',
url: '/api/upload',
},{
"name": "file.csv",
"extension": "csv"
}
).as('UploadFile')
cy.visit('localhost:8888');
cy.get('input[type="file"]').selectFile({
contents: Cypress.Buffer.from('fake csv'),
fileName: 'file.csv'
});
cy.contains('Upload the file').click();
cy.contains('Upload is completed').should('be.visible');
});
it('unsuccessfully uploads a file', () => {
cy.intercept(
{
method: 'POST',
url: '/api/upload',
},
{statusCode: 500}
).as('UploadFile')
cy.visit('localhost:8888');
cy.get('input[type="file"]').selectFile({
contents: Cypress.Buffer.from('fake csv'),
fileName: 'file.csv'
});
cy.contains('Upload the file').click();
cy.contains('Failed to upload the file. Please try again later.').should('be.visible');
});
})
|
import React from "react";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import Card from "../../ui/Card";
export default function MyComponent(props) {
return (
<>
<Box margin="2rem 5rem 2rem 5rem" width="95%">
<Typography variant="h6" sx={{ textAlign: "left", fontWeight: 700 }}>
{props.materialType}
</Typography>
<Box
sx={{
width: "100%", // '100%
display: "flex",
flexDirection: "row",
alignItems: "center",
overflowY: "auto",
}}
>
{
props.materialType === "Books" ? props.books.map((item) => (
<Card key={item.id} data={item} title={"Books"} />
)) : props.materialType === "Videos" ? props.videos.map((item) => (
<Card key={item.id} data={item} title={"Videos"} />
)) : props.materialType === "Quizzes" ? props.quizzes.map((item) => (
<Card key={item.id} data={item} title={"Quizzes"} />
)): null
}
</Box>
</Box>
</>
);
}
|
## 11.3 inverse of R...
n <- 5;R <- qr.R(qr(matrix(runif(n*n),n,n))) ## get an R
Ri <- backsolve(R,diag(ncol(R))) ## solve R %*% Ri = I
range(R %*% Ri-diag(n)) ## check R %*% Ri = I
## 11.3 QQ^T = I and |A|=|A^T| so |Q|^2 = 1 => |Q|= +/-1
set.seed(0);n<-100; A <-matrix(runif(n*n),n,n)
R <- qr.R(qr(A))
prod(abs(diag(R)))
determinant(A,log=FALSE)
A <-A*1000
R <- qr.R(qr(A))
prod(abs(diag(R))) ## overflow
determinant(A,log=FALSE) ## overflow
sum(log(abs(diag(R)))) ## fine
determinant(A) ## fine
## 11.5.1
X <- sweep(as.matrix(iris[,1:4]),2,colMeans(iris[,1:4])) ## column centred data matrix
V <- t(X)%*%X/(nrow(X)-1) ## estimated covariance matrix
sd <- diag(V)^.5 ## standard deviation
C <- t(t(V/sd)/sd) ## form C=diag(1/sd)%*%V%*$diag(1/sd) efficiently
## Actually cor(iris[,1:4]) does the same!!
ec <- eigen(C) ## eigen decompose the correlation matrix
U <- ec$vectors;lambda <- ec$values ## exract eigenvectors and values
Z <- X %*% U; ## the principle co-ordinated
plot(Z[,1],Z[,2],col=c(1,2,4)[as.numeric(iris$Species)],main="iris PCA",
xlab="PCA 1",ylab="PCA 2") ## plot first two components
sum(lambda[1:2])/sum(lambda)
## ... first 2 components explain lower proportion than with cov based PCA
## 11.6 (X^TX)^{-1}^Ty = (VD^2V^T)^{-1}VDU^Ty=VD^{-2}V^TVDU^Ty = VD^{-1}U^Ty
X <- model.matrix(~group,PlantGrowth)
sx <- svd(X)
beta.hat <- sx$v%*%((t(sx$u)%*%PlantGrowth$weight)/sx$d)
beta.hat;coef(lm(weight~group,PlantGrowth))
|
import React, { useEffect, useState } from 'react';
import * as userService from '../services/user.service';
import { User } from '../types/types';
import { useDispatch, useSelector } from 'react-redux';
import { updateUser } from '../redux/user';
import { showNewAlert } from '../redux/alert';
import { useLocation, useNavigate } from 'react-router-dom';
import { RootState } from '../redux/store';
import Field from '../components/Field';
import Avatars from './Avatars/Avatars';
import { Box, Button, Grid, Typography, AlertColor } from '@mui/material';
import routes from '../utils/routes';
const RegisterProfile = () => {
const navigate = useNavigate();
const location = useLocation();
const storedUser = useSelector((state: RootState) => state.users);
const dispatch = useDispatch();
const [currUser, setCurrUser] = useState<User>(storedUser);
const [usernameChanged, setUsernameChanged] = useState(false);
const content = location.state?.message || 'Update your information';
const [usernameProps, setUsernameProps] = useState({
name: 'username',
label: 'Username',
isRequired: true,
isError: false,
helperText: '',
});
useEffect(() => {
if (location.state?.authUser && location.state.newUser === undefined) {
const { authUser } = location.state;
// New user
setCurrUser({
...currUser,
id: authUser.sub,
email: authUser.email,
newUser: true,
});
location.state.newUser = false;
} else {
setCurrUser(storedUser);
}
}, [storedUser]);
const usernameExists = async (username: string) => {
const result = await userService.getUserByUsername(username);
return !('error' in result);
};
async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const tmpCurrUser = { ...currUser };
const userKey = e.target.name as
| 'firstName'
| 'lastName'
| 'username'
| 'avatar';
tmpCurrUser[userKey] = e.target.value;
if (userKey === 'username') setUsernameChanged(true);
setCurrUser(tmpCurrUser);
}
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (usernameChanged && (await usernameExists(currUser.username))) {
// Username already exists
setUsernameProps({
...usernameProps,
isError: true,
helperText: 'Username already in use',
});
} else {
// Reset username error
setUsernameProps({
...usernameProps,
isError: false,
helperText: '',
});
let userFromDb;
let successMessage;
if (currUser.newUser) {
// Create user
userFromDb = await userService.createUser(currUser);
successMessage = 'Successfully created user';
} else {
// Update user
userFromDb = await userService.updateUser(currUser);
successMessage = 'Successfully updated user';
}
// Update user
dispatch(
updateUser({
...userFromDb,
newUser: false,
inCall: false,
})
);
// Refresh page
if (location.pathname === routes.school.url) {
navigate(0); // refresh page
} else {
navigate(routes.school.url);
}
// Show alert
dispatch(
showNewAlert({
message: successMessage,
severity: 'success' as AlertColor,
checked: true,
})
);
}
};
function getCommonInputProps() {
return {
handleChange: handleChange,
isRequired: true,
};
}
return (
<>
<div className="profile">
<div className="profile__content">
<Typography
variant="h4"
gutterBottom
>
My Profile
</Typography>
{content && (
<Typography
variant="subtitle1"
gutterBottom
>
{content}
</Typography>
)}
</div>
<div className="_form">
<Box
component="form"
autoComplete="off"
onSubmit={handleSubmit}
>
<Grid
container
spacing={3}
>
<Grid
item
xs={6}
>
<Field
{...getCommonInputProps()}
name="firstName"
label="First name"
value={currUser.firstName}
/>
</Grid>
<Grid
item
xs={6}
>
<Field
{...getCommonInputProps()}
name="lastName"
label="Last name"
value={currUser.lastName}
/>
</Grid>
<Grid
item
xs={6}
>
<Field
{...usernameProps}
value={currUser.username}
handleChange={handleChange}
/>
</Grid>
<Grid
item
xs={6}
>
<Field
{...getCommonInputProps()}
name="email"
label="Email"
value={currUser.email}
isDisabled={true}
helperText="Contact administrator to change"
/>
</Grid>
<Grid
item
xs={12}
>
<Typography
variant="subtitle1"
gutterBottom
align="left"
>
Choose avatar
</Typography>
<Avatars
valChecked={currUser.avatar}
handleChange={handleChange}
/>
</Grid>
<Grid
item
xs={12}
>
<Button
className="_btnCustom _form__field _form__field--submit"
type="submit"
variant="contained"
size="large"
>
Save
</Button>
</Grid>
</Grid>
</Box>
</div>
</div>
</>
);
};
export default RegisterProfile;
|
import { Autocomplete } from "@mui/material";
import style from './CharacterSearch.module.scss'
import searchIcon from '../../images/icons/search.icon.svg'
interface ICharacterSearchProps {
charactersNames: Array<string>
searchHandler: (value: string | null) => void
}
export function CharacterSearch({ charactersNames, searchHandler }: ICharacterSearchProps) {
return (
<Autocomplete
id="combo-box-demo"
className={style.search}
options={charactersNames}
onChange={(e, value) => {
searchHandler(value)
}}
renderInput={params => (
<div ref={params.InputProps.ref}>
<span {...params.InputLabelProps}>
<img src={searchIcon} /> Search:
</span>
<input {...params.inputProps} autoFocus />
</div>
)}
/>
)
}
|
import tkinter as tk
from tkinter import messagebox
from tkinter.font import Font
def show_message():
messagebox.showinfo("Привет", "Добро пожаловать в моё первое приложение с графическим интерфейсом!")
def change_label_text():
label.config(text="Текст метки изменён!")
def clear_label_text():
label.config(text="")
def submit():
input_text = entry.get()
if input_text:
messagebox.showinfo("Введённый текст", f"Вы ввели: {input_text}")
else:
messagebox.showwarning("Внимание", "Пожалуйста, введите текст!")
root = tk.Tk()
root.title("Моё первое приложение")
# Создаем объект шрифта Montserrat
montserrat_font = Font(family="Montserrat", size=12)
label = tk.Label(root, text="Нажмите кнопку для приветствия", padx=20, pady=20, font=montserrat_font)
label.pack()
button_hello = tk.Button(root, text="Приветствие", command=show_message, font=montserrat_font)
button_hello.pack()
button_change_text = tk.Button(root, text="Изменить текст метки", command=change_label_text, font=montserrat_font)
button_change_text.pack()
button_clear_text = tk.Button(root, text="Очистить текст метки", command=clear_label_text, font=montserrat_font)
button_clear_text.pack()
entry = tk.Entry(root, font=montserrat_font)
entry.pack()
button_submit = tk.Button(root, text="Отправить", command=submit, font=montserrat_font)
button_submit.pack()
root.mainloop()
|
import React, { useContext, useEffect, useState } from "react";
import {
Navbar,
NavbarBrand,
NavbarContent,
Image,
Button,
Progress,
useDisclosure,
} from "@nextui-org/react";
import { useForm } from "react-hook-form";
import axios from "axios";
import AES from "crypto-js/aes";
import encUtf8 from "crypto-js/enc-utf8";
import QuestionnairesContext from "../../../context/questionnaires";
import Questionnaires from "./Questionnaires";
import logoImg from "../../../assets/TrendMicroLogo.png";
import "./index.css";
import RoadmapModal from "./RoadmapModal";
import NoticeCard from "./NoticeCard";
export default function App() {
const bearer =
"U2FsdGVkX184KWZlLhP23BFZpa6WmeF6Hu8lGZ59yI5VZXMLh3t56/KBxUwwpBcoib7oWdSQsrzG45gY+KqTCI8ArUfMxuEQfUdJxwqk7CT1FK9y0HtBIPzx9RrKQcWD4JozdXeFqlGLrVlDEosEKJblC+FIbb5fDt5t+6Y98AM=";
const {
isOpen: isModalOpen,
onOpen: onModalOpen,
onClose: onModalClose,
} = useDisclosure();
const [submitLoading, setSubmitLoading] = useState(false);
const {
ctxValue: {
step,
maxStep,
key,
formId,
loading,
questions,
questionNo,
nextText,
},
setStep,
setQuestionsForm,
setPersonalForm,
} = useContext(QuestionnairesContext);
const questionsForm = useForm({});
const { getValues: getQuestionsFormValues, watch: questionsWatch } =
questionsForm;
const personalForm = useForm({});
const { getValues: getPersonalFormValues, watch: personalWatch } =
personalForm;
useEffect(() => {
setQuestionsForm(questionsForm);
setPersonalForm(personalForm);
}, [setQuestionsForm, questionsForm, setPersonalForm, personalForm]);
const handleNext = () => {
window.scrollTo({ top: 0, behavior: "smooth" });
setStep(step + 1);
};
const handlePrev = () => {
window.scrollTo({ top: 0, behavior: "smooth" });
setStep(step - 1);
};
const postQuestionnaires = async () => {
setSubmitLoading(true);
const bearerBytes = AES.decrypt(bearer, key);
const headers = {
"Content-Type": "application/json",
Authorization: bearerBytes.toString(encUtf8),
};
const postData = {
...getQuestionsFormValues(),
time: new Date().toISOString(),
formId,
};
await axios.post(
"https://api.github.com/repos/trendmicro/2023-tw-devops-days/dispatches",
{
event_type: "submit-request",
client_payload: {
questionnaires: JSON.stringify(postData),
},
},
{
headers: headers,
}
);
setSubmitLoading(false);
handleNext();
};
const postPersonalInfo = async () => {
setSubmitLoading(true);
const bearerBytes = AES.decrypt(bearer, key);
const headers = {
"Content-Type": "application/json",
Authorization: bearerBytes.toString(encUtf8),
};
const postData = {
...getPersonalFormValues(),
time: new Date().toISOString(),
formId,
};
await axios.post(
"https://api.github.com/repos/trendmicro/2023-tw-devops-days/dispatches",
{
event_type: "submit-request",
client_payload: {
users: JSON.stringify(postData),
},
},
{
headers: headers,
}
);
setSubmitLoading(false);
};
const handleSubmit = () => {
postPersonalInfo();
onModalOpen();
};
const disableNextButton = () => {
const answer = questionsWatch(`answer-${questionNo - 1}`);
if (Array.isArray(answer)) {
return answer.length <= 0;
} else {
return answer === "";
}
};
const disableFinishButton = () => {
const answer = personalWatch([
"name",
"email",
"company",
"getRecruitInfo",
]);
return answer.filter((value) => value !== "").length < 4;
};
const renderNextButton = () => {
switch (true) {
case step <= 0:
return (
<Button color="primary" variant="shadow" onClick={() => handleNext()}>
開始填寫
</Button>
);
case step <= maxStep - 2:
return (
<Button
color="primary"
variant="shadow"
isDisabled={disableNextButton()}
onClick={() => handleNext()}
>
{nextText}
</Button>
);
case step <= maxStep - 1:
return (
<Button
color="success"
variant="shadow"
isDisabled={disableNextButton()}
onClick={() => postQuestionnaires()}
isLoading={submitLoading}
>
查看結果
</Button>
);
case step === maxStep:
return (
<Button
color="success"
variant="shadow"
isDisabled={disableFinishButton()}
onClick={() => handleSubmit()}
isLoading={submitLoading}
>
完成
</Button>
);
default:
}
};
return (
<>
<Navbar className="flex max-md:px-3 navbar">
<NavbarBrand className="flex-none max-w-[150px]">
<div className="max-sm:w-[35px] max-sm:relative overflow-hidden logo-div">
<Image width={150} alt="Trend Micro" src={logoImg} />
</div>
</NavbarBrand>
<NavbarContent
className="grow justify-end md:justify-center"
justify="none"
>
<h1 className="text-2xl max-md:text-base font-bold text-inherit">
{step !== 0 ? "What's Your DevOps Story?" : ""}
</h1>
</NavbarContent>
</Navbar>
<article className="flex-grow px-6 pt-6 max-md:px-3 max-md:pt-3">
<NoticeCard />
<Questionnaires />
<RoadmapModal {...{ isModalOpen, onModalClose }} />
</article>
<footer className="px-6">
<div
className={`flex w-full ${
step !== maxStep && step >= 2 ? "justify-between" : "justify-end"
} py-6 max-md:py-3`}
>
{step !== maxStep && step >= 2 ? (
<Button
color="secondary"
variant="ghost"
isDisabled={step <= 1}
onClick={() => handlePrev()}
>
上一步
</Button>
) : null}
{loading ? (
<Button color="primary" variant="shadow" isDisabled isLoading>
開始填寫
</Button>
) : (
renderNextButton()
)}
</div>
<Progress
size="md"
value={questionNo}
label={<></>}
valueLabel={`${questionNo} / ${questions.length}`}
maxValue={questions.length}
color="success"
showValueLabel={true}
className="w-full pb-4"
/>
</footer>
</>
);
}
|
# Copyright (C) 2006, 2007, 2009 Alex Schroeder <alex@gnu.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
require 't/test.pl';
package OddMuse;
use Test::More tests => 38;
clear_pages();
add_module('mac.pl');
# Search for broken regular expressions
test_page(get_page('search=%2Btest'),
'<h1>Malformed regular expression in \+test</h1>');
# Test search
update_page('SearchAndReplace', 'This is fooz and this is barz.', '', 1);
$page = get_page('search=fooz');
test_page($page,
'<h1>Search for: fooz</h1>',
'<p class="result">1 pages found.</p>',
'This is <strong>fooz</strong> and this is barz.');
xpath_test($page, '//span[@class="result"]/a[@class="local"][@href="http://localhost/wiki.pl/SearchAndReplace"][text()="SearchAndReplace"]');
# Search page name
$page = get_page('search=andreplace');
test_page($page,
'<h1>Search for: andreplace</h1>',
'<p class="result">1 pages found.</p>');
# FIXME: Not sure this should work... 'Search<strong>AndReplace</strong>'
xpath_test($page, '//span[@class="result"]/a[@class="local"][@href="http://localhost/wiki.pl/SearchAndReplace"][text()="SearchAndReplace"]');
# Brackets in the page name
test_page(update_page('Search (and replace)', 'Muu'),
'search=%22Search\+%5c\(and\+replace%5c\)%22');
# Make sure only admins can replace
test_page(get_page('search=foo replace=bar'),
'This operation is restricted to administrators only...');
# Simple replace where the replacement pattern is found
test_page(get_page('search=fooz replace=fuuz pwd=foo'), split('\n',<<'EOT'));
<h1>Replaced: fooz → fuuz</h1>
<p class="result">1 pages found.</p>
This is <strong>fuuz</strong> and this is barz.
EOT
# Replace with empty string
test_page(get_page('search=this%20is%20 replace= pwd=foo delete=1'), split('\n',<<'EOT'));
<h1>Replaced: this is → </h1>
<p class="result">1 pages found.</p>
fuuz and barz.
EOT
# Replace with backreferences, where the replacement pattern is no longer found
test_page(get_page('"search=([a-z]%2b)z" replace=x%241 pwd=foo'), '1 pages found');
test_page(get_page('SearchAndReplace'), 'xfuu and xbar.');
# Create an extra page that should not be found
update_page('NegativeSearchTest', 'this page contains an ab');
update_page('NegativeSearchTestTwo', 'this page contains another ab');
test_page(get_page('search=xb replace=[xa]b pwd=foo'), '1 pages found'); # not two ab!
test_page(get_page('SearchAndReplace'), 'xfuu and \[xa\]bar.');
# Handle quoting
test_page(get_page('search=xfuu replace=/fuu/ pwd=foo'), '1 pages found'); # not two ab!
test_page(get_page('SearchAndReplace'), '/fuu/ and \[xa\]bar.');
test_page(get_page('search=/fuu/ replace={{fuu}} pwd=foo'), '1 pages found');
test_page(get_page('SearchAndReplace'), '{{fuu}} and \[xa\]bar.');
# Check headers especially the quoting of non-ASCII characters.
$page = update_page("Alexander_Schröder", "Edit [[Alexander Schröder]]!");
xpath_test($page,
'//h1/a[@title="Click to search for references to this page"][@href="http://localhost/wiki.pl?search=%22Alexander+Schr%c3%b6der%22"][text()="Alexander Schröder" or text()="' . Encode::encode_utf8('Alexander Schröder') . '"]',
'//a[@class="local"][@href="http://localhost/wiki.pl/Alexander_Schr%c3%b6der"][text()="Alexander Schröder" or text()="' . Encode::encode_utf8('Alexander Schröder') . '"]');
xpath_test(update_page('IncludeSearch',
"first line\n<search \"ab\">\nlast line"),
'//p[text()="first line "]', # note the NL -> SPC
'//div[@class="search"]/p/span[@class="result"]/a[@class="local"][@href="http://localhost/wiki.pl/NegativeSearchTest"][text()="NegativeSearchTest"]',
'//div[@class="search"]/p/span[@class="result"]/a[@class="local"][@href="http://localhost/wiki.pl/NegativeSearchTestTwo"][text()="NegativeSearchTestTwo"]',
'//p[text()=" last line"]'); # note the NL -> SPC
# Search for zero
update_page("Zero", "This is about 0 and the empty string ''.");
test_page(get_page('search=0'),
'<h1>Search for: 0</h1>',
'<p class="result">1 pages found.</p>',
"This is about <strong>0</strong> and the empty string ''.",
'meta name="robots" content="NOINDEX,FOLLOW"');
# Search for tags
update_page("Tag", "This is <b>bold</b>.");
test_page(get_page('search="<b>"'),
'<h1>Search for: <b></h1>',
'<p class="result">1 pages found.</p>',
"This is <strong><b></strong>.");
# Test fallback when grep is unavailable
TODO: {
local $TODO = "Don't get a decent error when opening the grep pipe";
AppendStringToFile($ConfigFile, "\$ENV{PATH} = '';\n");
test_page(get_page('search=empty'),
"1 pages found");
}
|
#orderly::orderly_develop_start("21_fig4_other_plots", use_draft = "newer", parameters = list(tree_depth = 15, n_chains = 16))
#This script loads in the stanfit object and outputs some demos of paper figures to play around with
load("stanfit.RData")
load("model_data.RData")
dir.create("Case_Outputs")
################################################################################
#When running this code originally with just the cumulative vaccination numbers,
#there was an odd trend where it would punish the uptick of second jabs. I think
#this is because it allows for an additive impact of respective jabs which doesn't quite make sense
#Instead we change our cumulative vaccination, to PROPORTION vaccination,
#i.e. if you sum prop_no_dose, prop_1_dose, prop_2_dose, prop_3_dose for every i,j, it'll equal 1.
#Quickly added in this switch to deal with that:
################################################################################
T <- final_week - 1
#Let's print an output .txt of the parameters used:
param_string <- sprintf("tree_depth: %s \n
n_chains: %s \n
total_iterations: %s \n
scale_by_susceptible_pool: %s \n
cases_type: %s \n
use_SGTF_data: %s \n
final_week: %s \n
random_walk_prior_scale: %s \n
rw_penalty: %s \n
print_extra_gof: %s ", tree_depth, n_chains, total_iterations,
scale_by_susceptible_pool, cases_type,
use_SGTF_data, final_week,
random_walk_prior_scale, rw_penalty, print_extra_gof)
fileConn<-file("parameters_used.txt")
writeLines(param_string, fileConn)
close(fileConn)
############################################################################
#FIG 2
############################################################################
#This figure will show regional variation in certain covariates
#IMD, and,
load("Boundaries_Data.RData")
#Remove to just the indices I've modelled:
areaCodes_used <- unique(Case_Rates_Data$areaCode)
Boundaries_reduced <- filter(Boundaries, CODE %in% areaCodes_used)
#CAN DO THIS BETTER:
zetas_mean <- get_posterior_mean(stanfit, pars = 'zetas')
zetas_mean <- as.data.frame(zetas_mean[,(n_chains+1)])
Boundaries_reduced$zetas <- as.numeric(zetas_mean[,1])
#Tomato Red: '#FF6347'
# Cyan: '#28A1D7'
#PLOT standard
ggplot(Boundaries_reduced) +
geom_sf(aes(fill = zetas)) +
#scale_fill_viridis_c() +
scale_fill_gradientn(
colours = c("#28A1D7", "#FDFD96", "#FF6347"), # Blue, white, and red colors
values = scales::rescale(c(min(Boundaries_reduced$zetas), median(Boundaries_reduced$zetas), max(Boundaries_reduced$zetas)))
) +
ggtitle(expression(paste("Nearest-neighbour spatial kernel value,", zeta, ", by LTLA"))) +
labs(fill = "Zeta") +
theme_void() +
theme(plot.margin = unit(c(0, 0, 0, 0.5), "cm")) -> england_zetas
ggplot(Boundaries_reduced[grepl( 'London', Boundaries_reduced$DESCRIPTIO, fixed = TRUE),]) +
geom_sf(aes(fill = zetas), show.legend = FALSE) +
#scale_fill_viridis_c() +
scale_fill_gradientn(
colours = c("#28A1D7", "#FDFD96", "#FF6347"), # Blue, white, and red colors
values = scales::rescale(c(min(Boundaries_reduced$zetas), median(Boundaries_reduced$zetas), max(Boundaries_reduced$zetas)))
) +
#ggtitle("Average Index of Multiple Deprivation (IMD) by LTLA") +
labs(fill = "Average zeta Score") +
theme_void() +
theme(plot.margin = unit(c(0, 0, 0, 0), "cm")) -> london_zetas
##########################################################
#And now we do the same thing for Theta!
##########################################################
#CAN DO THIS BETTER:
theta_mean <- get_posterior_mean(stanfit, pars = 'theta')
theta_mean <- as.data.frame(theta_mean[,(n_chains+1)])
Boundaries_reduced$thetas <- as.numeric(theta_mean[,1])
#Tomato Red: '#FF6347'
# Cyan: '#28A1D7'
#PLOT standard
ggplot(Boundaries_reduced) +
geom_sf(aes(fill = thetas)) +
#scale_fill_viridis_c() +
scale_fill_gradientn(
colours = c("#39C687", "white", "#C63978"), # Blue, white, and red colors
values = scales::rescale(c(min(Boundaries_reduced$thetas), median(Boundaries_reduced$thetas), max(Boundaries_reduced$thetas)))
) +
ggtitle(expression(paste("Spatial error term, ", theta, ", by LTLA"))) +
labs(fill = "Theta") +
theme_void() +
theme(plot.margin = unit(c(0, 0, 0, 0.5), "cm")) -> england_theta
ggplot(Boundaries_reduced[grepl( 'London', Boundaries_reduced$DESCRIPTIO, fixed = TRUE),]) +
geom_sf(aes(fill = thetas), show.legend = FALSE) +
#scale_fill_viridis_c() +
scale_fill_gradientn(
colours = c("#39C687", "white", "#C63978"), # Blue, white, and red colors
values = scales::rescale(c(min(Boundaries_reduced$thetas), median(Boundaries_reduced$thetas), max(Boundaries_reduced$thetas)))
) +
#ggtitle("Average Index of Multiple Deprivation (IMD) by LTLA") +
labs(fill = "Average theta Score") +
theme_void() +
theme(plot.margin = unit(c(0, 0, 0, 0), "cm")) -> london_theta
Fig_AB_plot <- plot_grid(england_zetas, england_theta,
nrow = 1, labels = c("A", "B"), align = "v", axis = "bt") #+
#theme(plot.background = element_rect(fill = "white"))
ggsave(filename = "ab_fig.png",
path = 'Case_Outputs\\', plot = Fig_AB_plot,
dpi=300, height=6.31, width=11, units="in")
ggsave(filename = "ab_fig.tiff",
path = 'Case_Outputs\\', plot = Fig_AB_plot,
dpi=300, height=6.31, width=11, units="in")
ggsave(filename = "ab_fig.pdf",
path = 'Case_Outputs\\', plot = Fig_AB_plot,
dpi=300, height=6.31, width=11, units="in")
#########################################
#FIGURE C
#Now the random walk plot.
#Plot Random Walk but with CrI too
grey_lines <- c(
"2020-06-01", ## End of first stay-at-home-order
"2020-11-05", ## Start of second stay at home order
"2020-12-02", ## End of second stay-at-home order
"2021-01-06", ## Start of third stay-at-home order
"2021-03-08", ## End of third stay-at-home order (step 1)
"2021-07-19" ## End of steps, no more legal restrictions
)
variant_dates <- c( #Dates that variants first appear in our dataset
"2020-07-26", #ALPHA
"2021-03-28", #DELTA
"2021-09-12" #OMICRON
)
lockdown_shades <- data.frame(date_start = as.Date(c("2020-04-01", grey_lines)),
date_end = as.Date(c(grey_lines, '2022-04-01' )),
rect_bottom = rep(775, 7),
rect_top = rep(800, 7),
rect_col = c("red", "orange", "red", "orange", "red", "orange", "green"))
random_walk_summaries <- summary(stanfit, pars = c('beta_random_walk'))
random_walk_summaries <- random_walk_summaries$summary
All_dates <- sort(unique(Case_Rates_Data$date_begin))
rw_data <- data.frame( Week = All_dates, mean = random_walk_summaries[,1],
lower = random_walk_summaries[,4],
upper = random_walk_summaries[,8])
ggplot(rw_data) +
geom_line(aes(x = Week, y = mean), color = "#39C687") +
geom_ribbon(aes(x = Week, ymin = lower, ymax = upper), fill = "#39C687", alpha = 0.4) +
ylab(bquote(z[t] * " value")) + theme_classic() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
coord_cartesian(xlim = c(as.Date('2020-05-01'), as.Date('2022-04-01'))) +
geom_rect(data = lockdown_shades, aes(xmin = as.Date(date_start), xmax = as.Date(date_end),
ymin = max(rw_data$upper)-0.08,
ymax = max(rw_data$upper)),
fill = c('#FFB6B6', "#FFD6A5", '#FFB6B6', "#FFD6A5", '#FFB6B6', "#FFD6A5", "#C8E7C1"),
show.legend = FALSE) +
# geom_vline(xintercept = as.Date(variant_dates), alpha = 0.9, color = 'black') +
geom_vline(xintercept = as.Date(grey_lines), alpha = 0.7, color = 'gray23', lty = 'dashed') +
xlab("Date") +
ggtitle("Random Walk term trajectory") +
# annotate('text', x = as.Date("2020-07-26") - 13, label = "Alpha emergence", y = -1.3, colour = "black", size = 4, angle = 90) +
# annotate('text', x = as.Date("2021-03-28") - 13, label = "Delta emergence", y = -1.3, colour = "black", size = 4, angle = 90) +
# annotate('text', x = as.Date("2021-09-12") - 13, label = "Omicron emergence", y = 0.3, colour = "black", size = 4, angle = 90) +
theme(axis.text = element_text(size = rel(1.2)),
axis.title = element_text(size = rel(1.3)),
legend.text = element_text(size = rel(1.2)),
legend.title = element_text(size = rel(1.3))) +
scale_x_date(date_breaks = "2 month", date_labels = "%b %y") -> rw_plot
Fig_plot <- plot_grid(Fig_AB_plot, rw_plot,
nrow = 2, labels = c("", "C"), rel_heights = c(0.6,0.4),
align = "v", axis = "bt") +
theme(plot.background = element_rect(fill = "white"))
ggsave(filename = "fig.png",
path = 'Case_Outputs\\', plot = Fig_plot,
dpi=300, height=10, width=11, units="in")
ggsave(filename = "fig.tiff",
path = 'Case_Outputs\\', plot = Fig_plot,
dpi=300, height=10, width=11, units="in")
ggsave(filename = "fig.pdf",
path = 'Case_Outputs\\', plot = Fig_plot,
dpi=300, height=10, width=11, units="in")
|
package testutils
import (
"encoding/json"
"backend/api/v1"
"backend/api/v1/user"
"backend/db"
"backend/models"
"backend/router"
"backend/store"
"github.com/jmoiron/sqlx"
"github.com/labstack/echo/v4"
)
type Test struct {
Database *sqlx.DB
UserStore *store.UserStore
TodoStore *store.TodoStore
Handler *v1.Handler
Router *echo.Echo
}
func SetupTest() (*Test, error) {
t := Test{}
db, err := db.NewTestDb()
if err != nil {
return nil, err
}
t.Database = db
t.UserStore = store.NewUserStore(db)
t.TodoStore = store.NewTodoStore(db)
h, err := v1.NewHandler(t.UserStore, t.TodoStore)
if err != nil {
return nil, err
}
t.Handler = h
e := router.New()
t.Router = e
t.loadFixtures()
return &t, nil
}
func ResponseMap(b []byte, key string) map[string]interface{} {
var m map[string]interface{}
json.Unmarshal(b, &m)
return m[key].(map[string]interface{})
}
func (t Test) loadFixtures() error {
u1 := &models.User{
Username: "user1",
}
u1.Password, _ = user.HashPassword("secret")
u1, err := t.UserStore.Create(u1)
if err != nil {
return err
}
u2 := &models.User{
Username: "user2",
}
u2.Password, _ = user.HashPassword("secret")
u2, err = t.UserStore.Create(u2)
if err != nil {
return err
}
t1 := &models.Todo{
User_id: u1.Id,
Title: "test1",
Description: "test",
Done: false,
}
t1, err = t.TodoStore.Create(t1)
if err != nil {
return err
}
t2 := &models.Todo{
User_id: u1.Id,
Title: "test2",
Description: "test",
Done: true,
}
t2, err = t.TodoStore.Create(t2)
if err != nil {
return err
}
return nil
}
|
import pandas as pd
def extract(file_path):
"""Extract data from a CSV file."""
data = pd.read_csv(file_path)
return data
def transform(data):
"""Transform the data by cleaning and enriching."""
# Example transformation: Drop rows with missing values
data = data.dropna()
# Example transformation: Create a new column based on existing data
data['Full_Name'] = data['First_Name'] + ' ' + data['Last_Name']
# Example transformation: Convert all text to lowercase
data['Full_Name'] = data['Full_Name'].str.lower()
return data
def load(data, target_file_path):
"""Load the transformed data into a new CSV file."""
data.to_csv(target_file_path, index=False)
def etl_pipeline(source_file_path, target_file_path):
"""Run the full ETL pipeline."""
# Step 1: Extract
data = extract(source_file_path)
print("Data extracted successfully.")
# Step 2: Transform
data = transform(data)
print("Data transformed successfully.")
# Step 3: Load
load(data, target_file_path)
print("Data loaded successfully.")
# Example usage
source_file = 'data/source_data.csv'
target_file = 'data/transformed_data.csv'
etl_pipeline(source_file, target_file)
|
#ifndef ALGORITHMIC_DATA_STRUCTURE_LRU_CACHE_H_
#define ALGORITHMIC_DATA_STRUCTURE_LRU_CACHE_H_
#include <cstddef>
#include <memory>
#include <optional>
#include <queue>
#include <unordered_map>
#include <vector>
namespace algorithmic::data_structure {
template <typename K, typename V>
struct DLinkedNode {
K key;
V value;
DLinkedNode* prev;
DLinkedNode* next;
DLinkedNode() : prev(nullptr), next(nullptr) {}
DLinkedNode(K _key, V _value) : key(_key), value(_value), prev(nullptr), next(nullptr) {}
};
template <typename K, typename V, typename Container = std::unordered_map<K, DLinkedNode<K, V>*>>
class LRUCache {
private:
using DLinkedNode = DLinkedNode<K, V>;
Container cache;
DLinkedNode* head;
DLinkedNode* tail;
size_t size;
size_t capacity;
public:
LRUCache() = delete;
LRUCache(size_t _capacity) : size(0), capacity(_capacity) {
init();
}
~LRUCache() {
clear();
}
bool HasExisted(const K& key) {
return cache.count(key);
}
std::optional<V> Get(const K& key) {
if (!cache.count(key)) {
return std::nullopt;
}
DLinkedNode* node = cache[key];
moveToHead(node);
return node->value;
}
void Put(const K& key, const V& value) {
if (!cache.count(key)) {
DLinkedNode* node = new DLinkedNode(key, value);
cache[key] = node;
addToHead(node);
++size;
if (size > capacity) {
DLinkedNode* removed = removeTail();
cache.erase(removed->key);
delete removed;
--size;
}
} else {
DLinkedNode* node = cache[key];
node->value = value;
moveToHead(node);
}
}
size_t Size() const {
return size;
}
void Clear() {
clear();
init();
}
private:
void init() {
head = new DLinkedNode();
tail = new DLinkedNode();
head->next = tail;
tail->prev = head;
}
void clear() {
for (const auto& [k, v] : cache) {
if (v != nullptr) {
delete v;
}
}
cache.clear();
if (head != nullptr) {
delete head;
}
if (tail != nullptr) {
delete tail;
}
}
void addToHead(DLinkedNode* node) {
node->prev = head;
node->next = head->next;
head->next->prev = node;
head->next = node;
}
void removeNode(DLinkedNode* node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}
void moveToHead(DLinkedNode* node) {
removeNode(node);
addToHead(node);
}
DLinkedNode* removeTail() {
DLinkedNode* node = tail->prev;
removeNode(node);
return node;
}
};
} // namespace algorithmic::data_structure
#endif // ALGORITHMIC_DATA_STRUCTURE_LRU_CACHE_H_
|
import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle";
import axios from "axios";
import { Button } from "@mui/material";
import { UserContext } from "@/contexts/UserContext";
import { useContext } from "react";
import { JwtCookie } from "@/types/JwtCookie";
import { User as UserClass } from "@/models/User";
interface Props {
isOpen: boolean;
}
const LoginDialog: React.FC<Props> = ({ isOpen }) => {
const userContext = useContext(UserContext);
const [msg, setMsg] = useState("");
const [data, setData] = useState({
email: "",
password: "",
});
const handleDataChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const name = event.target.name;
const value = event.target.value;
setData({ ...data, [name]: value });
};
const handleLogin = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
event.preventDefault();
const data = new FormData(event.currentTarget);
const user: UserClass = new UserClass();
try {
const response = await user.loginRequest(
data.get("email") as string,
data.get("password") as string
);
localStorage.setItem("user_info", response);
userContext.login();
} catch (error: any) {
setMsg(error.message);
}
};
return (
<Dialog open={isOpen}>
<DialogTitle>Login</DialogTitle>
<DialogContent>
<DialogContentText>Login to continue</DialogContentText>
</DialogContent>
<DialogContent>
<form onSubmit={handleLogin} style={{ width: "30vw" }}>
<TextField
type="email"
label="Email"
value={data.email}
onChange={handleDataChange}
name="email"
sx={{ margin: "1vh", width: "95%" }}
/>
<TextField
type="password"
label="Password"
value={data.password}
name="password"
onChange={handleDataChange}
sx={{ margin: "1vh", width: "95%" }}
/>
{msg !== "" && <p style={{ color: "red" }}>{msg}</p>}
<Button
variant="contained"
sx={{ margin: "1vh", width: "95%" }}
type="submit"
disabled={data.email === "" || data.password === ""}
>
Login
</Button>
</form>
</DialogContent>
</Dialog>
);
};
export default LoginDialog;
|
//
// NotificationsViewModel.swift
// Instagram
//
// Created by 양승현 on 2023/01/11.
//
import UIKit
import Combine
class NotificationsViewModel {
//MARK: - Properties
fileprivate var _notifications = CurrentValueSubject<[NotificationModel],Never>([NotificationModel]())
//MARK: - Usecase
fileprivate let apiClient: ServiceProviderType
fileprivate let fetchedNotifiedUserInfo = PassthroughSubject<UserModel,Never>()
fileprivate let failedFetchedNotifiedUserInfo = PassthroughSubject<Void,Never>()
fileprivate let fetchNotifiedPostInfo = PassthroughSubject<PostModel,Never>()
//MARK: - Lifecycels
init(apiClient: ServiceProviderType) {
self.apiClient = apiClient
configure()
}
}
//MARK: - Helpers
extension NotificationsViewModel {
fileprivate func configure() {
fetchNotifications()
}
}
//MARK: - NotificationViewModelType
extension NotificationsViewModel: NotificationViewModelType {
func transform(with input: Input) -> Output {
let appear = appearChains(with: input)
let noti = notificationsChains(with: input)
let specificCellInit = specificCellInit(with: input)
let refresh = refreshChains(with: input)
let didSelectedCell = didSelectCellChains(with: input)
let didSelectedPost = didSelectPostChains(with: input)
let fetchedNotifiedUserUpstream = fetchNotifiedUserUpstreamChains()
let failedNotifiedUpstream = failNotifiedUpstreamChains()
let fetchedNotifiedPostUpstream = fetchNotifiedPostUpstreamChains()
let didSelectedSubscription = didSelectedCell.merge(with: didSelectedPost).eraseToAnyPublisher()
return Publishers
.Merge8(appear, noti, specificCellInit, refresh,
didSelectedSubscription , fetchedNotifiedUserUpstream,
fetchedNotifiedPostUpstream, failedNotifiedUpstream)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}
//MARK: - NotificationsVMComputedProperties
extension NotificationsViewModel: NotificationVMComputedProperties {
var count: Int {
_notifications.value.count
}
var notifications: [NotificationModel] {
get {
return _notifications.value
}
set {
_notifications.value = newValue
}
}
}
//MARK: - NotificationViewModelType subscription chains
extension NotificationsViewModel: NotificationViewModelConvenience {
private func appearChains(with input: Input) -> Output {
return input
.appear
.subscribe(on: DispatchQueue.main)
.map{ _ -> State in
return .appear
}.eraseToAnyPublisher()
}
private func notificationsChains(with input: Input) -> Output {
return _notifications
.subscribe(on: DispatchQueue.main)
.map { _ -> State in
return .updateTableView
}.eraseToAnyPublisher()
}
private func specificCellInit(with input: Input) -> Output {
return input
.specificCellInit
.subscribe(on: DispatchQueue.main)
.map { [unowned self] (cell, index) -> State in
cell.vm = NotificationCellViewModel(notification: _notifications.value[index], apiClient: apiClient)
cell.setupBindings()
cell.didTapFollowButton()
return .none
}.eraseToAnyPublisher()
}
private func refreshChains(with input: Input) -> Output {
return input
.refresh
.subscribe(on: DispatchQueue.main)
.map { [unowned self] _ -> State in
notifications.removeAll()
configure()
return .refresh
}.eraseToAnyPublisher()
}
private func didSelectCellChains(with input: Input) -> Output {
return input
.didSelectCell
.map{ [unowned self] uid -> State in
self.fetchNotifiedUserInfo(with: uid)
return .none
}.eraseToAnyPublisher()
}
private func fetchNotifiedUserUpstreamChains() -> Output {
return fetchedNotifiedUserInfo
.map{ notifiedSender -> State in
return .showProfile(notifiedSender)
}.eraseToAnyPublisher()
}
private func failNotifiedUpstreamChains() -> Output {
return failedFetchedNotifiedUserInfo
.map{ _ -> State in
return .endIndicator
}.eraseToAnyPublisher()
}
private func fetchNotifiedPostUpstreamChains() -> Output {
return fetchNotifiedPostInfo
.map{ post -> State in
return .showPost(post)
}.eraseToAnyPublisher()
}
private func didSelectPostChains(with input: Input) -> Output {
return input.didSelectedPost
.subscribe(on: DispatchQueue.main)
.map { uid -> State in
self.fetchNotifiedPost(uid)
return .none
}.eraseToAnyPublisher()
}
}
//MARK: - APIs
extension NotificationsViewModel {
private func fetchNotifiedPost(_ uid: String) {
Task(priority: .high) {
do {
var fetchedPost = try await apiClient.postCase.fetchPost(withPostId: uid)
//애매한데.. 단일 포스트 fetch할 때 안 받아지는 건지 다시 한번 살펴봐야겠음.
fetchedPost.postId = uid
let updatedPost = fetchedPost
DispatchQueue.main.async {
self.fetchNotifiedPostInfo.send(updatedPost)
}
}catch {
DispatchQueue.main.async {
self.failedFetchedNotifiedUserInfo.send()
}
}
}
}
private func fetchNotifiedUserInfo(with uid: String) {
Task(priority: .high) {
guard let user = try? await apiClient
.userCase
.fetchUserInfo(type: UserModel.self, withUid: uid) else {
DispatchQueue.main.async {
self.failedFetchedNotifiedUserInfo.send()
}
return
}
DispatchQueue.main.async {
self.fetchedNotifiedUserInfo.send(user)
}
}
}
private func fetchNotifications() {
Task(priority: .high) {
do {
let list = try await apiClient.notificationCase.fetchNotifications()
self._notifications.value = list
try self.checkIfUserIsFollowed()
} catch {
switch error {
case is NotificationServiceError:
fetchNotificationsErrorHandling(with: error)
case is CheckUserFollowedError:
fetchNotificationsFollowErrorHandling(with: error)
default:
print("DEBUG: Unknown error occured: \(error.localizedDescription)")
}
}
}
}
private func checkIfUserIsFollowed() throws {
_notifications.value.forEach{ notification in
Task(priority: .high) {
guard notification.type == .follow else { return }
let isFollowed = try await apiClient.userCase.checkIfUserIsFollowd(uid: notification.specificUserInfo.uid)
guard let idx = _notifications.value.firstIndex(where: {$0.id == notification.id}) else {
return
}
self._notifications.value[idx].specificUserInfo.userIsFollowed = isFollowed
}
}
}
}
//MARK: - APIs Error Handling
extension NotificationsViewModel {
private func fetchNotificationsErrorHandling(with error: Swift.Error) {
guard let error = error as? NotificationServiceError else { return }
switch error {
case .invalidNotificationList:
print("DEBUG: \(error)")
case .invalidCurrentUser:
print("DEBUG: \(error)")
case .invalidDocuments:
print("DEBUG: \(error)")
}
}
private func fetchNotificationsFollowErrorHandling(with error: Error) {
guard let error = error as? CheckUserFollowedError else {
return
}
switch error {
case .invalidSpecificUserInfo: return print("DEBUG: \(error.errorDescription)")
case .invalidCurrentUserUIDInUserDefaultsStandard: return print("DEBUG: \(error.errorDescription)")
}
}
}
|
module ent::ent {
use std::string;
use std::signer;
use aptos_framework::coin::{Self, BurnCapability, MintCapability, Coin};
use aptos_framework::timestamp::now_seconds;
use std::string::String;
use aptos_framework::event;
use aptos_framework::account;
use aptos_framework::timestamp;
/// coin DECIMALS
const DECIMALS: u8 = 8;
/// pow(10,8) = 10**8
const DECIMAL_TOTAL: u64 = 100000000;
/// 100 million
const MAX_SUPPLY_AMOUNT: u64 = 100000000;
/// 15%
const DEV_TEAM: u64 = 15000000 ;
/// 10%
const INVESTORS: u64 = 10000000 ;
/// 3%
const ADVISORS: u64 = 3000000 ;
/// 15%
const FOUNDATION: u64 = 15000000;
/// 57%
const COMMUNITY: u64 = 57000000;
/// Error codes
const ERR_NOT_ADMIN: u64 = 0x10004;
const ERR_TIME_ERROR: u64 = 0x10005;
const ERR_CANT_LARGE_BANK_VALUE: u64 = 0x10006;
const ERR_CANT_LARGE_BANK_SUPPLY: u64 = 0x10007;
const ERR_CANT_LARGE_BANK_RELEASE: u64 = 0x10008;
/// ENT Coin
struct ENT has key, store {}
/// store Capability for mint and burn
struct CapStore has key {
mint_cap: MintCapability<ENT>,
burn_cap: BurnCapability<ENT>,
}
/// genesis info
struct GenesisInfo has key, store {
/// seconds
genesis_time: u64,
/// withdraw bank event
withdraw_event: event::EventHandle<WithdrawBankEvent>
}
/// bank for community
struct CommunityBank has key, store { value: Coin<ENT> }
/// bank for dev team
struct DevTeamBank has key, store { value: Coin<ENT> }
/// bank for investor
struct InvestorsBank has key, store { value: Coin<ENT> }
/// bank for advisors
struct AdvisorsBank has key, store { value: Coin<ENT> }
/// bank for foundation
struct FoundationBank has key, store { value: Coin<ENT> }
/// It must be initialized first
public entry fun init(signer: &signer) {
assert_admin_signer(signer);
let (burn_cap, freeze_cap, mint_cap) =
coin::initialize<ENT>(signer, string::utf8(b"Enchanter Coin"), string::utf8(b"ENT"), DECIMALS, true);
coin::destroy_freeze_cap(freeze_cap);
coin::register<ENT>(signer);
let mint_coins = coin::mint<ENT>(MAX_SUPPLY_AMOUNT * DECIMAL_TOTAL, &mint_cap);
move_to(signer, CommunityBank { value: coin::extract(&mut mint_coins, COMMUNITY * DECIMAL_TOTAL) });
move_to(signer, DevTeamBank { value: coin::extract(&mut mint_coins, DEV_TEAM * DECIMAL_TOTAL) });
move_to(signer, InvestorsBank { value: coin::extract(&mut mint_coins, INVESTORS * DECIMAL_TOTAL) });
move_to(signer, FoundationBank { value: coin::extract(&mut mint_coins, FOUNDATION * DECIMAL_TOTAL) });
move_to(signer, AdvisorsBank { value: mint_coins });
move_to(signer, CapStore { mint_cap, burn_cap });
move_to(signer, GenesisInfo { genesis_time: now_seconds(), withdraw_event: account::new_event_handle<WithdrawBankEvent>(signer) });
}
/// Burn ENT
public fun burn(token: coin::Coin<ENT>) acquires CapStore {
coin::burn<ENT>(token, &borrow_global<CapStore>(@ent).burn_cap)
}
/// withdraw community bank
public entry fun withdraw_community(account: &signer, to: address, amount: u64) acquires CommunityBank, GenesisInfo {
assert_admin_signer(account);
let bank = borrow_global_mut<CommunityBank>(@ent);
assert_deposit_amount(amount, coin::value(&bank.value), COMMUNITY * DECIMAL_TOTAL);
coin::deposit<ENT>(to, coin::extract<ENT>(&mut bank.value, amount));
emit_withdraw_event(to, amount, string::utf8(b"community"));
}
/// withdraw dev team bank
public entry fun withdraw_team(account: &signer, to: address, amount: u64) acquires DevTeamBank, GenesisInfo {
assert_admin_signer(account);
let bank = borrow_global_mut<DevTeamBank>(@ent);
assert_deposit_amount(amount, coin::value(&bank.value), DEV_TEAM * DECIMAL_TOTAL);
coin::deposit<ENT>(to, coin::extract<ENT>(&mut bank.value, amount));
emit_withdraw_event(to, amount, string::utf8(b"team"));
}
/// withdraw foundation bank
public entry fun withdraw_foundation(account: &signer, to: address, amount: u64) acquires GenesisInfo, FoundationBank {
assert_admin_signer(account);
let bank = borrow_global_mut<FoundationBank>(@ent);
assert_deposit_amount(amount, coin::value(&bank.value), FOUNDATION * DECIMAL_TOTAL);
coin::deposit<ENT>(to, coin::extract<ENT>(&mut bank.value, amount));
emit_withdraw_event(to, amount, string::utf8(b"foundation"));
}
/// withdraw investors bank
public entry fun withdraw_investors(account: &signer, to: address, amount: u64) acquires InvestorsBank, GenesisInfo {
assert_admin_signer(account);
let bank = borrow_global_mut<InvestorsBank>(@ent);
assert_deposit_amount(amount, coin::value(&bank.value), INVESTORS * DECIMAL_TOTAL);
coin::deposit<ENT>(to, coin::extract<ENT>(&mut bank.value, amount));
emit_withdraw_event(to, amount, string::utf8(b"investors"));
}
/// withdraw advisors bank
public entry fun withdraw_advisors(account: &signer, to: address, amount: u64) acquires AdvisorsBank, GenesisInfo {
assert_admin_signer(account);
let bank = borrow_global_mut<AdvisorsBank>(@ent);
assert_deposit_amount(amount, coin::value(&bank.value), ADVISORS * DECIMAL_TOTAL);
coin::deposit<ENT>(to, coin::extract<ENT>(&mut bank.value, amount));
emit_withdraw_event(to, amount, string::utf8(b"advisors"));
}
/// deposit to bank
public entry fun deposit_community(account: &signer, amount: u64) acquires CommunityBank {
coin::merge<ENT>(&mut borrow_global_mut<CommunityBank>(@ent).value, coin::withdraw<ENT>(account, amount));
}
public entry fun deposit_team(account: &signer, amount: u64) acquires DevTeamBank {
coin::merge<ENT>(&mut borrow_global_mut<DevTeamBank>(@ent).value, coin::withdraw<ENT>(account, amount));
}
public entry fun deposit_investors(account: &signer, amount: u64) acquires InvestorsBank {
coin::merge<ENT>(&mut borrow_global_mut<InvestorsBank>(@ent).value, coin::withdraw<ENT>(account, amount));
}
public entry fun deposit_foundation(account: &signer, amount: u64) acquires FoundationBank {
coin::merge<ENT>(&mut borrow_global_mut<FoundationBank>(@ent).value, coin::withdraw<ENT>(account, amount));
}
public entry fun deposit_advisors(account: &signer, amount: u64) acquires AdvisorsBank {
coin::merge<ENT>(&mut borrow_global_mut<AdvisorsBank>(@ent).value, coin::withdraw<ENT>(account, amount));
}
/// register ENT to sender
public entry fun register(account: &signer) { coin::register<ENT>(account); }
/// helper must admin
fun assert_admin_signer(sign: &signer) { assert!(signer::address_of(sign) == @ent, ERR_NOT_ADMIN); }
/// helper release rule
fun assert_deposit_amount(amount: u64, bank_value: u64, supply: u64) acquires GenesisInfo {
assert!(bank_value >= amount, ERR_CANT_LARGE_BANK_VALUE);
let info = borrow_global<GenesisInfo>(@ent);
let now = timestamp::now_seconds();
assert!(now > info.genesis_time, ERR_TIME_ERROR);
let max = max_release(get_day(info.genesis_time, now), supply);
assert!(supply >= max, ERR_CANT_LARGE_BANK_SUPPLY);
assert!((bank_value - amount) >= (supply - max), ERR_CANT_LARGE_BANK_RELEASE);
}
/// get day form diff time
fun get_day(start: u64, end: u64): u64 { ((end - start) / 86400) + 1 }
/// get max release from day and supply
public fun max_release(day: u64, supply: u64): u64 {
// 1% per day
if (day <= 10) { supply * day / 100 }
// 0.16% per day + supply / 10 = 10%
// 16 / 10000 = 0.0016%
else if (day <= 100) { supply * (day - 10) / 625 + (supply / 10) }
// 0.1% per day + (supply * 244 / 1000) = 24.4%
else if (day <= 200) { supply * (day - 100) / 1000 + (supply * 244 / 1000) }
// 0.05% per day + (supply * 344 / 1000) = 34.4%
// 1/2000 = 0.0005
else if (day <= 1000) { supply * (day - 200) / 2000 + (supply * 344 / 1000) }
// 0.025% per day + (supply * 744 / 1000) = 74.4%
// 1 / 4000 = 0.025%
else if (day <= 2024) { supply * (day - 1000) / 4000 + (supply * 744 / 1000) }
// all
else if (day > 2024) { supply }
else { 0 }
}
struct WithdrawBankEvent has drop, store {
/// to address
to: address,
/// withdraw amount
amount: u64,
/// coin type
bank_name: String,
}
/// emit withdraw event
fun emit_withdraw_event(to: address, amount: u64, bank_name: String)acquires GenesisInfo {
event::emit_event(&mut borrow_global_mut<GenesisInfo>(@ent).withdraw_event, WithdrawBankEvent { to, amount, bank_name });
}
#[test]
fun test_max_release() {
let max = max_release(1, 10000000);
assert!(max == 100000, max);
let max = max_release(10, 10000000);
assert!(max == 1000000, max);
let max = max_release(11, 10000000);
assert!(max == 1016000, max);
let max = max_release(12, 10000000);
assert!(max == 1032000, max);
let max = max_release(99, 10000000);
assert!(max == 2424000, max);
let max = max_release(100, 10000000);
assert!(max == 2440000, max);
let max = max_release(150, 10000000);
assert!(max == 2940000, max);
let max = max_release(200, 10000000);
assert!(max == 3440000, max);
let max = max_release(700, 10000000);
assert!(max == 5940000, max);
let max = max_release(1000, 10000000);
assert!(max == 7440000, max);
let max = max_release(1001, 10000000);
assert!(max == 7442500, max);
let max = max_release(1024, 10000000);
assert!(max == 7500000, max);
let max = max_release(2024, 10000000);
assert!(max == 10000000, max);
let max = max_release(3000, 10000000);
assert!(max == 10000000, max);
let max = max_release(30000, 10000000);
assert!(max == 10000000, max);
}
#[test]
fun test_max_release_2() {
let max = max_release(1, 10000000 * DECIMAL_TOTAL);
assert!(max == 100000 * DECIMAL_TOTAL, max);
let max = max_release(10, 10000000 * DECIMAL_TOTAL);
assert!(max == 1000000 * DECIMAL_TOTAL, max);
let max = max_release(11, 10000000 * DECIMAL_TOTAL);
assert!(max == 1016000 * DECIMAL_TOTAL, max);
let max = max_release(12, 10000000 * DECIMAL_TOTAL);
assert!(max == 1032000 * DECIMAL_TOTAL, max);
let max = max_release(99, 10000000 * DECIMAL_TOTAL);
assert!(max == 2424000 * DECIMAL_TOTAL, max);
let max = max_release(100, 10000000 * DECIMAL_TOTAL);
assert!(max == 2440000 * DECIMAL_TOTAL, max);
let max = max_release(150, 10000000 * DECIMAL_TOTAL);
assert!(max == 2940000 * DECIMAL_TOTAL, max);
let max = max_release(200, 10000000 * DECIMAL_TOTAL);
assert!(max == 3440000 * DECIMAL_TOTAL, max);
let max = max_release(700, 10000000 * DECIMAL_TOTAL);
assert!(max == 5940000 * DECIMAL_TOTAL, max);
let max = max_release(1000, 10000000 * DECIMAL_TOTAL);
assert!(max == 7440000 * DECIMAL_TOTAL, max);
let max = max_release(1001, 10000000 * DECIMAL_TOTAL);
assert!(max == 7442500 * DECIMAL_TOTAL, max);
let max = max_release(1024, 10000000 * DECIMAL_TOTAL);
assert!(max == 7500000 * DECIMAL_TOTAL, max);
let max = max_release(2024, 10000000 * DECIMAL_TOTAL);
assert!(max == 10000000 * DECIMAL_TOTAL, max);
let max = max_release(3000, 10000000 * DECIMAL_TOTAL);
assert!(max == 10000000 * DECIMAL_TOTAL, max);
let max = max_release(30000, 10000000 * DECIMAL_TOTAL);
assert!(max == 10000000 * DECIMAL_TOTAL, max);
}
#[test]
fun test_max_release_3() {
let max = max_release(1, 100000000 * DECIMAL_TOTAL);
assert!(max == 1000000 * DECIMAL_TOTAL, max);
let max = max_release(10, 100000000 * DECIMAL_TOTAL);
assert!(max == 10000000 * DECIMAL_TOTAL, max);
let max = max_release(11, 100000000 * DECIMAL_TOTAL);
assert!(max == 10160000 * DECIMAL_TOTAL, max);
let max = max_release(12, 100000000 * DECIMAL_TOTAL);
assert!(max == 10320000 * DECIMAL_TOTAL, max);
let max = max_release(99, 100000000 * DECIMAL_TOTAL);
assert!(max == 24240000 * DECIMAL_TOTAL, max);
let max = max_release(100, 100000000 * DECIMAL_TOTAL);
assert!(max == 24400000 * DECIMAL_TOTAL, max);
let max = max_release(150, 100000000 * DECIMAL_TOTAL);
assert!(max == 29400000 * DECIMAL_TOTAL, max);
let max = max_release(200, 100000000 * DECIMAL_TOTAL);
assert!(max == 34400000 * DECIMAL_TOTAL, max);
let max = max_release(700, 100000000 * DECIMAL_TOTAL);
assert!(max == 59400000 * DECIMAL_TOTAL, max);
let max = max_release(1000, 100000000 * DECIMAL_TOTAL);
assert!(max == 74400000 * DECIMAL_TOTAL, max);
let max = max_release(1001, 100000000 * DECIMAL_TOTAL);
assert!(max == 74425000 * DECIMAL_TOTAL, max);
let max = max_release(1024, 100000000 * DECIMAL_TOTAL);
assert!(max == 75000000 * DECIMAL_TOTAL, max);
let max = max_release(2024, 100000000 * DECIMAL_TOTAL);
assert!(max == 100000000 * DECIMAL_TOTAL, max);
let max = max_release(3000, 100000000 * DECIMAL_TOTAL);
assert!(max == 100000000 * DECIMAL_TOTAL, max);
let max = max_release(30000, 100000000 * DECIMAL_TOTAL);
assert!(max == 100000000 * DECIMAL_TOTAL, max);
}
#[test]
fun test_max_release_4() {
let max = max_release(1, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 570000 * DECIMAL_TOTAL, max);
let max = max_release(10, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 5700000 * DECIMAL_TOTAL, max);
let max = max_release(11, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 5791200 * DECIMAL_TOTAL, max);
let max = max_release(12, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 5882400 * DECIMAL_TOTAL, max);
let max = max_release(99, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 13816800 * DECIMAL_TOTAL, max);
let max = max_release(100, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 13908000 * DECIMAL_TOTAL, max);
let max = max_release(150, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 16758000 * DECIMAL_TOTAL, max);
let max = max_release(200, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 19608000 * DECIMAL_TOTAL, max);
let max = max_release(700, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 33858000 * DECIMAL_TOTAL, max);
let max = max_release(1000, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 42408000 * DECIMAL_TOTAL, max);
let max = max_release(1001, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 42422250 * DECIMAL_TOTAL, max);
let max = max_release(1024, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 42750000 * DECIMAL_TOTAL, max);
let max = max_release(2000, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 56658000 * DECIMAL_TOTAL, max);
let max = max_release(2024, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 57000000 * DECIMAL_TOTAL, max);
let max = max_release(3000, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 57000000 * DECIMAL_TOTAL, max);
let max = max_release(30000, COMMUNITY * DECIMAL_TOTAL);
assert!(max == 57000000 * DECIMAL_TOTAL, max);
}
#[test]
fun test_supply() {
assert!(MAX_SUPPLY_AMOUNT == DEV_TEAM + FOUNDATION + INVESTORS + ADVISORS + COMMUNITY, 1)
}
#[test]
fun test_get_day() {
let day = get_day(1666108266, 1666108266 + 3600);
assert!(day == 1, day);
let day = get_day(1666108266, 1666108266 + 24 * 3600);
assert!(day == 2, day);
let day = get_day(1666108266, 1666108266 + 3 * 24 * 3600);
assert!(day == 4, day);
let day = get_day(1666108266, 1666108266 + 1000 * 24 * 3600 + 3600);
assert!(day == 1001, day);
}
}
|
1. **Using Parentheses:** The most common way to create a tuple is by placing elements inside parentheses. For example:
```python
my_tuple = (1, 2, 3, 'hello')
```
2. **Using the `tuple()` Constructor:** You can also create a tuple using the `tuple()` constructor, passing an iterable (e.g., a list) as an argument. For instance:
```python
my_list = [4, 5, 6]
my_tuple = tuple(my_list)
```
3. **Empty Tuples:** To create an empty tuple, simply use empty parentheses:
```python
empty_tuple = ()
```
4. **Single-Element Tuples:** Creating a single-element tuple can be a bit tricky. You need to include a comma after the element to distinguish it from a regular value in parentheses. For example:
```python
single_element_tuple = (42,)
```
5. **Using Repetition:** You can create tuples with repeated elements using the repetition operator `*`. For example:
```python
repeated_tuple = (1, 2) * 3 # This will create (1, 2, 1, 2, 1, 2)
```
Remember that once a tuple is created, its elements cannot be modified. This immutability is what sets tuples apart from lists. It ensures data integrity and makes tuples suitable for scenarios where data should not change.
As you explore the world of Python tuples, keep in mind the different ways to create and initialize them. Understanding these techniques will help you effectively work with tuples in your Python projects.
|
package com.ss.challenge.todolist.usecases.items.complete;
import com.ss.challenge.todolist.domain.items.Item;
import com.ss.challenge.todolist.infra.persistence.h2.ItemRepository;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
/**
* This class is a use case responsible for marking an item as completed.
*/
@Service
public class CompleteItemUseCase {
private final Logger logger;
private final ItemRepository itemRepository;
public CompleteItemUseCase(Logger logger, ItemRepository itemRepository) {
this.logger = logger;
this.itemRepository = itemRepository;
}
@Transactional
public void complete(CompleteItemCommand itemCommand) {
Item item = itemRepository.getReferenceById(itemCommand.getItemId());
itemRepository.save(item.markCompleted(LocalDateTime.now()));
if (logger.isDebugEnabled()) {
logger.info("Item id: " + item.getId() + " was marked as completed");
}
}
}
|
// Copyright (C) 2018 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
import AVFoundation
import SwiftyJSON
#if os(iOS)
@available(iOS 10.3, *)
class FPSContentKeySessionDelegate: NSObject, AVContentKeySessionDelegate {
var assetHelpersMap = [String: FPSLicenseHelper]()
func contentKeySession(_ session: AVContentKeySession, didProvide keyRequest: AVContentKeyRequest) {
handleContentKeyRequest(keyRequest: keyRequest)
}
func contentKeySession(_ session: AVContentKeySession, didProvideRenewingContentKeyRequest keyRequest: AVContentKeyRequest) {
handleContentKeyRequest(keyRequest: keyRequest)
}
func contentKeySession(_ session: AVContentKeySession, shouldRetry keyRequest: AVContentKeyRequest,
reason retryReason: AVContentKeyRequest.RetryReason) -> Bool {
var shouldRetry = false
switch retryReason {
/*
Indicates that the content key request should be retried because the key response was not set soon enough either
due the initial request/response was taking too long, or a lease was expiring in the meantime.
*/
case AVContentKeyRequest.RetryReason.timedOut:
shouldRetry = true
/*
Indicates that the content key request should be retried because a key response with expired lease was set on the
previous content key request.
*/
case AVContentKeyRequest.RetryReason.receivedResponseWithExpiredLease:
shouldRetry = true
/*
Indicates that the content key request should be retried because an obsolete key response was set on the previous
content key request.
*/
case AVContentKeyRequest.RetryReason.receivedObsoleteContentKey:
shouldRetry = true
default:
break
}
return shouldRetry
}
// Informs the receiver a content key request has failed.
func contentKeySession(_ session: AVContentKeySession, contentKeyRequest keyRequest: AVContentKeyRequest, didFailWithError err: Error) {
PKLog.error("contentKeySession has failed: \(err)")
}
func assetHelper(_ keyIdentifier: Any?) -> FPSLicenseHelper? {
guard let id = keyIdentifier as? String else { return nil }
return assetHelpersMap[id]
}
func handleContentKeyRequest(keyRequest: AVContentKeyRequest) {
guard let helper = assetHelper(keyRequest.identifier) else { return }
if helper.forceDownload, !(keyRequest is AVPersistableContentKeyRequest) {
// We want to download but we're given a non-download request
keyRequest.respondByRequestingPersistableContentKeyRequest()
return
}
helper.handleLicenseRequest(FPSContentKeyRequest(keyRequest)) { (error) in
PKLog.debug("Done handleStreamingContentKeyRequest for \(helper.assetId)")
self.assetHelpersMap.removeValue(forKey: helper.assetId)
}
}
}
@available(iOS 10.3, *)
extension FPSContentKeySessionDelegate {
func contentKeySession(_ session: AVContentKeySession, didProvide keyRequest: AVPersistableContentKeyRequest) {
handleContentKeyRequest(keyRequest: keyRequest)
}
func contentKeySession(_ session: AVContentKeySession,
didUpdatePersistableContentKey persistableContentKey: Data,
forContentKeyIdentifier keyIdentifier: Any) {
#if DEBUG
fatalError("Dual Expiry feature not implemented")
#endif
}
}
@available(iOS 10.3, *)
class FPSContentKeyRequest: FPSLicenseRequest {
let request: AVContentKeyRequest
init(_ request: AVContentKeyRequest) {
self.request = request
}
func getSPC(cert: Data, id: String, shouldPersist: Bool, callback: @escaping (Data?, Error?) -> Void) {
let options = [AVContentKeyRequestProtocolVersionsKey: [1]]
request.makeStreamingContentKeyRequestData(forApp: cert, contentIdentifier: id.data(using: .utf8)!, options: options, completionHandler: callback)
}
func processContentKeyResponse(_ keyResponse: Data) {
request.processContentKeyResponse(AVContentKeyResponse(fairPlayStreamingKeyResponseData: keyResponse))
}
func processContentKeyResponseError(_ error: Error?) {
request.processContentKeyResponseError(error ?? NSError())
}
func persistableContentKey(fromKeyVendorResponse keyVendorResponse: Data, options: [String : Any]?) throws -> Data {
if let request = self.request as? AVPersistableContentKeyRequest {
return try request.persistableContentKey(fromKeyVendorResponse: keyVendorResponse, options: options)
}
fatalError("Invalid state")
}
}
#endif
|
class Solution {
private:
void dfs(int row, int col, vector<vector<int>>& image, vector<vector<int>>& ans, int initialColor, int newColor, int delRow[], int delCol[]){
ans[row][col]=newColor;
int n=image.size();
int m=image[0].size();
for(int i=0; i<4; i++){
int nrow=row+delRow[i];
int ncol=col+delCol[i];
if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && image[nrow][ncol]==initialColor && ans[nrow ][ ncol]!=newColor){
dfs(nrow, ncol, image, ans, initialColor, newColor, delRow, delCol);
}
}
}
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
//Using BFS
//TC=O(N*M) + O(N*M*4) = O(N*M) as in worst case every node will be a part of queue i.e.every node will be traversed
//SC=O(N*M) {queue size at max = O(N*M) + external ans matrix O(N*M) for storing the answer}
// int n=image.size();
// int m=image[0].size();
// queue<pair<int, int>> q;
// vector<vector<int>> ans=image;
// int initialValue=image[sr][sc];
// q.push({sr,sc});
// int drow[]={-1, 0, +1, 0};
// int dcol[]={0, +1, 0, -1};
// while(!q.empty()){
// int r=q.front().first;
// int c=q.front().second;
// ans[r][c]=color;
// q.pop();
// for(int i=0; i<4; i++){
// int nrow=r+drow[i];
// int ncol=c+dcol[i];
// if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && ans[nrow][ncol]!=color && image[nrow][ncol]==initialValue){
// q.push({nrow, ncol});
// }
// }
// }
// return ans;
//Using DFS
// TC=O(N*M) as for X nodes, x dfs calls are made + for each of X nodes loop runs for 4 times
// which is X+X*4 = O(X) = O(N*M).
// SC=O(N*M){for storing the answer in ans matrix}+O(N*M){Recursion Stack Space}.
//getting initial color
int initialColor=image[sr][sc];
vector<vector<int>> ans=image;
//delta row and delta column for 4-directional neighbours
int delRow[]={-1, 0, +1, 0};
int delCol[]={0, +1, 0, -1};
dfs(sr, sc, image, ans, initialColor, color, delRow, delCol);
return ans;
}
};
|
package com.example.notifications;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private final int NOTIFICATION_ID = 1;
private final String CHANNEL_ID = "CHANNEL ID";
EditText editText;
Button button;
String message;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
message = editText.getText().toString();
sendNotification(message);
}
});
}
private void sendNotification(String message) {
createNotificationChannel();
Intent intent = new Intent(this, MainActivity2.class);
intent.putExtra("message", message);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Notification Demo")
.setContentText(message)
.setContentIntent(pendingIntent)
.setAutoCancel(false);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelMessage = "Channel Message", channelDescription = "This is a Channel Description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, channelMessage, importance);
notificationChannel.enableVibration(false);
notificationChannel.setDescription(channelDescription);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
|
import react, { MouseEvent, useState } from 'react'
import './App.css'
//@ts-ignore
import { BoxCoords, Route, User } from './types'
import Navigation from './components/Navigation/Navigation'
import Logo from './components/Logo/Logo'
import Main from './components/Main/Main'
import Particles from 'react-tsparticles'
import particleOptions from './ParticleOptions'
const App = () => {
const [route, setRoute] = useState(Route.SIGN_IN)
const [imgUrl, setImgUrl] = useState('')
const [modelId, setModelId] = useState('f76196b43bbd45c99b4f3cd8e8b40a8a')
const [boxes, setBoxes] = useState([] as Array<BoxCoords>)
const [user, setUser] = useState({
id: '',
name: '',
email: '',
entries: 0,
joined: ''
} as User)
const [isSignedIn, setIsSignedIn] = useState(false)
const [serverUrl, setServerUrl] = useState("http://localhost:3001")
const loadUser = (user: User) => {
setUser(user)
if (!isSignedIn)
setIsSignedIn(true)
}
const handleUrlSubmit = (event: MouseEvent<HTMLButtonElement>): void => {
/*
https://samples.clarifai.com/face-det.jpg
*/
const url = (document.getElementById('url-input') as HTMLInputElement)!.value
setImgUrl(url)
fetch(
`${serverUrl}/image`,
{
method: 'put',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: user.id, url: url, modelId: modelId })
})
.then((data: any) => {
if (data.ok) {
return data.json()
} else {
throw new Error(`ERROR GETTING IMAGE DATA BACK: \n ${data}` )
}
})
.then(data => {
console.log(data)
setBoxes(calculateBoxCoords(data.response))
setUser(data.user)
document.getElementById('inputImage')?.scrollIntoView({behavior: 'smooth'})
})
.catch((err: Error) => {
console.log(err)
})
}
const handleSignOut = () => {
setRoute(Route.SIGN_IN)
setImgUrl("")
setBoxes([])
setIsSignedIn(false)
}
// BoxCoords represents calculated from BoundingBox values relative to img size
const calculateBoxCoords = (response: any): BoxCoords[] => {
const id = 'inputImage'
const img = document.getElementById(id) as HTMLImageElement
//if getting element fails img is null
if (img) {
// shortcuts for convienience
const width = img.width
const height = img.height
const regions = response.outputs[0].data.regions.map((r: any) => {
const info = r.region_info.bounding_box
return({
bottom_row: height - (info.bottom_row * height),
left_column: info.left_col * width,
right_column: width - (info.right_col * width),
top_row: info.top_row * height
} as BoxCoords)
})
return regions
} else {
// temporary, TODO handle incorrect image id
throw Error(`target id was: ${id}`)
}
}
return (
<div className="App">
<Particles
id="tsparticles"
init={() => 0}
loaded={() => 0}
options={particleOptions}
/>
<Navigation
goSignIn={() => setRoute(Route.SIGN_IN)}
goSignUp={() => setRoute(Route.SIGN_UP)}
onSignOut={handleSignOut}
isSignedUp={isSignedIn}
route={route}
/>
<Logo />
<Main
route={route}
setRoute={setRoute}
loadUser={loadUser}
handleUrlSubmit={handleUrlSubmit}
url={imgUrl}
boxes={boxes}
user={user}
serverUrl={serverUrl}
/>
</div>
)
}
export default App
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>application MSG foundation</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
<!-- Font Awesome Cdn Link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
</head>
<body>
<header class="header">
<div class="logo">
<img src="{{ url_for('static', filename='images/logo.jpeg') }}" alt="MSG Mortgage Logo">
</div>
<div class="header-icons">
<a href="" class="search"><i class="fa fa-search"></i></a>
<a href=""><i class="fas fa-bell"></i></a>
<div class="account">
<a href=""><i class="fas fa-user"></i></a>
</div>
</div>
</header>
<div class="container">
<nav>
<div class="navbar">
<ul>
<li><a href="{{ url_for('userprofile') }}">
<i class="fas fa-user"></i>
<span class="nav-item">User Profile</span>
</a></li>
<li><a href="{{ url_for('predict') }}">
<i class="fas fa-chart-bar"></i>
<span class="nav-item">Loan Eligibility</span>
</a></li>
<li><a href="#">
<i class="fas fa-tasks"></i>
<span class="nav-item">Quick Links</span>
</a></li>
<li><a href="#">
<i class="fab fa-dochub"></i>
<span class="nav-item">Document Upload</span>
</a></li>
<li><a href="{{ url_for('admin_profile') }}">
<i class="fas fa-cog"></i>
<span class="nav-item">About</span>
</a></li>
<li><a href="#">
<i class="fas fa-question-circle"></i>
<span class="nav-item">Help</span>
</a></li>
<li><a href="{{ url_for('logout') }}" class="logout">
<i class="fas fa-sign-out-alt"></i>
<span class="nav-item">Logout</span>
</a></li>
</ul>
</div>
</nav>
<!-- searchbar-->
<div class="search-bar">
<!-- input-->
<div class="search-input">
<input type="text" placeholder="Search for Loans"/>
<!-- cancel-btn-->
<a href="#" class="search-cancel"><i class="fas fa-times"></i></a>
</div>
</div>
<div class="main-body">
<form class="prediction_form" action="/loan_application" method="POST">
<h1 class="application">Loan Application Form</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div id="flash-messages">
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}
<h2><b>{{prediction_text}}</b></h2>
<fieldset>
<legend>Basic Information</legend>
<label for="first_name">First Name</label>
<input type="text" name="first_name" />
<label for="middle_initial">Middle Initial</label>
<input type="text" name="middle_initial" />
<label for="last_name">Last Name</label>
<input type="text" name="last_name" />
<label for="gender" class="form-label"> gender</label>
<select class="form-select" id="gender" name="gender" aria-label="Default select example">
<option selected>-- select gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<br/>
<label for="email">Email</label>
<input type="text" name="email" placeholder="jdoe31@yahoo.com" />
<label for="telephone">Contact Number</label>
<input type="text" name="telephone" />
<label for="home_address">Home Address</label>
<input type="text" name="home_address" />
<label for="education" class="form_label">Education</label>
<select class="form_select" id="education" name="education" aria-label="Default select example">
<option selected>-- select education --</option>
<option value="Graduate">Graduate</option>
<option value="Not Graduate">Not Graduate</option>
</select>
</fieldset>
<fieldset>
<legend>Family Information</legend>
<label for="married" class="form-label"> Marital status</label>
<select class="form-select" id="married" name="married" aria-label="Default select example">
<option selected>-- select marital status --</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<label for="spouse">Spouse Name</label>
<input type="text" name="spouse" />
<label for="dependents" class="form-label">Dependents</label>
<select class="form-select" id="dependents" name="dependents" aria-label="Default select example">
<option selected>-- select dependents --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3+">3+</option>
</select>
</fieldset>
<fieldset>
<legend>Work Information</legend>
<label for="employed" class="form-label">Employement Status</label>
<select class="form-select" id="employed" name="employed" aria-label="Default select example">
<option selected>-- select status --</option>
<option value="Yes">employed</option>
<option value="No">unemployed</option>
</select>
<label for="company_name">Employer Name</label>
<input type="text" name="company_name" />
<label for="ApplicantIncome">Current Salary</label>
<input type="number" name="ApplicantIncome" />
<br>
<label for="credit" class="form-label">Credit Score</label>
<select class="form-select" id="credit" name="credit" aria-label="Default select example">
<option selected>-- select Credit_score --</option>
<option value="1.000000">1.000000</option>
<option value="0.000000">0.000000</option>
<option value="0.842199">0.842199</option>
</select>
<br>
<label for="spouse_employed" class="form-label">Spouse Employement Status</label>
<select class="form-select" id="spouse_employed" name="spouse_employed" aria-label="Default select example">
<option selected>-- select status --</option>
<option value="Yes">employed</option>
<option value="No">unemployed</option>
</select>
<label for="spouse_company_name">Employer Name</label>
<input type="text" name="spouse_company_name" />
<label for="CoapplicantIncome"> Spouse Salary:</label>
<input type="number" id="CoapplicantIncome" name="CoapplicantIncome" required>
</fieldset>
<fieldset>
<legend>Loan Details</legend>
<label for="area" class="form-label">Property Location</label>
<select class="form-select" id="area" name="area" aria-label="Default select example">
<option selected>-- select location --</option>
<option value="Urban">Urban</option>
<option value="Semiurban">Semi-Urban</option>
<option value="Rural">Rural</option>
</select>
<label for="LoanAmount">Loan Amount:</label>
<input type="number" id="LoanAmount" name="LoanAmount" required>
<label for="Loan_Amount_Term">Loan Term (in months):</label>
<input type="number" id="Loan_Amount_Term" name="Loan_Amount_Term" required>
</fieldset>
<!-- <fieldset>
<legend>Special Considerations</legend>
<label for="down payment">Down Payment</label>
<input type="text" name="down payment" />
<input type="checkbox" name="out-of-state" value="out-of-state">Out of State Resident
<input type="checkbox" name="cosigner" value="cosigner">Cosigner
<br/>
<label for="name">Name of Cosigner</label>
<input type="text" name="name-of-cosigner" />
<label for="occupation">Cosigner Occupation</label>
<input type="text" name="occupation" />
</fieldset>-->
<fieldset>
<legend>Declaration and Authorization</legend>
<!-- Declaration and Authorization -->
<label for="declaration">Declaration:</label>
<input type="text" id="declaration" class="declaration" name="declaration" >
</fieldset>
<button class="submit_app" type="submit">Submit</button>
</form>
</div>
</div>
</body>
</html>
|
import { Elysia, t } from 'elysia'
import { prisma } from '../../services/prisma';
import { authMiddleware } from '../../middlewares/auth.middleware'
import { UnauthorizedError } from '../../errors/auth';
import { ValidationError } from '../../errors/validation';
export const router = new Elysia()
.use(authMiddleware({ loggedOnly: true }))
.post(
'/api/artifacts/upload',
async ({ body: { artifact_id, code, diagram }, user }) => {
if (!user) {
throw new UnauthorizedError('You need to be logged in to upload artifacts');
}
const artifact = await prisma.artifact.findFirst({
where: {
artifactId: artifact_id,
},
})
if (artifact && artifact.userId !== user?.id) {
throw new UnauthorizedError('You can only update your own artifacts');
}
try {
JSON.stringify(JSON.parse(code));
} catch (error) {
throw new ValidationError([{ field: 'code', message: 'Invalid JSON in code' }]);
}
try {
JSON.stringify(JSON.parse(diagram));
} catch (error) {
throw new ValidationError([{ field: 'diagram', message: 'Invalid JSON in diagram' }]);
}
if (artifact) {
await prisma.artifact.update({
where: {
id: artifact.id,
},
data: {
code,
diagram,
},
});
} else {
await prisma.artifact.create({
data: {
artifactId: artifact_id,
code,
diagram,
userId: user.id,
},
});
}
return true;
},
{
body: t.Object({
artifact_id: t.String(),
code: t.String(),
diagram: t.String(),
}),
}
)
|
//
// ContentView.swift
// CheckSplit
//
// Created by Barış Bulgan on 11.02.2022.
//
import SwiftUI
struct ContentView: View {
@FocusState private var inputFocus:Bool
@State private var totalAmount = 0.0
@State private var totalPeople = 2
let tipOptions = [10,15,20,25]
@State private var defaultTip = 20
var result:Double{
let total = Double(totalAmount)
let people = Double(totalPeople)
let percent:Double = Double(defaultTip+100)/100
return total*percent/people
}
var body: some View {
NavigationView{
Form{
Section{
TextField("Check amount", value: $totalAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.numberPad)
.focused($inputFocus, equals: true)
}header: {
Text("total amount")
}
Section{
TextField("How many people", value: $totalPeople, format:
.number)
.keyboardType(.numberPad)
.focused($inputFocus, equals: true)
}header: {
Text("How many people")
}
Section{
Picker("Tip", selection: $defaultTip) {
ForEach(tipOptions, id:\.self){
Text($0, format: .percent)
}
}.pickerStyle(.segmented)
}header: {
Text("tip percentage")
}
Section{
Text(result, format: .currency(code: Locale.current.currencyCode ?? "USD"))
}header: {
Text("each wıll pay")
}
}.navigationTitle(Text("CheckSplit"))
.toolbar{ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done"){
inputFocus = false
}
}}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 200px;
height: 200px;
background-color: #bfa;
/*
边框
边框的宽度 border-width
边框的颜色 border-color
边框的样式 border-style
*/
/*
border-width: 10px;
默认值,一般都是3个像素
border-width 可以用来指定四个方向的边框的宽度
值得情况
四个值:上 右 下 左
三个值:上 左右 下
两个值: 上下 左右
除了border-width 还有一组border-xxx-width
xxx可以是 top right bottom left
用来单独指定某一个边框的宽度
*/
border-width: 10px;
/* border-width: 10px 20px 30px 40px; */
/* border-width: 10px 20px 30px; */
/* border-width: 10px 20px; */
/* border-top-width: 10px;
border-left-width: 30px; */
/*
border-color 用来指定边框的颜色,同样可以分别指定四个边的边框
规则和border-width 一样
border-color也可以省略不写,如果省略了则自动使用color的颜色值
*/
/* border-color: orange red yellow blue; */
border-color: orange;
/*
border-style指定边框的样式
solid 表示实线
dotted 点状虚线
dashed 虚线
double 双线
border-style的默认值是none 表示没有边框
*/
/* border-style: solid dotted dashed double; */
/* border-style: double; */
/*
border简写属性,通过该属性可以同时设置边框所有的相关样式,并且没有顺序要求
除了border意外还有四个border-xxx
border-top
border-left
border-right
border-bottom
*/
/* border: 10px orange solid; */
/* border-top: 10px solid red;
border-bottom: 10px solid red; */
border: 10px red solid;
border-right: none;
border-left: none;
}
</style>
</head>
<body>
<div class="box1"></div>
</body>
</html>
|
/*
* SuicaTrip.java
*
* Authors:
* Eric Butler <eric@codebutler.com>
*
* Based on code from http://code.google.com/p/nfc-felica/
* nfc-felica by Kazzz. See project URL for complete author information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Thanks to these resources for providing additional information about the Suica format:
* http://www.denno.net/SFCardFan/
* http://jennychan.web.fc2.com/format/suica.html
* http://d.hatena.ne.jp/baroqueworksdev/20110206/1297001722
* http://handasse.blogspot.com/2008/04/python-pasorisuica.html
* http://sourceforge.jp/projects/felicalib/wiki/suica
*
* Some of these resources have been translated into English at:
* https://github.com/micolous/metrodroid/wiki/Suica
*/
package com.codebutler.farebot.transit.suica;
import android.content.res.Resources;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.codebutler.farebot.card.felica.FelicaBlock;
import com.codebutler.farebot.card.felica.FelicaDBUtil;
import com.codebutler.farebot.transit.Station;
import com.codebutler.farebot.transit.Trip;
import com.google.auto.value.AutoValue;
import com.google.common.primitives.Ints;
import net.kazzz.felica.lib.Util;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
@AutoValue
abstract class SuicaTrip extends Trip {
@NonNull
static SuicaTrip create(@NonNull FelicaDBUtil dbUtil, @NonNull FelicaBlock block, long previousBalance) {
byte[] data = block.getData().bytes();
// 00000080000000000000000000000000
// 00 00 - console type
// 01 00 - process type
// 02 00 - ??
// 03 80 - ??
// 04 00 - date
// 05 00 - date
// 06 00 - enter line code
// 07 00
// 08 00
// 09 00
// 10 00
// 11 00
// 12 00
// 13 00
// 14 00
// 15 00
int consoleType = data[0];
int processType = data[1];
boolean isBus = consoleType == (byte) 0x05;
boolean isProductSale = (consoleType == (byte) 0xc7 || consoleType == (byte) 0xc8);
boolean isCharge = (processType == (byte) 0x02);
Date timestamp = SuicaUtil.extractDate(isProductSale, data);
long balance = (long) Util.toInt(data[11], data[10]);
int regionCode = data[15] & 0xFF;
long fare;
if (previousBalance >= 0) {
fare = (previousBalance - balance);
} else {
// Can't get amount for first record.
fare = 0;
}
int busLineCode = 0;
int busStopCode = 0;
int railEntranceLineCode = 0;
int railEntranceStationCode = 0;
int railExitLineCode = 0;
int railExitStationCode = 0;
Station startStation = null;
Station endStation = null;
if (timestamp == null) {
// Unused block (new card)
} else {
if (!isProductSale && !isCharge) {
if (isBus) {
busLineCode = Util.toInt(data[6], data[7]);
busStopCode = Util.toInt(data[8], data[9]);
startStation = SuicaUtil.getBusStop(dbUtil, regionCode, busLineCode, busStopCode);
} else {
railEntranceLineCode = data[6] & 0xFF;
railEntranceStationCode = data[7] & 0xFF;
railExitLineCode = data[8] & 0xFF;
railExitStationCode = data[9] & 0xFF;
startStation = SuicaUtil.getRailStation(
dbUtil, regionCode, railEntranceLineCode, railEntranceStationCode);
endStation = SuicaUtil.getRailStation(dbUtil, regionCode, railExitLineCode, railExitStationCode);
}
}
}
return new AutoValue_SuicaTrip.Builder()
.balance(balance)
.consoleType(consoleType)
.processType(processType)
.isProductSale(isProductSale)
.isBus(isBus)
.isCharge(isCharge)
.fare(fare)
.timestampData(timestamp)
.regionCode(regionCode)
.railEntranceLineCode(railEntranceLineCode)
.railEntranceStationCode(railEntranceStationCode)
.railExitLineCode(railExitLineCode)
.railExitStationCode(railExitStationCode)
.busLineCode(busLineCode)
.busStopCode(busStopCode)
.startStation(startStation)
.endStation(endStation)
.build();
}
@Override
public long getTimestamp() {
if (getTimestampData() != null) {
return getTimestampData().getTime() / 1000;
} else {
return 0;
}
}
@Override
public long getExitTimestamp() {
return 0;
}
@Override
public boolean hasTime() {
return getIsProductSale();
}
@Override
public String getRouteName(@NonNull Resources resources) {
return (getStartStation() != null)
? getStartStation().getLineName()
: (getConsoleTypeName(resources) + " " + getProcessTypeName(resources));
}
@Override
public String getAgencyName(@NonNull Resources resources) {
return (getStartStation() != null) ? getStartStation().getCompanyName() : null;
}
@Override
public String getShortAgencyName(@NonNull Resources resources) {
return getAgencyName(resources);
}
@Override
public boolean hasFare() {
return true;
}
@Override
public String getFareString(@NonNull Resources resources) {
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.JAPAN);
format.setMaximumFractionDigits(0);
if (getFare() < 0) {
return "+" + format.format(-getFare());
} else {
return format.format(getFare());
}
}
@Override
public String getBalanceString() {
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.JAPAN);
format.setMaximumFractionDigits(0);
return format.format(getBalance());
}
@Override
public String getStartStationName(@NonNull Resources resources) {
if (getIsProductSale() || getIsCharge()) {
return null;
}
if (getStartStation() != null) {
return getStartStation().getDisplayStationName();
}
if (getIsBus()) {
return String.format("Bus Area 0x%s Line 0x%s Stop 0x%s", Integer.toHexString(getRegionCode()),
Integer.toHexString(getBusLineCode()), Integer.toHexString(getBusStopCode()));
} else if (!(getRailEntranceLineCode() == 0 && getRailEntranceStationCode() == 0)) {
return String.format("Line 0x%s Station 0x%s", Integer.toHexString(getRailEntranceLineCode()),
Integer.toHexString(getRailEntranceStationCode()));
} else {
return null;
}
}
@Override
public String getEndStationName(@NonNull Resources resources) {
if (getIsProductSale() || getIsCharge() || isTVM()) {
return null;
}
if (getEndStation() != null) {
return getEndStation().getDisplayStationName();
}
if (!getIsBus()) {
return String.format("Line 0x%s Station 0x%s", Integer.toHexString(getRailExitLineCode()),
Integer.toHexString(getRailExitStationCode()));
}
return null;
}
@Override
public Mode getMode() {
int consoleType = getConsoleType() & 0xFF;
if (isTVM()) {
return Mode.TICKET_MACHINE;
} else if (consoleType == 0xc8) {
return Mode.VENDING_MACHINE;
} else if (consoleType == 0xc7) {
return Mode.POS;
} else if (getIsBus()) {
return Mode.BUS;
} else {
return Mode.METRO;
}
}
private String getConsoleTypeName(@NonNull Resources resources) {
return SuicaUtil.getConsoleTypeName(resources, getConsoleType());
}
private String getProcessTypeName(@NonNull Resources resources) {
return SuicaUtil.getProcessTypeName(resources, getProcessType());
}
private boolean isTVM() {
int consoleType = getConsoleType() & 0xFF;
int[] tvmConsoleTypes = {0x03, 0x07, 0x08, 0x12, 0x13, 0x14, 0x15};
return Ints.contains(tvmConsoleTypes, consoleType);
}
abstract long getBalance();
abstract int getConsoleType();
abstract int getProcessType();
abstract boolean getIsProductSale();
abstract boolean getIsBus();
abstract boolean getIsCharge();
abstract long getFare();
@Nullable
abstract Date getTimestampData();
abstract int getRegionCode();
abstract int getRailEntranceLineCode();
abstract int getRailEntranceStationCode();
abstract int getRailExitLineCode();
abstract int getRailExitStationCode();
abstract int getBusLineCode();
abstract int getBusStopCode();
@Nullable
public abstract Station getStartStation();
@Nullable
public abstract Station getEndStation();
@AutoValue.Builder
abstract static class Builder {
abstract Builder balance(long balance);
abstract Builder consoleType(int consoleType);
abstract Builder processType(int processType);
abstract Builder isProductSale(boolean isProductSale);
abstract Builder isBus(boolean isBus);
abstract Builder isCharge(boolean isCharge);
abstract Builder fare(long fare);
abstract Builder timestampData(Date timestamp);
abstract Builder regionCode(int regionCode);
abstract Builder railEntranceLineCode(int railEntranceLineCode);
abstract Builder railEntranceStationCode(int railEntranceStationCode);
abstract Builder railExitLineCode(int railExitLineCode);
abstract Builder railExitStationCode(int railExitStationCode);
abstract Builder busLineCode(int busLineCode);
abstract Builder busStopCode(int busStopCode);
abstract Builder startStation(Station startStation);
abstract Builder endStation(Station endStation);
abstract SuicaTrip build();
}
}
|
//
// Extensions.swift
// DANMAKER
//
// Created by yuki on 2015/06/24.
// Copyright © 2015 yuki. All rights reserved.
//
extension RandomAccessCollection {
@inlinable public func at(_ index: Self.Index) -> Element? {
self.indices.contains(index) ? self[index] : nil
}
}
extension Sequence {
@inlinable public func count(where condition: (Element) throws -> Bool) rethrows -> Int {
try self.lazy.filter(condition).count
}
@inlinable public func count(while condition: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try !condition(element) { return count }
count += 1
}
return count
}
@inlinable public func firstSome<T>(where condition: (Element) throws -> T?) rethrows -> T? {
try self.lazy.compactMap(condition).first
}
@inlinable public func allSome<T>(_ tranceform: (Element) throws -> T?) rethrows -> [T]? {
var values = [T]()
for element in self {
guard let element = try tranceform(element) else { return nil }
values.append(element)
}
return values
}
}
extension Array {
public mutating func move(fromIndex: Int, toIndex: Int) {
assert(indices.contains(fromIndex), "fromIndex '\(fromIndex)' is out of bounds.")
if fromIndex == toIndex { return }
let removed = self.remove(at: fromIndex)
if fromIndex < toIndex {
self.insert(removed, at: toIndex - 1)
} else {
self.insert(removed, at: toIndex)
}
}
public mutating func move<Range: RangeExpression>(fromRange: Range, toIndex: Int) where Range.Bound == Int {
assert(indices.contains(toIndex), "toIndex '\(toIndex)' is out of bounds.")
let range = fromRange.relative(to: self)
if range.contains(toIndex) { return }
let removed = self[range]
self.removeSubrange(range)
if range.upperBound < toIndex + range.count - 1 {
self.insert(contentsOf: removed, at: toIndex - range.count + 1)
} else {
self.insert(contentsOf: removed, at: toIndex)
}
}
}
extension Array {
@discardableResult
@inlinable public mutating func removeFirst(where condition: (Element) throws -> Bool) rethrows -> Element? {
for i in 0..<self.count {
if try condition(self[i]) { return remove(at: i) }
}
return nil
}
}
// MARK: - Equatable Array Extensions
extension Array where Element: Equatable {
@inlinable @discardableResult public mutating func removeFirst(_ element: Element) -> Element? {
for index in 0..<count where self[index] == element {
return remove(at: index)
}
return nil
}
}
extension Sequence where Element: Comparable {
@inlinable public func max(_ replace: Element) -> Element { self.max() ?? replace }
@inlinable public func min(_ replace: Element) -> Element { self.min() ?? replace }
}
extension Dictionary {
public mutating func arrayAppend<T>(_ value: T, forKey key: Key) where Self.Value == Array<T> {
if self[key] == nil { self[key] = [] }
self[key]!.append(value)
}
public mutating func arrayAppend<T, S: Sequence>(contentsOf newElements: S, forKey key: Key) where Self.Value == Array<T>, S.Element == T {
if self[key] == nil { self[key] = [] }
self[key]!.append(contentsOf: newElements)
}
}
|
import { unwatchFile } from 'fs'
import React, { useState } from 'react'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
type Props = TodoProps & {
saveTodo: (e: React.FormEvent, formData: ITodo | any) => void
}
const AddTodo: React.FC<Props> = ({todo, saveTodo }) => {
const [formData, setFormData] = useState<ITodo | {}>()
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [label, setLabel] = useState("")
const [priority, setPriority] = useState(todo.priority)
const [dueDate, setDueDate] = useState(todo.dueDate)
const [recurring, setRecurring] = useState(todo.recurring)
const [day, setDay] = useState("Monday")
const [show, setShow] = useState(false)
const user = todo.user
let priorities = [
{ label: "Select a priority", value: "" },
{ label: "Low", value: "Low" },
{ label: "Medium", value: "Medium" },
{ label: "High", value: "High" }
]
let recurrings = [
{ label: "Select a recurring schedule", value: "" },
{ label: "Daily", value: "Daily" },
{ label: "Weekly", value: "Weekly" }
]
let days = [
{ label: "Monday", value: "Monday" },
{ label: "Tuesday", value: "Tuesday" },
{ label: "Wednesday", value: "Wednesday" },
{ label: "Thursday", value: "Thursday" },
{ label: "Friday", value: "Friday" },
{ label: "Saturday", value: "Saturday" },
{ label: "Sunday", value: "Sunday" },
]
// const handleForm = (e: React.FormEvent<HTMLInputElement>): void => {
// setFormData({
// ...formData,
// [e.currentTarget.id]: e.currentTarget.value,
// })
// }
const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
e.preventDefault();
const todo: ITodo = {
_id: "",
name: name,
description: description,
label: label,
priority: priority,
dueDate: dueDate,
recurring: recurring,
day: day,
completed: [],
createdAt: new Date(),
user: user
}
saveTodo(e, todo);
setName("");
setDescription("");
setLabel("");
setPriority("");
setDueDate(null);
setRecurring("");
}
return ( show && (
<div>
<form className='Form' onSubmit={handleSubmit}>
<div className="form-group mt-3">
<input onChange={(e) => setName(e.currentTarget.value)} type='text' id='name' value={name} placeholder="Name"/>
</div>
<div className="form-group mt-3">
<textarea onChange={(e) => setDescription(e.currentTarget.value)} id='description' value={description} placeholder="Description"/>
</div>
<div className="form-group mt-3">
<input onChange={(e) => setLabel(e.currentTarget.value)} type='text' id='label' value={label} placeholder="Label"/>
</div>
<div className="form-group mt-3">
{/* <input
onChange={(e) => setPriority(e.currentTarget.value)}
type='text'
id='priority'
value={priority}
placeholder="Priority"/> */}
<select onChange={(e) => setPriority(e.currentTarget.value)} >
{/* <option value={priority}> -- Select a priority -- </option> */}
{priorities.map((p) => (p.value == priority && (<option value={p.value} selected>{p.label}</option>)) || (p.value != priority && (<option value={p.value}>{p.label}</option>)))}
</select>
</div>
<div className="form-group mt-3">
<DatePicker
selected={dueDate}
onChange={date => setDueDate(date)}
showTimeSelect
dateFormat="MMMM d, yyyy h:mmaa"
placeholderText="Due Date"
isClearable
filterDate={d => {
return new Date() <= d;
}}
/>
</div>
<div className="form-group mt-3">
<select onChange={(e) => setRecurring(e.currentTarget.value)} >
{recurrings.map((x) => (x.value == recurring && (<option value={x.value} selected>{x.label}</option>)) || (x.value != recurring && (<option value={x.value}>{x.label}</option>)))}
</select>
</div>
{recurring == "Weekly" &&
<div className="form-group mt-3">
<select onChange={(e) => setDay(e.currentTarget.value)}>
{days.map((x) => (x.value == day && (<option value={x.value} selected>{x.label}</option>)) || (x.value != day && (<option value={x.value}>{x.label}</option>)))}
</select>
</div>
}
<div className="form-group mt-3" >
<button disabled={name == "" ? true: false} >Add Todo</button>
</div>
<div className="form-group mt-3">
<button onClick={() => setShow(false)} >Close</button>
</div>
</form>
</div>) ||
<form className='Form'>
<div>
<button onClick={() => setShow(true)} >Create Todo</button>
</div>
</form>
)
}
export default AddTodo
|
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-light bg-light">
<a class="navbar-brand" href="#">S3rge</a>
<button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId"
aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Smartphone</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="dropdownId">
<a class="dropdown-item" href="https://www.apple.com/tw/iphone-12-pro/">iphone12-pro</a>
<a class="dropdown-item" href="https://store.google.com/tw/product/pixel_5">pixel-5</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-3">Season Choice</h1>
<p class="">Google-pixel 5/Apple-iphone-12-pro</p>
<img src="01.jpg"><img src="02.jpg">
<hr class="my-2">
<p class="lead">
<!-- <a class="btn btn-primary btn-lg" href="Jumbo action link" role="button">Jumbo action name</a> -->
</p>
</div>
</div>
<div class="m-5">
<form action="k5xN5E.gif" method="post">
<div class="form-group">
<label for="email">email</label>
<input type="text" name="e-mail" id="e-mail" class="form-control" placeholder="please enter email">
</div>
<div class="form-group">
<label for="password">password</label>
<input type="password" name="password" id="password" class="form-control"
placeholder="please enter password">
</div>
<div class="form-group">
<label for="date">birthday</label>
<input type="date" name="date" id="date" class="form-control" placeholder="please enter birthday">
</div>
<div class="form-group">
<label for="color">choose color</label>
<input type="color" name="color" id="color" class="form-control" placeholder="please enter color">
</div>
<div class="form-group">
<label for="msg">message to seller</label>
<textarea class="form-control" name="msg" id="msg" rows="4"></textarea>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" name="sex" id="" class="form-check-input" value="M" checked>
male</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" name="sex" id="" class="form-check-input" value="W">
female</label>
</div>
<!-- <div class="form-check form-check-inline">
<label class="form-check-label ml-2">
<input class="form-check-input" type="checkbox" name="" id="" value="checkedValue"> read
</label>
<label class="form-check-label ml-2">
<input class="form-check-input" type="checkbox" name="" id="" value="checkedValue"> music
</label>
<label class="form-check-label ml-2">
<input class="form-check-input" type="checkbox" name="" id="" value="checkedValue"> movie
</label>
</div> -->
<div class="form-group">
<label for="">Phone</label>
<select class="form-control" name="degree" id="degree">
<option value="4">Google-pixel 5</option>
<option value="3">Apple-iphone-12-pro</option>
<option value="2">random</option>
</select>
</div>
<button type="submit" class="btn btn-primary">send</button>
</form>
</div>
<table class="table table-striped table-bordered table-hover ">
<thead class="table-info text-center">
<tr>
<th>訂單編號</th>
<th>姓名</th>
<th>住址</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">1</td>
<td>TX</td>
<td>matrix</td>
</tr>
<tr>
<td scope="row">2</td>
<td class="table-danger">999</td>
<td>heaven</td>
</tr>
<tr>
<td scope="row">3</td>
<td>God</td>
<td>Hell</td>
</tr>
<tr>
<td scope="row">4</td>
<td>You</td>
<td>smd</td>
</tr>
</tbody>
</table>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
|
import sys, time, paramiko, json, re, os, multiprocessing, concurrent.futures
from netmiko import Netmiko
from netmiko.exceptions import NetmikoAuthenticationException
from openpyxl import Workbook
from openpyxl.styles import Alignment
from getInputs import getInputs
try: os.mkdir("scripts_Outputs")
except FileExistsError: pass
credentials = getInputs(f'{os.getcwd()}\\scripts_Outputs\\', os.path.basename(__file__)[:-3])
def autoFit_sheet(sheet):
for column in sheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 4)
sheet.column_dimensions[column_letter].width = adjusted_width
def CenterCells(sheet, num_of_columns):
for i in range(1, num_of_columns+1):
sheet.cell(row=sheet.max_row, column=i).alignment = Alignment(horizontal='center', vertical='center')
def generate_excel():
folders = [folder for folder in os.listdir('.') if os.path.isdir(folder)]
wb = Workbook()
files_list = []
for folder in folders:
files_list += [f"{folder}/{i}" for i in os.listdir(folder) if i.endswith(".txt")]
interfacesSheet = wb.create_sheet("disp ip interface brief", 0)
x = wb.remove(wb["Sheet"])
Columns_headers = ['NE Name', 'Interface', 'IP Address', 'Mask', 'Physical', 'Protocol', 'VPN'] #########
interfacesSheet.append(Columns_headers)
CenterCells(interfacesSheet, len(Columns_headers))
for site_file in files_list:
node_name = site_file.split('/')[-1][:-4]
with open(site_file, 'r') as f:
txt = f.read()
strict_info_regex = r'(Interface +IP Address.+?)\S*<{}>'.format(node_name) #########
site_info = re.split(r'[\r\n]+', re.findall(strict_info_regex, txt, re.DOTALL)[0])
interfaces = [i.strip().split() for i in site_info[1:] if i != '']
for i in interfaces:
if i[1] == 'unassigned':
interfacesSheet.append([node_name, i[0], 'unassigned', 'unassigned'] + i[2:])
else:
interfacesSheet.append([node_name, i[0]] + i[1].split('/') + i[2:])
autoFit_sheet(interfacesSheet)
excel_file_name = f'disp_ip_interface_brief_{time.strftime("%H;%M;%S")}'
wb.save(f'{excel_file_name}.xlsx')
print(f"Excel file {excel_file_name}.xlsx created successfully!")
start_time = time.time()
###### Using Paramiko
counter = 0
def mainCode(remote, counter):
if remote["host"] == "" or remote["username"] == "" or remote["password"] == "": return
try:
host = {
"host": remote["host"],
"username": remote["username"],
"password": remote["password"],
"device_type": "huawei_vrp",
"session_log": f'Logs/{remote["NE_Name"]}_session.log',
}#, "global_delay_factor": 2}
shell = Netmiko(**host)
time.sleep(1)
# except NetmikoAuthenticationException as e:
# # Handle authentication errors
# print(f'Authentication error for: {remote["host"]}, Pass is not {remote["password"]}')
# return
except Exception as e:
# Handle unexpected exceptions
print(f"An unexpected error occurred while trying to connect to {remote["NE_Name"]}: {str(e)}")
return 0
try:
output = ''
device_Sysname = shell.find_prompt().split('<')[-1].strip('>')
command = "display ip interface brief"
output += shell.send_command_timing(command, strip_prompt=False, strip_command=False, read_timeout=0)
print(f"Device name: {device_Sysname}, Success")
counter += 1
except Exception as e:
# Handle unexpected exceptions
print(f"An unexpected error occurred while executing commands on {remote["NE_Name"]}: {str(e)}")
return 0
# shell.disconnect()
# current_time = time.strftime("%H;%M;%S")
# current_date = time.strftime("%Y-%m-%d")
filename = device_Sysname+'.txt' #+ "\\" + "Commit_changes_with_username_" + current_date + "_" + current_time + ".txt"
with open(remote['Foldername'] + '/' + filename, 'w') as f:
# f.write(re.sub(r' ---- More ----\S+\s+\S+16D', '', output[output.index(command):]))
f.write(output)
return counter
num_threads = 100#min(int(multiprocessing.cpu_count() * (3/4)), len(credentials))
# Create a thread pool executor with the desired number of threads
with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
# Submit the slow function to the thread pool executor for each piece of data
futures = [executor.submit(mainCode, remote, counter) for remote in credentials]
# Wait for all the threads to complete
results = [f.result() for f in futures]
sum_counter = sum(results)
end_time = time.time()
print(f"success rate = {sum_counter}/{len(credentials)}")
# Calculate and print the elapsed time
execution_time = end_time - start_time
print(f"Execution time: {execution_time:.6f} seconds")
print("Generating Excel File...")
generate_excel()
|
package com.mainnet.bubbly.controller;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mainnet.bubbly.R;
import com.mainnet.bubbly.model.NFTSell_Item;
import com.mainnet.bubbly.model.NFT_Item;
import com.mainnet.bubbly.model.UserInfo;
import com.mainnet.bubbly.retrofit.ApiClient;
import com.mainnet.bubbly.retrofit.ApiInterface;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NFT_Adapter extends RecyclerView.Adapter<NFT_Adapter.ViewHolder> {
private Context context;
private ArrayList<NFT_Item> lists;
private Activity activity;
private SnackAndToast toast;
private ViewGroup v;
public NFT_Adapter(Context context, ArrayList<NFT_Item> lists, Activity activity, ViewGroup v) {
this.context = context;
this.lists = lists;
this.activity = activity;
this.v = v;
}
@NonNull
@Override
public NFT_Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_nft, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
String ipfsUrl = lists.get(position).getFile_save_url();
System.out.println(ipfsUrl);
Log.d("ipfsUrl",ipfsUrl);
if(ipfsUrl!=null&&!ipfsUrl.equals("")){
Glide.with(context)
.load(ipfsUrl)
.into(holder.iv_image);
}else{
//아무런 조치도하지 않는다. xml정의 따름.
}
//이미 판매중인 nft목록 가져오기 (만약 판매중이라면 Cancel로 버튼 표시 변경 위함)
ApiInterface api = ApiClient.getApiClient(context).create(ApiInterface.class);
Call<List<NFTSell_Item>> call = api.selectSelledNftListUsingSellerId(UserInfo.user_id);
call.enqueue(new Callback<List<NFTSell_Item>>() {
@Override
public void onResponse(Call<List<NFTSell_Item>> call, Response<List<NFTSell_Item>> response) {
if (response.isSuccessful() && response.body() != null) {
List<NFTSell_Item> responseResult = response.body();
for(int i=0; i<responseResult.size(); i++){
String element = responseResult.get(i).getNft_id();
System.out.println("nft 판매 목록"+element);
System.out.println("nft정보1"+ responseResult.get(i).toString());
if (element.equals(lists.get(position).getNft_id())) {
lists.get(position).setAlreadySell(true);
lists.get(position).setApp_id(responseResult.get(i).getApp_id());
lists.get(position).setSell_price(responseResult.get(i).getSell_price());
lists.get(position).setSeller_id(responseResult.get(i).getSeller_id());
break;
} else {
lists.get(position).setAlreadySell(false);
}
}
if(lists.get(position).isAlreadySell()){
holder.bt_sell.setVisibility(View.GONE);
holder.bt_stop.setVisibility(View.VISIBLE);
}else{
holder.bt_sell.setVisibility(View.VISIBLE);
holder.bt_stop.setVisibility(View.GONE);
}
}
}
@Override
public void onFailure(Call<List<NFTSell_Item>> call, Throwable t) {
Log.e("nft 판매 목록 가져오기 실패", t.getMessage());
}
});
holder.bt_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity).setTitle("NFT 판매 취소");
builder.setMessage("정말로 취소하시겠습니까?");
builder.setCancelable(false);
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ApiInterface api = ApiClient.getApiClient(context).create(ApiInterface.class);
System.out.println(UserInfo.mnemonic+"nftid"+lists.get(position).getNft_id()+lists.get(position).getSell_price()+UserInfo.user_id);
Call<String> call = api.nftStopSell(UserInfo.mnemonic,lists.get(position).getNft_id(),lists.get(position).getApp_id(),"" + lists.get(position).getSell_price());
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful() && response.body() != null) {
new SnackAndToast().createToast(context,"NFT 판매가 취소되었습니다.");
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("nft 판매 취소 실패", t.getMessage());
new SnackAndToast().createToast(context,"NFT 판매 취소에 실패하였습니다.");
}
});
//블록체인에서 nft 관련 트랜잭션이 느린 관계로 모든 response를 수신하기 전 timeout되는 문제가 있음.
//따라서 response 수신과 무관하게 토스트를 띄운다.
Toast.makeText(context, "NFT판매 취소 신청 완료. 블록체인 반영까지 3~5분이 소요될 수 있습니다.",Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
alert.getButton(alert.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(context, R.color.black));
alert.getButton(alert.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.blue));
}
});
holder.bt_sell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity).setTitle("NFT 판매");
EditText input = new EditText(context);
input.setPaddingRelative(100,100,100,100);
input.setBackground(null);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setSingleLine();
input.setHint("몇 버블에 판매하시겠습니까?");
builder.setView(input);
builder.setCancelable(false);
builder.setPositiveButton("판매", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String amount = input.getText().toString();
ApiInterface api = ApiClient.getApiClient(context).create(ApiInterface.class);
System.out.println(UserInfo.mnemonic+"nftid"+lists.get(position).getNft_id()+amount+UserInfo.user_id);
Call<String> call = api.nftSell(UserInfo.mnemonic,lists.get(position).getNft_id(),amount,UserInfo.user_id,"");
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful() && response.body() != null) {
new SnackAndToast().createToast(context, response.body());
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("nft 판매 실패", t.getMessage());
new SnackAndToast().createToast(context,"NFT 판매 등록에 실패했습니다.");
}
});
//블록체인에서 nft 관련 트랜잭션이 느린 관계로 모든 response를 수신하기 전 timeout되는 문제가 있음.
//따라서 response 수신과 무관하게 토스트를 띄운다.
Toast.makeText(context, "NFT판매 신청 완료. 블록체인 반영까지 3~5분이 소요될 수 있습니다.",Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
alert.getButton(alert.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(context, R.color.black));
alert.getButton(alert.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.blue));
}
});
}
@Override
public int getItemCount() {
return lists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView iv_image;
Button bt_sell, bt_stop;
public ViewHolder(@NonNull View view) {
super(view);
iv_image = view.findViewById(R.id.iv_nft_itemNFT);
bt_sell = view.findViewById(R.id.bt_sell_itemNFT);
bt_stop = view.findViewById(R.id.bt_stopSell_itemNFT);
}
}
}
|
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace CodeqoEditor
{
public abstract class EasyEditorWindow<WindowClass> : EditorWindow
where WindowClass : EditorWindow
{
const float DEFAULT_IMAGE_HEIGHT = 74f;
const float DEFAULT_IMAGE_WIDTH = 74f;
const float DEFAULT_ICON_HEIGHT = 32f;
const float DEFAULT_ICON_WIDTH = 32f;
const float DEFAULT_MIN_WINDOW_HEIGHT = 400f;
const float DEFAULT_MIN_WINDOW_WIDTH = 720f;
const float DEFAULT_MAX_WINDOW_HEIGHT = 1200f;
const float DEFAULT_MAX_WINDOW_WIDTH = 1800f;
const float DEFAULT_BUTTON_HEIGHT = 30f;
const float DEFAULT_BUTTON_WIDTH = 120f;
const float DEFAULT_MINI_BUTTON_HEIGHT = 20f;
const float DEFAULT_MINI_BUTTON_WIDTH = 80f;
protected string WindowName
{
get => EditorPrefs.GetString(typeof(WindowClass).Name + "_windowName");
set => EditorPrefs.SetString(typeof(WindowClass).Name + "_windowName", value);
}
protected bool DebugMode
{
get => EditorPrefs.GetBool(typeof(WindowClass).Name + "_debugMode", false);
set => EditorPrefs.SetBool(typeof(WindowClass).Name + "_debugMode", value);
}
protected static List<string> _debugInfo = new List<string>();
protected Vector2 ImageSize
{
get
{
float x = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_imageWidth", DEFAULT_IMAGE_WIDTH);
float y = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_imageHeight", DEFAULT_IMAGE_HEIGHT);
return new Vector2(x, y);
}
set
{
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_imageWidth", value.x);
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_imageHeight", value.y);
}
}
protected Vector2 IconSize
{
get
{
float x = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_iconWidth", DEFAULT_ICON_WIDTH);
float y = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_iconHeight", DEFAULT_ICON_HEIGHT);
return new Vector2(x, y);
}
set
{
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_iconWidth", value.x);
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_iconHeight", value.y);
}
}
public static Vector2 MinWindowSize
{
get
{
float x = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_minWindowWidth", DEFAULT_MIN_WINDOW_WIDTH);
float y = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_minWindowHeight", DEFAULT_MIN_WINDOW_HEIGHT);
return new Vector2(x, y);
}
set
{
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_minWindowWidth", value.x);
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_minWindowHeight", value.y);
}
}
public static Vector2 MaxWindowSize
{
get
{
float x = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_maxWindowWidth", DEFAULT_MAX_WINDOW_WIDTH);
float y = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_maxWindowHeight", DEFAULT_MAX_WINDOW_HEIGHT);
return new Vector2(x, y);
}
set
{
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_maxWindowWidth", value.x);
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_maxWindowHeight", value.y);
}
}
protected Vector2 ButtonSize
{
get
{
float x = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_buttonWidth", DEFAULT_BUTTON_WIDTH);
float y = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_buttonHeight", DEFAULT_BUTTON_HEIGHT);
return new Vector2(x, y);
}
set
{
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_buttonWidth", value.x);
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_buttonHeight", value.y);
}
}
protected Vector2 MiniButtonSize
{
get
{
float x = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_miniButtonWidth", DEFAULT_MINI_BUTTON_WIDTH);
float y = EditorPrefs.GetFloat(typeof(WindowClass).Name + "_miniButtonHeight", DEFAULT_MINI_BUTTON_HEIGHT);
return new Vector2(x, y);
}
set
{
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_miniButtonWidth", value.x);
EditorPrefs.SetFloat(typeof(WindowClass).Name + "_miniButtonHeight", value.y);
}
}
protected Vector2 minWindowSize;
protected Vector2 maxWindowSize;
protected Vector2 imageSize;
protected Vector2 iconSize;
protected Vector2 buttonSize;
protected Vector2 miniButtonSize;
protected string windowName;
protected GUILayoutOption[] buttonOptions;
protected GUILayoutOption[] innerButtonOptions;
protected bool _isShowingSettings;
protected static void Initialize()
{
Debug.Log("Opening " + typeof(WindowClass).Name);
WindowClass window = (WindowClass)GetWindow(typeof(WindowClass), false, typeof(WindowClass).Name);
window.Show();
window.minSize = MinWindowSize;
window.maxSize = MaxWindowSize;
window.autoRepaintOnSceneChange = true;
}
protected virtual void OnEnable()
{
windowName = WindowName;
minWindowSize = MinWindowSize;
maxWindowSize = MaxWindowSize;
imageSize = ImageSize;
iconSize = IconSize;
buttonSize = ButtonSize;
miniButtonSize = MiniButtonSize;
buttonOptions = new GUILayoutOption[] { GUILayout.Width(buttonSize.x), GUILayout.Height(buttonSize.y), GUILayout.ExpandWidth(true) };
innerButtonOptions = new GUILayoutOption[] { GUILayout.Width(miniButtonSize.x), GUILayout.Height(miniButtonSize.y), GUILayout.ExpandWidth(true) };
}
protected void InternalMenuHeader(string title)
{
/* centered button with width 100 */
CUILayout.HorizontalLayout(() =>
{
EditorGUILayout.LabelField(title, EditorStyles.boldLabel);
GUILayout.FlexibleSpace();
if (GUILayout.Button("Close"))
{
_isShowingSettings = false;
}
});
GUILayout.Space(5);
}
protected void OpenSettings()
{
CUILayout.VerticalLayout(CUI.Box(10, 10, 10, 10, CUIColor.None), (System.Action)(() =>
{
float currentWindowSizeX = position.width;
float currentWindowSizeY = position.height;
InternalMenuHeader("Window Settings");
CUILayout.VerticalLayout(CUI.box, () =>
{
EditorGUILayout.LabelField("Current Window Size : " + currentWindowSizeX + " x " + currentWindowSizeY);
});
GUILayout.Space(5);
EditorGUILayout.LabelField("UI Window", EditorStyles.boldLabel);
windowName = EditorGUILayout.TextField("Window Name", windowName);
minWindowSize = EditorGUILayout.Vector2Field("Minimum Window Size", minWindowSize);
maxWindowSize = EditorGUILayout.Vector2Field("Maximum Window Size", maxWindowSize);
GUILayout.Space(5);
EditorGUILayout.LabelField("UI Buttons", EditorStyles.boldLabel);
buttonSize = EditorGUILayout.Vector2Field("Button Size", buttonSize);
miniButtonSize = EditorGUILayout.Vector2Field("Inner Button Size", miniButtonSize);
GUILayout.Space(5);
EditorGUILayout.LabelField("UI Images (Textures/Icons)", EditorStyles.boldLabel);
imageSize = EditorGUILayout.Vector2Field("Image Size", imageSize);
iconSize = EditorGUILayout.Vector2Field("Icon Size", iconSize);
GUILayout.Space(5);
CUILayout.HorizontalLayout(() =>
{
if (GUILayout.Button("Save Settings", innerButtonOptions))
{
WindowName = windowName;
MinWindowSize = minWindowSize;
MaxWindowSize = maxWindowSize;
ButtonSize = buttonSize;
MiniButtonSize = miniButtonSize;
ImageSize = imageSize;
IconSize = iconSize;
Initialize();
}
});
}));
}
}
}
|
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useRecoilValue } from "recoil";
import styled from "styled-components";
import { ReactComponent as SearchIcon } from "../../assets/images/Search.svg";
import { loginState } from "../../atoms/atoms";
const StyledSearchBar = styled.div`
width: 35%;
position: relative;
display: inline-block;
input {
width: 100%;
padding: 0.5rem 2.5rem 0.5rem 0.75rem !important;
}
.search_icon {
position: absolute;
top: 50%;
transform: translatey(-50%);
right: 0.75rem;
display: flex;
}
@media (max-width: 64rem) {
width: 50%;
}
@media (max-width: 30rem) {
width: 100%;
}
`;
const SearchBar = (): JSX.Element => {
const navigate = useNavigate();
const [inputValue, setInputValue] = useState("");
const isLogin = useRecoilValue(loginState);
const handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (inputValue.replace(" ", "").length < 1) {
return;
}
if (event.key === "Enter") {
navigate(`/search?page=1&keyword=${inputValue}`);
}
};
const handleMouseClick = () => {
if (inputValue.replace(" ", "").length < 1) {
return;
}
navigate(`/search?page=1&keyword=${inputValue}`);
};
return (
<StyledSearchBar className={isLogin ? "login" : ""}>
<input
onKeyUp={handleKeyUp}
onChange={(event) => {
setInputValue(event?.target.value);
}}
type="text"
placeholder="Search"
/>
<div className="search_icon" onClick={handleMouseClick}>
<SearchIcon />
</div>
</StyledSearchBar>
);
};
export default SearchBar;
|
package study_Array;
/*
* 算法的考查:数组的复制、反转、查找(线性查找、二分法查找)
*
*
*/
public class ArrayTest5 {
public static void main(String[] args) {
String[] arr = new String[] { "JJ", "DD", "MM", "BB", "GG","AA"};
//数组的复制(区别于数组变量的赋值 arr1 = arr)
String [] arr1 = new String[arr.length];
for (int i = 0; i < arr1.length; i++) {
arr1[i] = arr[i];
}
/*//数组的反转
//方式一
for(int i = 0;i < arr.length / 2;i++) {
String temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
//方式二
for (int i = 0,j = arr.length; i < j; i++ , j--) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
*/
//遍历
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]+'\t');
}
//查找(或搜索)
//线性查找
String dest = "BB";
boolean isFlag = true;
for (int i = 0; i < arr.length; i++) {
if (dest.equals(arr[i])) {
System.out.println("找到了指定位置元素,位置为" + i);
isFlag = false;
break;
}
}
isFlag = true;
System.out.println("没有找到");
//二分法查找
//前提:所要查找的数组必须有序
int[] arr2 = new int[]{-98,-34,2,34,54,66,79,105,210,333};
int dest1 = -34;
int head = 0;//初始的首索引
int end = arr2.length-1;//初始的末索引
boolean isFlag1 = true;
while(head <= end){
int middle = (head + end) / 2;
if (dest1 == arr2[middle]){
System.out.println("找到了指定位置元素,位置为" + middle);
isFlag1 = false;
break;
} else if (arr2[middle] > dest1) {
end = middle - 1;
}else {//arr2[middle] < dest1
head = middle + 1;
}
}
if (isFlag1){
System.out.println("没有找到");
}
}
}
|
from datetime import datetime
import os
import logging
import sys
import argparse
import torch
from peft import (
LoraConfig,
get_peft_model,
get_peft_model_state_dict,
)
import transformers
from transformers import AutoTokenizer, AutoModelForCausalLM
from datasets import load_from_disk
logger = logging.getLogger("synapse")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(handler)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
def create_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", type=str)
parser.add_argument("--top_k_elements", type=int, default=50)
parser.add_argument("--base_model", type=str)
parser.add_argument("--cache_dir", type=str, default=None)
parser.add_argument("--lora_dir", type=str, default=None)
parser.add_argument("--no_trajectory", action="store_true", default=False)
return parser
def main():
parser = create_parser()
args = parser.parse_args()
wandb_project = "naive" if args.no_trajectory else "trajectory"
os.environ["WANDB_PROJECT"] = wandb_project
if args.no_trajectory:
per_device_train_batch_size = 1
else:
per_device_train_batch_size = 1
batch_size = 128
gradient_accumulation_steps = batch_size // per_device_train_batch_size
# load model
device_map = "auto"
model = AutoModelForCausalLM.from_pretrained(
args.base_model,
torch_dtype=torch.bfloat16,
device_map=device_map,
cache_dir=args.cache_dir,
use_flash_attention_2=True,
)
tokenizer = AutoTokenizer.from_pretrained(args.base_model, cache_dir=args.cache_dir)
tokenizer.pad_token_id = 0
tokenizer.padding_side = "left"
def tokenize_prompt(data_point):
tokenized_full_prompt = tokenizer(
data_point["input"] + data_point["output"],
padding=False,
return_tensors=None,
)
tokenized_full_prompt["labels"] = tokenized_full_prompt["input_ids"].copy()
tokenized_user_prompt = tokenizer(
data_point["input"],
padding=False,
return_tensors=None,
)
user_prompt_len = len(tokenized_user_prompt["input_ids"])
tokenized_full_prompt["labels"] = [
-100
] * user_prompt_len + tokenized_full_prompt["labels"][user_prompt_len:]
return tokenized_full_prompt
peft_config = LoraConfig(
r=16,
lora_alpha=16,
target_modules=[
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
"lm_head",
],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
if torch.cuda.device_count() > 1:
model.is_parallelizable = True
model.model_parallel = True
# load dataset
train_data = load_from_disk(
os.path.join(
args.data_dir,
f"train/{'naive' if args.no_trajectory else 'trajectory'}_top{args.top_k_elements}",
)
)
train_data = train_data.map(
tokenize_prompt, remove_columns=train_data.column_names, num_proc=8
).shuffle()
val_data = None
# Training
cur_time = datetime.now().strftime("%Y-%m-%d-%H-%M")
output_dir = (
args.lora_dir + f"-{'naive' if args.no_trajectory else 'trajectory'}-{cur_time}"
)
trainer = transformers.Trainer(
model=model,
train_dataset=train_data,
eval_dataset=val_data,
args=transformers.TrainingArguments(
per_device_train_batch_size=per_device_train_batch_size,
gradient_accumulation_steps=gradient_accumulation_steps,
warmup_steps=100,
num_train_epochs=4,
learning_rate=3e-4,
bf16=True,
logging_steps=5,
optim="adamw_torch",
evaluation_strategy="steps" if val_data is not None else "no",
save_strategy="steps",
eval_steps=50 if val_data is not None else None,
save_steps=50,
output_dir=output_dir,
load_best_model_at_end=False,
ddp_find_unused_parameters=None,
group_by_length=True,
report_to="wandb",
run_name=f"{args.base_model}-{cur_time}",
),
data_collator=transformers.DataCollatorForSeq2Seq(
tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
),
)
model.config.use_cache = False
old_state_dict = model.state_dict
model.state_dict = (
lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
).__get__(model, type(model))
if torch.__version__ >= "2" and sys.platform != "win32":
model = torch.compile(model)
trainer.train()
model.save_pretrained(output_dir)
if __name__ == "__main__":
main()
|
package main
import (
"fmt"
"time"
)
func main() {
jobs := make(chan int, 5) // 创建一个可以存储 5 个 int 类型值的 channel
done := make(chan bool) // 创建一个 bool 类型的 channel
go func() { // 启动一个新的 goroutine
for { // 无限循环
// 在 Go 语言中,从 channel 接收数据时,可以返回两个值。第一个值是从 channel 接收到的数据,第二个值是一个 bool 类型的值,表示 channel 是否已经关闭并且没有更多的数据可以接收。
j, more := <-jobs // 从 jobs channel 接收数据
if more { // 如果 jobs channel 还有数据
fmt.Println("received job", j) // 打印接收到的数据
} else { // 如果 jobs channel 没有数据
fmt.Println("received all jobs") // 打印 "received all jobs"
done <- true // 向 done channel 发送 true
return // 结束 goroutine
}
}
}()
for j := 1; j <= 3; j++ { // 循环 3 次
jobs <- j // 向 jobs channel 发送数据
fmt.Println("sent job", j) // 打印发送的数据
time.Sleep(100 * time.Millisecond) // 等待 100 毫秒
}
close(jobs) // 关闭 jobs channel
fmt.Println("sent all jobs") // 打印 "sent all jobs"
<-done // 从 done channel 接收数据,如果 done channel 没有数据,这会阻塞,直到有数据可接收
}
|
package WebsiteBanDienThoai.service.impl;
import WebsiteBanDienThoai.entity.CartItem;
import WebsiteBanDienThoai.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Service
public class ShoppingCartServiceImp implements ShoppingCartService {
Map<Integer, CartItem> shoppingCart = new HashMap<>();
@Override
public void add(CartItem newItem) {
CartItem cartItem = shoppingCart.get(newItem.getProductId());
if (cartItem == null) {
shoppingCart.put (newItem.getProductId (), newItem);
}else {
cartItem.setQuantity (cartItem.getQuantity()+1);
}
}
@Override
public void remove(int id) {
shoppingCart.remove(id);
}
@Override
public CartItem update(int productID, int quantity) {
CartItem cartItem = shoppingCart.get(productID);
cartItem.setQuantity(quantity);
return cartItem;
}
@Override
public void clear() {
shoppingCart.clear();
}
@Override
public double getAmount() {
return shoppingCart.values().stream().mapToDouble(item -> item.getQuantity()* item.getPrice()).sum();
}
@Override
public int getCount() {
return shoppingCart.values().size();
}
@Override
public Collection<CartItem> getAllItems() {
return shoppingCart.values();
}
}
|
module.exports = function(app) {
/**
* Filter
* @class Filter
* @module Router
* @param {Object} req Request
* @param {Object} res Response
*/
function Filter(req, res) {
if (!(this instanceof Filter))
return new Filter(req, res);
this.req = req;
this.res = res;
this.last = true;
};
/**
* Hashmap of filters to apply
* @property filters
* @type {Object}
* @private
*/
var filters = {};
/**
* Takes a filter name, runs that filter, and decides if it passes
* @method validate
* @param {String} filter Name of the filter
* @return {Filter} Returns itself
*/
Filter.prototype.validate = function(filter) {
var inverted = (filter.substr(0, 1) == '!');
filter = (inverted) ? filter.substr(1) : filter;
if (this.last)
this.last = this.evaluate(filter, inverted);
return this;
};
/**
* Evaluates the given filter, using the filters Hash
* @method evaluate
* @param {String} filter Name of the filter
* @param {Boolean} inverted If filter is negated
*/
Filter.prototype.evaluate = function(filter, inverted) {
var fltr = filters[filter];
if (!fltr.condition(this.req) != !inverted) {
this.res.json(fltr.error);
return false;
} else {
return true;
}
};
/**
* Returns the result of the validation
* @method run
* @return {Boolean}
*/
Filter.prototype.run = function() {
return this.last;
};
/**
* FILTERS
*/
filters = {
'logged': {
condition: function(req) {
return !app.users.isLogged(req.connection.remoteAddress);
},
error: {
status: 'error',
type: 1,
msj: app.lang.get("api.notLogged")
}
},
'admin': {
condition: function(req) {
return !app.users.isAdminFromIP(req.connection.remoteAddress);
},
error: {
status: 'error',
type: 0,
msj: app.lang.get("api.adminAuth")
}
},
'owner': {
condition: function(req) {
return !app.users.isOwner(req.connection.remoteAddress);
},
error: {
status: 'error',
type: 0,
msj: app.lang.get("api.adminAuth")
}
},
};
return Filter;
};
|
<div class="sign">
<h2>Welcome to ƎvolvE</h2>
<h3>Please Sign Up</h3>
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), data: { turbo: :false }) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :bio, as: :text, label: "Biography" %>
<%= f.input :DOB, label: "Date of birth", start_year: Date.today.year - 70, end_year: Date.today.year - 18 %>
<%= f.input :photo, as: :file , input_html: { multiple: false } %>
<%= f.input :email,
required: true,
autofocus: true,
input_html: { autocomplete: "email" }%>
<%= f.input :password,
required: true,
hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length),
input_html: { autocomplete: "new-password" } %>
<%= f.input :password_confirmation,
required: true,
input_html: { autocomplete: "new-password" } %>
</div>
<div class="form-actions">
<%= f.button :submit, "Sign up", class: "text-white" %>
</div>
<% end %>
<div><p>Have an account? <a href=""><%= render "devise/shared/links" %></p></div>
</div>
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<f:facet name="first">
<meta content='text/html; charset=UTF-8' http-equiv="Content-Type" />
<title>MODIFICAR HISTORIA CLINICA</title>
</f:facet>
</h:head>
<h:body>
<p:layout fullPage="true">
<p:layoutUnit position="north" size="103" resizable="true"
closable="true" collapsible="true">
<center>
<h1>MODIFICAR HISTORIA CLINICA</h1>
</center>
</p:layoutUnit>
<p:layoutUnit position="west" size="232" header="NUTRICIONISTA"
collapsible="true">
<p:menu>
<p:submenu label="MIS DATOS">
<p:menuitem value="Modificar Mis Datos"
url="NutricionistaModForm.xhtml" />
</p:submenu>
<p:submenu label="PACIENTES">
<p:menuitem value="Agregar" url="PacienteNewForm.xhtml" />
<p:menuitem value="Modificar" url="PacienteModForm.xhtml" />
<p:menuitem value="Eliminar" url="PacienteDelForm.xhtml" />
<p:menuitem value="Mostrar" url="PacienteShowForm.xhtml" />
</p:submenu>
<p:submenu label="HISTORIA CLINICA">
<p:menuitem value="Agregar" url="HCNewForm.xhtml" />
<p:menuitem value="Modificar" url="HCModForm.xhtml" />
<p:menuitem value="Eliminar" url="HCDelForm.xhtml" />
<p:menuitem value="Mostrar" url="HCShowForm.xhtml" />
</p:submenu>
<p:submenu label="SESION">
<p:menuitem value="Cerrar Sesión" url="login.xhtml" />
</p:submenu>
</p:menu>
</p:layoutUnit>
<p:layoutUnit position="center">
<ui:insert name="pf"></ui:insert>
<h:form id="formTabla">
<p:panel styleClass="session" header="Modificar Historia Clinica">
<p:dataTable id="phclinica" var="_phclinica"
value="#{phclinicaMB.phclinicasList}" style="width: 100%"
emptyMessage="No hay registros disponibles" paginator="true"
rows="10" paginatorPosition="top"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column filterBy="#{_phclinica.id}" headerText="ID HC"
filterMatchMode="contains">
<h:outputText value="#{_phclinica.id}" />
</p:column>
<p:column filterBy="#{_phclinica.idPaciente}"
headerText="ID Paciente" filterMatchMode="contains">
<h:outputText value="#{_phclinica.idPaciente}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Fecha Creación" />
</f:facet>
<h:outputText value="#{_phclinica.fechaHclinica}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="ID Enfermedad" />
</f:facet>
<h:outputText value="#{_phclinica.idEnfermedad}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="ID Tratamiento" />
</f:facet>
<h:outputText value="#{_phclinica.idTratamiento}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="ID Dieta" />
</f:facet>
<h:outputText value="#{_phclinica.idDieta}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Estado" />
</f:facet>
<h:outputText value="#{_phclinica.estado}" />
</p:column>
<p:column headerText="Modificar">
<p:commandButton onclick="PF('dlg2').show();"
actionListener="#{phclinicaMB.setPhclinica(_phclinica)}"
icon="ui-icon-document" update="phclinica">
</p:commandButton>
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</p:layoutUnit>
</p:layout>
<p:dialog header="MODIFICAR HISTORIA CLINICA" widgetVar="dlg2"
modal="true" height="250" width="700">
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel value="ID Enfermedad: " />
<p:selectOneMenu id="idEnfermedad"
value="#{phclinicaMB.idEnfermedad}" style="width:150px">
<f:selectItem itemLabel="Seleccione" itemValue="0"
required="false" requiredMessage="Campo Requerido" />
<f:selectItems value="#{phclinicaMB.getEnfermedadByNombre()}" />
</p:selectOneMenu>
<h:outputLabel value="ID Tratamiento: " />
<p:selectOneMenu id="idTratamiento"
value="#{phclinicaMB.idTratamiento}" style="width:150px">
<f:selectItem itemLabel="Seleccione" itemValue="0"
required="false" requiredMessage="Campo Requerido" />
<f:selectItems value="#{phclinicaMB.getTratamientoByNombre()}" />
</p:selectOneMenu>
<h:outputLabel value="ID Dieta: " />
<p:selectOneMenu id="idDieta" value="#{phclinicaMB.idDieta}"
style="width:150px">
<f:selectItem itemLabel="Seleccione" itemValue="0"
required="false" requiredMessage="Campo Requerido" />
<f:selectItems value="#{phclinicaMB.getDietaByNombre()}" />
</p:selectOneMenu>
<h:outputLabel value="Estado: " />
<h:panelGrid columns="1" style="margin-bottom:1px" cellpadding="0">
<p:outputLabel for="estado" />
<p:selectOneRadio id="estado" var="estado"
value="#{phclinicaMB.estado}" required="false">
<f:selectItem itemLabel="Activo" itemValue="A" />
<f:selectItem itemLabel="Inactivo" itemValue="I" />
</p:selectOneRadio>
</h:panelGrid>
<p:commandButton value="Modificar" id="modPhclinica" update="growl"
actionListener="#{phclinicaMB.modPhclinica()}" ajax="false"
styleClass="ui-priority-primary" />
<p:growl id="growl" life="2000" />
</h:panelGrid>
</h:form>
</p:dialog>
</h:body>
</f:view>
</html>
|
import {
action,
computed,
IObservableArray,
observable,
runInAction,
} from 'mobx';
import { autobind, Offset } from '@nara.platform/accent';
import { OffsetElementList } from 'shared/model';
import LectureApi from '../apiclient/LectureApi';
import LectureFlowApi from '../apiclient/LectureFlowApi';
import StudentFlowApi from '../apiclient/StudentFlowApi';
import LectureModel from '../../../model/LectureModel';
import LectureRdoModel from '../../../model/LectureRdoModel';
import LectureViewModel from '../../../model/LectureViewModel';
import RecommendLectureRdo from '../../../model/RecommendLectureRdo';
import RecommendLectureListRdo from '../../../model/RecommendLectureListRdo';
import InstructorRdoModel from '../../../model/InstructorRdoModel';
import OrderByType from '../../../model/OrderByType';
import LectureFilterRdoModel from '../../../model/LectureFilterRdoModel';
import SharedRdoModel from '../../../model/SharedRdoModel';
import StudentCdoModel from '../../../model/StudentCdoModel';
import LectureFilterRdoModelV2 from '../../../model/LectureFilterRdoModelV2';
import {
findByRdo,
findCardsByRdo,
findByQdo,
countLearningTab,
countRequiredCards,
} from '../../../detail/api/cardApi';
import { CardWithCardRealtedCount } from '../../../model/CardWithCardRealtedCount';
import { Direction } from '../../../../myTraining/model/Direction';
import { FilterCondition } from '../../../../myTraining/model/FilterCondition';
import { findCardStudentsByCardIds } from '../../../../certification/api/CardStudentApi';
import LectureTableViewModel from '../../../model/LectureTableViewModel';
import MyTrainingApi from '../../../../myTraining/present/apiclient/MyTrainingApi';
import { parsePolyglotString } from '../../../../shared/viewmodel/PolyglotString';
import {
CardProps,
parseUserLectureCards,
UserLectureCard,
} from '@sku/skuniv-ui-lecture-card';
import { SkProfileService } from '../../../../profile/stores';
import CardForUserViewModel from 'lecture/model/learning/CardForUserViewModel';
import CardQdo from 'lecture/model/learning/CardQdo';
import { patronInfo } from '@nara.platform/dock';
import EnrolledCardModel from 'lecture/model/EnrolledCardModel';
import {
getAddLearningCardIds,
setAddLearningCardIds,
} from 'playlist/playlistAddPopUp/playlistAddPopUpView.store';
import { CheckboxProps } from 'semantic-ui-react';
@autobind
class LectureService {
//
static instance: LectureService;
private lectureApi: LectureApi;
private lectureFlowApi: LectureFlowApi;
private studentFlowApi: StudentFlowApi;
private myTrainingApi: MyTrainingApi;
@observable
_lectures: UserLectureCard[] = [];
@observable
_userLectureCards: CardProps[] = [];
@observable
_requiredLectures: LectureModel[] = [];
@observable
totalLectureCount: number = 0;
@observable
enrolledCount: number = 0;
@observable
enrolledList: EnrolledCardModel[] = [];
// @observable
// _recommendLectures: RecommendLectureRdo[] = [];
// 추천과정 리스트
@observable
_recommendLectureListRdo: RecommendLectureListRdo = new RecommendLectureListRdo();
// 추천과정
@observable
recommendLecture: RecommendLectureRdo = new RecommendLectureRdo();
@observable
_lectureViews: LectureViewModel[] = [];
// Learning Page
@observable
_myStampCount: number = 0;
@observable
_myLearningCards: CardForUserViewModel[] = [];
@observable
_totalMyLearningCardCount: number = 0;
@observable
_selectedServiceIds: string[] = [];
@observable
cardQdo: CardQdo = new CardQdo();
@observable
column: string = '';
@observable
direction: Direction | null = null;
//
@action
setLectureViews(views: any) {
this._lectureViews = views;
}
@observable
subLectureViewsMap: Map<string, LectureViewModel[]> = new Map();
@action
setSubLectureViews(courseId: string, lectureViews: LectureViewModel[]) {
runInAction(() => this.subLectureViewsMap.set(courseId, lectureViews));
}
// Learning page
@observable
inProgressCount: number = 0;
@observable
bookmarkCount: number = 0;
@observable
requiredLecturesCount: number = 0;
@observable
completedCount: number = 0;
@observable
retryCount: number = 0;
constructor(
lectureApi: LectureApi,
lectureFlowApi: LectureFlowApi,
studentFlowApi: StudentFlowApi,
myTrainingApi: MyTrainingApi
) {
this.lectureApi = lectureApi;
this.lectureFlowApi = lectureFlowApi;
this.studentFlowApi = studentFlowApi;
this.myTrainingApi = myTrainingApi;
}
@computed
get lectures(): UserLectureCard[] {
//
const lectures = this._lectures as IObservableArray;
return lectures.peek();
}
@computed
get requiredLectures(): LectureModel[] {
//
const lectures = this._requiredLectures as IObservableArray;
return lectures.peek();
}
@computed
get recommendLectures() {
//
return (
this._recommendLectureListRdo.recommendLectureRdos as IObservableArray
).peek();
}
@computed
get recommendLecturesCount() {
return this._recommendLectureListRdo.totalCount;
}
@computed
get lectureViews() {
//
return (this._lectureViews as IObservableArray).peek();
}
@computed
get myLearningCards() {
//
return this._myLearningCards;
}
@computed
get totalMyLearningCardCount() {
//
return this._totalMyLearningCardCount;
}
@computed
get myStampCount() {
//
return this._myStampCount;
}
// Learning page
@action
async countMyStamp() {
//
const count = await this.lectureApi.countMyStamp();
runInAction(() => (this._myStampCount = count));
}
@action
clearMyLearningCard() {
//
this._totalMyLearningCardCount = 0;
this._myLearningCards = [];
this.clearSortParam();
}
@action
setCardQdo(cardQdo: CardQdo) {
runInAction(() => {
this.cardQdo = new CardQdo(cardQdo);
});
}
@action
async findMyLearningCardByQdo(firstCheck?: boolean) {
//
const findReulst = await this.lectureApi.findMyLearningLectures(
this.cardQdo
);
const cardNotes =
(await this.lectureApi.findCardNoteList(
findReulst.results.map((card) => card.id)
)) || [];
const myLearningCards = findReulst.results.map((card) => {
//
const myLectureCard = card;
myLectureCard.useNote = cardNotes.some(
(note: string) => note === card.id
);
return myLectureCard;
});
findReulst &&
runInAction(() => {
if (firstCheck) {
this._myLearningCards = myLearningCards || [];
} else {
this._myLearningCards = [
...this._myLearningCards,
...myLearningCards,
];
}
this._totalMyLearningCardCount = findReulst && findReulst.totalCount;
});
}
@action
async findMyLearningCardForExcel(cardQdo: CardQdo) {
//
const findList = await this.lectureApi.findMyLearningLectures(cardQdo);
const result: CardForUserViewModel[] = [];
runInAction(() => {
return findList.results.map((item) => {
result.push(new CardForUserViewModel(item));
});
});
return result;
}
@action
private clearSortParam() {
//
this.column = '';
this.direction = null;
}
@action
async sortMyLearningTableViews(column: string, direction: Direction) {
// 전달되는 컬럼이 오브젝트의 프로퍼티와 상이해, 변환해야함.
const propKey = convertToKeyInMyLearningTable(column);
this.column = propKey;
this.direction = direction;
if (direction === Direction.ASC) {
this._myLearningCards = this._myLearningCards.sort(
(a, b) => a[propKey] - b[propKey]
);
return;
}
if (direction === Direction.DESC) {
this._myLearningCards = this._myLearningCards.sort(
(a, b) => b[propKey] - a[propKey]
);
}
}
@computed
get selectedServiceIds() {
//
return this._selectedServiceIds;
}
@action
selectOne(serviceId: string) {
runInAction(() => {
this._selectedServiceIds = [...this._selectedServiceIds, serviceId];
});
}
@action
clearOne(serviceId: string) {
this._selectedServiceIds = this._selectedServiceIds.filter(
(selectedServiceId) => selectedServiceId !== serviceId
);
}
@action
selectAll() {
this._selectedServiceIds = this._myLearningCards.map(
(tableView) => tableView.id
);
}
@action
clearAll() {
this._selectedServiceIds = [];
}
@action
clearAllSelectedServiceIds() {
this._selectedServiceIds = [];
}
// Lectures ----------------------------------------------------------------------------------------------------------
@action
clearLectures() {
//
return runInAction(() => (this._lectures = []));
}
@action
clearCollegeLectures() {
//
return runInAction(() => (this._userLectureCards = []));
}
@action
clearEnrolledList() {
//
runInAction(() => {
this.enrolledList = [];
});
}
@action
async findPagingCollegeLectures(
collegeId: string,
limit: number,
offset: number,
orderBy: OrderByType
) {
//
const response =
(await findByQdo({
collegeIds: collegeId,
limit,
offset,
orderBy,
})) || new OffsetElementList<UserLectureCard>();
const lectureOffsetElementList = new OffsetElementList<UserLectureCard>(
response
);
const userLanguage = SkProfileService.instance.skProfile.language;
runInAction(
() =>
(this._userLectureCards = this._userLectureCards.concat(
parseUserLectureCards(lectureOffsetElementList.results, userLanguage)
))
);
return lectureOffsetElementList;
}
@action
async findPagingChannelLectures(
channelId: string,
limit: number,
offset: number,
orderBy: OrderByType
) {
const response =
(await findByQdo({
channelIds: channelId,
limit,
offset,
orderBy,
})) || new OffsetElementList<UserLectureCard>();
const lectureOffsetElementList = new OffsetElementList<UserLectureCard>(
response
);
runInAction(
() =>
(this._lectures = this._lectures.concat(
lectureOffsetElementList.results
))
);
return lectureOffsetElementList;
}
@action
async findPagingChannelOrderLectures(
collegeId: string,
channelId: string,
limit: number,
offset: number,
orderBy: OrderByType
) {
//
const response =
(await findByQdo({
collegeIds: collegeId,
channelIds: channelId,
limit,
offset,
orderBy,
})) || new OffsetElementList<UserLectureCard>();
if (offset >= 8) {
sessionStorage.setItem('channelOffset', JSON.stringify(offset + limit));
}
const lectureOffsetElementList = new OffsetElementList<UserLectureCard>(
response
);
runInAction(
() =>
(this._lectures = this._lectures.concat(
lectureOffsetElementList.results
))
);
return lectureOffsetElementList;
}
// 권장과정
@action
async findPagingRequiredLectures(
limit: number,
offset: number,
channelIds: string[] = [],
orderBy: OrderByType = OrderByType.New,
fromMain: boolean = false
) {
//
const response = await this.lectureFlowApi.findRqdLectures(
LectureFilterRdoModel.new(limit, offset, channelIds)
);
const lectureOffsetElementList = new OffsetElementList<LectureModel>(
response
);
if (fromMain) {
window.sessionStorage.setItem(
'RequiredLearningList',
JSON.stringify(lectureOffsetElementList)
);
}
lectureOffsetElementList.results = lectureOffsetElementList.results.map(
(lecture) => new LectureModel(lecture)
);
runInAction(
() =>
(this._requiredLectures = this._requiredLectures.concat(
lectureOffsetElementList.results
))
);
return lectureOffsetElementList;
}
// LectureViews ------------------------------------------------------------------------------------------------------
@action
clearLectureViews() {
//
return runInAction(() => (this._lectureViews = []));
}
@action
async findLectureViews(
coursePlanId: string,
lectureCardUsids: string[],
courseLectureUsids?: string[]
) {
//
const lectureViews = await this.lectureApi.findLectureViews(
coursePlanId,
lectureCardUsids,
courseLectureUsids
);
runInAction(() => (this._lectureViews = lectureViews));
return lectureViews;
}
@action
async findLectureViewsV2(
coursePlanId: string,
lectureCardUsids: string[],
courseLectureUsids?: string[]
) {
//
const lectureViews = await this.lectureApi.findLectureViewsV2(
coursePlanId,
lectureCardUsids,
courseLectureUsids
);
runInAction(() => (this._lectureViews = lectureViews));
return lectureViews;
}
findLectureViewsFromJson(lectures: string) {
runInAction(() => (this._lectureViews = JSON.parse(lectures)));
}
// SubLectureViewMap -------------------------------------------------------------------------------------------------
@action
async findSubLectureViews(
courseId: string,
coursePlanId: string,
lectureCardIds: string[],
courseLectureIds?: string[]
) {
//
const lectureViews = await this.lectureApi.findLectureViews(
coursePlanId,
lectureCardIds,
courseLectureIds
);
runInAction(() => this.subLectureViewsMap.set(courseId, lectureViews));
return lectureViews;
}
@action
async findSubLectureViewsV2(
courseId: string,
coursePlanId: string,
lectureCardIds: string[],
courseLectureIds?: string[]
) {
//
const lectureViews = await this.lectureApi.findLectureViewsV2(
coursePlanId,
lectureCardIds,
courseLectureIds
);
runInAction(() => this.subLectureViewsMap.set(courseId, lectureViews));
return lectureViews;
}
getSubLectureViews(courseId: string) {
//
// if (this.subLectureViewsMap.get(courseId)) {
// }
return this.subLectureViewsMap.get(courseId) || [];
}
@action
async findAllLecturesByInstructorId(
instructorId: string,
limit: number,
offset: number
) {
//
const response = await this.lectureApi.findAllLecturesByInstructorId(
InstructorRdoModel.new(instructorId, limit, offset)
);
const lectureOffsetElementList = new OffsetElementList<LectureModel>(
response
);
lectureOffsetElementList.results = lectureOffsetElementList.results.map(
(lecture) => new LectureModel(lecture)
);
// jz - 강사 상세 페이지
// runInAction(
// () =>
// (this._lectures = this._lectures.concat(
// lectureOffsetElementList.results
// ))
// );
return lectureOffsetElementList;
}
// shared list 조회
@action
async findSharedLectures(
limit: number,
offset: number,
channelIds: string[] = []
) {
//
const response = await this.lectureApi.findAllSharedLectures(
SharedRdoModel.newShared(limit, offset, channelIds)
);
const lectureOffsetElementList = new OffsetElementList<LectureModel>(
response
);
lectureOffsetElementList.results = lectureOffsetElementList.results.map(
(lecture) => new LectureModel(lecture)
);
// add totalLectureCount by gon
// jz - shared
// runInAction(() => {
// this._lectures = this._lectures.concat(lectureOffsetElementList.results);
// this.totalLectureCount = lectureOffsetElementList.totalCount;
// });
return lectureOffsetElementList;
}
@action
async addFindPagingRecommendLectures(
channelLimit: number,
channelOffset: number,
limit: number,
offset: number,
channelId?: string,
orderBy?: OrderByType
) {
//
const lectureRdo = LectureRdoModel.newRecommend(
channelLimit,
channelOffset,
limit,
offset,
channelId,
orderBy
);
const recommendLectureListRdo =
await this.lectureFlowApi.findAllRecommendLectures(lectureRdo);
runInAction(() => {
this._recommendLectureListRdo.totalCount =
recommendLectureListRdo.totalCount;
this._recommendLectureListRdo.recommendLectureRdos =
this._recommendLectureListRdo.recommendLectureRdos.concat(
recommendLectureListRdo.recommendLectureRdos
);
});
return recommendLectureListRdo;
}
@action
async addPagingRecommendLectures(
channelLimit: number,
channelOffset: number,
limit: number,
offset: number,
channelId?: string,
orderBy?: OrderByType
) {
//
const lectureRdo = LectureRdoModel.newRecommend(
channelLimit,
channelOffset,
limit,
offset,
channelId,
orderBy
);
const recommendLectureListRdo =
await this.lectureFlowApi.findAllRecommendLectures(lectureRdo);
if (
recommendLectureListRdo.recommendLectureRdos &&
recommendLectureListRdo.recommendLectureRdos.length === 1
) {
const recommendLecture = recommendLectureListRdo.recommendLectureRdos[0];
runInAction(
() =>
(this.recommendLecture.lectures.results =
this.recommendLecture.lectures.results.concat(
recommendLecture.lectures.results
))
);
return recommendLecture.lectures;
}
return null;
}
@action
clearRecommendLectures() {
//
this.recommendLecture = new RecommendLectureRdo();
}
async confirmUsageStatisticsByCardId(studentCdo: StudentCdoModel) {
//
return this.studentFlowApi.confirmUsageStatisticsByCardId(studentCdo);
}
@action
async countLearningTab() {
const countModel = await countLearningTab();
const requiredCount = await countRequiredCards();
runInAction(() => {
this.inProgressCount = (countModel && countModel.inProgressCount) || 0;
this.bookmarkCount = (countModel && countModel.bookmarkCount) || 0;
this.requiredLecturesCount = requiredCount || 0;
this.completedCount = (countModel && countModel.completedCount) || 0;
this.retryCount = (countModel && countModel.retryCount) || 0;
this.enrolledCount = (countModel && countModel.enrolledCount) || 0;
});
}
@observable
_lectureTableViews: LectureTableViewModel[] = [];
@observable
_lectureTableViewCount: number = 0;
_lectureFilterRdoV2: LectureFilterRdoModelV2 = new LectureFilterRdoModelV2();
@computed get lectureTableViews() {
return this._lectureTableViews;
}
@computed get lectureTableCount() {
return this._lectureTableViewCount;
}
initFilterRdo() {
this._lectureFilterRdoV2 = new LectureFilterRdoModelV2();
}
setFilterRdoByConditions(conditions: FilterCondition) {
this._lectureFilterRdoV2.setByConditions(conditions);
this._lectureFilterRdoV2.setDefaultOffset();
}
@action
clearAllTableViews() {
this._lectureTableViews = [];
this._lectureTableViewCount = 0;
}
@action
async findAllRqdTableViews() {
return this.findAllRequiredCards();
}
@action
async findAllRqdTableViewsByConditions() {
return this.findAllRequiredCards();
}
@action
async findAllRequiredCards(): Promise<boolean> {
const cardRdo = this._lectureFilterRdoV2.toCardRdo();
const offsetRequiredCard = await findCardsByRdo(cardRdo);
if (
offsetRequiredCard &&
offsetRequiredCard.results &&
offsetRequiredCard.results.length > 0
) {
const cardIds = offsetRequiredCard.results.map((result) => result.id);
const cardStudents = await findCardStudentsByCardIds(cardIds);
const cardNotes =
(await this.myTrainingApi.findCardNoteList(cardIds)) || [];
const lectureTableViews = offsetRequiredCard.results.map((card) => {
const mainCategory = card.categories.find(
(category) => category.mainCategory === true
) || {
collegeId: '',
channelId: '',
mainCategory: false,
};
const student =
cardStudents &&
cardStudents.find((student) => student.lectureId === card.id);
const useNote =
(cardNotes &&
cardNotes.length > 0 &&
cardNotes.some((note: any) => {
if (note?.cardId === card.id) {
return true;
}
return false;
})) ||
false;
if (student) {
const lectureTableView = new LectureTableViewModel();
lectureTableView.serviceId = card.id;
lectureTableView.type = card.type;
lectureTableView.category = mainCategory;
lectureTableView.difficultyLevel = card.difficultyLevel || '';
// 김민준
lectureTableView.name = card.name;
lectureTableView.learningTime = card.learningTime;
lectureTableView.learningState = student.learningState;
lectureTableView.updateTime = student.modifiedTime;
lectureTableView.updateTimeForTest = student.modifiedTimeForTest;
lectureTableView.passedLearningCount = student.completePhaseCount;
lectureTableView.totalLearningCount = student.phaseCount;
lectureTableView.useNote = useNote;
return lectureTableView;
}
const lectureTableView = new LectureTableViewModel();
lectureTableView.serviceId = card.id;
lectureTableView.type = card.type;
lectureTableView.category = mainCategory!;
lectureTableView.difficultyLevel = card.difficultyLevel!;
// 김민준
lectureTableView.name = card.name;
lectureTableView.learningTime = card.learningTime;
lectureTableView.useNote = useNote;
return lectureTableView;
});
runInAction(() => {
this._lectureTableViews = lectureTableViews;
this._lectureTableViewCount = offsetRequiredCard.totalCount;
});
return false;
}
return true;
}
@action
async findAllRqdTableViewsWithPage(offset: Offset) {
this._lectureFilterRdoV2.setOffset(offset);
const cardRdo = this._lectureFilterRdoV2.toCardRdo();
const offsetRequiredCard = await findCardsByRdo(cardRdo);
if (
offsetRequiredCard &&
offsetRequiredCard.results &&
offsetRequiredCard.results.length > 0
) {
const cardIds = offsetRequiredCard.results.map((card) => card.id);
const cardStudents = await findCardStudentsByCardIds(cardIds);
const cardNotes =
(await this.myTrainingApi.findCardNoteList(cardIds)) || [];
const addLectureTableViews = offsetRequiredCard.results.map((card) => {
const mainCategory = card.categories.find(
(category) => category.mainCategory === true
) || {
collegeId: '',
channelId: '',
mainCategory: false,
};
const student =
cardStudents &&
cardStudents.find((student) => student.lectureId === card.id);
const useNote =
(cardNotes &&
cardNotes.length > 0 &&
cardNotes.some((note: any) => {
if (note?.cardId === card.id) {
return true;
}
return false;
})) ||
false;
if (student) {
const lectureTableView = new LectureTableViewModel();
lectureTableView.serviceId = card.id;
lectureTableView.type = card.type;
lectureTableView.category = mainCategory;
lectureTableView.difficultyLevel = card.difficultyLevel || '';
// 김민준
lectureTableView.name = card.name;
lectureTableView.learningTime = card.learningTime;
lectureTableView.learningState = student.learningState;
lectureTableView.updateTime = student.updateTime;
lectureTableView.updateTimeForTest = student.updateTimeForTest;
lectureTableView.passedLearningCount = student.completePhaseCount;
lectureTableView.totalLearningCount = student.phaseCount;
lectureTableView.useNote = useNote;
return lectureTableView;
}
const lectureTableView = new LectureTableViewModel();
lectureTableView.serviceId = card.id;
lectureTableView.type = card.type;
lectureTableView.category = mainCategory!;
lectureTableView.difficultyLevel = card.difficultyLevel!;
// 김민준
lectureTableView.name = card.name;
lectureTableView.learningTime = card.learningTime;
lectureTableView.useNote = useNote;
return lectureTableView;
});
runInAction(() => {
this._lectureTableViews = [
...this._lectureTableViews,
...addLectureTableViews,
];
this._lectureTableViewCount = offsetRequiredCard.totalCount;
});
}
}
@action
sortTableViews(column: string, direction: Direction) {
const propKey = converToKey(column);
if (direction === Direction.ASC) {
this._lectureTableViews = this._lectureTableViews.sort(
(a, b) => a[propKey] - b[propKey]
);
return;
}
if (direction === Direction.DESC) {
this._lectureTableViews = this._lectureTableViews.sort(
(a, b) => b[propKey] - a[propKey]
);
}
}
@action
sortMyTrainingCards(column: string, direction: Direction) {
const propKey =
converToKey(column) === 'updateTime'
? 'modifiedTime'
: converToKey(column);
if (direction === Direction.ASC) {
this._myLearningCards = this._myLearningCards.sort(
(a, b) => a[propKey] - b[propKey]
);
return;
}
if (direction === Direction.DESC) {
this._myLearningCards = this._myLearningCards.sort(
(a, b) => b[propKey] - a[propKey]
);
}
}
@action
sortEnrolledCards(column: string, direction: Direction) {
//
const propKey = convertToKeyInMyLearningTable(column);
if (direction === Direction.ASC) {
this.enrolledList = this.enrolledList.sort(
(a, b) => a[propKey] - b[propKey]
);
return;
}
if (direction === Direction.DESC) {
this.enrolledList = this.enrolledList.sort(
(a, b) => b[propKey] - a[propKey]
);
}
}
@action
clearAllTabCount() {
this.requiredLecturesCount = 0;
}
@action
async findEnrolledList() {
const result = await this.lectureApi.findEnrolledList();
const cardIds = (await result.map((card) => card.cardId)) || [];
const usingNoteList = await this.lectureApi.findCardNoteList(cardIds);
runInAction(() => {
result &&
result.map((card) => {
card.useNote =
(usingNoteList &&
usingNoteList.length > 0 &&
usingNoteList.some(
(noteCard: string) => noteCard === card.cardId
)) ||
false;
this.enrolledList.push(new EnrolledCardModel(card));
});
});
result.length !== this.enrolledCount && this.countLearningTab();
}
// 찜한 과정 체크박스 이벤트
@action
onAllCheckedCard() {
const checkedCardIds = getAddLearningCardIds();
const isAllChecked = checkedCardIds.length === this._myLearningCards.length;
if (isAllChecked) {
setAddLearningCardIds([]);
} else {
const allCardIds = this._myLearningCards.map((card) => card.id);
setAddLearningCardIds(allCardIds);
}
}
// 찜한 과정 체크박스 이벤트
@action
onCheckedCard(_: React.MouseEvent, data: CheckboxProps) {
const checkedCardIds = getAddLearningCardIds();
const cardId = data.value as string;
const isChecked = checkedCardIds.includes(cardId);
if (isChecked) {
const filteredCardIds = checkedCardIds.filter(
(checkedCardId) => checkedCardId !== cardId
);
setAddLearningCardIds(filteredCardIds);
} else {
const addedCardIds = [...checkedCardIds, cardId];
setAddLearningCardIds(addedCardIds);
}
}
}
LectureService.instance = new LectureService(
LectureApi.instance,
LectureFlowApi.instance,
StudentFlowApi.instance,
MyTrainingApi.instance
);
export default LectureService;
/* globals */
const converToKey = (column: string): any => {
switch (column) {
case '학습시간':
return 'learningTime';
case '최근학습일':
return 'updateTime';
case '스탬프':
return 'stampCount';
case '등록일':
return 'creationTime';
default:
return '';
}
};
export const convertToKeyInMyLearningTable = (column: string): any => {
switch (column) {
case '학습시간':
return 'learningTime';
case '학습완료일':
return 'passedTime';
case '최근학습일':
case '취소/미이수일':
return 'modifiedTime';
case '스탬프':
return 'stampCount';
case '획득일자':
return 'passedTime';
case '학습예정일':
return 'longLearningStartDate';
default:
return '';
}
};
|
# Football Results - Web Frontend using Open Data
## Faculty: BUT FIT, Course: WAP
For this project, we used [React](https://react.dev/) with [Typescript](https://www.typescriptlang.org/). [Vite](https://vitejs.dev/guide/build) for building and [MUI](https://mui.com/system/styles/basics/) for styling.
For the documentation the [jsdoc](https://jsdoc.app/) with [betterdocs](https://betterdocs.co/) was used
For the tests, we primarily did manual testing, trying all possible teams/players/leagues to render and clicking on everything. We also did End-to-End automatic tests with [Selenium](https://www.selenium.dev), which require the [Chromium driver](https://sites.google.com/chromium.org/driver/).
**Points: 29/30**
## Team:
**Name: xkanko00 (Adam Kaňkovský)**
Name: xbakaj00 (Štěpán Bakaj)
Name: xkuzni04 (Jakub Kuznik)
## Files
| File | Purpose |
|-------------|---------|
| README.md | Readme with all the instructions |
| index.html | Entry point web page. |
| package.json | Project dependencies and settings. |
| tsconfig.json | Typescript settings. |
| vite.config.ts | Vite build tool settings. |
| docs/* | Documetnation generated using jsdoc and better-docs|
| public/* | Contains images and gifs.|
| src/components/* | All the web components. |
| src/hooks/* | Custom hooks for loading the data. |
| src/stores/* | Features of the main top bar. |
| tests/* | Selenium tests |
## Instal Dependencies
Tested with node.js version `20.12.2`
```npm install```
## Run
```npm run dev```
## Run in produciton
This will first compile typescript files into the js and them it build project for production with the optimalization.
```npm run build```
Then run on your server. You can try run on:
```npm install -g http-server```
```http-server dist```
## Generate documentation
```npm run doc```
## Run tests
Run with the port where the application is running:
```npm test PORT```
example
```npm test 1234```
## Explain your decision
For a long time before the actual development of the application, we researched current technologies and tried to choose the most actual ones that are used in practice.
### Build tool
For the actual running of the application we chose [Vite](https://vitejs.dev/guide/) which takes care of the actual running of the application and the configuration of the proxy server for the API.
### UI library
For development we chose React, because it is still one of the most used frameworks for creating Web UI.
### Eslint
A long time before the development we also spent a lot of time setting up eslint rules to make our code not only functional, but also formatted correctly as much as possible, so we have set rules for writing double quotes, import and agrumnent stamping and also for type correctness.
### Component library
Another integral part was the selection of the component library, where after trying several libraries such as [Ant](https://ant.design/docs/react/getting-started), [Chakra](https://chakra-ui.com/getting-started) and [React-bootsrap](https://react-bootstrap.netlify.app/docs/getting-started/introduction/) we finally chose the most unused one [MUI](https://mui.com/material-ui/getting-started/), where the most important for us was the possibility of creating our own theme, which was actually required by the specification.
### API calls
For queries to the API I used react-query, mainly because it uses the cache and so the API is not so tired by repeated queries for the same results, because the API is quite a bottleneck in this project and frequent calls could slow down the work with the application.
### Persist color mode and selected competition
For better user-friendliness, we used the browser memory persistence to store the current color mode and selected competiton. Thanks to this, when returning to the page, the user can always count the competition he/she last browsed in the color mode he/she used.
### Palette mode
In Material-UI (MUI), the "palette mode" is a feature within the theme configuration that allows developers to define
and switch between "light" and "dark" color schemes. This capability enhances visual accessibility and user experience
by adapting the application's appearance to match user preferences or ambient lighting conditions.
Palette mode is seamlessly integrated into the theme system of MUI, enabling dynamic style adjustments across the
application components based on the selected mode. Configuration is located in src/theme.tsx.
## Open data source
[football-data.org](https://www.football-data.org)
|
import { useContext, useEffect, useState } from "react";
import SideNavBottomSection from "./SideNavBottomSection";
import { useConvex, useMutation } from "convex/react";
import { api } from "@/convex/_generated/api";
import { Team } from "@/app/types/Team";
import { useKindeBrowserClient } from "@kinde-oss/kinde-auth-nextjs";
import { toast } from "sonner";
import SideNavTopSection from "./SideNavTopSection";
import { FileListContext } from "@/app/context/FileListContext";
function SideNav() {
const { setFileList } = useContext(FileListContext);
const convex = useConvex();
const createFile = useMutation(api.files.createFile);
const { user } = useKindeBrowserClient();
const [totalFiles, setTotalFiles] = useState<number>(0);
const [activeTeam, setActiveTeam] = useState<Team | null>();
const getFiles = async () => {
const result = await convex.query(api.files.getFiles, {
teamId: "2",
});
setFileList(result);
setTotalFiles(result?.length);
};
const onFileCreate = (fileName: string) => {
user?.email &&
createFile({
fileName: fileName,
teamId: "2",
createdBy: user?.email,
archive: false,
document: "",
whiteboard: "",
})
.then((res) => {
if (res) {
getFiles();
toast("File created successfully!");
console.log(res);
}
})
.catch((e) => {
toast("Error while creating file");
});
};
useEffect(() => {
activeTeam && getFiles();
}, [activeTeam]);
return (
<div
className=" h-screen
fixed w-72 borde-r border-[1px] p-6
flex flex-col
"
>
<div className="flex-1">
<SideNavTopSection
user={user}
activeTeam={activeTeam}
setActiveTeam={(activeTeam: Team) => setActiveTeam(activeTeam)}
/>
</div>
<div>
<SideNavBottomSection
totalFiles={totalFiles}
onFileCreate={onFileCreate}
/>
</div>
</div>
);
}
export default SideNav;
|
from rest_framework import serializers, validators
from .models import Student
# Validators
def start_with_j(value):
if value[0].lower() != 'j':
raise serializers.ValidationError('Name should be start with J')
class StudentSerializer(serializers.Serializer):
name = serializers.CharField(max_length=100, validators=[start_with_j])
roll = serializers.IntegerField()
city = serializers.CharField(max_length=100)
def create(self, validated_data):
return Student.objects.create(**validated_data)
def update(self, instance, validated_data):
print(instance.name)
instance.name = validated_data.get('name', instance.name)
print(instance.name)
instance.roll = validated_data.get('roll', instance.roll)
instance.city = validated_data.get('city', instance.city)
instance.save()
return instance
# Field level validation
def validate_roll(self, value):
if value >= 200:
raise serializers.ValidationError('Seat Full')
return value
# Object level validation
def validate(self, data):
nm = data.get('name')
ct = data.get('city')
if nm.lower() == 'rafsan' and ct.lower() != 'barisal':
raise serializers.ValidationError('City must be Barisal !')
return data
|
import { Body, Controller, Delete, Get, Patch, Post } from '@nestjs/common';
import {
ApiBody,
ApiOkResponse,
ApiOperation,
ApiParam,
ApiTags,
} from '@nestjs/swagger';
import { RoleType } from '../../constants';
import {
ApiTranslateOptions,
Auth,
AuthUser,
UUIDParam,
} from '../../decorators';
import { UserEntity } from '../user/user.entity';
import { ParamTodoType } from './decorators';
import { CategoryRecommendationDto } from './dto/category-recommendation.dto';
import { CategoryRecommendationV2Dto } from './dto/category-recommendation-v2.dto';
import { CreateMultipleCategoriesTasksDto } from './dto/create-multiple-categories-tasks.dto';
import { CreateTodoCategoryDto } from './dto/create-todo-category.dto';
import { RecommendedCategoryDto } from './dto/recommended-category.dto';
import { TodoCategoryDto } from './dto/todo-category.dto';
import { UpdateTodoCategoryDto } from './dto/update-todo-category.dto';
import { TodoCategoriesService } from './todo-categories.service';
import { TodoType } from './types/todo.type';
@Controller('todo-categories')
@ApiTags('Todo categories')
export class TodoCategoriesController {
constructor(private readonly todoCategoriesService: TodoCategoriesService) {}
@Get()
@ApiOperation({ description: 'Get all todo categories' })
@ApiOkResponse({
type: [TodoCategoryDto],
})
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER, RoleType.KID])
async findAll(@AuthUser() user: UserEntity) {
const categories = await this.todoCategoriesService.findAll(user);
return categories.toDtos();
}
/**
*
* @deprecated
* TODO: To be removed after confirmation of the old app version is longer in used
*/
@Get('5-mins')
@ApiOperation({ description: 'Get categories and tasks recommendation' })
@ApiTranslateOptions()
@ApiOkResponse({
type: [CategoryRecommendationDto],
})
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER, RoleType.KID])
getCategoriesRecommendation() {
return this.todoCategoriesService.getCategoriesRecommendation();
}
// TODO: Remove the old one
@Get('v2/5-mins')
@ApiOperation({
description: 'Get categories and tasks recommendation - version 2',
})
@ApiTranslateOptions()
@ApiOkResponse({
type: [CategoryRecommendationV2Dto],
})
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER, RoleType.KID])
getCategoriesRecommendationV2() {
return this.todoCategoriesService.getCategoriesRecommendationV2();
}
@Get(':type')
@ApiOperation({ description: 'Get todo categories by type' })
@ApiParam({
name: 'type',
enum: TodoType,
})
@ApiOkResponse({
type: [TodoCategoryDto],
})
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER, RoleType.KID])
async findByType(
@AuthUser() user: UserEntity,
@ParamTodoType() type: TodoType,
) {
const categories = await this.todoCategoriesService.findByType(user, type);
return categories.toDtos();
}
@Post()
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER])
@ApiOperation({ description: 'Create a todo category' })
@ApiOkResponse({
type: TodoCategoryDto,
})
create(
@AuthUser() user: UserEntity,
@Body() createTodoCategoryDto: CreateTodoCategoryDto,
) {
return this.todoCategoriesService.create(user, createTodoCategoryDto);
}
@Post('create-many')
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER])
@ApiOperation({ description: 'Create multiple categories and tasks' })
@ApiBody({ type: [CreateMultipleCategoriesTasksDto] })
@ApiOkResponse({
type: [TodoCategoryDto],
})
createMany(
@AuthUser() user: UserEntity,
@Body() manyCategories: CreateMultipleCategoriesTasksDto[],
) {
return this.todoCategoriesService.createMany(user, manyCategories);
}
@Post('v2/create-many')
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER])
@ApiOperation({ description: 'Create multiple categories and tasks v2' })
@ApiBody({ type: [RecommendedCategoryDto] })
@ApiOkResponse({
type: [TodoCategoryDto],
})
createManyV2(
@AuthUser() user: UserEntity,
@Body() manyCategories: RecommendedCategoryDto[],
) {
return this.todoCategoriesService.createManyV2(user, manyCategories);
}
@Patch(':id')
@Auth([RoleType.SPOUSE, RoleType.ADMIN, RoleType.SUPERUSER])
@ApiOperation({ description: 'Update a todo category' })
@ApiOkResponse({
type: TodoCategoryDto,
})
update(
@UUIDParam('id') id: Uuid,
@Body() updateTodoCategoryDto: UpdateTodoCategoryDto,
) {
return this.todoCategoriesService.update(id, updateTodoCategoryDto);
}
@Delete(':id')
@ApiOperation({ description: 'Delete a todo category' })
@Auth([RoleType.SPOUSE, RoleType.ADMIN])
remove(@UUIDParam('id') id: Uuid) {
return this.todoCategoriesService.remove(id);
}
}
|
Console Log with CSS
--------------------
format:
%c // apply css
%s // message placeholder
syntax:
console.log('%c <message>', '<style>');
console.log('%c%s', '<style>', '<message>');
support:
console.log
console.info
console.debug
console.warn
console.error
sample:
console.log('%cHello World', 'color: green');
console.log('%cHello World', 'color: green; font-size: 22px;');
console.log('%cHello World', 'color: green; font-size: 22px; font-family: serif;');
console.log('%cHello World', 'color: #fff; background: red; padding: 10px;');
// using array
const styles = [
'color: #fff',
'background: red',
'padding: 10px'
].join(';');
console.log('%cHello World', styles);
// using %s
console.log('%c%s', styles, 'Hello World');
|
package com.example.testcomposethierry.data.http
import com.example.testcomposethierry.data.models.DataResponseRealm
import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.ext.query
import okhttp3.Headers
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.asResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer
import java.io.IOException
import javax.inject.Inject
class PersistentHttpDataManager @Inject constructor(
) {
private var realm: Realm
private val responseHeaders = Headers.Builder()
.add("content-type", "application/json")
.add("strict-transport-security", "max-age=2592000")
.add("request-context", "appId=cid-v1:5f69f122-c4a2-4f7d-8b1e-6d66af0e0e99")
.add("x-powered-by", "ASP.NET")
.add("x-cache", "CONFIG_NOCACHE")
.build()
init {
val config = RealmConfiguration.create(schema = setOf(DataResponseRealm::class))
realm = Realm.open(config)
}
fun saveResponse(url: String, response: Response) {
try {
response.body?.let { body2 ->
val body3 = copyBody(body2, 1000000)
body3?.let { body4 ->
realm.writeBlocking {
copyToRealm(
DataResponseRealm(
url = url,
body = body4.bytes(),
), UpdatePolicy.ALL
)
}
}
}
} catch(t: Throwable) {
println(t.message)
}
}
fun loadResponse(url: String, request: Request, response: Response?) : Response {
try {
return realm.writeBlocking {
val data: DataResponseRealm = realm.query<DataResponseRealm>("url == $0", url).find().firstOrNull() ?: DataResponseRealm()
val builder: Response.Builder = Response.Builder()
builder
.protocol(response?.protocol ?: Protocol.HTTP_2)
.request(request)
.headers(responseHeaders)
.code(200)
.message("success")
.body(data.body.toResponseBody(String.format("application/json; charset=utf-8").toMediaType()))
builder.build()
}
} catch(t: Throwable) {
println(t.message)
throw t
}
}
/**
* Returns a copy of `body` without consuming it. This buffers up to `limit` bytes of
* `body` into memory.
*
* @throws IOException if `body` is longer than `limit`.
*/
// https://github.com/square/okhttp/issues/1740
@Throws(IOException::class)
private fun copyBody(body: ResponseBody, limit: Long): ResponseBody? {
val source = body.source()
if (source.request(limit)) throw IOException("body too long!")
val bufferedCopy: Buffer = source.buffer.clone()
return bufferedCopy.asResponseBody(body.contentType(), body.contentLength())
}
fun close() {
realm.close()
}
}
|
package com.security.config.security.hander;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.security.dto.request.ApiError;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(
HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
ApiError error = new ApiError();
error.setMessage("Acesso negado. Não tem permissão necessária para acessar esta função. Por favor contactar o administardor do sistema.");
error.setBackedMessage(accessDeniedException.getLocalizedMessage());
error.setTime(LocalDateTime.now());
error.setHttpCode(HttpStatus.FORBIDDEN.value());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
String apiErroToJson = objectMapper.writeValueAsString(error);
response.getWriter().write(apiErroToJson);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpStatus.FORBIDDEN.value());
}
}
|
export abstract class StorageService implements Storage{
constructor(protected readonly api:Storage) { }
get length(): number{
return this.api.length;
}
setItem(key: string, value: unknown): void {
const data = JSON.stringify(value);
this.api.setItem(key, data);
}
getItem<T>(key: string): T | null {
const data = this.api.getItem(key);
if (data!== null) {
return JSON.parse(data) as T;
}
return null;
}
clear(): void {
this.api.clear();
}
key(index: number): string | null {
return this.api.key(index);
}
removeItem(key: string): void {
this.api.removeItem(key);
}
}
|
#!/usr/bin/python3
"""This module defines a base class for all models in our hbnb clone"""
import uuid
from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Integer, String, Text, Column, DateTime
Base = declarative_base()
class BaseModel:
"""A base class for all hbnb models"""
"""A base class for all hbnb models"""
id = Column(String(60), unique=True, nullable=False, primary_key=True)
created_at = Column(DateTime, default=datetime.utcnow(), nullable=False)
updated_at = Column(DateTime, default=datetime.utcnow(), nullable=False)
def __init__(self, *args, **kwargs):
"""Instatntiates a new model"""
self.id = str(uuid.uuid4())
self.created_at = datetime.now()
self.updated_at = datetime.now()
if kwargs:
if 'updated_at' in kwargs.keys():
kwargs['updated_at'] = datetime.strptime(kwargs['updated_at'],
'%Y-%m-%dT%H:%M:%S.%f')
if 'created_at' in kwargs.keys():
kwargs['created_at'] = datetime.strptime(kwargs['created_at'],
'%Y-%m-%dT%H:%M:%S.%f')
if '__class__' in kwargs.keys():
del kwargs['__class__']
self.__dict__.update(kwargs)
for k, v in kwargs.items():
if k != '__class__':
setattr(self, k, v)
def __str__(self):
"""Returns a string representation of the instance"""
cls = (str(type(self)).split('.')[-1]).split('\'')[0]
return '[{}] ({}) {}'.format(cls, self.id, self.to_dict())
def save(self):
"""Updates updated_at with current time when instance is changed"""
from models import storage
self.updated_at = datetime.now()
storage.new(self)
storage.save()
def to_dict(self):
"""Convert instance into dict format"""
dictionary = {}
dictionary.update(self.__dict__)
dictionary.update({'__class__':
(str(type(self)).split('.')[-1]).split('\'')[0]})
dictionary['created_at'] = self.created_at.isoformat()
dictionary['updated_at'] = self.updated_at.isoformat()
if '_sa_instance_state' in dictionary.keys():
del dictionary['_sa_instance_state']
return dictionary
def delete(self):
"Method of instance delate"
from models import storage
if storage.__objects is not None or storage.__objects != '{}':
for keys in storage.__objects.keys().copy():
storage.delete(keys)
|
import { lazy } from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import { Layout } from 'pages/Layout/Layout';
import { GlobalStyle } from 'styles/GlobalStyle';
const Home = lazy(() =>
import('pages/Home/Home' /* webpackChunkName: "Home" */)
);
const Movies = lazy(() =>
import('pages/Movies/Movies' /* webpackChunkName: "Movies" */)
);
const MovieDetails = lazy(() =>
import(
'components/MovieDetails/MovieDetails' /* webpackChunkName: "MovieDetails" */
)
);
const Cast = lazy(() =>
import('components/Cast/Cast' /* webpackChunkName: "Cast" */)
);
const Reviews = lazy(() =>
import('components/Reviews/Reviews' /* webpackChunkName: "Reviews" */)
);
export const App = () => {
return (
<>
<GlobalStyle />
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="movies" element={<Movies />} />
<Route path="movies/:movieId" element={<MovieDetails />}>
<Route path="cast" element={<Cast />} />
<Route path="reviews" element={<Reviews />} />
</Route>
</Route>
<Route
path="*"
element={
<>
<h2>404 Not found :(</h2>
<Link to="/">Back to home</Link>
</>
}
/>
</Routes>
</>
);
};
|
import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const sheet = new ServerStyleSheet();
const view = ctx.renderPage;
try {
ctx.renderPage = () =>
view({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: [initialProps.styles, sheet.getStyleElement()],
};
} finally {
sheet.seal();
}
}
}
|
import { DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MaritalData, Person, PersonData } from 'src/app/models/person';
import { PersonService } from 'src/app/services/person.service';
import { MaritalStatusService } from 'src/app/services/maritalStarus.service';
import { HttpErrorResponse } from '@angular/common/http';
import { MessageComponent } from '../message/message/message.component';
import { throwError } from 'rxjs/internal/observable/throwError';
import { catchError, map } from 'rxjs';
import { NgxPaginationModule } from 'ngx-pagination';
@Component({
selector: 'app-person',
templateUrl: './person.component.html',
styleUrls: ['./person.component.scss']
})
export class PersonComponent implements OnInit {
personaForm!: FormGroup;
currentPersona!: PersonData;
isEdit: boolean = false;
selectedFile: any;
opciones: MaritalData[] = [];;
listPersonas: PersonData[] = [];
EmployeeList: Person[] = [];
title = 'Evertecprueba';
textButton:string = "Guardar";
optionActual:string ="Registrando";
numberRecords:number=0;
currentPage: number = 1;
pageSize:number=10;
itemPerPage: number[] = [ 2,5,10,15,20];
constructor(private formBuilder: FormBuilder,
private personService: PersonService,
private maritalservice:MaritalStatusService,
private datePipe: DatePipe,
private message:MessageComponent,
) { }
formattedBirthDate( fecha: Date) {
return this.datePipe.transform(fecha, 'yyyy-MM-dd');
}
ngOnInit() {
this.personaForm = this.formBuilder.group({
nombre: ['', Validators.required],
apellido: ['', Validators.required],
fecha_nacimiento: ['', Validators.required],
foto_usuario: [''],
estado_civil: ['', Validators.required],
tiene_hermanos: ['', Validators.required],
file: ['', Validators.required]
});
this.getMaritasStatus();
this.getinitialData();
}
onSubmit() {
const formData = this.personaForm.value;
const newPersona: Person = {
Id: this.EmployeeList.length + 1,
name: formData.nombre,
LastName: formData.apellido,
BirthDate: formData.fecha_nacimiento,
MaritalStatus: formData.estado_civil,
HasSiblings: formData.tiene_hermanos,
Photo:this.selectedFile
};
this.personService.create(newPersona).subscribe({
complete:() => {
this.message.showToastSuccesfull("Empleado ingresado satisfactoriamnete");
this.getinitialData();
this.personaForm.reset();
},
error: (error) =>{
this.message.showToastFailed(error);
}
});
}
handleFileInput(files: any) {
let fileList: FileList = files.target.files;
const file: File = fileList[0];
var pattern = /image-*/;
const reader = new FileReader();
if (!file.type.match(pattern)) {
this.message.showToastFailed('invalid format');
alert('invalid format');
return;
}
reader.onloadend = this._handleReaderLoaded.bind(this);
reader.readAsDataURL(file);
}
_handleReaderLoaded(e:any) {
let reader = e.target;
var base64result = reader.result.substr(reader.result.indexOf(',') + 1);
this.selectedFile = base64result;
}
onEdit(persona: PersonData) {
this.isEdit = true;
this.textButton ="Actualizar"
this.optionActual="Actualizando"
this.currentPersona = persona;
this.personaForm.setValue({
nombre : persona.name,
apellido: persona.lastName,
fecha_nacimiento:this.formattedBirthDate(persona.birthDate),
foto_usuario: persona.photo,
estado_civil: persona.id_marital,
tiene_hermanos: persona.hasSiblings,
file:persona.photo
});
}
onUpdate() {
const formData = this.personaForm.value;
this.currentPersona.name =formData.nombre;
this.currentPersona.lastName = formData.apellido;
this.currentPersona.birthDate = formData.fecha_nacimiento;
this.currentPersona.photo = this.selectedFile;
this.currentPersona.maritalStatus = formData.estado_civil;
this.currentPersona.hasSiblings = formData.tiene_hermanos;
this.personService.update(this.currentPersona)
.pipe(
map((response: any) => {
this.message.showToastSuccesfull(response.message);
}),
catchError(error => {
console.error(error);
this.message.showToastFailed(error);
return throwError(() => error);
})
)
.subscribe(response => {
console.log(response);
});
///.subscribe({
// // complete:() => {
// // this.message.showToastSuccesfull("Empleado Actualizado con Exito!!")
// // this.getinitialData();
// // },
// // error: (error) =>{
// // this.message.showToastFailed(error);
// // }
// })
this.isEdit = false;
this.textButton ="Guardar";
this.optionActual="Registrando";
this.personaForm.reset();
}
onDelete(persona: PersonData) {
this.optionActual="Eliminando";
let data = JSON.stringify(persona);
console.log(data);
this.personService.delete(data).subscribe ({
complete:() => {
this,this.message.showToastSuccesfull("Empleado Eliminado con !!Exito")
this.getinitialData();
this.optionActual="Registrando";
},
error: (error:HttpErrorResponse) =>{
this,this.message.showToastFailed(error.message);
alert(error.message)
}
});
}
getinitialData():void{
this.personService.getAll(this.currentPage, this.pageSize).subscribe(datos => {
this.listPersonas = datos;
this.numberRecords=datos[0].totalRecords;
});
}
onPageChanged(event: any) {
this.currentPage = event;
this.getinitialData();
}
onPageSizeChange(event:any):void{
this.pageSize = event.target.value;
this.currentPage =1;
this.getinitialData();
}
getMaritasStatus(){
this.maritalservice.getAll().subscribe(opciones => {
this.opciones = opciones;
});
}
onReset(){
this.personaForm.reset();
}
}
|
import { connect } from 'react-redux'
import { clearPokemon, lookupPokemon } from '../actions'
import Favourites from '../components/Favourites'
/**
*
* @param state {
* // list of favourites that can be populated through the initial application
* // syncing state or the uesr adding and removing entries
* favourites: Favourite[]
* }
*/
const mapStateToProps = (state) => {
return {
favourites: state.favourites,
inProgress: state.selected.inProgress,
selectedPokemon: state.selected.pokemon
}
}
/**
*
* @resolves dispatchProps {
* // store hook into the user requesting a new search, this will clear the existing
* // session
* onSelectSearch: (): void
* }
*/
const mapDispatchToProps = (dispatch) => {
return {
onSelectSearch: () => dispatch(clearPokemon()),
onSelectFavourite: (pokemonName) => dispatch(lookupPokemon(pokemonName))
}
}
const SessionFavourites = connect(mapStateToProps, mapDispatchToProps)(Favourites)
export default SessionFavourites
|
package com.example.appdum.ui.donaciones
import androidx.lifecycle.ViewModel
import com.example.appdum.api.RetrofitInstance
import com.example.appdum.model.Donacion
import com.paypal.checkout.approve.OnApprove
import com.paypal.checkout.cancel.OnCancel
import com.paypal.checkout.createorder.CreateOrder
import com.paypal.checkout.createorder.CurrencyCode
import com.paypal.checkout.createorder.OrderIntent
import com.paypal.checkout.createorder.UserAction
import com.paypal.checkout.error.ErrorInfo
import com.paypal.checkout.error.OnError
import com.paypal.checkout.order.*
import com.paypal.checkout.paymentbutton.PayPalButton
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class SlideshowViewModel : ViewModel() {
fun setupPaypal(payPalButton: PayPalButton, monto: String, preID: String, correo: String, view: com.example.appdum.ui.donaciones.SlideshowFragment){
payPalButton.setup(
createOrder = CreateOrder { createOrderActions ->
val order = Order(
intent = OrderIntent.CAPTURE,
appContext = AppContext(
userAction = UserAction.PAY_NOW
),
purchaseUnitList = listOf(
PurchaseUnit(
amount = Amount(
currencyCode = CurrencyCode.MXN,
value = "$monto"
)
)
)
)
createOrderActions.create(order)
},
onApprove = OnApprove { approval ->
approval.orderActions.capture { captureOrderResult ->
//Log.i("CaptureOrder", "CaptureOrderResult: $captureOrderResult")
println("AAAAAAAAAAAAAAAAAAQUI: \n ${approval.data.paymentId} ${approval.data.orderId} ${approval.data.payerId}")
println("ORDER RESULT: ${captureOrderResult.toString()}")
var currentTime = System.currentTimeMillis()
var paymentID = preID + "${currentTime}"
view.toasting("¡Muchas gracias por tu donativo!")
transactionApproved(captureOrderResult, paymentID, monto, paymentID, correo)
println("$captureOrderResult")
}
},
onError = OnError { error ->
transactionError(error)
view.toasting("¡Oh, no! Ocurrió un error al procesar tu donativo.")
}
)
}
fun transactionApproved(orderResult: CaptureOrderResult, paymentID: String?, monto: String, ID:String, correo: String){
println("CORREO: ${correo}")
var donativo = Donacion(ID,monto,null,"1", correo)
val call = RetrofitInstance.servicioUsuarioApi.generarDonativo(donativo)
call.enqueue(object: Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
println(response)
if (response.isSuccessful) {
println("Registro exitoso")
println(response.body().toString())
if(response.body().toString()=="1"){//Error
//registroActivity.toasting("El correo o el RFC ya están registrados.")
}
else if(response.body().toString()=="0"){ //Exitoso
//registroActivity.toasting("Registro exitoso, puedes iniciar sesión.")
//registroActivity.finish()
}
} else {
println("Registro fallido")
println(response.body().toString())
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
//registroActivity.toasting("Verifica tu conexión a Internet.")
if(t.cause.toString() == "java.net.ConnectException: Network is unreachable"){
//registroActivity.toasting("Verifica tu conexión a Internet.")
}
else{
//registroActivity.toasting("El servidor no está disponible.")
}
}
})
println("Resultado: ${orderResult}")
println("paymentID:${paymentID}")
}
fun transactionError(error: ErrorInfo) {
println("Error: ${error.reason}")
}
}
|
// routes/users.js
const express = require("express");
const multer = require("multer");
const path = require("path");
const router = express.Router();
const passport = require("passport");
const jwt = require("jsonwebtoken");
const Users = require("../models/User.js");
const baseURL = "http://192.168.1.33:3000/download/users/";
// const baseURL = "https://8c73-171-97-8-66.ngrok-free.app/download/users/";
// Upload Setup
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "profileImage/");
},
filename: (req, file, cb) => {
const userId = req.params.id;
const extension = path.extname(file.originalname);
const fileName = `profileImage_${userId}${extension}`;
cb(null, fileName);
},
});
const upload = multer({ storage });
/**
* @swagger
* tags:
* name: Users
* description: APIs for managing users
*/
router.post("/login", (req, res, next) => {
passport.authenticate("local", { session: false }, (err, user, info) => {
if (err || !user) {
return res.status(401).json({ message: "Authentication failed", user, info });
}
try {
// Sign a JWT token with a secure secret key
const token = jwt.sign({ id: user._id, username: user.username }, process.env.JWT_SECRET, { expiresIn: "1h" });
return res.json({ token });
} catch (error) {
// Handle JWT signing error
console.error("JWT signing error:", error);
return res.status(500).json({ message: "Internal Server Error" });
}
})(req, res, next);
});
/**
* @swagger
* /users:
* get:
* summary: Get all users
* tags: [Users]
* responses:
* '200':
* description: List of users
* '500':
* description: Internal server error
*/
// GET All Users DATA
router.get("/", async (req, res, next) => {
try {
const users = await Users.find().exec();
res.json(users);
} catch (err) {
next(err);
}
});
/**
* @swagger
* /users/profile:
* get:
* summary: Get user profile
* tags: [Users]
* security:
* - bearerAuth: []
* responses:
* '200':
* description: User profile data
* '401':
* description: Unauthorized
* '404':
* description: User not found
* '500':
* description: Internal server error
*/
// GET User Profile
router.get("/profile", passport.authenticate("jwt", { session: false }), async (req, res) => {
try {
const { _id, username } = req.user;
const user = await Users.findOne({ username }).exec();
if (!user) {
return res.status(404).json({ message: "User not found" });
}
console.table({
id: _id.toString(),
username: user.username,
email: user.email,
address: user.address,
phoneNum: user.phoneNum,
dateOfBirth: user.dateOfBirth.toISOString().split("T")[0], // Convert date to YYYY-MM-DD format
image: user.image ? `${baseURL}${user.image}` : null, // Append baseURL to user's image file name if available
});
res.json({
id: _id.toString(),
username: user.username,
email: user.email,
address: user.address,
phoneNum: user.phoneNum,
dateOfBirth: user.dateOfBirth.toISOString().split("T")[0], // Convert date to YYYY-MM-DD format
image: user.image ? `${baseURL}${user.image}` : null, // Append baseURL to user's image file name if available
});
} catch (err) {
console.error(err);
res.status(500).json({ message: "Internal Server Error" });
}
});
/**
* @swagger
* /users/{id}:
* get:
* summary: Get user by ID
* tags: [Users]
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User ID
* responses:
* '200':
* description: User data
* '404':
* description: User not found
* '500':
* description: Internal server error
*/
// GET Users DATA (Single)
router.get("/:id", async (req, res, next) => {
try {
const user = await Users.findById(req.params.id).exec();
if (!user) {
return res.status(404).json({ message: "User not found" });
}
res.json(user);
} catch (err) {
next(err);
}
});
/**
* @swagger
* /users/{id}:
* put:
* summary: Update user details
* tags: [Users]
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User ID
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* properties:
* username:
* type: string
* email:
* type: string
* address:
* type: string
* phoneNum:
* type: string
* dateOfBirth:
* type: string
* format: date
* image:
* type: string
* format: binary
* responses:
* '200':
* description: User updated successfully
* '400':
* description: Bad request
* '404':
* description: User not found
* '500':
* description: Internal server error
*/
// UPDATE User DATA (Single) and image upload
router.put("/:id", upload.single("image"), async (req, res, next) => {
try {
const userId = req.params.id;
const user = await Users.findById(userId);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
user.username = req.body.username;
user.email = req.body.email;
user.address = req.body.address;
user.phoneNum = req.body.phoneNum;
user.dateOfBirth = req.body.dateOfBirth;
if (req.file) {
user.image = req.file.filename;
}
await user.save();
res.json(user);
} catch (err) {
res.status(500).json({ message: "Internal Server Error" });
}
});
/**
* @swagger
* /users/{id}:
* delete:
* summary: Delete user by ID
* tags: [Users]
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: User ID
* responses:
* '200':
* description: User deleted successfully
* '404':
* description: User not found
* '500':
* description: Internal server error
*/
// DELETE User by ID
router.delete("/:id", async (req, res, next) => {
try {
const deletedUser = await Users.findByIdAndDelete(req.params.id).exec();
if (!deletedUser) {
return res.status(404).json({ message: "User not found" });
}
res.json({ message: "User deleted successfully", user: deletedUser });
} catch (err) {
next(err);
}
});
module.exports = router;
|
import React, { useEffect, useState } from "react";
import Loading from "./Loading";
import { useParams, Link } from "react-router-dom";
const url = "https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=";
const SingleCocktail = () => {
const { id } = useParams();
const [isLoading, setIsLoading] = useState(false);
const [cocktail, setCocktail] = useState(null);
useEffect(() => {
setIsLoading(true);
async function getCocktail() {
try {
const data = await (
await fetch(
`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${id}`
)
).json();
if (data.drinks) {
const {
strDrink: name,
strDrinkThumb: image,
strAlcoholic: info,
strCategory: category,
strGlass: glass,
strInstructions: instructions,
strIngredient1,
strIngredient2,
strIngredient3,
strIngredient4,
strIngredient5,
} = data.drinks[0];
const ingredients = [
strIngredient1,
strIngredient2,
strIngredient3,
strIngredient4,
strIngredient5,
];
const newCocktail = {
name,
image,
info,
category,
glass,
instructions,
ingredients,
};
setCocktail(newCocktail);
} else {
setCocktail(null);
}
setIsLoading(false);
} catch (err) {
console.log(err);
setIsLoading(false);
}
}
getCocktail();
}, [id]);
if (isLoading) {
return <Loading />;
}
if (!cocktail) {
return <h2 className="section-title">No cocktail matched.</h2>;
}
const { name, image, category, info, glass, instructions, ingredients } =
cocktail;
return (
<section className="section cocktail-section">
<Link to={"/"} className="btn btn-primary">
Back
</Link>
<h2 className="section-title">{name}</h2>
<div className="drink">
<img src={image} alt={name} />
<div className="drink-info">
<p>
<span className="drink-data">name :</span> {name}
</p>
<p>
<span className="drink-data">category :</span> {category}
</p>
<p>
<span className="drink-data">info :</span> {info}
</p>
<p>
<span className="drink-data">glass :</span> {glass}
</p>
<p>
<span className="drink-data">instructons :</span> {instructions}
</p>
<p>
<span className="drink-data">ingredients :</span>
{ingredients.map((ingredient, index) => {
return ingredient ? <span key={index}>{ingredient}</span> : null;
})}
</p>
</div>
</div>
</section>
);
};
export default SingleCocktail;
|
import "reflect-metadata";
import "./extensions";
import express, { Express } from "express";
import dotenv from "dotenv";
import cors from "cors";
import { EnvService } from "./services/env-service";
import { graphqlHTTP } from "express-graphql";
import { getGraphqlContext } from "./graphql/type-defs";
import { buildSchema } from "type-graphql";
import { schemaOptions } from "./graphql/schema";
import { wellKnownNostrController } from "./controllers/well-known-nostr-controller";
import { hexController } from "./controllers/hex-controller";
import { reportFraudController } from "./controllers/report-fraud-controller";
import { confirmFraudController } from "./controllers/confirm-fraud-controller";
import { wellKnownLightningController } from "./controllers/well-known-lightning-controller";
import { testController } from "./controllers/test-controller";
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/lib/use/ws";
import { Context as WsContext } from "graphql-ws";
var path = require("path");
// Load any environmental variables from the local .env file
dotenv.config();
const GRAPHQL_ENDPOINT = "/graphql";
const WS_ENDPOINT = "/subscriptions";
const app: Express = express();
const port = EnvService.instance.env.PORT;
app.use(express.json());
app.use(cors());
app.set("views", path.join(__dirname, "views"));
app.engine("html", require("ejs").renderFile);
// API Controller routes
app.get("/.test", testController);
app.get("/.well-known/nostr.json", wellKnownNostrController);
app.get("/.well-known/lnurlp/:username", wellKnownLightningController);
app.get("/hex", hexController);
app.get("/", (req, res, next) => {
let appUrl = "";
// req.hostname could be:
// www.nip05.social
// nip05.social
// dev.nip05.social
// www.protonostr.com
// protonostr.com
// dev.protonostr.com
// localhost
// ...
if (req.hostname.includes("wwww.")) {
appUrl = `${req.protocol}://${req.hostname.replace("wwww.", "app.")}`;
} else if (req.hostname.includes("dev.")) {
appUrl = `${req.protocol}://${req.hostname.replace(
"dev.",
"dev.app."
)}`;
} else if (req.hostname.includes("localhost")) {
res.send("You are on localhost. No forwarding to any app location.");
return;
} else {
appUrl = `${req.protocol}://${"app." + req.hostname}`;
}
console.log(appUrl);
res.redirect(appUrl);
});
app.get("/report-fraud/:userId/:fraudId", reportFraudController);
app.get("/confirm-fraud/:userId/:fraudId", confirmFraudController);
async function bootstrap() {
const schema = await buildSchema(schemaOptions);
app.use(
GRAPHQL_ENDPOINT,
graphqlHTTP((req, res, graphQLParams) => {
return {
schema: schema,
context: getGraphqlContext(req),
graphiql: { headerEditorEnabled: true },
pretty: true,
};
})
);
const server = app.listen(port, () => {
console.log(`⚡️[server]: Running at http://localhost:${port}`);
console.log(`⚡️[server]: GraphQL endpoint is '${GRAPHQL_ENDPOINT}'`);
console.log(`⚡️[server]: WS endpoint is '${WS_ENDPOINT}'`);
// Start the Web Socket Server on the same port
const wsServer = new WebSocketServer({
server,
path: WS_ENDPOINT,
});
// https://github.com/enisdenjo/graphql-ws
useServer(
{
schema,
// On initial WS connect: Check and verify the user JWT and only setup the subscription with a valid token
// onConnect: async (ctx: WsContext) => {
// const params =
// ctx.connectionParams as unknown as WebSocketConnectionParams;
// try {
// const decodedPayload =
// await AccessTokenService.instance.verifyAsync(
// params.accessToken
// );
// console.log(
// `[ws-server] - ${new Date().toISOString()} - ${
// decodedPayload.email
// } has opened an authenticated web socket connection.`
// );
// } catch (error) {
// (ctx.extra as WsContextExtra).socket.close(
// 4401,
// "Unauthorized"
// ); // This will force the client to NOT reconnect
// }
// return true;
// },
// Every following subscription access will uses the initial JWT (from the "onConnect") in the connectionParams
context: (ctx: WsContext) => {
return {
name: "Peter",
};
// return getGraphqlSubContext(
// ctx.connectionParams as unknown as WebSocketConnectionParams
// );
},
},
wsServer
);
});
}
bootstrap();
|
# isemail
Node email address validation library
[](https://travis-ci.org/hapijs/isemail)<a href="#footnote-1"><sup>[1]</sup></a>
Lead Maintainer: [Eli Skeggs][skeggse]
This library is a port of the PHP `is_email` function by Dominic Sayers.
Install
=======
```sh
$ npm install isemail
```
Test
====
The tests were pulled from `is_email`'s extensive [test suite][tests] on October 15, 2013. Many thanks to the contributors! Additional tests have been added to increase code coverage and verify edge-cases.
Run any of the following.
```sh
$ lab
$ npm test
$ make test
```
_remember to_ `npm install` to get the development dependencies!
API
===
validate(email, [options])
--------------------------
Determines whether the `email` is valid or not, for various definitions thereof. Optionally accepts an `options` object. Options may include `errorLevel`.
Use `errorLevel` to specify the type of result for `validate()`. Passing a `false` literal will result in a true or false boolean indicating whether the email address is sufficiently defined for use in sending an email. Passing a `true` literal will result in a more granular numeric status, with zero being a perfectly valid email address. Passing a number will return `0` if the numeric status is below the `errorLevel` and the numeric status otherwise.
The `tldBlacklist` option can be either an object lookup table or an array of invalid top-level domains. If the email address has a top-level domain that is in the whitelist, the email will be marked as invalid.
The `tldWhitelist` option can be either an object lookup table or an array of valid top-level domains. If the email address has a top-level domain that is not in the whitelist, the email will be marked as invalid.
The `allowUnicode` option governs whether non-ASCII characters are allowed. Defaults to `true` per RFC 6530.
Only one of `tldBlacklist` and `tldWhitelist` will be consulted for TLD validity.
The `minDomainAtoms` option is an optional positive integer that specifies the minimum number of domain atoms that must be included for the email address to be considered valid. Be careful with the option, as some top-level domains, like `io`, directly support email addresses.
As of `3.1.1`, the `callback` parameter is deprecated, and will be removed in `4.0.0`.
### Examples
```js
$ node
> var Isemail = require('isemail');
undefined
> Isemail.validate('test@iana.org');
true
> Isemail.validate('test@iana.123');
true
> Isemail.validate('test@iana.org', {errorLevel: true});
0
> Isemail.validate('test@iana.123', {errorLevel: true});
10
> Isemail.validate('test@iana.123', {errorLevel: 17});
0
> Isemail.validate('test@iana.123', {errorLevel: 10});
10
> Isemail.validate('test@iana&12');
false
> Isemail.validate('test@iana&12', {errorLevel: true});
65
> Isemail.validate('test@', {errorLevel: true});
131
```
<sup name="footnote-1">[1]</sup>: if this badge indicates the build is passing, then isemail has 100% code coverage.
[skeggse]: https://github.com/skeggse "Eli Skeggs"
[tests]: http://isemail.info/_system/is_email/test/?all "is_email test suite"
|
//
// EncodeDecode+Helpers.swift
// Snack
//
// Created by Khaled Khaldi on 15/03/2022.
//
import Foundation
//import URLQueryItemEncoder
func newJSONEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
// encoder.keyEncodingStrategy = .convertToSnakeCase
return encoder
}
func newJSONDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
return decoder
}
extension DateFormatter {
static let json_T_DateTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" // "2023-03-28T17:04:24"
formatter.locale = Locale(identifier: "en_US_POSIX")
// formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
static let json_T_DateTimeFormatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" // "2023-03-07T11:56:50.8877295"
formatter.locale = Locale(identifier: "en_US_POSIX")
// formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
static let json_T_DateTimeFormatter3: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // "2023-05-04T11:53:13.5700758+03:00"
formatter.locale = Locale(identifier: "en_US_POSIX")
// formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
static let json_AM_PM_DateTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm a" // "2023-03-28 11:32 AM"
formatter.locale = Locale(identifier: "en_US_POSIX")
// formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
}
//func newURLQueryItemEncoder() -> URLQueryItemEncoder {
// let encoder = URLQueryItemEncoder()
// //encoder.keyEncodingStrategy = .convertToSnakeCase
// return encoder
//}
extension Array where Element == URLQueryItem {
var dictionaryStrings: [String: String?]? {
Dictionary(uniqueKeysWithValues: self.map { ($0.name, $0.value) })
}
}
extension Encodable {
var dictionary: [String: Any?]? {
guard let data = try? newJSONEncoder().encode(self) else { return nil }
let fragmented = try? JSONSerialization.jsonObject(
with: data,
options: .allowFragments
)
return fragmented as? [String: Any?]
}
}
// extension Encodable {
// var urlFormData: Data? {
// dictionary?
// .compactMap {key, value in "\(key)=\(value ?? "")" }
// .joined(separator:"&")
// .data(using: .utf8)
// }
// }
protocol CaseIterableDefaultsValue: Decodable & RawRepresentable
where Self.RawValue: Decodable {
static var defaultValue: Self { get }
}
extension CaseIterableDefaultsValue {
init(from decoder: Decoder) throws {
self = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? Self.defaultValue
}
}
extension Bool {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let boolVal = try? container.decode(Bool.self) {
self = boolVal
} else if let intVal = try? container.decode(Int.self) {
self = (intVal == 1)
} else if let string = try? container.decode(String.self).trimmingCharacters(in: .whitespacesAndNewlines) {
self = ["true", "yes", "1"].contains(string.lowercased())
} else {
self = false
}
}
}
extension KeyedDecodingContainer {
public func decodeIfPresent(_ type: String.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> String? {
do {
return try decode(String.self, forKey: key)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch DecodingError.typeMismatch {
return try String(decode(Int.self, forKey: key))
} catch { //DecodingError.typeMismatch, DecodingError.keyNotFound ,DecodingError.valueNotFound{
print("❌❌❌ \(error)")
return nil
}
}
public func decodeIfPresent(_ type: Int.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Int? {
do {
return try decode(Int.self, forKey: key)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch DecodingError.typeMismatch {
do {
return try Int(decode(String.self, forKey: key))
} catch DecodingError.typeMismatch {
return try Int(decode(Bool.self, forKey: key) == true ? 1 : 0)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch {
print("❌❌❌ \(error)")
return nil
}
} catch { //DecodingError.typeMismatch, DecodingError.keyNotFound ,DecodingError.valueNotFound{
print("❌❌❌ \(error)")
return nil
}
}
public func decodeIfPresent(_ type: Double.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Double? {
do {
return try decode(Double.self, forKey: key)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch {//DecodingError.typeMismatch, DecodingError.keyNotFound ,DecodingError.valueNotFound{
print("❌❌❌ \(error)")
return nil
}
}
public func decodeIfPresent(_ type: Bool.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Bool? {
do {
return try decode(Bool.self, forKey: key)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch DecodingError.typeMismatch {
do {
return try Bool(decode(Int.self, forKey: key) == 1)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch {
print("❌❌❌ \(error)")
return nil
}
} catch {//DecodingError.typeMismatch, DecodingError.keyNotFound, DecodingError.valueNotFound {
print("❌❌❌ \(error)")
return nil
}
}
// public func decodeIfPresent<T:Decodable>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> NewBaseResponse<T>? {
// do {
// return try decode(NewBaseResponse<T>.self, forKey: key)
// } catch {//DecodingError.typeMismatch, DecodingError.keyNotFound ,DecodingError.valueNotFound{
// return nil
// }
// }
public func decodeIfPresent<T: Decodable>(_ type: T?.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T? {
do {
return try decode(T?.self, forKey: key)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch { //DecodingError.typeMismatch, DecodingError.dataCorrupted {
print("❌❌❌ \(error)")
return nil
}
}
public func decodeIfPresent<T: Decodable>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T? {
do {
return try decode(T?.self, forKey: key)
} catch DecodingError.keyNotFound, DecodingError.valueNotFound {
return nil
} catch { //DecodingError.typeMismatch, DecodingError.dataCorrupted {
print("❌❌❌ \(error)")
return nil
}
}
// public func decodeIfPresent(_ type: [].Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> []? {
// do {
// return try decode(String.self, forKey: key)
// } catch {//DecodingError.typeMismatch, DecodingError.keyNotFound ,DecodingError.valueNotFound{
// return nil
// }
// }
}
// MARK: - JSONNumber
// enum JSONNumber<T: Numeric>: Codable where T: Codable { // Correct
// Numeric & Codable & LosslessStringConvertible
enum JSONNumber<T: Codable & LosslessStringConvertible>: Codable { // Correct
case value(T)
//case string(String)
var value: T {
switch self {
case .value(let num):
return num
// case .string(let string):
// return T(string)
}
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
// Decode the number
do {
let numVal = try container.decode(T.self)
self = .value(numVal)
} catch DecodingError.typeMismatch {
// Decode the string
let string = try container.decode(String.self)
if let value_ = T(string.trimmingCharacters(in: .whitespacesAndNewlines)) {
self = .value(value_)
} else {
throw DecodingError.typeMismatch(
T.self,
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Encoded payload not of an expected type"
)
)
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .value(let value):
try container.encode(value)
/*
case .string(let value):
try container.encode(value)
*/
}
}
}
// // MARK: - JSONString
//
// struct JSONString: Codable {
// let value: String
//
// static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError {
// let context = DecodingError.Context(codingPath: codingPath, debugDescription: "JSONString")
// return DecodingError.typeMismatch(JSONString.self, context)
// }
//
// init(from decoder: Decoder) throws {
// let container = try decoder.container(keyedBy: CodingKeys.self)
// if let value = try? container.decode(Bool.self, forKey: .value) {
// self.value = "\(value)"
//
// } else if let value = try? container.decode(Int64.self, forKey: .value) {
// self.value = "\(value)"
//
// } else if let value = try? container.decode(Double.self, forKey: .value) {
// self.value = "\(value)"
//
// } else if let value = try? container.decode(String.self, forKey: .value) {
// self.value = value
//
// } else {
// throw JSONString.decodingError(forCodingPath: container.codingPath)
//
// }
// }
//
// }
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {
hasher.combine(0)
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
class JSONCodingKey: CodingKey {
let key: String
required init?(intValue: Int) {
return nil
}
required init?(stringValue: String) {
key = stringValue
}
var intValue: Int? {
return nil
}
var stringValue: String {
return key
}
}
class JSONAny: Codable {
let value: Any
static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny")
return DecodingError.typeMismatch(JSONAny.self, context)
}
static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError {
let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny")
return EncodingError.invalidValue(value, context)
}
static func decode(from container: SingleValueDecodingContainer) throws -> Any {
if let value = try? container.decode(Bool.self) {
return value
}
if let value = try? container.decode(Int64.self) {
return value
}
if let value = try? container.decode(Double.self) {
return value
}
if let value = try? container.decode(String.self) {
return value
}
if container.decodeNil() {
return JSONNull()
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any {
if let value = try? container.decode(Bool.self) {
return value
}
if let value = try? container.decode(Int64.self) {
return value
}
if let value = try? container.decode(Double.self) {
return value
}
if let value = try? container.decode(String.self) {
return value
}
if let value = try? container.decodeNil() {
if value {
return JSONNull()
}
}
if var container = try? container.nestedUnkeyedContainer() {
return try decodeArray(from: &container)
}
if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) {
return try decodeDictionary(from: &container)
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any {
if let value = try? container.decode(Bool.self, forKey: key) {
return value
}
if let value = try? container.decode(Int64.self, forKey: key) {
return value
}
if let value = try? container.decode(Double.self, forKey: key) {
return value
}
if let value = try? container.decode(String.self, forKey: key) {
return value
}
if let value = try? container.decodeNil(forKey: key) {
if value {
return JSONNull()
}
}
if var container = try? container.nestedUnkeyedContainer(forKey: key) {
return try decodeArray(from: &container)
}
if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) {
return try decodeDictionary(from: &container)
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] {
var arr: [Any] = []
while !container.isAtEnd {
let value = try decode(from: &container)
arr.append(value)
}
return arr
}
static func decodeDictionary(from container: inout KeyedDecodingContainer<JSONCodingKey>) throws -> [String: Any] {
var dict = [String: Any]()
for key in container.allKeys {
let value = try decode(from: &container, forKey: key)
dict[key.stringValue] = value
}
return dict
}
static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws {
for value in array {
if let value = value as? Bool {
try container.encode(value)
} else if let value = value as? Int64 {
try container.encode(value)
} else if let value = value as? Double {
try container.encode(value)
} else if let value = value as? String {
try container.encode(value)
} else if value is JSONNull {
try container.encodeNil()
} else if let value = value as? [Any] {
var container = container.nestedUnkeyedContainer()
try encode(to: &container, array: value)
} else if let value = value as? [String: Any] {
var container = container.nestedContainer(keyedBy: JSONCodingKey.self)
try encode(to: &container, dictionary: value)
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
}
static func encode(to container: inout KeyedEncodingContainer<JSONCodingKey>, dictionary: [String: Any]) throws {
for (key, value) in dictionary {
let key = JSONCodingKey(stringValue: key)!
if let value = value as? Bool {
try container.encode(value, forKey: key)
} else if let value = value as? Int64 {
try container.encode(value, forKey: key)
} else if let value = value as? Double {
try container.encode(value, forKey: key)
} else if let value = value as? String {
try container.encode(value, forKey: key)
} else if value is JSONNull {
try container.encodeNil(forKey: key)
} else if let value = value as? [Any] {
var container = container.nestedUnkeyedContainer(forKey: key)
try encode(to: &container, array: value)
} else if let value = value as? [String: Any] {
var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key)
try encode(to: &container, dictionary: value)
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
}
static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws {
if let value = value as? Bool {
try container.encode(value)
} else if let value = value as? Int64 {
try container.encode(value)
} else if let value = value as? Double {
try container.encode(value)
} else if let value = value as? String {
try container.encode(value)
} else if value is JSONNull {
try container.encodeNil()
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
public required init(from decoder: Decoder) throws {
if var arrayContainer = try? decoder.unkeyedContainer() {
self.value = try JSONAny.decodeArray(from: &arrayContainer)
} else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) {
self.value = try JSONAny.decodeDictionary(from: &container)
} else {
let container = try decoder.singleValueContainer()
self.value = try JSONAny.decode(from: container)
}
}
public func encode(to encoder: Encoder) throws {
if let arr = self.value as? [Any] {
var container = encoder.unkeyedContainer()
try JSONAny.encode(to: &container, array: arr)
} else if let dict = self.value as? [String: Any] {
var container = encoder.container(keyedBy: JSONCodingKey.self)
try JSONAny.encode(to: &container, dictionary: dict)
} else {
var container = encoder.singleValueContainer()
try JSONAny.encode(to: &container, value: self.value)
}
}
}
|
classdef GemMarkerPoint < CoreBaseClass
% GemMarkerPoint. Part of the internal gui for the Pulmonary Toolkit.
%
% You should not use this class within your own code. It is intended to
% be used internally within the gui of the Pulmonary Toolkit.
%
% A GemMarkerPoint object is created for each marker currently displayed
% on the image. The purpose behind this class is to store the previous
% marker position in order to remove points from the underlying marker
% image when markers are moved.
%
%
% Licence
% -------
% Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
% Author: Tom Doel, 2012. www.tomdoel.com
% Distributed under the GNU GPL v3 licence. Please see website for details.
%
properties (SetAccess = private)
Colour
end
properties (Constant)
% Blue, Green, Red, Cyan, Magenta, Yellow, Grey, Black
DefaultColours = {[0.4 0.4 1.0], [0 0.8 0], [0.8 0 0], [0 0.8 0.8], [0.9 0 0.9], [0.8 0.8 0.4], [0.7 0.7 0.7], [0.1 0.1 0.1]}
end
properties (Access = private)
Handle
Colours
Manager
HighlightColour = false
Position
LabelOn = false
String = ''
CallbackId
FigureHandle
end
methods
function obj = GemMarkerPoint(coords, axes_handle, colour, manager, coord_limits)
obj.Colour = colour;
obj.Colours = obj.DefaultColours;
obj.Manager = manager;
limits_x = [1, coord_limits(2)];
limits_y = [1, coord_limits(1)];
constraint_function = makeConstrainToRectFcn('impoint', limits_x, limits_y);
obj.Handle = impoint(axes_handle.GetContainerHandle, coords(1), coords(2));
obj.Handle.setPositionConstraintFcn(constraint_function);
obj.Handle.addNewPositionCallback(@obj.PositionChangedCallback);
obj.Handle.setColor(obj.Colours{colour});
obj.FigureHandle = axes_handle.GetParentFigure;
obj.CallbackId = obj.FigureHandle.RegisterMarkerPoint(obj.Handle);
obj.AddContextMenu(obj.FigureHandle.GetContainerHandle);
obj.Position = round(obj.Handle.getPosition);
end
function delete(obj)
if ~isempty(obj.FigureHandle) && isvalid(obj.FigureHandle)
obj.FigureHandle.UnRegisterMarkerPoint(obj.Handle, obj.CallbackId);
end
end
function AddTextLabel(obj)
obj.LabelOn = true;
image_coords = obj.Manager.GetGlobalImageCoordinates(obj.Handle.getPosition);
image_coords = round(image_coords);
coords_text = ['(' int2str(image_coords(2)) ',' int2str(image_coords(1)) ',' int2str(image_coords(3)) ')'];
if ~strcmp(coords_text, obj.String)
obj.Handle.setString(coords_text);
obj.String = coords_text;
end
end
function RemoveTextLabel(obj)
obj.LabelOn = false;
obj.String = '';
obj.Handle.setString('');
end
function coords = GetPosition(obj)
coords = obj.Handle.getPosition;
end
function Highlight(obj)
current_colour = obj.Handle.getColor;
current_colour = min(1, current_colour + 0.3);
obj.Handle.setColor(current_colour);
obj.HighlightColour = true;
end
function HighlightOff(obj)
if obj.HighlightColour
obj.Handle.setColor(obj.Colours{obj.Colour});
obj.HighlightColour = false;
end
end
function ChangePosition(obj, coords)
obj.Handle.setPosition(coords(1), coords(2));
obj.Manager.AddPointToMarkerImage(obj.Position, 0);
obj.Position = round(coords);
obj.Manager.AddPointToMarkerImage(obj.Position, obj.Colour);
if obj.LabelOn
obj.AddTextLabel;
end
end
function RemoveGraphic(obj)
delete(obj.Handle);
end
function DeleteMarker(obj)
obj.Manager.AddPointToMarkerImage(obj.Position, 0);
obj.Manager.RemoveThisMarker(obj)
obj.RemoveGraphic();
end
end
methods (Access = private)
function AddContextMenu(obj, figure_handle)
marker_menu = uicontextmenu('Parent', figure_handle);
marker_menu_delete = @(x, y) obj.DeleteMarkerCallback(x, y);
marker_menu_blue = @(x, y) obj.ChangeMarkerColourCallback(x, y, 1);
marker_menu_green = @(x, y) obj.ChangeMarkerColourCallback(x, y, 2);
marker_menu_red = @(x, y) obj.ChangeMarkerColourCallback(x, y, 3);
marker_menu_cyan = @(x, y) obj.ChangeMarkerColourCallback(x, y, 4);
marker_menu_magenta = @(x, y) obj.ChangeMarkerColourCallback(x, y, 5);
marker_menu_yellow = @(x, y) obj.ChangeMarkerColourCallback(x, y, 6);
marker_menu_grey = @(x, y) obj.ChangeMarkerColourCallback(x, y, 7);
uimenu(marker_menu, 'Label', 'Delete marker', 'Callback', marker_menu_delete);
uimenu(marker_menu, 'Label', 'Change marker colour to:', 'Separator', 'on', 'Enable', 'off');
uimenu(marker_menu, 'Label', ' Blue', 'Callback', marker_menu_blue, 'ForegroundColor', obj.Colours{1});
uimenu(marker_menu, 'Label', ' Green', 'Callback', marker_menu_green, 'ForegroundColor', obj.Colours{2});
uimenu(marker_menu, 'Label', ' Red', 'Callback', marker_menu_red, 'ForegroundColor', obj.Colours{3});
uimenu(marker_menu, 'Label', ' Cyan', 'Callback', marker_menu_cyan, 'ForegroundColor', obj.Colours{4});
uimenu(marker_menu, 'Label', ' Magenta', 'Callback', marker_menu_magenta, 'ForegroundColor', obj.Colours{5});
uimenu(marker_menu, 'Label', ' Yellow', 'Callback', marker_menu_yellow, 'ForegroundColor', obj.Colours{6});
uimenu(marker_menu, 'Label', ' Grey', 'Callback', marker_menu_grey, 'ForegroundColor', obj.Colours{7});
set(obj.Handle, 'uicontextmenu', marker_menu)
end
function ChangeMarkerColourCallback(obj, ~, ~, colour)
obj.Colour = colour;
obj.Handle.setColor(obj.Colours{colour});
% obj.Manager.ChangeCurrentColour(colour); %ToDo
obj.Manager.AddPointToMarkerImage(obj.Position, colour);
end
function DeleteMarkerCallback(obj, ~, ~)
obj.DeleteMarker;
end
function PositionChangedCallback(obj, new_position)
obj.Manager.AddPointToMarkerImage(obj.Position, 0);
obj.Position = round(new_position);
obj.Manager.AddPointToMarkerImage(obj.Position, obj.Colour);
if obj.LabelOn
obj.AddTextLabel;
end
end
end
end
|
# Binary search, transfer 2D to 1D.
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
length = len(matrix) * len(matrix[0])
width = len(matrix[0])
left = 0
right = length - 1
while left <= right:
mid = (left + right) / 2
if target < matrix[mid / width][mid % width]:
right = mid - 1
elif target > matrix[mid / width][mid % width]:
left = mid + 1
else:
return True
return False
|
package com.book.study.zen.chapter14.demob;
public class Meditor extends AbstractMediator {
// 中介者最重要的方法
@Override
public void execute(String str, Object... objects) {
if (str.equals("purchase.buy")) {
// 采购电脑
this.buyComputer((Integer) objects[0]);
} else if (str.equals("sale.sell")) {
// 销售电脑
this.sellComputer((Integer) objects[0]);
} else if (str.equals("sale.offsell")) {
this.offSell();
} else if (str.equals("stock.clear")) {
this.clearStock();
}
}
private void clearStock() {
// 要求清仓销售
super.sale.offSale();
// 要求采购人员不要采购
super.purchase.refuseBuyIBM();
}
private void offSell() {
System.out.println("折价销售IBM电脑" + stock.getStockNumber());
}
private void sellComputer(Integer number) {
if (super.stock.getStockNumber() < number) {
super.purchase.buyIBMcomputer(number);
}
super.stock.decrease(number);
}
private void buyComputer(int number) {
int saleStatus = super.sale.getSaleStatus();
if (saleStatus > 80) {
System.out.println("采购IBM电脑:" + number + "台");
super.stock.increase(number);
} else {
int buyNumber = number / 2;
System.out.println("采购IBM电脑:" + buyNumber + "台");
}
}
}
|
---
title: "\"2024 Approved Navigating New Horizines YouTube Video Uploads to Facebook\""
date: 2024-05-31T12:47:51.213Z
updated: 2024-06-01T12:47:51.213Z
tags:
- ai video
- ai youtube
categories:
- ai
- youtube
description: "\"This Article Describes 2024 Approved: Navigating New Horizines: YouTube Video Uploads to Facebook\""
excerpt: "\"This Article Describes 2024 Approved: Navigating New Horizines: YouTube Video Uploads to Facebook\""
keywords: "\"YouTube & FB Upload Guide,Social Media Content Sharing,YouTube Video Transfer,Facebook Video Integration,Cross-Platform Content Posting,Multimedia Platform Sync,Streaming Content to FB\""
thumbnail: https://www.lifewire.com/thmb/GZPwyDD3GdFRcinLvhj32Aht3ZA=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/apple-tv-4k-8ff89d451bf44fea81d11459802846c5.jpg
---
## Navigating New Horizines: YouTube Video Uploads to Facebook
##### Create High-Quality Video - Wondershare Filmora
An easy and powerful YouTube video editor
Numerous video and audio effects to choose from
Detailed tutorials provided by the official channel
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook.

#### In this article
01 [How to Post YouTube video on Facebook?](#part1)
02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2)
03 [Frequently Asked Question about Facebook video](#part3)
## How to Post YouTube video on Facebook?
Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook.
#### How to share a YouTube video on Facebook using a computer
If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it.
Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser.
Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook.
Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video.
Step 4\. Choose “Facebook” from the sharing options that pop up.

Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.”
Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook.
#### How to share a YouTube video on Facebook using a mobile device
Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device.
Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website.
Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook.
Step 3\. Check below the video and click on the “Share” icon.
Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable.
Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing.

Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page.
Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook.

#### How to post a YouTube video on Facebook
Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly.
Step 1\. Copy the YouTube video’s link
First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code.
Step 2\. Embed the video link you copied
This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box.
Step 3\. Paste your link
Right-click on the “What’s on your mind” box, then select the “Paste” option.
Step 4\. Preview video
Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it.
Step 5\. Post your video
Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook.
## Extra Tip: Facebook Video Tips for more Views and Shares
You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need.
#### \- Catch viewer’s attention within the shortest time possible
Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately.
#### \- Add captions to the video
It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode.
#### \- Emphasize on one key-point
Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand.
#### \- Add a Call To Action
Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels.
#### \- Facebook ads can make a great difference
Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly.
#### \- Embed your videos on blog posts
Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post.
## Frequently Asked Question about Facebook video
Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you.
#### 1) Is it legal to share YouTube videos?
YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc.
#### 2) What is the best time to post to your Facebook page?
The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates.
#### 3) What are Facebook business accounts and personal accounts?
Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage.
#### 4) Can I mobilize people to share my posted content on Facebook?
Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing.
#### 5) Does the quality of my YouTube content drop when I share it with Facebook?
Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution.
## Conclusion
● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook.

#### In this article
01 [How to Post YouTube video on Facebook?](#part1)
02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2)
03 [Frequently Asked Question about Facebook video](#part3)
## How to Post YouTube video on Facebook?
Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook.
#### How to share a YouTube video on Facebook using a computer
If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it.
Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser.
Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook.
Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video.
Step 4\. Choose “Facebook” from the sharing options that pop up.

Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.”
Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook.
#### How to share a YouTube video on Facebook using a mobile device
Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device.
Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website.
Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook.
Step 3\. Check below the video and click on the “Share” icon.
Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable.
Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing.

Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page.
Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook.

#### How to post a YouTube video on Facebook
Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly.
Step 1\. Copy the YouTube video’s link
First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code.
Step 2\. Embed the video link you copied
This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box.
Step 3\. Paste your link
Right-click on the “What’s on your mind” box, then select the “Paste” option.
Step 4\. Preview video
Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it.
Step 5\. Post your video
Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook.
## Extra Tip: Facebook Video Tips for more Views and Shares
You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need.
#### \- Catch viewer’s attention within the shortest time possible
Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately.
#### \- Add captions to the video
It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode.
#### \- Emphasize on one key-point
Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand.
#### \- Add a Call To Action
Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels.
#### \- Facebook ads can make a great difference
Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly.
#### \- Embed your videos on blog posts
Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post.
## Frequently Asked Question about Facebook video
Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you.
#### 1) Is it legal to share YouTube videos?
YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc.
#### 2) What is the best time to post to your Facebook page?
The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates.
#### 3) What are Facebook business accounts and personal accounts?
Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage.
#### 4) Can I mobilize people to share my posted content on Facebook?
Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing.
#### 5) Does the quality of my YouTube content drop when I share it with Facebook?
Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution.
## Conclusion
● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook.

#### In this article
01 [How to Post YouTube video on Facebook?](#part1)
02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2)
03 [Frequently Asked Question about Facebook video](#part3)
## How to Post YouTube video on Facebook?
Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook.
#### How to share a YouTube video on Facebook using a computer
If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it.
Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser.
Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook.
Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video.
Step 4\. Choose “Facebook” from the sharing options that pop up.

Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.”
Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook.
#### How to share a YouTube video on Facebook using a mobile device
Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device.
Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website.
Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook.
Step 3\. Check below the video and click on the “Share” icon.
Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable.
Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing.

Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page.
Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook.

#### How to post a YouTube video on Facebook
Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly.
Step 1\. Copy the YouTube video’s link
First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code.
Step 2\. Embed the video link you copied
This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box.
Step 3\. Paste your link
Right-click on the “What’s on your mind” box, then select the “Paste” option.
Step 4\. Preview video
Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it.
Step 5\. Post your video
Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook.
## Extra Tip: Facebook Video Tips for more Views and Shares
You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need.
#### \- Catch viewer’s attention within the shortest time possible
Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately.
#### \- Add captions to the video
It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode.
#### \- Emphasize on one key-point
Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand.
#### \- Add a Call To Action
Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels.
#### \- Facebook ads can make a great difference
Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly.
#### \- Embed your videos on blog posts
Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post.
## Frequently Asked Question about Facebook video
Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you.
#### 1) Is it legal to share YouTube videos?
YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc.
#### 2) What is the best time to post to your Facebook page?
The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates.
#### 3) What are Facebook business accounts and personal accounts?
Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage.
#### 4) Can I mobilize people to share my posted content on Facebook?
Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing.
#### 5) Does the quality of my YouTube content drop when I share it with Facebook?
Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution.
## Conclusion
● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook.

#### In this article
01 [How to Post YouTube video on Facebook?](#part1)
02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2)
03 [Frequently Asked Question about Facebook video](#part3)
## How to Post YouTube video on Facebook?
Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook.
#### How to share a YouTube video on Facebook using a computer
If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it.
Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser.
Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook.
Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video.
Step 4\. Choose “Facebook” from the sharing options that pop up.

Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.”
Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook.
#### How to share a YouTube video on Facebook using a mobile device
Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device.
Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website.
Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook.
Step 3\. Check below the video and click on the “Share” icon.
Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable.
Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing.

Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page.
Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook.

#### How to post a YouTube video on Facebook
Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly.
Step 1\. Copy the YouTube video’s link
First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code.
Step 2\. Embed the video link you copied
This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box.
Step 3\. Paste your link
Right-click on the “What’s on your mind” box, then select the “Paste” option.
Step 4\. Preview video
Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it.
Step 5\. Post your video
Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook.
## Extra Tip: Facebook Video Tips for more Views and Shares
You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need.
#### \- Catch viewer’s attention within the shortest time possible
Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately.
#### \- Add captions to the video
It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode.
#### \- Emphasize on one key-point
Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand.
#### \- Add a Call To Action
Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels.
#### \- Facebook ads can make a great difference
Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly.
#### \- Embed your videos on blog posts
Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post.
## Frequently Asked Question about Facebook video
Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you.
#### 1) Is it legal to share YouTube videos?
YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc.
#### 2) What is the best time to post to your Facebook page?
The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates.
#### 3) What are Facebook business accounts and personal accounts?
Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage.
#### 4) Can I mobilize people to share my posted content on Facebook?
Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing.
#### 5) Does the quality of my YouTube content drop when I share it with Facebook?
Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution.
## Conclusion
● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options.
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## Creating User-Friendly YouTube Subscribe Icons
# How to Make a YouTube Subscribe Link - Easy

##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
If you want to increase the total number of subscribers that you have on your YouTube page it is important that your page is easy to subscribe to.
A subscribe link is a link to your channel page which takes the person who clicks it to the same view of the page they would have if they had already clicked to subscribe. It triggers a pop-up asking them to confirm their subscription. If they were already interested enough to click the link and check out your channel they may confirm the subscription in the window, whereas they may forget to subscribe if they aren’t prompted.
A YouTube subscribe link is one of the best ways to share a link on your website, in social media posts, or anywhere you mention your channel.
## How to Get a YouTube Subscribe Link
YouTube subscribe links aren’t some kind of exclusive perk – anyone can have one!
**Step 1:** Go to your YouTube channel page and click into the address bar so you can edit the URL.
**Step 2:** Add the following to the end of your channel URL:
?sub\_confirmation=1
**Step 3:** Copy the entire URL including the part you added and paste it into a word document to save. Any time you share a link to your channel, make sure it is this link.
This will work both with channels that have custom URLs and channels which do not. Here’s an example:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w>_
That's a link for Wondershare Filmora Video Editor's YouTube channel. With the modifier it looks like this:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w?sub\_confirmation=1>_
Getting subscribers is tough, but you’ll get more if you ask and this is just another way of asking. The process for creating a YouTube subscribe link is easy and accessible to everyone.
### Touch Up Your YouTube Videos with Filmora
[Filmora](https://tools.techidaily.com/wondershare/filmora/download/) features lots of video and audio editing tools that enables you to cut, trim and touch up the video clip easily. There are plentiful texts templates and elements, which can be used to create attractive call-outs.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
If you want to increase the total number of subscribers that you have on your YouTube page it is important that your page is easy to subscribe to.
A subscribe link is a link to your channel page which takes the person who clicks it to the same view of the page they would have if they had already clicked to subscribe. It triggers a pop-up asking them to confirm their subscription. If they were already interested enough to click the link and check out your channel they may confirm the subscription in the window, whereas they may forget to subscribe if they aren’t prompted.
A YouTube subscribe link is one of the best ways to share a link on your website, in social media posts, or anywhere you mention your channel.
## How to Get a YouTube Subscribe Link
YouTube subscribe links aren’t some kind of exclusive perk – anyone can have one!
**Step 1:** Go to your YouTube channel page and click into the address bar so you can edit the URL.
**Step 2:** Add the following to the end of your channel URL:
?sub\_confirmation=1
**Step 3:** Copy the entire URL including the part you added and paste it into a word document to save. Any time you share a link to your channel, make sure it is this link.
This will work both with channels that have custom URLs and channels which do not. Here’s an example:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w>_
That's a link for Wondershare Filmora Video Editor's YouTube channel. With the modifier it looks like this:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w?sub\_confirmation=1>_
Getting subscribers is tough, but you’ll get more if you ask and this is just another way of asking. The process for creating a YouTube subscribe link is easy and accessible to everyone.
### Touch Up Your YouTube Videos with Filmora
[Filmora](https://tools.techidaily.com/wondershare/filmora/download/) features lots of video and audio editing tools that enables you to cut, trim and touch up the video clip easily. There are plentiful texts templates and elements, which can be used to create attractive call-outs.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
If you want to increase the total number of subscribers that you have on your YouTube page it is important that your page is easy to subscribe to.
A subscribe link is a link to your channel page which takes the person who clicks it to the same view of the page they would have if they had already clicked to subscribe. It triggers a pop-up asking them to confirm their subscription. If they were already interested enough to click the link and check out your channel they may confirm the subscription in the window, whereas they may forget to subscribe if they aren’t prompted.
A YouTube subscribe link is one of the best ways to share a link on your website, in social media posts, or anywhere you mention your channel.
## How to Get a YouTube Subscribe Link
YouTube subscribe links aren’t some kind of exclusive perk – anyone can have one!
**Step 1:** Go to your YouTube channel page and click into the address bar so you can edit the URL.
**Step 2:** Add the following to the end of your channel URL:
?sub\_confirmation=1
**Step 3:** Copy the entire URL including the part you added and paste it into a word document to save. Any time you share a link to your channel, make sure it is this link.
This will work both with channels that have custom URLs and channels which do not. Here’s an example:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w>_
That's a link for Wondershare Filmora Video Editor's YouTube channel. With the modifier it looks like this:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w?sub\_confirmation=1>_
Getting subscribers is tough, but you’ll get more if you ask and this is just another way of asking. The process for creating a YouTube subscribe link is easy and accessible to everyone.
### Touch Up Your YouTube Videos with Filmora
[Filmora](https://tools.techidaily.com/wondershare/filmora/download/) features lots of video and audio editing tools that enables you to cut, trim and touch up the video clip easily. There are plentiful texts templates and elements, which can be used to create attractive call-outs.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
If you want to increase the total number of subscribers that you have on your YouTube page it is important that your page is easy to subscribe to.
A subscribe link is a link to your channel page which takes the person who clicks it to the same view of the page they would have if they had already clicked to subscribe. It triggers a pop-up asking them to confirm their subscription. If they were already interested enough to click the link and check out your channel they may confirm the subscription in the window, whereas they may forget to subscribe if they aren’t prompted.
A YouTube subscribe link is one of the best ways to share a link on your website, in social media posts, or anywhere you mention your channel.
## How to Get a YouTube Subscribe Link
YouTube subscribe links aren’t some kind of exclusive perk – anyone can have one!
**Step 1:** Go to your YouTube channel page and click into the address bar so you can edit the URL.
**Step 2:** Add the following to the end of your channel URL:
?sub\_confirmation=1
**Step 3:** Copy the entire URL including the part you added and paste it into a word document to save. Any time you share a link to your channel, make sure it is this link.
This will work both with channels that have custom URLs and channels which do not. Here’s an example:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w>_
That's a link for Wondershare Filmora Video Editor's YouTube channel. With the modifier it looks like this:
_<https://www.youtube.com/channel/UCY\_LMaDAoa6hwHKBE4Dx56w?sub\_confirmation=1>_
Getting subscribers is tough, but you’ll get more if you ask and this is just another way of asking. The process for creating a YouTube subscribe link is easy and accessible to everyone.
### Touch Up Your YouTube Videos with Filmora
[Filmora](https://tools.techidaily.com/wondershare/filmora/download/) features lots of video and audio editing tools that enables you to cut, trim and touch up the video clip easily. There are plentiful texts templates and elements, which can be used to create attractive call-outs.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
|
package com.example.b1_prak2_13120220008;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.ArrayAdapter;
public class MainActivity extends AppCompatActivity {
EditText editStb, editNama;
Spinner spinner;
RadioGroup Rg;
RadioButton btnTi, btnSi;
CheckBox cbBEM, cbKir, cbPkw, cbSeni, cbJurnal, cbOlgar;
Button button2;
TextView txtProdi, txtMinat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editStb = findViewById(R.id.editStb);
editNama = findViewById(R.id.editNama);
spinner = findViewById(R.id.spinner);
Rg = findViewById(R.id.Rg);
btnTi = findViewById(R.id.btnTi);
btnSi = findViewById(R.id.btnSi);
cbBEM = findViewById(R.id.cbBEM);
cbKir = findViewById(R.id.cbKir);
cbPkw = findViewById(R.id.cbPkw);
cbSeni = findViewById(R.id.cbSeni);
cbJurnal = findViewById(R.id.cbJurnal);
cbOlgar = findViewById(R.id.cbOlgar);
button2 = findViewById(R.id.button2);
txtProdi = findViewById(R.id.txtProdi);
txtMinat = findViewById(R.id.txtMinat);
String[] item = new String[]{"-Pilih Angkatan-","2022", "2021", "2020", "2019", "2018", "2017",
"2016", "2015", "2014"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, item);
spinner.setAdapter(adapter);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String stambuk = editStb.getText().toString();
String nama = editNama.getText().toString();
String programStudi = getProgramStudi();
String angkatan = spinner.getSelectedItem().toString();
String minat = getMinat();
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
intent.putExtra("STAMBUK", stambuk);
intent.putExtra("NAMA", nama);
intent.putExtra("PROGRAM_STUDI", programStudi);
intent.putExtra("ANGKATAN", angkatan);
intent.putExtra("MINAT", minat);
startActivity(intent);
}
});
}
private String getProgramStudi() {
int selectedId = Rg.getCheckedRadioButtonId();
if (selectedId == R.id.btnTi) {
return "Teknik Informatika";
}
else if (selectedId == R.id.btnSi) {
return "Sistem Informasi";
}
else {
return "";
}
}
private String getMinat() {
StringBuilder minat = new StringBuilder();
if (cbBEM.isChecked()) {
minat.append("- ").append(cbBEM.getText()).append("\n");
}
if (cbKir.isChecked()) {
minat.append("- ").append(cbKir.getText()).append("\n");
}
if (cbPkw.isChecked()) {
minat.append("- ").append(cbPkw.getText()).append("\n");
}
if (cbSeni.isChecked()) {
minat.append("- ").append(cbSeni.getText()).append("\n");
}
if (cbJurnal.isChecked()) {
minat.append("- ").append(cbJurnal.getText()).append("\n");
}
if (cbOlgar.isChecked()) {
minat.append("- ").append(cbOlgar.getText()).append("\n");
}
return minat.toString();
}
}
|
using System;
namespace Object
{
class Programe
{
public class Cat
{
// Field name
private string name;
// Field color
private string color;
public string Name
{
// Getter of the property "Name"
get
{
return this.name;
}
// Setter of the property "Name"
set
{
this.name = value;
}
}
public string Color
{
// Getter of the property "Color"
get
{
return this.color;
}
// Setter of the property "Color"
set
{
this.color = value;
}
}
// Default constructor
public Cat()
{
this.name = "Unnamed";
this.color = "gray";
}
// Constructor with parameters
public Cat(string name, string color)
{
this.name = name;
this.color = color;
}
// Method SayMiau
public void SayMiau()
{
Console.WriteLine("Cat {0} said: Miauuuuuu!", name);
}
static void Main()
{
Cat firstCat = new Cat();
firstCat.Name = "Tony";
firstCat.SayMiau();
Cat secondCat = new Cat("Pepy", "red");
secondCat.SayMiau();
Console.WriteLine("Cat {0} is {1}.",
secondCat.Name, secondCat.Color);
}
}
}
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Course;
class CoursesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$courses = Course::all();
return view('courses.index', [
'courses' => $courses
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('courses.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:courses',
'added_in' => 'required|integer',
'description' => 'required',
'image' => 'required|mimes:jpg,png,jpeg|max:5048'
]);
$newImageName = time() . '-' . $request->title . '.' . $request->image->extension();
$request->image->move(public_path('images'), $newImageName);
$course = Course::create([
'title' => $request->input('title'),
'added_in' => $request->input('added_in'),
'description' => $request->input('description'),
'image_path' => $newImageName
]);
return redirect('/courses');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$course = Course::find($id);
return view('courses.show')->with('course', $course);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$course = Course::find($id);
return view('courses.edit')->with('course', $course);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'title' => 'required',
'added_in' => 'required|integer',
'description' => 'required',
'image' => 'required|mimes:jpg,png,jpeg|max:5048'
]);
$newImageName = time() . '-' . $request->title . '.' . $request->image->extension();
$request->image->move(public_path('images'), $newImageName);
$course = Course::where('id', $id)
->update([
'title' => $request->input('title'),
'added_in' => $request->input('added_in'),
'description' => $request->input('description'),
'image_path' => $newImageName
]);
return redirect('/courses');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Course $course)
{
$course->delete();
return redirect('/courses');
}
}
|
@extends('dashboard.layouts.main')
@if (session()->has('success'))
<div class="container-fluid">
<div aria-live="polite" aria-atomic="true" class="position-relative">
<div class="toast-container top-0 end-0 p-3">
<div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header bg-success-10 text-color-100">
<strong class="me-auto"><i class="las la-check-circle text-color-hs fs-18"></i> Kpop
Soulmate</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body bg-success-10 fs-inter-14 text-color-100">
{{ session('success') }}
</div>
</div>
</div>
</div>
</div>
@endif
@section('content')
<section id="header-analytics">
<div class="row m-bottom-30">
<div class="col">
<div class="d-flex justify-content-between">
<div>
<h1 class="fw-bold">Categories</h1>
</div>
<div>
<a class="btn btn-primary-color" href="/dashboard/categories/create">
<i class="las la-plus fs-18 m-right-5"></i>
Add Category
</a>
</div>
</div>
</div>
</div>
</section>
<section id="table-category">
<div class="row mb-5">
<div class="col">
<div class="table-container">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr class="fs-14 fw-semibold">
<th scope="col">#</th>
<th scope="col">Category Name</th>
<th scope="col">Slug</th>
<th scope="col">Icon Class</th>
<th>
<i class="las la-ellipsis-v" id="categoryMenu" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false"></i>
</th>
</tr>
</thead>
<tbody>
@forelse ($categories as $category)
<tr class="fs-12">
<td class="align-middle">{{ $loop->iteration }}</td>
<td class="align-middle">{{ $category->category_name }}</td>
<td class="align-middle text-color-100">
{{ $category->slug }}
</td>
<td class="align-middle">{{ $category->icon_class }}</td>
<td class="align-middle">
<div class="btn-group dropstart">
<button class="btn p-0" type="button" data-bs-toggle="dropdown"
aria-expanded="false">
<i class="las la-ellipsis-v"> </i>
</button>
<ul class="dropdown-menu fs-14">
<li>
<a class="dropdown-item"
href="/dashboard/categories/{{ $category->slug }}"><i
class="las la-external-link-alt"></i> Detail</a>
</li>
<li>
<a href="/dashboard/categories/{{ $category->slug }}/edit"
class="dropdown-item" type="button"><i class="las la-edit"></i>
Update</a>
</li>
<li>
<button class="dropdown-item button-delete" type="button"
data-bs-toggle="modal" data-bs-target="#confirmDeleteModal"
data-id="{{ $category->slug }}"
data-title="{{ $category->category_name }}"><i
class="las la-trash-alt"
id="buttonDelete{{ $category->slug }}"></i>
Delete</button>
</li>
</ul>
</div>
</td>
</tr>
@empty
<tr>
<td colspan="8" class="text-center text-color-100">
<i class="las la-icons fs-48"></i>
<p class="fs-14 fw-medium mt-1 mb-0">No Category Found!</p>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
<!-- Modal Confirm Delete -->
<div class="modal fade " id="confirmDeleteModal" tabindex="-1" aria-labelledby="confirmDeleteModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="d-flex flex-column align-items-center">
<i class="las la-trash-alt fs-24 text-color-ad rounded-circle p-2 bg-alert-10 m-bottom-15"></i>
<h6 class="fw-semibold m-bottom-5">Delete Category</h6>
<p class="fs-14">Are you sure you want to delete this category?</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-border" data-bs-dismiss="modal">Cancel</button>
<form action="/dashboard/categories/" method="post" id="deleteForm">
@method('delete')
@csrf
<button type="submit" class="btn btn-alert-color">Yes, Delete Category</button>
</form>
</div>
</div>
</div>
</div>
<script>
var buttonDelete = document.querySelectorAll('.button-delete');
var modalTitle = document.querySelector('.modal-body h6')
for (var i = 0; i < buttonDelete.length; i++) {
var buttons = buttonDelete[i];
buttonDelete[i].addEventListener('click', function() {
modalTitle.textContent = "Delete " + this.attributes[5].value;
document.querySelector("#deleteForm").attributes[0].textContent =
"/dashboard/categories/" + this
.attributes[4].value;
}, false);
}
</script>
@endsection
|
import React from "react";
import { useForm } from "react-hook-form";
const API = "https://stingray-app-axdpn.ondigitalocean.app/api/todo/add";
import axios from "axios";
import { Link, Navigate, useNavigate } from "react-router-dom";
const AddTodo = () => {
const title = "ToDo";
const description = "Add your ToDo here";
const navigate = useNavigate();
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm();
const Submit = async (data) => {
console.log(data);
const {
user_id = sessionStorage.getItem("id"),
todo_title,
todo_description,
} = data;
try {
await axios
.post(API, {
user_id,
todo_title,
todo_description,
})
.then((res) => {
navigate("/dashboard");
console.log(res);
})
.catch((err) => {
console.log(err);
});
} catch (e) {
console.log(e);
}
};
return (
<div className="hero min-h-screen bg-base-200">
<div className="hero-content flex-col lg:flex-row-reverse">
<div className="text-center lg:text-left">
<h1 className="text-5xl font-bold">{title}</h1>
<p className="py-5">{description}</p>
</div>
<div className="card shrink-0 w-full max-w-sm shadow-2xl bg-base-100">
<form className="card-body" onClick={handleSubmit(Submit)}>
<div className="form-control">
<label className="label">
<span className="label-text">ToDo Title</span>
</label>
<input
type="text"
placeholder="title"
className="input input-bordered"
{...register("todo_title", { required: true })}
/>
{errors.todo_title && <span>Title is required</span>}
</div>
<div className="form-control">
<label className="label">
<span className="label-text">ToDo Description</span>
</label>
<input
type="text"
placeholder="description"
className="input input-bordered"
{...register("todo_description", { required: true })}
/>
{errors.todo_description && <span>Description is required</span>}
</div>
<div className="form-control mt-6">
<button className="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
);
};
export default AddTodo;
|
import { Route, Routes, useNavigate } from "react-router-dom";
import { useDropzone } from "react-dropzone";
import { useContext } from "react";
import { actionType, ImageContext } from "../../contexts/image.context";
import { RequirementsInputForm } from "./components/requirementsInputForm/RequirementsInputForm";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faImage } from "@fortawesome/free-solid-svg-icons";
export function HomeView() {
const { state, dispatch } = useContext(ImageContext);
const navigate = useNavigate();
const handleUploadeFile = (file) => {
if (file.length !== 1) return;
dispatch({ type: actionType.file, payload: { file: file[0] } });
navigate("/config");
};
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDropAccepted: handleUploadeFile,
accept: "image/*",
maxFiles: 1,
});
return (
<div>
<Routes>
<Route
path="/config"
element={
<div
className={`container flex justify-center items-center h-screen mx-auto`}
>
<RequirementsInputForm
onChange={(config) => {
dispatch({ type: actionType.config, payload: { config } });
navigate("/workbench");
}}
defaultConfig={{
size: state.file && Number(state.file.size),
sizeUnit: "B",
}}
/>
</div>
}
/>
<Route
path="/"
element={
<div
className={`container flex justify-center items-center h-screen mx-auto`}
>
<div
{...getRootProps({
className: `w-96 h-40 max-w-full border-4 border-dashed border-blue-400 hover:border-blue-500
p-4 rounded-lg cursor-pointer flex justify-center items-center
${isDragActive ? "border-blue-500" : ""}`,
})}
>
<input {...getInputProps()} />
{isDragActive ? (
<p className="text-center text-blue-500 text-lg font-bold">
<FontAwesomeIcon icon={faImage} /> Drop the image here ...
</p>
) : (
<p className="text-center text-blue-500 text-lg font-bold">
<FontAwesomeIcon icon={faImage} /> Drag 'n' drop some image
here, or click to select image
</p>
)}
</div>
</div>
}
/>
</Routes>
</div>
);
}
|
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
type JwtPayload = {
sub: string;
email: string;
};
@Injectable()
export class AccessTokenStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get<string>('JWT_ACCESS_SECRET'),
});
}
validate(payload: JwtPayload) {
return payload;
}
}
|
import { configureStore, combineReducers} from '@reduxjs/toolkit'
import { BoardReducer } from './Slices/Board/BoardSlice'
import { UserReducer } from './Slices/User/UserSlice'
const rootReducer = combineReducers({
BoardReducer, UserReducer,
})
export const setupStore = () => {
return configureStore({
reducer: rootReducer,
})
}
export type RootState = ReturnType<typeof rootReducer>
export type AppStore = ReturnType<typeof setupStore>
export type AppDispatch = AppStore['dispatch']
|
import { Task } from '../../src/@types/task'
import { Db } from '../../src/repositories/db'
import { Status } from '../../src/enums/task'
import { testClient } from '../setup'
import { allTasks, createTask, updateTask, reorderTask } from './task.gpl'
describe('TaskResolver.allTasks', () => {
beforeAll(async () => {
await Db.conn.migrate.rollback()
await Db.conn.migrate.latest()
await Db.conn.seed.run({ specific: 'test_data.ts' })
})
afterAll(async () => {
await Db.conn.migrate.rollback()
})
test('get all tasks without filter should return all tasks', async () => {
const { query } = await testClient()
const response = await query({
query: allTasks,
})
const results: Task[] = response.data.allTasks
expect(results.length).toBe(9)
})
test('get all tasks with given id should return task of given id', async () => {
const { query } = await testClient()
const givenId = 3
const response = await query({
query: allTasks,
variables: {
options: {
id: givenId,
},
},
})
const results: Task[] = response.data.allTasks
expect(results.length).toBe(1)
expect(results[0].id).toBe(givenId)
})
test('get all tasks with given list id should return all tasks of given list id', async () => {
const { query } = await testClient()
const givenId = 2
const response = await query({
query: allTasks,
variables: {
options: {
listId: givenId,
},
},
})
const results: Task[] = response.data.allTasks
expect(results.length).toBe(3)
expect(results[0].id).toBe(4)
expect(results[1].id).toBe(5)
expect(results[2].id).toBe(6)
})
test('get all tasks with given status should return all tasks with given status', async () => {
const { query } = await testClient()
const givenStatus = 'TODO'
const response = await query({
query: allTasks,
variables: {
options: {
status: givenStatus,
},
},
})
const results: Task[] = response.data.allTasks
expect(results.length).toBe(5)
expect(results.every((task) => Status[task.status] === Status[givenStatus])).toBe(true)
})
})
describe('TaskResolver.createTask', () => {
beforeAll(async () => {
await Db.conn.migrate.rollback()
await Db.conn.migrate.latest()
await Db.conn.seed.run({ specific: 'test_data.ts' })
})
afterAll(async () => {
await Db.conn.migrate.rollback()
})
test('create task with given valid info should return new task with given info', async () => {
const { mutate } = await testClient()
const givenListId = 1
const givenTitle = 'test create task abc'
const response = await mutate({
mutation: createTask,
variables: {
options: {
listId: givenListId,
title: givenTitle,
},
},
})
const result: Task = response.data.createTask
expect(result).not.toBeUndefined
expect(result.title).toBe(givenTitle)
expect(result.listId).toBe(givenListId)
})
})
describe('TaskResolver.updateTask', () => {
beforeAll(async () => {
await Db.conn.migrate.rollback()
await Db.conn.migrate.latest()
await Db.conn.seed.run({ specific: 'test_data.ts' })
})
afterAll(async () => {
await Db.conn.migrate.rollback()
})
test('update task with given valid info should return updated task with given info', async () => {
const { mutate } = await testClient()
const givenId = 1
const givenTitle = 'test update task xyz'
const givenStatus = 'COMPLETED'
const response = await mutate({
mutation: updateTask,
variables: {
options: {
id: givenId,
title: givenTitle,
status: givenStatus,
},
},
})
const result: Task = response.data.updateTask
expect(result).not.toBeUndefined
expect(result.id).toBe(givenId)
expect(result.title).toBe(givenTitle)
expect(Status[result.status]).toBe(Status[givenStatus])
})
})
describe('TaskResolver.reorderTask', () => {
beforeAll(async () => {
await Db.conn.migrate.rollback()
await Db.conn.migrate.latest()
await Db.conn.seed.run({ specific: 'test_data.ts' })
})
afterAll(async () => {
await Db.conn.migrate.rollback()
})
test('reorder task with given new order should return new reordered list of tasks with same parent list id', async () => {
const { query, mutate } = await testClient()
const givenListId = 1
const givenId = 1
const givenOrder = 2
const beforeResponse = await query({
query: allTasks,
variables: {
options: {
listId: givenListId,
},
},
})
const response = await mutate({
mutation: reorderTask,
variables: {
options: {
id: givenId,
order: givenOrder,
},
},
})
const beforeResults: Task[] = beforeResponse.data.allTasks
const results: Task[] = response.data.reorderTask
expect(results).not.toBeUndefined
expect(beforeResults.length).toBe(3)
expect(results.length).toBe(3)
expect(beforeResults[0].id).toBe(1)
expect(beforeResults[1].id).toBe(2)
expect(beforeResults[2].id).toBe(3)
expect(results[0].id).toBe(2)
expect(results[1].id).toBe(1)
expect(results[2].id).toBe(3)
})
test('reorder task with out of bound position should throw out of bound error', async () => {
const { mutate } = await testClient()
const givenId = 1
const givenOrder = 999
const response = await mutate({
mutation: reorderTask,
variables: {
options: {
id: givenId,
order: givenOrder,
},
},
})
expect(response.data).toBeNull
if (response.errors) {
expect(response.errors[0].message).toContain(`New position ${givenOrder} is out of bound`)
}
})
})
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.b1 {
width: 100px;
height: 100px;
background-color: blue;
}
.b2 {
width: 200px;
height: 200px;
background-color: brown;
}
</style>
<script>
window.onload = function () {
var btn = document.getElementById("btn");
var box1 = document.getElementById("box1");
btn.onclick = function () {
// addClass(box1,"b2");
// removeClass(box1, "b1");
toggleClass(box1,"b2");
};
/*定义一个函数,用来修改样式
参数:
obj: 需要添加属性的对象
cn:需要添加的样式
*/
function addClass(obj, cn) {
if (!hasClass(obj, cn)) {
obj.className += " " + cn;
}
}
/*定义一个函数,用来判断需要添加的属性是否已经有了
参数:
obj: 需要添加属性的对象
cn:需要添加的样式
*/
function hasClass(obj, cn) {
//创建一个正则表达式
var reg = new RegExp("\\b" + cn + "\\b");
return reg.test(obj.className);
}
/*
定义一个函数,用来删除一个元素中指定的class属性
参数:
obj:需要删除属性的对象
cn:需要删除的样式名
*/
function removeClass(obj, cn) {
//创建一个正则表达式
var reg = new RegExp("\\b" + cn + "\\b");
obj.className = obj.className.replace(reg, "");
}
/*
创建一个函数,用来切换一个类,如果元素有该类则删除,如果没有则添加
参数:obj:需要切换属性的对象
cn:需要切换的属性名
*/
function toggleClass(obj, cn) {
if(hasClass(obj,cn)){
removeClass(obj,cn);
}else{
//没有则添加
addClass(obj,cn);
}
}
};
</script>
<body>
<button id="btn">改变样式</button>
<br /><br />
<div id="box1" class="b1"></div>
</body>
</html>
|
import { useNavigate } from 'react-router';
import './SearchResult.less';
interface SearchResult {
Title: string;
Year: string;
imdbID: string;
Type: string;
Poster: string;
}
type SearchResultProps = {
searchResult: SearchResult;
};
function SearchResult(props: SearchResultProps) {
const navigate = useNavigate();
const { searchResult } = props;
const { Poster, Title, Year, imdbID } = searchResult;
return (
<button
onClick={() => navigate(`/result/${imdbID}`)}
className='SearchResult'
>
<img src={Poster} alt={`${Title} poster`} className='MoviePoster' />
<div className='MovieDetails'>
<div className='MovieTitle'>{Title}</div>
<div className='MovieYear'>{Year}</div>
</div>
</button>
);
}
export default SearchResult;
|
<script setup>
import { computed, reactive } from 'vue'
import { buttons } from '../buttons'
const state = reactive({
operation: [],
formula: [],
current: 0
})
const operationDisplay = computed(() => {
return state.operation.join('')
})
const handleButtonClick = function(event) {
const targetButton = event.target;
buttons.forEach(button => {
if (button.name == targetButton.id) {
calculator(button)
}
})
}
const calculator = function(button) {
switch (button.class) {
case 'clear':
state.operation = []
break
case 'number':
case 'operator':
case 'func':
state.operation.push(button.label)
state.formula.push(button.formula)
break
case 'calculate':
calculate()
}
}
const calculate = function() {
state.current = 42
console.log(`formula: {state.formula}`)
}
</script>
<template>
<div class="container">
<div class="display">
<div class="brand">
<a href="https://github.com/adamstirtan/calcyoulator" target="_blank">
Adam Stirtan
</a>
</div>
<div class="glass" >
<div class="operation">
{{ operationDisplay }}
</div>
<div class="current">
{{ state.current }}
</div>
</div>
</div>
<div class="buttons">
<button
v-for="button in buttons"
:key="button.name"
:id="button.name"
:value="button.formula"
:class="button.class"
@click="handleButtonClick">
{{ button.label }}
</button>
</div>
</div>
</template>
<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Martian+Mono&display=swap');
.container {
width: 500px;
border: 3px solid #000;
border-radius: 8px
}
.display {
background-color: #212121;
padding: 1rem 1rem 1.5rem 1rem;
vertical-align: center;
}
.brand,
.brand a {
font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
color: #fff;
text-align: left;
text-transform: uppercase;
padding-bottom: 0.5rem;
font-size: 0.9em;
text-decoration: none;
}
.glass {
background: #fff;
border-radius: 10px;
padding: 1rem;
text-align: right;
font-family: 'Martian Mono', monospace;
color: #000;
}
.operation {
min-height: 22px;
font-size: 1.1em;
}
.current {
font-size: 3em;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 1rem;
padding: 1rem;
background-color: #fff;
}
button {
height: 64px;
border: none;
border-radius: 16px;
font-size: 2em;
background-color: #bdbdbd;
}
button:hover {
cursor: pointer;
box-shadow: inset 0 0 100px rgb(255, 255, 255, 0.3);
}
button.empty {
visibility: hidden;
}
button.key {
color: #fff;
background-color: #536DFE;
}
button.operator,
button.func {
color: #fff;
background-color: #757575;
}
button.clear {
color: #fff;
background-color: #F44336;
}
button.calculate {
color: #fff;
background-color: #4CAF50;
}
</style>
|
<template>
<div class="weather-card">
<p v-if="weatherInfo.location">{{ weatherInfo.location["name"] }}区</p>
<div class="weather-icon" :title="iconTitle"></div>
<p v-if="weatherInfo.now">
{{ weatherInfo.now["temp"] }}℃/{{ weatherInfo.now["rh"] }}%/{{
weatherInfo.now["wind_dir"]
}}/{{ weatherInfo.now["wind_class"] }}
</p>
</div>
</template>
<script>
import { loadBMap } from "@/utils/location";
import { fetchAreaByLocation, fetchWeather } from "@/api/weather";
import { weatherIcon } from "@/utils/weather";
import { fetchSiteInfo } from "@/api/site";
import {
AnimatedWeatherIcon,
AnimatedWeatherTypes,
AnimatedWeatherTimes,
} from "animated-weather-icon";
import dayjs from "dayjs";
import districtJson from "@/assets/json/district.json";
export default {
data() {
return {
areaInfo: {},
weatherInfo: {},
iconTitle: "",
};
},
created() {
// this.getPos();
// window.initBaiduMapScript = () => {
// this.getPosByBaidu();
// };
// loadBMap("initBaiduMapScript");
this.getSiteInfo();
},
methods: {
async getSiteInfo() {
try {
const res = await fetchSiteInfo();
if (res.code === 200) {
let area_code = res.data.area_code;
area_code = area_code ? area_code.split("*")[2] : "141102";
this.getWeather(area_code);
} else {
this.$message.error(res.errors);
}
} catch (error) {
this.$message.error(error);
}
},
// web API获取经纬度位置信息(只能用于https或本地测试)
getPos() {
navigator.geolocation.getCurrentPosition(
(pos) => {
const { longitude, latitude } = pos.coords;
Promise.all([this.getAreaByLocation(longitude, latitude)])
.then((result) => {
this.getWeather(
result[0] &&
result[0].addressComponent &&
result[0].addressComponent.adcode
? result[0].addressComponent.adcode
: "330212"
);
})
.catch((err) => {
this.$message.error(err);
});
},
(err) => {
this.$message.warning("ERROR(" + err.code + "): " + err.message);
},
{
enableHighAccuracy: true,
timeout: 1000 * 10,
maximumAge: 0,
}
);
},
// 百度地图 API获取经纬度位置信息
getPosByBaidu() {
const that = this;
this.$nextTick(function () {
try {
const geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function (r) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
const { district = null } = r.address;
const districtObj = districtJson.find((item) => {
return district.indexOf(item.district) >= 0;
});
if (districtObj) {
const districtCode = districtObj.districtcode
? districtObj.districtcode
: "330212";
that.getWeather(districtCode);
}
}
});
} catch (err) {
this.$message.error(err);
}
});
},
// 根据经纬度获取所在区县代码
async getAreaByLocation(lng, lat) {
try {
const res = await fetchAreaByLocation({ lng, lat });
if (res.code === 0) {
this.areaInfo = res.result || {};
return this.areaInfo;
} else {
this.$message.error(res.errors);
}
} catch (error) {
this.$message.error(error);
}
},
// 根据区县代码获取天气情况
async getWeather(district_id) {
try {
const res = await fetchWeather({ district_id });
if (res.status === 0) {
this.weatherInfo = res.result;
const renderTarget = document.querySelector(".weather-icon");
const icon = new AnimatedWeatherIcon(renderTarget);
this.iconTitle = this.weatherInfo?.now?.text
? this.weatherInfo.now.text
: null;
const exactHour = dayjs().format("HH") * 1;
const hourType = exactHour < 18 && exactHour >= 6 ? "Day" : "Night";
icon.setType(
AnimatedWeatherTypes[weatherIcon(this.iconTitle)],
AnimatedWeatherTimes[hourType]
);
} else {
this.$message.error(res.errors);
}
} catch (error) {
this.$message.error(error);
}
},
},
};
</script>
<style lang="less" scoped>
.weather-card {
min-width: 160px;
height: 50px;
padding: 0 12px;
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
display: flex;
align-items: center;
border-radius: 12px;
.weather-icon {
width: 36px;
height: 36px;
margin: 0 12px;
}
:deep(.AnimatedWeatherIcon) {
line-height: 0;
}
}
</style>
|
# Projet API avec Docker
Ce projet implémente une API REST simple avec Node.js et Express, permettant de créer et de supprimer des tables dans une base de données PostgreSQL. Le projet utilise Docker pour faciliter la configuration et le déploiement de l'application et de la base de données.
## Utilité de l'API
L'API fournie par ce projet permet d'interagir facilement avec une base de données PostgreSQL en offrant des endpoints pour créer et supprimer des tables. Cette API peut être utilisée pour gérer dynamiquement la structure de la base de données dans des applications qui nécessitent une modification fréquente des schémas de base de données.
## Installation
### Prérequis
- Docker et Docker Compose doivent être installés sur votre machine.
- Node.js doit être installé si vous souhaitez exécuter l'application hors conteneurs.
### Mise en place avec Docker
1. Clonez le dépôt contenant les fichiers du projet.
2. Dans le répertoire du projet, choisissez l'un des fichiers Docker Compose fournis pour démarrer l'application et la base de données.
### Utilisation de `docker-compose.yml`
Ce fichier Docker Compose configure et lance un conteneur pour l'application Node.js et un conteneur pour la base de données PostgreSQL.
Pour l'utiliser :
```
docker-compose up --build
```
Cette commande construit l'image de l'application à partir du Dockerfile situé dans le dossier `./app` et lance les services `app` et `db` comme configuré.
### Utilisation de `docker-compose-bis.yml`
Ce fichier Docker Compose est configuré pour connecter l'application à une instance PostgreSQL hébergée (dans cet exemple, sur Aiven Cloud). Il ne démarre pas de conteneur pour la base de données PostgreSQL localement mais configure l'application pour se connecter à une base de données distante.
Pour l'utiliser :
```
docker-compose -f docker-compose-bis.yml up --build
```
## Différences entre les deux configurations Docker Compose
- `docker-compose.yml` crée un environnement local complet avec une base de données PostgreSQL hébergée dans un conteneur Docker. Il est idéal pour le développement et les tests locaux.
- `docker-compose-bis.yml` est configuré pour utiliser une base de données PostgreSQL distante. Cela convient aux environnements de production ou lorsque l'accès à une base de données PostgreSQL spécifique est nécessaire.
## Accéder à l'API
Une fois l'application lancée, l'API est accessible via `http://localhost:3000/api`. Vous pouvez utiliser les endpoints suivants pour interagir avec la base de données :
- POST `/api/table/create/:tableName` : Crée une nouvelle table avec le nom spécifié.
- POST `/api/table/delete/:tableName` : Supprime la table spécifiée.
Utilisez un outil comme Postman ou curl pour envoyer des requêtes à l'API.
|
// medecins-par-centre.component.ts
import { Component, OnInit } from '@angular/core';
import { Medecin } from '../medecin.model';
import { CentreService } from '../centre.service';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-medecins-par-centre',
templateUrl: './medecins-par-centre.component.html',
styleUrls: ['./medecins-par-centre.component.css']
})
export class MedecinsParCentreComponent implements OnInit {
centreId!: number;
medecins: Medecin[] = [];
nouvelMedecin: Medecin = {
id: 0,
nom: '',
prenom: '',
email: '',
telephone: '',
centre: { id: 0 }
};
constructor(private centreService: CentreService, private route: ActivatedRoute, private router: Router) {}
ngOnInit(): void {
this.route.params.subscribe(params => {
this.centreId = +params['id'];
if (isNaN(this.centreId)) {
console.error('ID du centre invalide.');
} else {
this.loadMedecins();
}
});
}
medecinEnModification: Medecin | null = null;
afficherFormulaireCreation = false;
loadMedecins(): void {
this.centreService.getMedecinsByCentreId(this.centreId).subscribe(
(data: Medecin[]) => {
this.medecins = data;
this.nouvelMedecin.centre!.id = this.centreId;
},
(error: any) => {
console.error('Erreur lors du chargement des médecins :', error);
}
);
}
creerMedecin(): void {
this.centreService.creerMedecin(this.nouvelMedecin).subscribe(
(medecinCree: Medecin) => {
console.log('Medecin créé avec succès :', medecinCree);
this.medecins.push(medecinCree);
this.nouvelMedecin = {
id: 0,
nom: '',
prenom: '',
email: '',
telephone: '',
centre: { id: this.centreId }
};
this.afficherFormulaireCreation = false;
},
(error: any) => {
console.error('Erreur lors de la création du medecin :', error);
}
);
}
modifierMedecin(medecin: Medecin): void {
if (medecin) {
this.medecinEnModification = { ...medecin };
if (!this.medecinEnModification.centre) {
this.medecinEnModification.centre = { id: this.centreId };
} else {
this.medecinEnModification.centre.id = this.centreId;
}
console.log('this.medecinEnModification est défini:', this.medecinEnModification);
console.log('this.centreId:', this.centreId);
} else {
console.error('Le medecin à modifier est undefined.');
}
}
soumettreModification(): void {
if (this.medecinEnModification) {
this.centreService.modifierMedecin(this.medecinEnModification.id, this.medecinEnModification).subscribe(
(medecinModifie: Medecin) => {
console.log('Medecin modifié avec succès :', medecinModifie);
// Mettez à jour l'administrateur dans la liste administrateurs
const index = this.medecins.findIndex(a => a.id === medecinModifie.id);
if (index !== -1) {
this.medecins[index] = medecinModifie;
}
this.medecinEnModification = null; // Effacer le formulaire de modification
},
(error: any) => {
console.error('Erreur lors de la modification du medecin :', error);
}
);
} else {
console.error('Le medecin en modification est undefined.');
}
}
afficherFormulaireCreationMedecin(): void {
this.afficherFormulaireCreation = true;
}
afficherInscriptionsCentre(): void {
// Naviguer vers la page des inscriptions liées à ce centre en utilisant le centreId
this.router.navigate(['/centre', this.centreId, 'inscriptions']);
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Schduler</title>
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- fullCalendar 2.2.5-->
<link rel="stylesheet" href="plugins/fullcalendar/fullcalendar.min.css">
<link rel="stylesheet" href="plugins/fullcalendar/fullcalendar.print.css" media="print">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/adminlte.min.css">
<!-- Google Font: Source Sans Pro -->
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
<!-- Navbar -->
<nav class="main-header navbar navbar-expand bg-white navbar-light border-bottom">
<!-- Left navbar links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-widget="pushmenu" href="#"><i class="fa fa-bars"></i></a>
</li>
<li class="nav-item d-none d-sm-inline-block">
<a href="index3.html" class="nav-link">Home</a>
</li>
<li class="nav-item d-none d-sm-inline-block">
<a href="#" class="nav-link">Contact</a>
</li>
</ul>
<!-- SEARCH FORM -->
<form class="form-inline ml-3">
<select class=" vendor form-control">
<option value >--- All clinics ---</option>
<option value >BUITEMS</option>
</select>
</form>
<!-- Right navbar links -->
<ul class="navbar-nav ml-auto">
<!-- Messages Dropdown Menu -->
<!-- Notifications Dropdown Menu -->
<li class="nav-item">
<a class="nav-link" href="#"> <i class="nav-icon fa fa-dashboard"></i></a>
</li>
<li class="nav-item">
<a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#"><i
class="fa fa-th-large"></i></a>
</li>
</ul>
</nav>
<!-- /.navbar -->
<!-- Main Sidebar Container -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<!-- Brand Logo -->
<a href="index3.html" class="brand-link">
<span class="brand-text font-weight-light">Click for support</span>
</a>
<!-- Sidebar -->
<div class="sidebar">
<!-- Sidebar user panel (optional) -->
<div class="user-panel mt-3 pb-3 mb-3 d-flex">
<div class="image">
<img src="dist/img/user2-160x160.jpg" class="img-circle elevation-2" alt="User Image">
</div>
<div class="info">
<a href="#" class="d-block">Alexander Pierce</a>
</div>
</div> <!-- Sidebar Menu -->
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<!-- Add icons to the links using the .nav-icon class
with font-awesome or any other icon font library -->
<li class="nav-item has-treeview menu-open">
<a href="Dashboard.html" class="nav-link">
<i class="nav-icon fa fa-dashboard"></i>
<p>
Dashboard
</p>
</a>
</li>
<li class="nav-item">
<a href="Patients.html" class="nav-link">
<i class="nav-icon fa fa-group"></i>
<p>
Patients
</p>
</a>
</li>
<li class="nav-item has-treeview">
<a href="schduler.html" class="nav-link active">
<i class="nav-icon fa fa-calendar"></i>
<p>
Scheduler
</p>
</a>
</li>
<li class="nav-item has-treeview">
<a href="#" class="nav-link">
<i class="fa fa-line-chart"></i>
<p>
Finance
<i class="right fa fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="Quotations.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Quotations</p>
</a>
</li>
<li class="nav-item">
<a href="Billing.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p> Billing statements</p>
</a>
</li>
<li class="nav-item">
<a href="Balance.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Balance report</p>
</a>
</li>
</ul>
</li>
<li class="nav-item has-treeview">
<a href="#" class="nav-link">
<i class="fa fa-cog"></i>
<p>
Maintenance
<i class="right fa fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="Chief.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Chief complaints</p>
</a>
</li>
<li class="nav-item">
<a href="Signs .html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Signs and symptoms</p>
</a>
</li>
<li class="nav-item">
<a href="Diagnoses.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Diagnoses</p>
</a>
</li>
<li class="nav-item">
<a href="Procedures.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Procedures</p>
</a>
</li>
<li class="nav-item">
<a href="Materials.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Materials</p>
</a>
</li>
<li class="nav-item">
<a href="Statuses.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Statuses</p>
</a>
</li>
<li class="nav-item">
<a href="Prescriptions.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Prescriptions</p>
</a>
</li>
</ul>
</li>
<li class="nav-item has-treeview">
<a href="#" class="nav-link">
<i class="fa fa-sliders"></i>
<p>
Manage my acount
<i class="right fa fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="Manage.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p>Manage my account</p>
</a>
</li>
<li class="nav-item">
<a href=" Access.html" class="nav-link">
<i class="fa fa-circle-o nav-icon"></i>
<p> Logs ➤ Access</p>
</a>
</li>
</ul>
</li>
<form>
<select class=" vendor form-control" id="sel vendor">
<option>Find me a...</option>
<optgroup label="Operations">
<option value="/dental-treatment/patients">Patients</option>
<option value="/finance">Finance</option>
</optgroup>
<optgroup label="Maintenance">
<option value="/maintenace/chief-complaints">Chief complaints</option>
<option value="/maintenace/signs-and-symptoms">Signs and symptoms</option>
<option value="/maintenace/diagnoses">Diagnoses</option>
<option value="/maintenace/procedures">Procedures</option>
<option value="/maintenace/materials">Materials</option>
<option value="/maintenace/ststuses">Statuses</option>
<option value="/maintenace/prescriptions">Prescriptions</option>
</optgroup>
</select>
</form>
</ul>
</nav>
</div>
<!-- /.sidebar-menu -->
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Schduler</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active">Schduler</li>
</ol>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2 ">
<div class="icons-location">
<i class="fa fa-globe"> Location:</i>
</div>
</div>
<div class="col-lg-3 ">
<div class="locations">
<select class=" vendor form-control">
<option>All selected</option>
<option> [Select all]</option>
<option> BUITEMS</option>
<option>Chair 1</option>
</select>
<select class=" vendor form-control">
<option>All selected</option>
<option> [Select all]</option>
<option> Account holder</option>
<option> khattak, Anees (Engin)</option>
</select>
</div>
</div>
<div class="col-lg-3 manage-locations ">
<button type="button" class="btn btn-primary"><a href="#">Manage locations</a></button>
</div>
</div>
<!-- /.container-fluid -->
</section>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<table border="0" width="100%" class="add_edit_del_table" style="opacity:1; filter:alpha(opacity=100);">
<tbody><tr>
<td class="table_subheader" colspan="6">Add appointment:
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Location</b>:</td>
<td class="table_content">
<select class=" vendor form-control" style="width: 33%">
<option>Selected all</option>
<option> Account holder</option>
<option>Chair 1</option>
</select>
</td>
</tr>
<tr>
<td class="table_content"><b>Staff</b>:</td>
<td class="table_content">
<select class=" vendor form-control" style="width: 33%">
<option>All selected</option>
<option> [Select all]</option>
<option> BUITEMS</option>
<option>Chair 1</option>
</select>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>All day</b>:</td>
<td class="table_content">
<input type="radio" name="all_day" value="yes" class="all_day_yes_no" id="all_day_1"> <label for="all_day_1">Yes</label>
<input type="radio" name="all_day" value="no" class="all_day_yes_no" id="all_day_0" checked=""> <label for="all_day_0">No</label>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>From</b>:</td>
<td class="table_content">
<div class="col-md-3 form-vender invoice-input " style="padding: 0px;">
<input type="date" style="width: 70px; " value="" name="from" class="datepicker hasDatepicker ">
<i class="fa fa-calendar"></i>
</div>
<input type="text" style="width: 35px;" class="edit_appointment_time_input" maxlength="5" name="from_hour_min" value="07:45"> <i>HH:MM</i> <span class="mandatory_field">*</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Till</b>:</td>
<td class="table_content">
<div class="col-md-3 form-vender invoice-input " style="padding: 0px;">
<input type="date" style="width: 70px; " value="" name="from" class="datepicker hasDatepicker ">
<i class="fa fa-calendar"></i>
</div>
<input type="text" style="width: 35px;" class="edit_appointment_time_input" maxlength="5" name="till_hour_min" value="08:00"> <i>HH:MM</i> <span class="mandatory_field">*</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Type</b>:</td>
<td class="table_content">
<select class=" vendor form-control" style="width: 33%">
<option>Meeting</option>
<option> Not available</option>
<option> --Other--</option>
<option>Patient appointment</option>
</select>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Patient</b> <i>(optional)</i>:</td>
<td class="table_content">
<input type="text" style="width: 200px" name="patient_name">
Patient ID: <input type="text" style="width: 35px" name="patient_id" value="" class="patient_id" disabled="">
<input type="hidden" name="patient_id" value="" class="patient_id">
<span class="patient_id_link">
</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Description</b>:</td>
<td class="table_content"><textarea style="width: 200px; height: 100px" name="title"></textarea> <span class="mandatory_field">*</span></td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Link</b> <i>(optional)</i>:</td>
<td class="table_content"><input type="text" style="width: 200px" name="url" value=""></td>
</tr>
</tbody></table>
<!-- /.col -->
<table border="0" width="100%" class="add_edit_del_table_buttons" style="opacity:1; filter:alpha(opacity=100);">
<tbody><tr>
<td><input type="submit" name="opslaan" value="Save" class="primary-button"> <input type="button" name="opslaan" value="Save + send email to patient" id="submit_save_and_send_email"> <input type="button" name="cancel" value="Cancel" class="ajax_form_cancel_button"></td>
<td align="right">
<input type="button" name="delete" value="Delete appointment" class="ajax_load_form_button" style="background: none repeat scroll 0 0 #F36248; border: 1px solid #666666; color: #FFFFFF" data-form_action="delete" data-form_id="event-actions" data-module="scheduler" data-form_target="add_edit_appointment" data-item_id="">
</td>
</tr>
</tbody></table>
<!-- <div id="zoombox" class="lightbox"> <div class="zoombox_mask" style="display: block; opacity: 0.6;"></div> <div class="zoombox_container multimedia" style="width: 600px; height: 50px; top: 50px; left: 383px; display: block; opacity: 1;"> <div class="zoombox_content">
<div id="add_edit_appointment">
<form method="post" action="" class="ajax_form" data-form_id="event-actions" data-module="scheduler" data-form_target="add_edit_appointment">
<input type="hidden" name="action" value="add" class="ajax_form_action">
<input type="hidden" name="event_id" value="">
<input type="hidden" name="timeDifference" value="300">
<table border="0" width="100%" class="add_edit_del_table" style="opacity:1; filter:alpha(opacity=100);">
<tbody><tr>
<td class="table_subheader" colspan="6">Add appointment:
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Location</b>:</td>
<td class="table_content">
<div class="dropdown edit-appointment" data-target_class="edit-appointment" data-type="location_id" data-field_name="location_id"><select name="location_id" style="width: 206px; display: none;" class="edit-appointment_location_id"><option value="">-- Please select --</option><optgroup label="dreamstech"><option value="2610" selected="">Chair 1</option></optgroup></select><div class="ms-parent"><button type="button" class="ms-choice" style="width: 200px;"><span class=""> Chair 1</span><div></div></button><div class="ms-drop bottom" style="width: 205px;"><ul style="max-height: 250px;"><li><label><input type="radio" name="selectItemlocation_id" value=""> -- Please select --</label></li><li class="group"><label class="optgroup" data-group="group_1">dreamstech</label></li><li><label><input type="radio" name="selectItemlocation_id" value="2610" checked="checked" data-group="group_1"> Chair 1</label></li><li class="ms-no-results">No matches found</li></ul></div></div></div>
<span class="mandatory_field">*</span>
</td>
</tr>
<tr>
<td class="table_content"><b>Staff</b>:</td>
<td class="table_content">
<div class="dropdown edit-appointment" data-target_class="edit-appointment" data-type="dentist_id" data-field_name="dentist_id[]"><select name="dentist_id[]" style="width: 310px; display: none;" multiple="multiple" size="3" class="edit-appointment_dentist_id"><optgroup label="Account holder"><option value="102746" selected="">siddiqui, Awais jameel (awais)</option></optgroup></select><div class="ms-parent"><button type="button" class="ms-choice" style="width: 304px;"><span class="">All selected</span><div></div></button><div class="ms-drop bottom" style="width: 304px;"><ul style="max-height: 250px;"><li><label><input type="checkbox" name="selectAlldentist_id[]"> [Select all]</label></li><li class="group"><label class="optgroup" data-group="group_0"><input type="checkbox" name="selectGroupdentist_id[]"> Account holder</label></li><li class="multiple" style="width: 130px;"><label><input type="checkbox" name="selectItemdentist_id[]" value="102746" checked="checked" data-group="group_0"> siddiqui, Awais jameel (awais)</label></li><li class="ms-no-results">No matches found</li></ul></div></div></div>
<span class="mandatory_field">*</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>All day</b>:</td>
<td class="table_content">
<input type="radio" name="all_day" value="yes" class="all_day_yes_no" id="all_day_1"> <label for="all_day_1">Yes</label>
<input type="radio" name="all_day" value="no" class="all_day_yes_no" id="all_day_0" checked=""> <label for="all_day_0">No</label>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>From</b>:</td>
<td class="table_content">
<input type="text" style="width: 66px" maxlength="10" name="from_date" id="from_date" value="2018-10-04" class="datepicker hasDatepicker"><img class="ui-datepicker-trigger" src="https://dentalcharting.com/images/icons/month_calendar.png" alt="Select a date" title="Select a date"> <i>YYYY-MM-DD</i>
<input type="text" style="width: 32px; margin-left: 15px" class="edit_appointment_time_input" maxlength="5" name="from_hour_min" value="00:15"> <i>HH:MM</i> <span class="mandatory_field">*</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Till</b>:</td>
<td class="table_content">
<input type="text" style="width: 66px" maxlength="10" name="till_date" id="till_date" value="2018-10-04" class="datepicker hasDatepicker"><img class="ui-datepicker-trigger" src="https://dentalcharting.com/images/icons/month_calendar.png" alt="Select a date" title="Select a date"> <i>YYYY-MM-DD</i>
<input type="text" style="width: 32px; margin-left: 15px" class="edit_appointment_time_input" maxlength="5" name="till_hour_min" value="00:30"> <i>HH:MM</i> <span class="mandatory_field">*</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Type</b>:</td>
<td class="table_content">
<select name="type" style="width: 206px; display: none;" class="types_filter"><option value="9">Meeting</option><option value="10">Not available</option><option value="11">-- Other --</option><option value="8" selected="">Patient appointment</option>
</select><div class="ms-parent"><button type="button" class="ms-choice" style="width: 200px;"><span class=""> Patient appointment</span><div></div></button><div class="ms-drop bottom" style="width: 205px;"><ul style="max-height: 250px;"><li><label><input type="radio" name="selectItemtype" value="9"> Meeting</label></li><li><label><input type="radio" name="selectItemtype" value="10"> Not available</label></li><li><label><input type="radio" name="selectItemtype" value="11"> -- Other --</label></li><li><label><input type="radio" name="selectItemtype" value="8" checked="checked"> Patient appointment</label></li><li class="ms-no-results">No matches found</li></ul></div></div> <span class="mandatory_field">*</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Patient</b> <i>(optional)</i>:</td>
<td class="table_content">
<input type="text" style="width: 200px" name="patient_name">
Patient ID: <input type="text" style="width: 35px" name="patient_id" value="" class="patient_id" disabled="">
<input type="hidden" name="patient_id" value="" class="patient_id">
<span class="patient_id_link">
</span>
</td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Description</b>:</td>
<td class="table_content"><textarea style="width: 200px; height: 100px" name="title"></textarea> <span class="mandatory_field">*</span></td>
</tr>
<tr>
<td class="table_content" width="140px"><b>Link</b> <i>(optional)</i>:</td>
<td class="table_content"><input type="text" style="width: 200px" name="url" value=""></td>
</tr>
</tbody></table>
<table border="0" width="100%" class="add_edit_del_table_buttons" style="opacity:1; filter:alpha(opacity=100);">
<tbody><tr>
<td><input type="submit" name="opslaan" value="Save" class="primary-button"> <input type="button" name="opslaan" value="Save + send email to patient" id="submit_save_and_send_email"> <input type="button" name="cancel" value="Cancel" class="ajax_form_cancel_button"></td>
<td align="right">
<input type="button" name="delete" value="Delete appointment" class="ajax_load_form_button" style="background: none repeat scroll 0 0 #F36248; border: 1px solid #666666; color: #FFFFFF" data-form_action="delete" data-form_id="event-actions" data-module="scheduler" data-form_target="add_edit_appointment" data-item_id="">
</td>
</tr>
</tbody></table>
</form>
</div></div> <div class="zoombox_title" style="display: block;"></div> <div class="zoombox_close" style="display: block;"></div> </div> </div> -->
</div>
<!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div id="footer">
Copyright © 2018 DentalCharting - <a href="#" title="Terms & Conditions">Terms & Conditions</a> - <a href="#" title="Privacy">Privacy</a> - <a href="#" title="Copyright">Copyright</a> - <a href="#" title="Disclaimer">Disclaimer</a> - <a href="#" title="Changelog">Changelog</a>
<br><br>
</div>
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<!-- /.control-sidebar -->
</div>
<!-- ./wrapper -->
<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Slimscroll -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="dist/js/demo.js"></script>
<!-- fullCalendar 2.2.5 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="plugins/fullcalendar/fullcalendar.min.js"></script>
<!-- Page specific script -->
<script>
$(function () {
/* initialize the external events
-----------------------------------------------------------------*/
function ini_events(ele) {
ele.each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
}
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject)
// make the event draggable using jQuery UI
$(this).draggable({
zIndex : 1070,
revert : true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
})
})
}
ini_events($('#external-events div.external-event'))
/* initialize the calendar
-----------------------------------------------------------------*/
//Date for the calendar events (dummy data)
var date = new Date()
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear()
$('#calendar').fullCalendar({
header : {
left : 'prev,next today',
center: 'title',
right : 'month,agendaWeek,agendaDay'
},
buttonText: {
today: 'today',
month: 'month',
week : 'week',
day : 'day'
},
//Random default events
events : [
{
title : 'All Day Event',
start : new Date(y, m, 1),
backgroundColor: '#f56954', //red
borderColor : '#f56954' //red
},
{
title : 'Long Event',
start : new Date(y, m, d - 5),
end : new Date(y, m, d - 2),
backgroundColor: '#f39c12', //yellow
borderColor : '#f39c12' //yellow
},
{
title : 'Meeting',
start : new Date(y, m, d, 10, 30),
allDay : false,
backgroundColor: '#0073b7', //Blue
borderColor : '#0073b7' //Blue
},
{
title : 'Lunch',
start : new Date(y, m, d, 12, 0),
end : new Date(y, m, d, 14, 0),
allDay : false,
backgroundColor: '#00c0ef', //Info (aqua)
borderColor : '#00c0ef' //Info (aqua)
},
{
title : 'Birthday Party',
start : new Date(y, m, d + 1, 19, 0),
end : new Date(y, m, d + 1, 22, 30),
allDay : false,
backgroundColor: '#00a65a', //Success (green)
borderColor : '#00a65a' //Success (green)
},
{
title : 'Click for Google',
start : new Date(y, m, 28),
end : new Date(y, m, 29),
url : 'http://google.com/',
backgroundColor: '#3c8dbc', //Primary (light-blue)
borderColor : '#3c8dbc' //Primary (light-blue)
}
],
editable : true,
droppable : true, // this allows things to be dropped onto the calendar !!!
drop : function (date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject')
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject)
// assign it the date that was reported
copiedEventObject.start = date
copiedEventObject.allDay = allDay
copiedEventObject.backgroundColor = $(this).css('background-color')
copiedEventObject.borderColor = $(this).css('border-color')
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true)
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove()
}
}
})
/* ADDING EVENTS */
var currColor = '#3c8dbc' //Red by default
//Color chooser button
var colorChooser = $('#color-chooser-btn')
$('#color-chooser > li > a').click(function (e) {
e.preventDefault()
//Save color
currColor = $(this).css('color')
//Add color effect to button
$('#add-new-event').css({
'background-color': currColor,
'border-color' : currColor
})
})
$('#add-new-event').click(function (e) {
e.preventDefault()
//Get value and make sure it is not null
var val = $('#new-event').val()
if (val.length == 0) {
return
}
//Create events
var event = $('<div />')
event.css({
'background-color': currColor,
'border-color' : currColor,
'color' : '#fff'
}).addClass('external-event')
event.html(val)
$('#external-events').prepend(event)
//Add draggable funtionality
ini_events(event)
//Remove event from text input
$('#new-event').val('')
})
})
</script>
</body>
</html>
|
import type { FC, ReactNode } from "react";
import { useMemo } from "react";
import { useClassnames } from "../../../hooks/useClassnames";
type ButtonColourScheme = "primary" | "secondary" | "danger" | "success";
type Size = "xs" | "sm" | "md" | "lg";
type AnimationVariant = "default" | "scale";
const buttonColourSchemes: Record<ButtonColourScheme, string> = {
primary:
"bg-blue-500 hover:bg-blue-700 text-white focus:ring-blue-300 disabled:bg-blue-200",
secondary:
"bg-gray-200 hover:bg-gray-300 text-gray-700 focus:ring-gray-300 disabled:bg-gray-200",
danger:
"bg-red-500 hover:bg-red-600 text-white focus:ring-red-300 disabled:bg-red-200",
success:
"bg-lime-500 hover:bg-lime-600 text-white focus:ring-lime-300 disabled:bg-lime-200",
};
const sizes: Record<Size, string> = {
xs: "px-2 py-1 text-sm",
sm: "px-2 py-2 text-sm",
md: "px-4 py-2 text-base",
lg: "px-8 py-4 text-xl",
};
const animationVariants: Record<AnimationVariant, string> = {
default: "transition-colors transition-bg duration-200",
scale:
"transition-colors transition-bg duration-100 transition-transform hover:scale-105",
};
export type ButtonProps = {
children: string | ReactNode;
colourScheme?: ButtonColourScheme;
size?: Size;
animationVariant?: AnimationVariant;
} & React.ButtonHTMLAttributes<HTMLButtonElement>;
export const Button: FC<ButtonProps> = ({
children,
colourScheme = "primary",
size = "md",
animationVariant = "default",
className,
...restBtnProps
}) => {
const colourSchemeClassnames = useClassnames(
colourScheme,
buttonColourSchemes
);
const sizeClassnames = useClassnames(size, sizes);
const animationVariantClassnames = useClassnames(
animationVariant,
animationVariants
);
const fullClassnames = useMemo(
() =>
colourSchemeClassnames +
" " +
sizeClassnames +
" " +
animationVariantClassnames +
" " +
className,
[
colourSchemeClassnames,
sizeClassnames,
animationVariantClassnames,
className,
]
);
return (
<button
{...restBtnProps}
className={`transform cursor-pointer rounded-md font-medium capitalize tracking-wide focus:outline-none focus:ring focus:ring-opacity-80 disabled:cursor-default ${fullClassnames}`}
>
{children}
</button>
);
};
|
import 'package:flutter/material.dart';
import 'package:react_link_app/models/pixel.dart';
import 'package:react_link_app/utils/http_utils.dart';
import 'package:react_link_app/views/add_pixel.dart';
import 'package:react_link_app/widget/drawer.dart';
import 'homescreen.dart';
class TrackingPixel extends StatefulWidget {
@override
_TrackingPixelState createState() => _TrackingPixelState();
}
class _TrackingPixelState extends State<TrackingPixel> {
List<Pixel> allPixels;
Future<bool> getPixel() async {
allPixels = null;
allPixels = await HttpUtils.getPixels();
setState(() {});
return true;
}
@override
void initState() {
getPixel();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: DrawerOnly(),
appBar: AppBar(
title: Text(
"ReactLink",
style: TextStyle(fontWeight: FontWeight.bold),
),
actions: [
Container(
margin: EdgeInsets.only(right: 5),
child: IconButton(
onPressed: () {
showSearch(context: context, delegate: Searchitem());
},
icon: Icon(
Icons.search,
)))
],
backgroundColor: Colors.deepPurpleAccent,
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () async {
var data = await Navigator.push(
context, MaterialPageRoute(builder: (context) => AddPixel()));
getPixel();
},
backgroundColor: Colors.deepPurpleAccent,
label: Text(
"Add Pixel",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
// body: Column(
// mainAxisAlignment: MainAxisAlignment.start,
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Container(
// margin: EdgeInsets.only(left: 12, top: 8, bottom: 10),
// child: Text(
// "Pixels",
// style: TextStyle(
// fontSize: 18,
// fontWeight: FontWeight.bold,
// ),
// ),
// ),
// Divider(
// color: Colors.black38,
// ),
// Align(
// alignment: Alignment.center,
// child: Text(
// "No pixel found .Add one!",
// style: TextStyle(color: Colors.black54, fontSize: 16),
// ),
// )
// ],
// ),
body: allPixels != null
? allPixels.isNotEmpty
? ListView.builder(
itemCount: allPixels.length,
itemBuilder: (context, index) {
Pixel model = allPixels[index];
return ListTile(
title: Text(model.name),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: () async {
var data = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddPixel(
editModel: model,
)));
getPixel();
},
icon: Icon(Icons.edit),
),
model.isDeleteLoading
? Container(
height: 20,
width: 20,
child: CircularProgressIndicator())
: IconButton(
onPressed: () async {
setState(() {
model.isDeleteLoading = true;
});
await HttpUtils.deletePixel(
id: model.sId);
await getPixel();
setState(() {
model.isDeleteLoading = false;
});
},
icon: Icon(Icons.delete),
)
],
),
);
})
: Center(
child: Text("no pixel found"),
)
: Center(
child: CircularProgressIndicator(),
));
}
}
|
package io.github.zyrouge.symphony.ui.view.nowPlaying
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.launch
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.automirrored.outlined.Article
import androidx.compose.material.icons.filled.GraphicEq
import androidx.compose.material.icons.filled.MotionPhotosPaused
import androidx.compose.material.icons.filled.Repeat
import androidx.compose.material.icons.filled.RepeatOne
import androidx.compose.material.icons.filled.Shuffle
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.Timer
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.github.zyrouge.symphony.services.radio.RadioLoopMode
import io.github.zyrouge.symphony.ui.helpers.Routes
import io.github.zyrouge.symphony.ui.helpers.ViewContext
import io.github.zyrouge.symphony.ui.helpers.navigate
import io.github.zyrouge.symphony.ui.view.NowPlayingData
import io.github.zyrouge.symphony.ui.view.NowPlayingDefaults
import io.github.zyrouge.symphony.ui.view.NowPlayingLyricsLayout
import io.github.zyrouge.symphony.ui.view.NowPlayingStates
import io.github.zyrouge.symphony.utils.Logger
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NowPlayingBodyBottomBar(
context: ViewContext,
data: NowPlayingData,
states: NowPlayingStates,
) {
val coroutineScope = rememberCoroutineScope()
val equalizerActivity = rememberLauncherForActivityResult(
context.symphony.radio.session.createEqualizerActivityContract()
) {}
val sleepTimer by context.symphony.radio.observatory.sleepTimer.collectAsState()
var showSleepTimerDialog by remember { mutableStateOf(false) }
var showSpeedDialog by remember { mutableStateOf(false) }
var showPitchDialog by remember { mutableStateOf(false) }
var showExtraOptions by remember { mutableStateOf(false) }
data.run {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
start = 8.dp,
end = 8.dp,
bottom = 4.dp,
),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(
onClick = {
context.navController.navigate(Routes.Queue)
}
) {
Icon(
Icons.AutoMirrored.Filled.Sort,
null,
modifier = Modifier.size(20.dp),
)
Spacer(modifier = Modifier.width(8.dp))
Text(
context.symphony.t.PlayingXofY(
(currentSongIndex + 1).toString(),
queueSize.toString(),
),
overflow = TextOverflow.Ellipsis,
)
}
Spacer(modifier = Modifier.weight(1f))
states.showLyrics.let { showLyricsState ->
val showLyrics by showLyricsState.collectAsState()
IconButton(
onClick = {
when (lyricsLayout) {
NowPlayingLyricsLayout.ReplaceArtwork -> {
val nShowLyrics = !showLyricsState.value
showLyricsState.value = nShowLyrics
NowPlayingDefaults.showLyrics = nShowLyrics
}
NowPlayingLyricsLayout.SeparatePage -> {
context.navController.navigate(Routes.Lyrics)
}
}
}
) {
Icon(
Icons.AutoMirrored.Outlined.Article,
null,
tint = when {
showLyrics -> MaterialTheme.colorScheme.primary
else -> LocalContentColor.current
}
)
}
}
IconButton(
onClick = {
context.symphony.radio.queue.toggleLoopMode()
}
) {
Icon(
when (currentLoopMode) {
RadioLoopMode.Song -> Icons.Filled.RepeatOne
else -> Icons.Filled.Repeat
},
null,
tint = when (currentLoopMode) {
RadioLoopMode.None -> LocalContentColor.current
else -> MaterialTheme.colorScheme.primary
}
)
}
IconButton(
onClick = {
context.symphony.radio.queue.toggleShuffleMode()
}
) {
Icon(
Icons.Filled.Shuffle,
null,
tint = if (!currentShuffleMode) LocalContentColor.current
else MaterialTheme.colorScheme.primary
)
}
IconButton(
onClick = {
showExtraOptions = !showExtraOptions
}
) {
Icon(Icons.Outlined.MoreHoriz, null)
}
}
if (showSleepTimerDialog) {
sleepTimer?.let {
NowPlayingSleepTimerDialog(
context,
sleepTimer = it,
onDismissRequest = {
showSleepTimerDialog = false
}
)
} ?: run {
NowPlayingSleepTimerSetDialog(
context,
onDismissRequest = {
showSleepTimerDialog = false
}
)
}
}
if (showSpeedDialog) {
NowPlayingSpeedDialog(
context,
currentSpeed = data.currentSpeed,
persistedSpeed = data.persistedSpeed,
onDismissRequest = {
showSpeedDialog = false
}
)
}
if (showPitchDialog) {
NowPlayingPitchDialog(
context,
currentPitch = data.currentPitch,
persistedPitch = data.persistedPitch,
onDismissRequest = {
showPitchDialog = false
}
)
}
if (showExtraOptions) {
val sheetState = rememberModalBottomSheetState()
val closeBottomSheet = {
showExtraOptions = false
coroutineScope.launch {
sheetState.hide()
}
}
ModalBottomSheet(
sheetState = sheetState,
onDismissRequest = {
showExtraOptions = false
},
) {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Card(
onClick = {
closeBottomSheet()
try {
equalizerActivity.launch()
} catch (err: Exception) {
Logger.error(
"NowPlayingBottomBar",
"launching equalizer failed",
err
)
Toast.makeText(
context.activity,
context.symphony.t.LaunchingEqualizerFailedX(
err.localizedMessage ?: err.toString()
),
Toast.LENGTH_SHORT,
).show()
}
}
) {
ListItem(
leadingContent = {
Icon(Icons.Filled.GraphicEq, null)
},
headlineContent = {
Text(context.symphony.t.Equalizer)
},
)
}
Card(
onClick = {
closeBottomSheet()
context.symphony.radio.setPauseOnCurrentSongEnd(!pauseOnCurrentSongEnd)
}
) {
ListItem(
leadingContent = {
Icon(
Icons.Filled.MotionPhotosPaused,
null,
tint = when {
pauseOnCurrentSongEnd -> MaterialTheme.colorScheme.primary
else -> LocalContentColor.current
}
)
},
headlineContent = {
Text(context.symphony.t.PauseOnCurrentSongEnd)
},
supportingContent = {
Text(
if (pauseOnCurrentSongEnd) context.symphony.t.Enabled
else context.symphony.t.Disabled
)
},
)
}
Card(
onClick = {
closeBottomSheet()
showSleepTimerDialog = !showSleepTimerDialog
}
) {
ListItem(
leadingContent = {
Icon(
Icons.Outlined.Timer,
null,
tint = when {
hasSleepTimer -> MaterialTheme.colorScheme.primary
else -> LocalContentColor.current
}
)
},
headlineContent = {
Text(context.symphony.t.SleepTimer)
},
supportingContent = {
Text(
if (hasSleepTimer) context.symphony.t.Enabled
else context.symphony.t.Disabled
)
},
)
}
Card(
onClick = {
closeBottomSheet()
showSpeedDialog = !showSpeedDialog
}
) {
ListItem(
leadingContent = {
Icon(Icons.Outlined.Speed, null)
},
headlineContent = {
Text(context.symphony.t.Speed)
},
supportingContent = {
Text("x${data.currentSpeed}")
},
)
}
Card(
onClick = {
closeBottomSheet()
showPitchDialog = !showPitchDialog
}
) {
ListItem(
leadingContent = {
Icon(Icons.Outlined.Speed, null)
},
headlineContent = {
Text(context.symphony.t.Pitch)
},
supportingContent = {
Text("x${data.currentPitch}")
},
)
}
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
}
|
export interface MenuItem {
name: string;
image: string;
price: number;
alt: string;
count: number;
total: number;
}
export interface CartItem extends MenuItem {}
export interface InitialStoreState {
menuItems: Array<MenuItem>;
cart: {
items: Array<CartItem>;
subtotal: number;
total: number;
tax: number;
};
}
export type CART_STORE_ACTIONS =
| { type: "add"; payload: InitialStoreState }
| { type: "remove"; payload: InitialStoreState }
| { type: "delete"; payload: InitialStoreState };
|
<script setup lang="ts">
import { computed } from 'vue';
import { useCellMetaData, type Lineage } from '@/stores/cellMetaData';
import { useImageViewerStoreUntrracked } from '@/stores/imageViewerStoreUntrracked';
import { storeToRefs } from 'pinia';
import { useGlobalSettings } from '@/stores/globalSettings';
const cellMetaData = useCellMetaData();
const globalSettings = useGlobalSettings();
const imageViewerStoreUntrracked = useImageViewerStoreUntrracked();
const { sizeT } = storeToRefs(imageViewerStoreUntrracked);
interface DisplayInfo {
label: string;
value: string;
}
const displayList = computed<DisplayInfo[]>(() => {
const info: DisplayInfo[] = [
{
label: 'Cells',
value: cellMetaData.cellArray?.length.toLocaleString() ?? 'UNKNOWN',
},
{
label: 'Tracks',
value:
cellMetaData.trackArray?.length.toLocaleString() ?? 'UNKNOWN',
},
{
label: 'Lineages',
value:
cellMetaData.lineageArray
?.filter((lineage: Lineage) => {
return lineage.founder.children.length > 0;
})
.length.toLocaleString() ?? 'UNKNOWN',
},
{
label: 'Images',
value: sizeT.value.toLocaleString() ?? 'UNKNOWN',
},
];
return info;
});
</script>
<template>
<NoDataSplash></NoDataSplash>
<div
v-if="cellMetaData.dataInitialized"
class="flex items-center justify-center align-center h-100"
>
<q-card
v-for="info in displayList"
:key="info.label"
bordered
:dark="globalSettings.darkMode"
class="q-ma-sm inner-card"
>
<q-card-section>
<div class="text-overline text-center">{{ info.label }}</div>
</q-card-section>
<q-card-section class="text-center text-h4 q-pt-none">
{{ info.value }}
</q-card-section>
</q-card>
</div>
</template>
<style scoped lang="scss">
.inner-card {
border-radius: 30px;
}
</style>
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// 화살표 함수
// 화살표(=>)를 사용해서 함수를 선언하는 방법
// () => {};
// ES5에서 일반적인 방법
var greeting1 = function (name) {
return 'hello ' + name;
};
// 화살표 함수로 바꾸면
const greeting2 = (name) => {
return 'hello ' + name;
};
// 매개변수가 하나만 있으면 괄호 생략 가능
const greeting3 = name => {
return 'hello ' + name;
};
// 매개변수가 전혀 없으면 다음과 같이 꼭 빈 괄호를 써야 함!(생략 불가)
const greeting4 = () => {
return 'hello';
};
// 암시적 반환
// 리턴문 한 줄만 있을 경우 중괄호(함수 블록)랑 return 키워드 둘 다 생략 가능
// 주의! return 키워드만 생략하면 안됨!!
const greeting5 = name => 'hello ' + name;
// (중요) 코드의 간결함보다는 가독성이 우선
// 아직 ES6차가 익숙하지 않다면 greeting2 와 같이 작성하는 것도 좋다.
// 객체를 암시적으로 반환하기
function getFavoriteMovie() {
return {
title: 'Inception',
year: '2010',
director: 'Nolan',
rating: 9.6
};
}
console.log(getFavoriteMovie());
// 객체를 소괄호로 감싸야한다.
// 그렇지 않으면 {}을 함수의 실행 블록으로 인식해서 에러가 발생함
const getFavoriteMovie2 = () => ({
title: 'Inception',
year: '2010',
director: 'Nolan',
rating: 9.6
});
console.log(getFavoriteMovie2());
// () => {};
// 화살표 함수는 익명 함수
// 참조할 이름이 필요하다면 함수를 변수에 할당하면 됨
// Quiz
// 2.1 다음 중 화살표 함수를 문법에 맞게 활용한 예는? b)
let arr = [1, 2, 3];
// a)
// let func = arr.map(n -> n + 1);
// b)
// let func = arr.map(n => n + 1);
// c)
// let func = arr.map(n ~> n + 1);
// Quiz2.2~2.4: 화살표 함수로 변경하기
// 2.2
function testFunc(arg) {
console.log(arg);
}
const testFunc2 = arg => {
console.log(arg);
};
// 2.3
function add(num1, num2) {
return num1 + num2;
}
const add2 = (num1, num2) => num1 + num2;
// 2.4
// function ask(question, yes, no) {
// if (confirm(question)) yes();
// else no();
// }
// ask(
// '동의하십니까?',
// function() { alert('동의하셨습니다.'); },
// function() { alert('취소 버튼을 누르셨습니다.'); }
// );
const ask2 = (question, yes, no) => {
if (confirm(question)) yes();
else no();
};
ask2(
'동의하십니까?',
() => alert('동의하셨습니다.'),
() => alert('취소 버튼을 누르셨습니다.')
);
// 전역 스코프에서 this는 window 객체를 가리킴(실행 환경이 브라우저일 때)
console.log(this);
</script>
</head>
<body>
</body>
</html>
|
<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\User;
use App\Repositories\StoreRepository;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class UsersController extends Controller
{
protected $userRepository;
protected $storeData;
public function __construct(UserRepository $userRepository, StoreRepository $storeData)
{
// php
$this->userRepository = $userRepository;
$this->storeData = $storeData;
}
public function index()
{
$id = Auth::id();
$user = User::find($id);
$role = $user->roles()->first()->name;
if($role == 'Admin')
{
$response = $this->userRepository->index();
return response()->json(['status'=> 'success','data'=> $response],200);
}elseif($role == 'Generalist')
{
$response = $this->userRepository->index2();
return response()->json(['status'=> 'success','data'=> $response],200);
}
}
public function show($id)
{
$response = $this->userRepository->findById($id);
return response()->json(['status'=> 'success','data'=> $response],200);
}
public function update(Request $request, $id)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string',
'last_name' => 'required|string',
'email' =>'required|email',
'regional' => 'string',
'password'=>'required|min:8|confirmed',
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()] ,500);
}
if($request->store){
$store = $this->storeData->findById($request->store);
}else{
$store = $this->storeData->findById(1);
}
$user = $this->userRepository->findById($id);
$response = $this->userRepository->update($user,$store,$request->all());
return response()->json(['status'=> 'success','data'=> $response],200);
}
public function destroy($id)
{
$user = $this->userRepository->findById($id);
$response = $this->userRepository->delete($user);
return response()->json(['status'=> 'success','data'=> $response],200);
}
}
|
export interface Media {
_id: number;
ean?: number;
title: string;
releaseYear?: number;
publisher?: string[];
description?: string;
genre?: string;
mediaTyp: string,
language?: string;
//currently no use case for them, tags?: string[];
previewImageLink?: string;
externalProductLink?: string; // link to external pages, so user may be able to have a sneak peak in the book there. not for afiliation link earnings
}
export interface Book extends Media{
// ean and isbn same number;; isbn: number; /* todo: debatte if number or string, for 9-999-999 representation instead 999999 */
authors: string[];
pages: number;
tableOfContentLink?: string; //link to a picture of the page of content
}
// CD, DVD, Blu-ray
// Optional split this in more preceise categories i.e movies, music,..
export interface Disc extends Media{
fsk?: number;
tableOfContentLink?: string; //link to a picture of the page of content
duration?: number; //in minutes
involvedPerson?: string[]; // singers, actors,...
}
export interface digitalGame extends Media{
developers: string[]; // in case multiple developers
usk: number;
// does make less sense right now;; tableOfContentLink?: string; //link to a picture of the page of content
platform: string; // platform (single not multiple). Different platforms have different ean, and therefore different entries
}
// No digital games, i.e card, boardgames,..
export interface Game extends Media{
minAge?: number; //minimum advised age
playTime?: number; //either in minutes or a string to handle later
playersMinimum?: number; //minimum players needed
playersMaximum?: number; //maximum players possible
}
// not assuming scientific magazines for now other DIO
export interface Magazine extends Media{
issn: string; //string as the last number (#8) could also be a "X"
tableOfContentLink?: string; // link to a picture of the page of content
magazineNumber?: number;
pages?: number;
}
|
## DESCRIPTION
## A problem that asks students to convert a fraction to its equivalent representation as a number involving percents.
## ENDDESCRIPTION
## KEYWORDS('percent')
## DBsubject('College Algebra')
## DBchapter('Fractions')
## DBsection('Conversions to Percents')
## Author('Sandeep Bhargava')
## Institution('Humber College')
## TitleText1('')
## EditionText1('')
## AuthorText1('')
## Section1('')
## Problem1('')
########################################################################
# Initialization
DOCUMENT();
loadMacros(
"PGstandard.pl",
"MathObjects.pl",
"contextFraction.pl",
"AnswerFormatHelp.pl",
);
########################################################################
# Setup
# make sure we're in the context we want
Context("Numeric");
$numerator = list_random(1,3);
$denominator = 4;
$whole = random(1,9,1);
$improperFracNum = ($denominator*$whole)+$numerator;
$improperFracDenom = $denominator;
$solution = Compute(($improperFracNum/$improperFracDenom)*100);
########################################################################
# Main Text
TEXT(beginproblem());
Context()->texStrings;
BEGIN_TEXT
Convert the (mixed) fraction \( \ \displaystyle $whole \, \frac{$numerator}{$denominator} \ \) into its equivalent percent.
$BR
$BR
Answer\( = \) \{ ans_rule(10) \} $PERCENT
$BR
END_TEXT
Context()->normalStrings;
########################################################################
# Answer Evaluation
ANS(num_cmp($solution,
tol => 0.0001,
tolType => "absolute",
));
########################################################################
# Solution
Context()->texStrings;
BEGIN_SOLUTION
$PAR
${BUL}Solution:${EUL} We begin by converting the given mixed number into its equivalent improper fraction:
$BR
$BR
\[ \displaystyle $whole \, \frac{$numerator}{$denominator} \ = \ \frac{($denominator \times $whole)+ $numerator}{$denominator} \ = \ \frac{$improperFracNum}{$improperFracDenom} \]
$BR
$BR
Next, we convert this improper fraction into its equivalent percent:
$BR
$BR
\[ \displaystyle \frac{$improperFracNum}{$improperFracDenom} \ = \frac{$improperFracNum}{$improperFracDenom} \times 1 \ = \frac{$improperFracNum}{$improperFracDenom} \times \frac{100}{100} \ = \ \frac{$improperFracNum}{$improperFracDenom} \times 100 \times \frac{1}{100} \ = \ \frac{$improperFracNum \times 100}{$improperFracDenom} \, $PERCENT \ = \ $solution \,$PERCENT \]
END_SOLUTION
Context()->normalStrings;
ENDDOCUMENT();
|
''File: xstring.bas
''Description: Demonstration of ext.strings.xstring object.
''
''Copyright (c) 2007-2014 FreeBASIC Extended Library Development Group
''
''Distributed under the FreeBASIC Extended Library Group license. (See
''accompanying file LICENSE.txt or copy at
''http://code.google.com/p/fb-extended-lib/wiki/License)
# include once "ext/xstring.bi"
using ext.strings
dim as xstring myxstring = "Hello, World!"
var s2 = myxstring
print myxstring
myxstring.reverse()
print myxstring
print myxstring <> "Hai, World!"
print myxstring = "Hai, World!"
myxstring.reverse()
print myxstring + " Tacos Rule!"
myxstring.replace(" Tacos Rule!", "")
print myxstring
print myxstring & " From FreeBASIC"
print instr(myxstring, ",") 'You may use xstring with any procedure that takes a string
scope
var sx = xstring("the freeBASIC extended library development team")
sx.ucwords()
print sx
end scope
scope
var s1 = xstring("apple")
s1 &= "peaches"
s1 &= "grapes" & s1
print s1
end scope
'xstring also supports the operators - and *
var mystr = xstring("testing, testing, testing")
mystr -= ","
print mystr
mystr *= 2
print mystr
print -mystr
|
import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import {
FormGroup,
FormControl,
FormBuilder,
Validators
} from "@angular/forms";
import {
StateMatcher,
DateLessThanNow,
EmptyOrNull
} from "src/app/shared/validate";
import { COMMA, ENTER } from "@angular/cdk/keycodes";
import { Observable } from "rxjs";
import {
MatAutocomplete,
MatChipInputEvent,
MatAutocompleteSelectedEvent
} from "@angular/material";
import { TranslateService } from "@ngx-translate/core";
import { AppService } from "src/app/common/services/app.service";
import { Router } from "@angular/router";
import { CommonService } from "src/app/common/method";
import { CURRENT_USER } from "src/app/constants/localStorageKey";
import { DetailUserAPIs, ProjectAPIs } from "src/app/constants/api";
import * as moment from "moment";
@Component({
selector: "app-project-add",
templateUrl: "./project-add.component.html",
styleUrls: ["./project-add.component.scss"]
})
export class ProjectAddComponent implements OnInit {
initLisEmployee: any[] = [];
formProject: FormGroup;
onSubmit: boolean = false;
currentUser: any;
matcher = new StateMatcher();
selectedEmployee: number;
employeeList: [];
employeeSelect: [];
selectable = true;
removable = true;
addOnBlur = false;
separatorKeysCodes: number[] = [ENTER, COMMA];
employeeControl = new FormControl();
filteredFruits: Observable<string[]>;
lstSelectedEmployee: any[] = [];
@ViewChild("employeeInput", { static: false }) employeeInput: ElementRef<
HTMLInputElement
>;
@ViewChild("auto", { static: false }) matAutocomplete: MatAutocomplete;
constructor(
public translate: TranslateService,
private appService: AppService,
private fb: FormBuilder,
private route: Router,
private commonService: CommonService
) {
translate.setDefaultLang("vi");
this.currentUser = JSON.parse(localStorage.getItem(CURRENT_USER));
this.onCheckPermission();
console.log(this.currentUser);
this.initialForm();
// this.getEmployeeNoDepartment();
this.onGetEmployee();
}
onCheckPermission() {
this.appService
.get(ProjectAPIs.CHECK_PERMISSION, () => {}, {
companyId: JSON.parse(localStorage.getItem(CURRENT_USER)).CompanyId
})
.subscribe((res: any) => {});
}
ngOnInit() {}
onGetEmployee() {
this.appService
.get(DetailUserAPIs.GET_ALL, () => {}, {
companyId: parseInt(this.currentUser.CompanyId)
})
.subscribe((res: any) => {
console.log(res);
if (res.success) {
this.employeeList = Array.isArray(res.data) ? res.data : [];
} else {
this.commonService.showAlert(res.message, "danger", "Cảnh báo");
}
});
}
initialForm() {
const companyId = parseInt(this.currentUser.CompanyId);
this.formProject = this.fb.group({
projectName: ["", [EmptyOrNull.SpaceValidator, Validators.required]],
startDate: [
new Date(),
[Validators.required, DateLessThanNow.dateVaidator]
],
endDate: [
new Date(
new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate() + 1
),
[Validators.required]
],
description: ["", [EmptyOrNull.SpaceValidator, Validators.required]],
managerId: ["", [EmptyOrNull.SpaceValidator, Validators.required]],
companyId: [companyId],
lstEmployee: [this.initLisEmployee]
});
}
onChangeManager(e) {
console.log(e);
if (e.value) {
this.selectedEmployee = e.value;
this.formProject.controls.managerId.setValue(e.value);
console.log(this.formProject.value);
} else {
this.formProject.controls.managerId.setValue("");
}
}
onChangeSearch(e) {
let lstVm = this.formProject.controls.lstEmployee.value.join(";");
this.appService
.get(DetailUserAPIs.GET_SELECT_PROJECT, () => {}, {
companyId: parseInt(this.currentUser.CompanyId),
lstVm: lstVm,
keyword: e
})
.subscribe((res: any) => {
console.log(res);
if (res.success) {
this.employeeSelect = res.data;
}
});
}
add(event: MatChipInputEvent): void {
console.log("dsd");
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || "").trim()) {
this.lstSelectedEmployee.push(value.trim());
}
// Reset the input value
if (input) {
input.value = "";
}
}
}
remove(employee: any): void {
const index = this.formProject.controls.lstEmployee.value.findIndex(
x => x == employee.id
);
if (index >= 0) {
this.formProject.controls.lstEmployee.setValue(
this.formProject.controls.lstEmployee.value.filter(
x => x !== employee.id
)
);
this.lstSelectedEmployee = this.lstSelectedEmployee.filter(
x => x.id != employee.id
);
}
// if (index >= 0) {
// this.fruits.splice(index, 1);
// }
}
selected(event: MatAutocompleteSelectedEvent): void {
this.formProject.controls.lstEmployee.value.push(event.option.value);
console.log(this.formProject.controls.lstEmployee.value);
this.lstSelectedEmployee.push({
id: event.option.value,
name: event.option.viewValue
});
this.employeeControl.setValue("");
}
compareTwoDates() {
var date = this.formProject.controls.endDate.value;
this.formProject.controls.startDate.markAsTouched();
this.formProject.controls.endDate.markAsTouched();
if (date == null) {
this.formProject.controls.endDate.setErrors({
matDatepickerParse: true
});
return;
}
if (
this.formProject.controls.startDate.value >=
this.formProject.controls.endDate.value
) {
this.formProject.controls.endDate.setErrors({
endDateLess: true
});
return;
}
this.formProject.controls.endDate.setErrors(null);
}
onAddProject() {
this.formProject.markAllAsTouched();
console.log(this.formProject);
if (!this.formProject.invalid) {
this.toggleOnRequest();
this.appService
.post(ProjectAPIs.ADD, this.toggleOnRequest, {
...this.formProject.value,
startDate: moment(this.formProject.controls.startDate.value).format(
"YYYY-MM-DD HH:mm:ss"
),
endDate: moment(this.formProject.controls.endDate.value).format(
"YYYY-MM-DD HH:mm:ss"
)
})
.subscribe((res: any) => {
this.toggleOnRequest();
if (res.success) {
this.commonService.showAlert(
"Thêm thành công",
"success",
"Thông báo"
);
this.route.navigate(["/company/project-manager/project-list"]);
} else {
this.commonService.showAlert(res.message, "danger", "Thông báo");
}
});
} else {
this.commonService.showAlert(
"Vui lòng điền đủ thông tin",
"danger",
"Lỗi"
);
}
}
toggleOnRequest = (): void => {
this.onSubmit = !this.onSubmit;
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.