text
stringlengths
184
4.48M
import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { PlannerCell } from "./PlannerCell"; import { PlannerHeadCell } from "./PlannerHeadCell"; import { setBreakfast, setLunch, setDinner, } from "../../redux/actions/plannerTable"; import { parceStringToWeekDay } from "../../helpers/parseStringToWeekDay"; import { weekDay } from "../../consts/week"; export const PlannerTable = ({ week }) => { const dispatch = useDispatch(); const { breakfast, lunch, dinner, firstDay } = useSelector( ({ plannerTable }) => plannerTable ); const breakfastHandler = (value) => { dispatch(setBreakfast(value)); }; const lunchHandler = (value) => { dispatch(setLunch(value)); }; const dinnerHandler = (value) => { dispatch(setDinner(value)); }; return ( <div className="table-responsive"> <table className="table text-start align-middle table-bordered table-hover mb-0"> <thead> <tr className="text-dark"> <th scope="col"></th> {week && week.map((item, index) => ( <PlannerHeadCell dataAtt={index} key={item} date={item} day={weekDay[parceStringToWeekDay(item)]} /> ))} </tr> </thead> <tbody> <tr> <td>Завтрак</td> {Array(7) .fill(null) .map((item, index) => ( <PlannerCell dataAtt={index} key={index} firstDay={firstDay} typeOfMeal={breakfast} handler={breakfastHandler} /> ))} </tr> <tr> <td>Обед</td> {Array(7) .fill(null) .map((item, index) => ( <PlannerCell dataAtt={index} key={index} firstDay={firstDay} typeOfMeal={lunch} handler={lunchHandler} /> ))} </tr> <tr> <td>Ужин</td> {Array(7) .fill(null) .map((item, index) => ( <PlannerCell dataAtt={index} key={index} firstDay={firstDay} typeOfMeal={dinner} handler={dinnerHandler} /> ))} </tr> </tbody> </table> </div> ); };
/* eslint-disable react/jsx-no-bind */ import Button from "elements/button"; import { Dispatch, SetStateAction, useRef, useState } from "react"; import ReactQuill from "@mantine/rte/node_modules/react-quill"; import type { Delta, DeltaOperation, Sources } from "quill"; import type { Editor } from "@mantine/rte"; import { useQueryClient } from "react-query"; import toast from "react-hot-toast"; import instance from "utils/axios"; import RichEditor from "./customeditor.comp"; export default function EditorRich(props: { workspace: string; toogle: Dispatch<SetStateAction<boolean>> }) { const { workspace, toogle } = props; const [value, setValue] = useState(""); const queryClient = useQueryClient(); const editorRef = useRef<ReactQuill>(null); async function submitPost(payload: { raw: DeltaOperation[]; html: string; workspace: string }) { try { const { data, status } = await instance.post("/blog/create", payload); if (status !== 200) { console.log("error", status, data); } queryClient.refetchQueries("blog"); toast.success("Successfully posted"); toogle(false); } catch (error) { console.log("🚀 ~ file: editor.comp.tsx ~ line 55 ~ EditorRich ~ error", error); } } const [editor, setEditor] = useState<Editor.UnprivilegedEditor>(); function onChange(data: string, _delta: Delta, _sources: Sources, editors: Editor.UnprivilegedEditor): void { if (!editor) setEditor(editors); setValue(data); } // console.log("content", editor && editor.getContents()); return ( <div className="border rounded"> <RichEditor ref={editorRef} controls={[ ["bold", "italic", "underline", "link"], ["clean", "h1", "h2", "h3"], ["alignLeft", "alignCenter", "alignRight"], ]} value={value} style={{ border: "none" }} placeholder="Write Something!" onChange={onChange} /> <Button className="ml-auto my-4 mr-4" onClick={() => { let raw; if (editor && editor.getContents) raw = editor.getContents(); if (raw && raw.ops) { const payload = { raw: raw.ops, html: value, workspace, }; submitPost(payload); } }} > Submit </Button> </div> ); }
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:google_speech/generated/google/cloud/speech/v1/cloud_speech.pb.dart' show StreamingRecognizeResponse; import '../../models/message/message.dart'; import '../../services/services/google_speech_service/google_speech_service_impl.dart'; import '../../services/services/google_speech_service/i_google_speech_service.dart'; part 'google_speech_state.dart'; part 'google_speech_cubit.freezed.dart'; class GoogleSpeechCubit extends Cubit<GoogleSpeechState> { GoogleSpeechCubit() : super(const GoogleSpeechState()); final IGoogleSpeechService _googleSpeechService = GoogleSpeechServiceImpl( assetPath: 'assets/com-tan-5f0885096433.json', languageCode: "vi-Vn"); StreamSubscription? _recognizeStreamSubscription; Stream<StreamingRecognizeResponse>? _recognizeStream; void recognize() { if (state.recordingDataRecognitionController != null) { emit(state.copyWith(isRecognizing: true)); // emit(state.copyWith( // finalReconizerText: "Công thức nấu món gà chiên mắm.", // isFinalReconizerText: true)); // emit(state.copyWith( // finalReconizerText: "Việt nam có bao nhiêu tỉnh?", // isFinalReconizerText: true)); _recognizeStream = _googleSpeechService .getRecognizeStream(state.recordingDataRecognitionController!); _recognizeStreamSubscription = _recognizeStream!.listen((data) { if (data.results.isNotEmpty) { String recognizedText = data.results.first.alternatives.first.transcript; Timer(const Duration(seconds: 2), () { if (state.checkChangeReconizerText == recognizedText) { emit(state.copyWith(isRecognizing: false)); } }); debugPrint("check recognizedText: |$recognizedText"); debugPrint("Check result's isFinal: ${data.results.first.isFinal}"); if (data.results.first.isFinal) { emit(state.copyWith( finalReconizerText: state.finalReconizerText + recognizedText, currentReconizerText: "", isFinalReconizerText: true)); } else { emit(state.copyWith( currentReconizerText: recognizedText, isFinalReconizerText: false)); } emit(state.copyWith(checkChangeReconizerText: recognizedText)); } }); } } void cancelRecognize() async { if (_recognizeStreamSubscription != null) { await _recognizeStreamSubscription!.cancel(); _recognizeStreamSubscription = null; } emit(state.copyWith(isRecognizing: false)); } void updateCurrentListeningMessage({Message? message, required bool isDone}) { if (isDone && state.currentListeningMessage != null) { emit(state.copyWith( currentListeningMessage: state.currentListeningMessage! .copyWith(message: state.finalReconizerText, isDone: true), currentReconizerText: "", checkChangeReconizerText: "", finalReconizerText: "", )); } else { emit(state.copyWith( currentListeningMessage: message, )); } } void updateRecordingDataRecognitionController( StreamController<List<int>>? controller) => emit(state.copyWith(recordingDataRecognitionController: controller)); void updateFinalReconizerText(String text) => emit(state.copyWith(finalReconizerText: text)); void updateIsFinalReconizerText(bool isFinal) => emit(state.copyWith(isFinalReconizerText: isFinal)); void resetErrorMessage() => emit(state.copyWith(errorMessage: null)); updateState(GoogleSpeechState Function(GoogleSpeechState) onUpdate) => emit(onUpdate(state)); }
import RemoveFrame from "../../../Commands/Implementation/RemoveFrame" import SaveContainer from "../../../Persistence/SaveContainer" import { ProjectTree } from "../../ProjectTree" import { FrameBuilder } from "../FrameBuilder" import { FrameComponent } from "../FrameComponent" import BaseArray from "./BaseArray" export default class TableArray extends BaseArray { static SAVE_KEY_NAME: string = 'arrayName' static SAVE_KEY_ROWS: string = 'ArrayRows' static SAVE_KEY_COLS: string = 'ArrayCols' static SAVE_KEY_LEFT_X: string = 'ArrayLeftX' static SAVE_KEY_TOP_Y: string = 'ArrayTopY' static SAVE_KEY_X_GAP: string = 'ArrayXGap' static SAVE_KEY_Y_GAP: string = 'ArrayYGap' static SAVE_KEY_ELEMENTS: string = 'ArrayElements' static SAVE_KEY_EACH_ELEMENT_NAME: string = 'ElementName' public target: FrameComponent private rows: number private columns: number private leftX: number private topY: number private gapX: number private gapY: number public constructor( target: FrameComponent, rows: number, columns: number, leftX: number, topY: number, gapX: number, gapY: number, ownerArray: boolean ) { super() this.target = target this.rows = rows this.columns = columns this.leftX = leftX this.topY = topY this.gapX = gapX this.gapY = gapY this.ownerArray = ownerArray this.arrayName = this.target.getName().replace('[', '').replace(']', '') } public create(): void { this.elements[0] = this.target this.target.array = this const parent = this.target.getParent() let index = 0 for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { if (i == 0 && j == 0) continue index++ const builder = FrameBuilder.copy(this.target) builder.name = this.arrayName + 'T[' + index + ']' builder.x = this.leftX + (builder.width + this.gapX) * j builder.y = this.topY + builder.height - (builder.height + this.gapY) * i const newFrame = parent?.createAsChild(builder) if (newFrame) { this.elements.push(newFrame) newFrame.array = this if (this.ownerArray) { //find if parent array has the same index. If yes, change parent for (const el of ProjectTree.getInstance().getIterator()) { const checkingName = parent?.getName().slice(0, parent.getName().length - 4) if (el.getName() == checkingName + '[' + index + ']' || el.getName() == checkingName + '[' + '0' + index + ']') { el.makeAsParentTo(newFrame) if (this.target.getTooltip()) newFrame.setTooltip(true) break } } } } } } } public destroy(): void { this.elements.forEach(el => { if(el != this.target) el.destroy() }) this.elements = [] this.target.array = undefined } public setXGap(gap: number): void { this.gapX = gap for(let i = 0; i < this.elements.length; i++) { const el = this.elements[i] el.custom.setLeftX(this.leftX + (el.custom.getWidth() + this.gapX) * (i % this.columns)) } } public setYGap(gap: number): void { this.gapY = gap for(let i = 0; i < this.elements.length; i++) { const el = this.elements[i] el.custom.setBotY(this.topY + el.custom.getHeight() - (el.custom.getHeight() + this.gapY) * Math.floor(i / this.columns)) } } public setRows(rows: number): void { this.rows = rows this.destroy() this.create() } public setCols(columns: number): void { this.columns = columns this.destroy() this.create() } public cloneProps(cloningTarget: FrameComponent): void { const el = this.target el.setTooltip(cloningTarget.getTooltip()) el.type = cloningTarget.type el.custom.setText(cloningTarget.custom.getText()) el.custom.setWidth(cloningTarget.custom.getWidth()) el.custom.setHeight(cloningTarget.custom.getHeight()) el.custom.setTrigVar(cloningTarget.custom.getTrigVar()) el.custom.setIsRelative(cloningTarget.custom.getIsRelative()) el.custom.setDiskTexture(cloningTarget.custom.getDiskTexture('normal'), 'normal') el.custom.setWc3Texture(cloningTarget.custom.getWc3Texture('normal'), 'normal') el.custom.setDiskTexture(cloningTarget.custom.getDiskTexture('back'), 'back') el.custom.setWc3Texture(cloningTarget.custom.getWc3Texture('back'), 'back') el.custom.setColor(cloningTarget.custom.getColor()) el.custom.setScale(cloningTarget.custom.getScale()) el.custom.setHorAlign(cloningTarget.custom.getHorAlign()) el.custom.setVerAlign(cloningTarget.custom.getVerAlign()) this.destroy() this.create() } getXGap(): number { return this.gapX } getYGap(): number { return this.gapY } getRows(): number { return this.rows } getCols(): number { return this.columns } getTarget(): FrameComponent { return this.target } save(container: SaveContainer): void { container.save(TableArray.SAVE_KEY_NAME, this.arrayName) container.save(TableArray.SAVE_KEY_ROWS, this.rows) container.save(TableArray.SAVE_KEY_COLS, this.columns) container.save(TableArray.SAVE_KEY_LEFT_X, this.leftX) container.save(TableArray.SAVE_KEY_TOP_Y, this.topY) container.save(TableArray.SAVE_KEY_X_GAP, this.gapX) container.save(TableArray.SAVE_KEY_Y_GAP, this.gapY) const elementsSaveArray: SaveContainer[] = [] for (const element of this.elements) { const elementSaveContainer = new SaveContainer(null) elementSaveContainer.save(TableArray.SAVE_KEY_EACH_ELEMENT_NAME, element.getName()) elementsSaveArray.push(elementSaveContainer) } container.save(TableArray.SAVE_KEY_ELEMENTS, elementsSaveArray) } static load(container: SaveContainer): TableArray { const arrayName = container.load(TableArray.SAVE_KEY_NAME) const rows = container.load(TableArray.SAVE_KEY_ROWS) const columns = container.load(TableArray.SAVE_KEY_COLS) const leftX = container.load(TableArray.SAVE_KEY_LEFT_X) const topY = container.load(TableArray.SAVE_KEY_TOP_Y) const gapX = container.load(TableArray.SAVE_KEY_X_GAP) const gapY = container.load(TableArray.SAVE_KEY_Y_GAP) const elementsSaveArray = container.load(TableArray.SAVE_KEY_ELEMENTS) as SaveContainer[] const elements: FrameComponent[] = [] for (const elementSaveContainer of elementsSaveArray) { const elementName = elementSaveContainer.load(TableArray.SAVE_KEY_EACH_ELEMENT_NAME) const element = ProjectTree.getInstance().findByName(elementName) if (element) { elements.push(element) } } const tableArray = new TableArray(elements[0], rows, columns, leftX, topY, gapX, gapY, true) tableArray.arrayName = arrayName tableArray.elements = elements tableArray.elements.forEach(el => el.array = tableArray) return tableArray } }
import axios from "axios"; import chalk from "chalk"; import { publishBlockFromTarball } from "../src/lib/api/blocks/from-tarball"; import { connectToDatabase } from "../src/lib/api/mongodb"; const blockTarballUrls = [ "https://blockprotocol.hashai.workers.dev/block-uploads/hash/callout/0.2.0.tar.gz", "https://blockprotocol.hashai.workers.dev/block-uploads/hash/code/0.2.0.tar.gz", "https://blockprotocol.hashai.workers.dev/block-uploads/hash/image/0.2.0.tar.gz", "https://blockprotocol.hashai.workers.dev/block-uploads/hash/paragraph/0.1.1.tar.gz", "https://blockprotocol.hashai.workers.dev/block-uploads/hash/timer/0.2.0.tar.gz", "https://blockprotocol.hashai.workers.dev/block-uploads/hash/video/0.2.0.tar.gz", ]; const script = async () => { console.log(chalk.bold("Mirroring blocks from production deployment...")); const { client, db } = await connectToDatabase(); for (const blockTarballUrl of blockTarballUrls) { process.stdout.write(`Mirroring ${blockTarballUrl}...`); const response = await axios(blockTarballUrl, { responseType: "arraybuffer", }); await publishBlockFromTarball(db, { createdAt: null, pathWithNamespace: blockTarballUrl .match(/\/block-uploads(\/[^/]+\/[^/]+)\//)![1]! .replace("/", "@"), tarball: Buffer.from(response.data, "binary"), }); process.stdout.write(` Done.\n`); } await client.close(); console.log(`✅ Number of blocks mirrored: ${blockTarballUrls.length}`); }; await script();
def permutation(arr, r): # 1. arr = sorted(arr) used = [0 for _ in range(len(arr))] def generate(chosen, used): # 2. if len(chosen) == r: print(chosen) return # 3. for i in range(len(arr)): if not used[i]: chosen.append(arr[i]) used[i] = 1 generate(chosen, used) used[i] = 0 chosen.pop() generate([], used) # permutation('ABCD', 2) # permutation([1, 2, 3, 4, 5], 3) ### 조합 def combination(arr, r): # 1. arr = sorted(arr) # 2. def generate(chosen): if len(chosen) == r: print(chosen) return # 3. start = arr.index(chosen[-1]) + 1 if chosen else 0 for nxt in range(start, len(arr)): chosen.append(arr[nxt]) generate(chosen) chosen.pop() generate([]) # combination('ABCDE', 2) combination([1, 2, 3, 4, 5], 3)
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace ScorpiconAccess { public class ExcelUtlity { /// <summary> /// FUNCTION FOR EXPORT TO EXCEL /// </summary> /// <param name="dataTable"></param> /// <param name="worksheetName"></param> /// <param name="saveAsLocation"></param> /// <returns></returns> public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string fileTitle, string fileSubtitle) { Microsoft.Office.Interop.Excel.Application excel; Microsoft.Office.Interop.Excel.Workbook excelworkBook; Microsoft.Office.Interop.Excel.Worksheet excelSheet; Microsoft.Office.Interop.Excel.Range excelCellrange; try { // Start Excel and get Application object. excel = new Microsoft.Office.Interop.Excel.Application(); // for making Excel visible excel.Visible = false; excel.DisplayAlerts = false; // Creation a new Workbook excelworkBook = excel.Workbooks.Add(Type.Missing); // Work sheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet; excelSheet.Name = worksheetName; //Work sheet title excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[1, 35]].Merge(); excelSheet.Cells[1, 1] = fileTitle; excelSheet.Cells[1, 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; excelSheet.Cells[1, 1].EntireRow.Font.Bold = true; excelSheet.Range[excelSheet.Cells[2, 1], excelSheet.Cells[2, 35]].Merge(); excelSheet.Cells[2, 1] = fileSubtitle; excelSheet.Cells[2, 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; excelSheet.Range[excelSheet.Cells[3, 1], excelSheet.Cells[3, 35]].Merge(); // loop through each row and add values to our sheet int rowcount = 5; foreach (DataRow datarow in dataTable.Rows) { rowcount += 1; for (int i = 1; i <= dataTable.Columns.Count; i++) { // on the first iteration we add the column headers if (rowcount == 6) { excelSheet.Cells[5, i] = dataTable.Columns[i - 1].ColumnName; excelSheet.Cells.Font.Color = System.Drawing.Color.Black; } excelSheet.Cells[rowcount, i] = datarow[i - 1].ToString(); //for alternate rows if (rowcount > 5) { if (i == dataTable.Columns.Count) { if (rowcount % 2 == 0) { excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]]; FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false); } } } } } //change column name excelSheet.Cells[4, 1] = "STT"; excelSheet.Cells[4, 1].EntireRow.Font.Bold = true; excelSheet.Range[excelSheet.Cells[4, 1], excelSheet.Cells[5, 1]].Merge(); excelSheet.Cells[4, 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; excelSheet.Cells[4, 1].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; excelSheet.Cells[4, 2] = "Số thẻ"; excelSheet.Cells[4, 2].EntireRow.Font.Bold = true; excelSheet.Range[excelSheet.Cells[4, 2], excelSheet.Cells[5, 2]].Merge(); excelSheet.Cells[4, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; excelSheet.Cells[4, 2].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; excelSheet.Cells[4, 3] = "Họ và tên"; excelSheet.Cells[4, 3].EntireRow.Font.Bold = true; excelSheet.Range[excelSheet.Cells[4, 3], excelSheet.Cells[5, 3]].Merge(); excelSheet.Cells[4, 3].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; excelSheet.Cells[4, 3].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; excelSheet.Cells[4, 35] = "Tổng cộng"; excelSheet.Cells[4, 35].EntireRow.Font.Bold = true; excelSheet.Range[excelSheet.Cells[4, 35], excelSheet.Cells[5, 35]].Merge(); excelSheet.Cells[4, 35].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; excelSheet.Cells[4, 35].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; excelSheet.Range[excelSheet.Cells[4, 4], excelSheet.Cells[4, 34]].Merge(); excelSheet.Cells[4, 4] = "Ngày trong tháng"; excelSheet.Cells[4, 4].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; excelSheet.Cells[4, 4].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; excelSheet.Cells[4, 4].EntireRow.Font.Bold = true; // now we resize the columns excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount-3, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]]; excelCellrange.EntireColumn.AutoFit(); Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders; border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; border.Weight = 2d; excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[1, dataTable.Columns.Count]]; FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true); //now save the workbook and exit Excel excelworkBook.SaveAs(saveAsLocation); ; excelworkBook.Close(); excel.Quit(); return true; } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } finally { excelSheet = null; excelCellrange = null; excelworkBook = null; } } /// <summary> /// FUNCTION FOR FORMATTING EXCEL CELLS /// </summary> /// <param name="range"></param> /// <param name="HTMLcolorCode"></param> /// <param name="fontColor"></param> /// <param name="IsFontbool"></param> public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool) { range.Interior.Color = System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode); range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor); if (IsFontbool == true) { range.Font.Bold = IsFontbool; } } } }
import { AzureFunction, Context } from '@azure/functions'; import fetchMovedComputers from '../global/apis/notifii/fetchMovedComputers'; import fetchLocation from '../global/apis/teamdynamix/fetchLocation'; import fetchLocations from '../global/apis/teamdynamix/fetchLocations'; import searchAssets from '../global/apis/teamdynamix/searchAssets'; import updateAsset from '../global/apis/teamdynamix/updateAsset'; import fetchAsset from '../global/apis/teamdynamix/fetchAsset'; import AssetEditable from '../global/types/teamdynamix/AssetEditable'; import LocationRoomLimited from '../global/types/teamdynamix/LocationRoomLimited'; import Location from '../global/types/teamdynamix/Location'; import getAssetStatusId from '../global/helpers/teamdynamix/getAssetStatusId'; import uploadBlob from '../global/apis/azure/uploadBlob'; import sendToWebhook from '../global/apis/teams/sendToWebhook'; /** * Every day at 9:00 AM EST, computers that have moved locations will be updated in TeamDynamix. * * 1. Fetch all packages that have been signed out in Notifii. * 2. Extract only the computers from those packages. * 3. Parse information from each computer. * 4. Find that computer in TeamDynamix. * 5. Update that computer with the new information. * 6. Upload completed logs to Azure. * 7. Send summary notification to Teams. */ const timerTrigger: AzureFunction = async function (context: Context, myTimer: any): Promise<void> { // Fetch computers that have moved const movedComputersResult = await fetchMovedComputers(); if (!movedComputersResult.ok) { printAndWebhook(context, 'An error occured while fetching the moved computers: ' + movedComputersResult.error); return; } if (!movedComputersResult.data.length) { printAndWebhook(context, 'No computers have been moved.'); return; } // Fetch all locations from TDX const locationsResult = await fetchLocations(); if (!locationsResult.ok) { printAndWebhook(context, 'An error occured while fetching the list of TDX locations: ' + locationsResult.error); return; } // Validate and update each computer in TDX const statusLogs: { success: boolean; message: string }[] = []; const locationsCache = new Map<string, Location>(); for (const movedComputer of movedComputersResult.data) { // Check if tag or serial exists if (!movedComputer.tag && !movedComputer.serial) { statusLogs.push({ success: false, message: 'Asset is missing tag and serial: ' + movedComputer.rawDescription }); continue; } // Get if the tag or serial will be used to search TDX const searchAssetText = movedComputer.tag?.toString() ?? movedComputer.serial; // Check if new location exists if (!movedComputer.location) { statusLogs.push({ success: false, message: `Asset ${searchAssetText} is missing location: ` + movedComputer.rawSender }); continue; } // Check if new status exists if (!movedComputer.status) { statusLogs.push({ success: false, message: `Asset status could not be determined for ${searchAssetText}.` }); continue; } // Check that the location exists in the TDX locations list const foundLocation = locationsResult.data.find((location) => location.Name === movedComputer.location!.building); if (!foundLocation) { statusLogs.push({ success: false, message: `Building ${movedComputer.location.building} does not exist for ${searchAssetText}.` }); continue; } // Check that the room exists for the location // First check the cache to avoid making an HTTP request let room: LocationRoomLimited | undefined; if (locationsCache.has(foundLocation.Name)) { room = locationsCache.get(foundLocation.Name)?.Rooms?.find((room) => room.Name === movedComputer.location!.room); } else { // If not in cache, fetch location from TDX to get its rooms const locationResult = await fetchLocation(foundLocation.ID); if (!locationResult.ok) { statusLogs.push({ success: false, message: locationResult.error }); continue; } // Add fetched location to cache locationsCache.set(locationResult.data.Name, locationResult.data); // Search rooms list to see if it exists room = locationResult.data.Rooms?.find((room) => room.Name === movedComputer.location!.room); } // Room does not exist if (!room) { statusLogs.push({ success: false, message: `Room ${movedComputer.location.room} does not exist.` }); continue; } // Search TDX assets by tag or serial (does not return all properties of the asset) const searchAssetsResult = await searchAssets({ SerialLike: searchAssetText }); if (!searchAssetsResult.ok) { statusLogs.push({ success: false, message: searchAssetsResult.error }); continue; } if (!searchAssetsResult.data.length) { statusLogs.push({ success: false, message: `No assets found for ${searchAssetText}.` }); continue; } // Verify search result contains the asset with the specified tag/serial const foundAsset = searchAssetsResult.data.find( (asset) => asset.Tag === movedComputer.tag?.toString() || asset.SerialNumber === movedComputer.serial ); if (!foundAsset) { statusLogs.push({ success: false, message: `No search results returned for '${searchAssetText}'.` }); continue; } // Fetch full asset details from TDX. PATCH is not supported so the full asset must be loaded as a payload for the update request const assetResult = await fetchAsset(foundAsset.ID); if (!assetResult.ok) { statusLogs.push({ success: false, message: assetResult.error }); continue; } // Get the TDX status ID to send in the payload const statusId = getAssetStatusId(movedComputer.status); if (!statusId) { statusLogs.push({ success: false, message: `Status '${movedComputer.status}' does not exist in TDX.` }); continue; } // Format payload to update the computer const updatedAsset: AssetEditable = { ...assetResult.data, LocationID: foundLocation.ID, LocationRoomID: room.ID, StatusID: statusId }; // Send request to update the computer const updatedAssetResult = await updateAsset(foundAsset.ID, updatedAsset); if (!updatedAssetResult.ok) { statusLogs.push({ success: false, message: updatedAssetResult.error }); continue; } // Finished updating computer, begin next computer if exists statusLogs.push({ success: true, message: `Updated asset ${foundAsset.Tag} (${foundAsset.SerialNumber}) to ${foundLocation.Name} ${room.Name} with status ${movedComputer.status}.` }); } // Format blob properties to upload the logs to Azure const fileName = new Date().toISOString() + '.txt'; const fileContent = statusLogs.reduce((prev, curr) => (prev += curr.message + '\n'), ''); const totalSuccess = statusLogs.reduce((prev, curr) => prev + (curr.success ? 1 : 0), 0); const totalFailure = statusLogs.reduce((prev, curr) => prev + (curr.success ? 0 : 1), 0); // Upload logs to Azure const uploadBlobResult = await uploadBlob('dispositions', fileName, fileContent); if (!uploadBlobResult.ok) { printAndWebhook(context, uploadBlobResult.error); } // Send notification to Teams const webhookResponse = await sendToWebhook(`Disposition updates finished with ${totalSuccess} updates and ${totalFailure} failures.`); if (!webhookResponse.ok) context.log(webhookResponse.error); context.log(`Disposition updates finished with ${totalSuccess} updates and ${totalFailure} failures.`); }; /* ---------------------------- Helper functions ---------------------------- */ const printAndWebhook = (context: Context, message: string) => { context.log(message); sendToWebhook(message); } export default timerTrigger;
import { IoMdAdd } from "react-icons/io"; import CompanyReviewSummary from "./CompanyReviewSummary"; import CardLayout from "../../layouts/CardLayout"; import TextDropdown from "../form/TextDropdown"; import { CONSTANTS } from "../../utils/constants"; import CompanyReviewItem from "./CompanyReviewItem"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { IReviewSortForm } from "../../pages/employee/CompanyDetailPage"; import { useQueryGetSelfReview, useQueryReviews } from "../../datas/queries/reviewQueries"; import WrappedPaginationSelection, { Pagination } from "../form/WrappedPaginationSelection"; import { Review } from "../../../../declarations/HireVerse_review/HireVerse_review.did"; interface Props { companyId: string; onCreateReviewClick?: () => void; setEditable: (value: Review) => void; } export default function CompanyDetailReview({ companyId, onCreateReviewClick, setEditable }: Props) { const [pagination, setPagination] = useState<Pagination>({ totalPage: 1, currentPage: 1, amountPerPage: 5, }); const { control, getValues: getFilters } = useForm<IReviewSortForm>({ defaultValues: { orderBy: "Newest", }, }); const { data: reviews, refetch: refetchReviews } = useQueryReviews(companyId, getFilters); const { data: myReview } = useQueryGetSelfReview(companyId); const getReviewStart = () => (pagination.currentPage - 1) * pagination.amountPerPage; const getReviewEnd = () => pagination.currentPage * pagination.amountPerPage; const changePage = (nextPage: number) => setPagination({ ...pagination, currentPage: nextPage }); useEffect(() => { if (reviews) { setPagination({ ...pagination, totalPage: Math.ceil(reviews.length / pagination.amountPerPage), }); } }, [reviews]); return ( <> <CardLayout className="flex min-h-[25rem] flex-col gap-5 rounded-lg p-10"> <div className="flex w-full flex-row justify-between"> <h3 className="m-0 flex flex-row justify-between p-0 text-4xl font-semibold">Reviews</h3> {onCreateReviewClick && !myReview && ( <button onClick={onCreateReviewClick} className="bg-signature-yellow hover:bg-signature-yellow flex w-fit flex-row items-center justify-center gap-3 rounded-md px-5 py-3 text-lg font-semibold text-black transition-colors"> <IoMdAdd /> <span>Create Review</span> </button> )} </div> <div> <CompanyReviewSummary companyId={companyId} /> </div> </CardLayout> {reviews && reviews.length > 0 && ( <CardLayout className="flex flex-row items-center justify-between gap-5 rounded-lg p-4"> <div> <span className="text-xl font-semibold">Review Selections</span> <p>Showing 10 reviews</p> </div> <span className="flex flex-row items-center gap-4"> Order By <TextDropdown states={CONSTANTS.REVIEWS.ORDER_BY} control={control} name="orderBy" onChange={() => refetchReviews()} /> </span> </CardLayout> )} <div className="flex flex-1 flex-row"> <div className="flex w-full flex-col gap-2"> {myReview && ( <CompanyReviewItem review={myReview} setEditable={setEditable} /> )} {reviews?.slice(getReviewStart(), getReviewEnd()).map((review, i) => { if (review.id === myReview?.id) return; return ( <CompanyReviewItem key={i} review={review} /> ); })} {reviews && reviews.length > 5 && ( <WrappedPaginationSelection pagination={pagination} setPagination={changePage} /> )} </div> </div> </> ); }
/******************************************************************************* * Copyright 2014 Analog Devices, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ package com.analog.lyric.dimple.events; import java.io.IOException; import java.io.ObjectOutputStream; import com.analog.lyric.dimple.model.core.FactorGraph; import com.analog.lyric.dimple.model.core.Node; import com.analog.lyric.dimple.model.factors.Factor; import org.eclipse.jdt.annotation.Nullable; /** * * @since 0.06 * @author Christopher Barber */ public abstract class FactorGraphSubgraphEvent extends FactorGraphEvent { private static final long serialVersionUID = 1L; /*------- * State */ private transient final FactorGraph _subgraph; private final @Nullable String _subgraphName; /*-------------- * Construction */ /** * @param source of the event * @param subgraph involved in the event * @since 0.06 */ protected FactorGraphSubgraphEvent(FactorGraph source, FactorGraph subgraph) { super(source); _subgraph = subgraph; _subgraphName = null; } /*--------------- * Serialization */ private void writeObject(ObjectOutputStream out) throws IOException { // Write out _factorName field with non-null value. out.writeObject(getSubgraphName()); } // The default readObject method should work... /*-------------------------- * FactorGraphEvent methods */ @Override public @Nullable Node getNode() { return _subgraph; } @Override public String getNodeName() { return getSubgraphName(); } @Override protected final NodeType nodeType() { return NodeType.SUBGRAPH; } /*-------------------------------- * FactorGraphFactorEvent methods */ /** * The subgraph involved in the event. * <p> * Will be null if event was obtained through deserialization. * @since 0.06 * @see #getSubgraphName() */ public @Nullable FactorGraph getSubgraph() { return _subgraph; } /** * The name of the subgraph involved in the event. * <p> * The value of {@link Factor#getEventSourceName()} on the * factor. Unlike {@link #getSubgraph}, this is preserved by * serialization. * @since 0.06 */ public String getSubgraphName() { final String name = _subgraphName; return name == null ? _subgraph.getEventSourceName() : name; } }
public class AllCharsExcept { // write your method here public static String allCharsExcept(String s, char c) { String result=""; // this builds the string "result" one letter at a time, by checking if the character //at position i is equivilant to the character "c" for(int i=0; i<s.length(); i++) { if(s.charAt(i)!= c) { result+=s.charAt(i); } } return result; } public static void main(String[] args) { // test your method here System.out.println(allCharsExcept("bananas", 'a')); System.out.println(allCharsExcept("bananas", 'n')); System.out.println(allCharsExcept("bbb", 'b')); System.out.println(allCharsExcept("apple", 'b')); } }
import Foundation import ComposableArchitecture import Product import ApiClient import SiteRouter import FavoritesClient extension IdentifiedArrayOf: @unchecked Sendable {} public struct Favorites: ReducerProtocol, Sendable { @Dependency(\.apiClient) var apiClient @Dependency(\.favouritesClient) var favouritesClient public init() {} } public extension Favorites { struct State: Equatable, Sendable { public var productList: IdentifiedArrayOf<Product> public var searchText: String public var searchResults: [Product] public var isProductDetailSheetPresented: Bool public var productDetailView: Product? public var quantity: Int public var favoriteProducts: FavoriteProducts public init( productList: IdentifiedArrayOf<Product> = [], searchText: String = "", searchResults: [Product] = [], isProductDetailSheetPresented: Bool = false, productDetailView: Product? = nil, quantity: Int = 1, favoriteProducts: FavoriteProducts = .init() ) { self.productList = productList self.searchText = searchText self.searchResults = searchResults self.isProductDetailSheetPresented = isProductDetailSheetPresented self.productDetailView = productDetailView self.quantity = quantity self.favoriteProducts = favoriteProducts } } enum Action: Equatable, Sendable { case `internal`(InternalAction) case delegate(DelegateAction) public enum DelegateAction: Equatable, Sendable { case addProductToCart(quantity: Int, product: Product) } public enum InternalAction: Equatable, Sendable { case onAppear case getProductResponse(TaskResult<[Product]>) case searchTextReceivesInput(String) case showProductDetailViewFor(Product) case toggleSheet case loadFavoriteProducts([Product.ID]?) case favoriteButtonClicked(Product) case removeFavouriteProduct(Product.ID?) } } var body: some ReducerProtocol<State, Action> { Reduce { state, action in switch action { case .internal(.onAppear): // return .run { send in // await send(.internal(.loadFavoriteProducts(try favouritesClient.getFavourites()))) // } return .run { [apiClient] send in return await send(.internal(.getProductResponse( TaskResult { try await apiClient.decodedResponse( for: .products(.fetch), as: ResultPayload<[Product]>.self).value.status.get() } ))) } case let .internal(.getProductResponse(.success(products))): state.productList = IdentifiedArray(uniqueElements: products) return .run { send in await send(.internal(.loadFavoriteProducts(try favouritesClient.getFavourites()))) } case let .internal(.loadFavoriteProducts(products)): guard let products else { return .none } state.favoriteProducts.sku = products state.productList = state.productList.filter { state.favoriteProducts.sku.contains($0.id) } return .none case let .internal(.getProductResponse(.failure(error))): print(error) return .none case let .internal(.searchTextReceivesInput(text)): state.searchText = text state.searchResults = state.productList.filter { $0.boardgame.title.contains(text) } return .none case let .internal(.showProductDetailViewFor(product)): state.productDetailView = product state.isProductDetailSheetPresented.toggle() return .none case .internal(.toggleSheet): state.isProductDetailSheetPresented.toggle() return .none case let .internal(.favoriteButtonClicked(product)): if state.favoriteProducts.sku.contains(product.id) { return .run { send in await send(.internal(.removeFavouriteProduct(try favouritesClient.removeFavorite(product.id)))) } } return .none case let .internal(.removeFavouriteProduct(sku)): guard let sku else { return .none } state.productList.removeAll(where: { $0.id == sku }) return .none case .delegate(_): return .none } } } }
#function:zscore.rows2 #input: # x: matrix with features as rows and samples as columns #output: scaled matrix #description: matrix scaled removing mean and dive by standard deviation zscore.rows2 <- function(x){ return(t(apply(x, 1, function(x) (x - mean(na.omit(x)))/sd(na.omit(x))))) } #function:create.met.anot #input: # epic:EPIC arrays anotation #output: data.frame with probe names as row.names and columns with # information about chromosome, start and end position, Island, # fgroup, DMR genes and UCSC reference group #description: takes Epic anotation and transform it to easy anotation matrix for #epic probes create.met.anot <- function(epic) { genes <- strsplit(as.character(epic$UCSC_RefGene_Name),';') genes[lengths(genes) == 0] <- NA group <- strsplit(as.character(epic$UCSC_RefGene_Group),';') group[lengths(group) == 0] <- NA met_anot <- data.frame('ID' = rep(epic$IlmnID, sapply(genes, length)) , "genes" = unlist(genes) , "CpG_chrm" = rep(epic$CHR_hg38, sapply(genes, length)) , "CpG_beg" = rep(epic$Start_hg38, sapply(genes, length)) , "CpG_end" = rep(epic$End_hg38, sapply(genes, length)) , "UCSC_RefGene_Group" = unlist(group) , "ISLAND" = rep(epic$Relation_to_UCSC_CpG_Island, sapply(genes, length)) , "FGROUP" = rep(epic$Regulatory_Feature_Group, sapply(genes, length)) , "DMR" = rep(epic$DMR, sapply(genes, length))) met_anot <- met_anot[!duplicated(paste(met_anot$ID,met_anot$genes)),] met_anot <- met_anot %>% group_by(ID,CpG_chrm,CpG_beg, CpG_end,ISLAND,FGROUP, DMR) %>% dplyr::summarise(genes = toString(genes), UCSC_RefGene_Group = toString(UCSC_RefGene_Group)) met_anot$genes <- gsub(', ','_',met_anot$genes) rownames(met_anot) <- met_anot$ID return(met_anot) } theme_general <- function(plot) { themed <- plot + theme(text=element_text(size=40), axis.text.x = element_text(angle = 0 ,vjust = 1, hjust = 0.5), legend.key.height = unit(2,'cm'), aspect.ratio=1/1 ) }
package main import ( "bootdev/api" "bootdev/database" "fmt" "log" "net/http" "github.com/go-chi/chi/v5" ) const port = "8080" type apiConfig struct { fileServerHits int } func main() { err := database.NewDb() if err != nil { log.Fatal(err) } apiCfg := apiConfig{} router := chi.NewRouter() fsHandler := apiCfg.middlewareMetricsInc(http.StripPrefix("/app", http.FileServer(http.Dir("public")))) // app router.Handle("/app/*", fsHandler) router.Handle("/app", fsHandler) // api apiRouter := chi.NewRouter() apiRouter.HandleFunc("/reset", apiCfg.resetMetrics) apiRouter.Get("/healthz", api.Healthz) apiRouter.Post("/chirps", api.CreateChirp) apiRouter.Get("/chirps/{id}", api.GetChirp) apiRouter.Get("/chirps", api.GetChrips) apiRouter.Delete("/chirps/{id}", api.DeleteChirp) apiRouter.Post("/users", api.CreateUser) apiRouter.Put("/users", api.UpdateUser) apiRouter.Post("/login", api.Login) apiRouter.Post("/refresh", api.RefreshToken) apiRouter.Post("/revoke", api.RevokeToken) apiRouter.Post("/polka/webhooks", api.UpgradeUser) // admin adminRouter := chi.NewRouter() adminRouter.Get("/metrics", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") w.Write([]byte(fmt.Sprintf(adminTemplate, apiCfg.fileServerHits))) }) router.Mount("/api", apiRouter) router.Mount("/admin", adminRouter) corsMux := middlewareCors(router) srv := &http.Server{ Addr: ":" + port, Handler: corsMux, } fmt.Printf("Serving on %s\n", srv.Addr) log.Fatal(srv.ListenAndServe()) }
'use client'; import { ArrowDownTrayIcon } from '@heroicons/react/24/outline'; import type { NewsroomGallery } from '@prezly/sdk'; import { useEffect, useState } from 'react'; import { twMerge } from 'tailwind-merge'; import { ButtonLink } from '../Button'; import { StoryShareLinks } from '../StoryShareLinks'; export function GalleryTitle({ className, gallery }: GalleryTitle.Props) { const { name, description, downloadHref } = gallery; const [url, setUrl] = useState(''); useEffect(() => { if (typeof window !== 'undefined') { setUrl(window.location.href); } }, []); return ( <div className={twMerge('container px-6 py-12 sm:p-12', className)}> <div className="max-w-3xl mx-auto"> <h1 className="title-large">{name}</h1> {description && <p className="subtitle-large mt-3">{description}</p>} <div className="mt-6 flex items-center gap-4"> {downloadHref && ( <ButtonLink href={downloadHref} forceRefresh icon={ArrowDownTrayIcon} iconPlacement="right" size="small" > Download </ButtonLink> )} <StoryShareLinks shareUrl={url} /> </div> </div> </div> ); } export namespace GalleryTitle { export interface DisplayedGallery { name: NewsroomGallery['name']; description: NewsroomGallery['description']; downloadHref?: string | null; } export interface Props { className?: string; gallery: DisplayedGallery; } }
import 'dart:developer'; import 'package:chopper/chopper.dart'; import 'package:ddnc_new/api/response/common_success_response.dart'; import 'package:ddnc_new/api/response/list_committee_response.dart'; import 'package:ddnc_new/api/response/list_notification_response.dart'; import 'package:ddnc_new/api/response/list_schedule_response.dart'; import 'package:ddnc_new/api/response/list_schedule_today_response.dart'; import 'package:ddnc_new/api/response/list_topic_proposal_response.dart'; import 'package:ddnc_new/api/response/list_topic_response.dart'; import 'package:ddnc_new/api/response/list_user_response.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:logging/logging.dart' as logging; import 'package:provider/provider.dart'; import 'header_interceptor.dart'; import 'json_to_type_converter.dart'; import 'response/list_stats_response.dart'; import 'response/sign_in_response.dart'; class ApiClient extends ChopperClient { ApiClient() : super( // baseUrl: Uri.parse("http://10.0.2.2:8001"), // baseUrl: Uri.parse("http://192.168.1.254:8001"), baseUrl: Uri.parse("http://hungpq.click:8001"), interceptors: [HeaderInterceptor(), HttpLoggingInterceptor()], converter: const JsonToTypeConverter({ CommonSuccessResponse: CommonSuccessResponse.fromJson, SignInResponse: SignInResponse.fromJson, ListUserResponse: ListUserResponse.fromJson, ListTopicResponse: ListTopicResponse.fromJson, ListTopicProposalResponse: ListTopicProposalResponse.fromJson, ListScheduleResponse: ListScheduleResponse.fromJson, ListCommitteeResponse: ListCommitteeResponse.fromJson, ListScheduleTodayResponse: ListScheduleTodayResponse.fromJson, ListNotificationResponse: ListNotificationResponse.fromJson, ListStatsResponse: ListStatsResponse.fromJson, }), ) { if (kDebugMode) { Logger.root.level = logging.Level.ALL; Logger.root.onRecord.listen((rec) { log('${rec.level.name}: ${rec.time}: ${rec.message}'); }); } } static ApiClient of(BuildContext context) => Provider.of<ApiClient>(context, listen: false); }
version: 'v0.0.0' LabBook: null SciViz: # top level tab website_title: SciViz Title # route: /some-route/another-route favicon_name: /favicon.ico # In /public dir header: image_route: /logo.svg # In /public dir text: Data Portal hostname: 'localdb' login: image_route: /logo.svg # In /public dir auth: mode: 'database' # database | oidc | none endpoint: https://keycloak.dev.datajoint.io/realms/master database: xtradb.dev.datajoint.io client_id: my-client # datadog: # applicationId: Your app ID # clientToken: Your client token # service: 'sciviz-dev' pages: # individual pages # The first page in the list of pages is the splash page after login # By convention this should be a home page with a markdown component Home: route: /home grids: grid5: type: fixed columns: 1 row_height: 680 components: comp: x: 0 y: 0 height: 1 width: 1 type: markdown # this example of image_route has the image in the /public dir image_route: /logo.svg text: | # Welcome! This is a basic homepage created entirely through the config file. It is comprised of a single markdown component that supports the [github markdown spec.](https://guides.github.com/features/mastering-markdown/) For more examples of the markdown component go the the markdown page. Markdown: route: /mkdown # dev, be careful of name collisions grids: grid1: type: fixed max_component_per_page: 20 columns: 2 row_height: 680 components: component1: x: 0 y: 0 height: 1 width: 1 type: markdown text: | ![Image](https://www.datajoint.org/static/images/djopen-color-dark.png) # Markdown support ### Hello! this is an example of the markdown component ~~~python print('Nice! Codeblock support!') ~~~ list: * apple * pear * melon ordered list: 1. one 2. two 3. three `Inline code highlight! ` [Hyperlinks!](https://www.google.com/) # h1 ## h2 ### h3 #### h4 ##### h5 ###### h6 nested lists: * parent * child task lists: * [x] apples * [x] pizza * [ ] chicken tables: first header | second header ------------ | ------------- Content cell 1 | content cell 2 Content cell 3 | content cell 4 Table: route: /tableExample args: - subject_name - session_number grids: grid1: type: fixed columns: 2 row_height: 680 components: Example table (conditional row coloring): # yaml allows keys with spaces! route: /query2 x: 0 y: 0 height: 1 width: 1 type: antd-table link: /hiddenpage restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) q = ((TableA * TableB).proj( ..., #_sciviz_font='IF(a_name = "Raphael", "rgb(255, 0, 0)", NULL)', _sciviz_background='IF(a_name = "Raphael", "rgba(50, 255, 0, 0.16)", "NULL")', )) return {'query': q, 'fetch_args': {'order_by': '_sciviz_background ASC'}} page_size_default: 6 example table 1 markdown: x: 1 y: 0 height: 1 width: 1 type: markdown text: | # Hello! This is a Datajoint table component populated by the codeblock: ~~~python def dj_query(vms): TableA, TableB = (vms['test_group1_simple'].TableA, vms['test_group1_simple'].TableB) q = ((TableA * TableB).proj( ..., _sciviz_background=''' IF(a_name = "Raphael", "rgba(50, 255, 0, 0.16)", "rgba(255, 0, 0, 0.16)") ''',)) return dict(query=q, fetch_args=[]) ~~~ # *Sci-Viz* speaks datajoint natively, isnt that neat! ### About the coloring in the table: Notice that this query has a projection that produces an additional column. The column `_sciviz_background` accepts any css compatable color, so if you want custom coloring based off of a condition in your query result all you have to do is make a projection with a condition that inserts a color into the `_sciviz_background` column. If the `_sciviz_background` column exists, the frontend automatically hides the column and applys its css colors to each row. The onlt thing that the `_sciviz_background` column cares about is that it has a valid css color or NULL in it, so you can enforce as many color conditions as you want. This same functionality also exists for the text using the column `_sciviz_font` [here is a good tool for picking css colors.](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Colors/Color_picker_tool) Example table 2 (restriction): route: /exampletable2 x: 0 y: 1 height: 1 width: 1 type: antd-table link: /hiddenpage restriction: > def restriction(**kwargs): return dict(**kwargs, a_id=1) dj_query: > def dj_query(test_group1_simple): TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) return dict(query=(TableA * TableB), fetch_args=[]) example table 2 markdown: x: 1 y: 1 height: 1 width: 1 type: markdown text: | # DJ table with restriction: This is a datajoint table from the following query: ~~~python def dj_query(test_group1_simple): TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) return dict(query=(TableA * TableB), fetch_args=[]) ~~~ But it also has the following restriction applied to it: ~~~python def restriction(**kwargs): return dict(**kwargs, a_id=1) ~~~ ## Why is this useful? What this does is it injects the additional restriction into the query. This is useful because you can use anchoring and aliasing in the config to copy one query to many components and only have to change the restriction on the component Mouse table with linking: route: /dawdgargaefdaefa x: 0 y: 2 height: 1 width: 1 type: antd-table link: /hiddenpage restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse), fetch_args=[]) Plots: route: /plots grids: grid1: type: fixed columns: 2 row_height: 80 components: mybuttons: x: 0 y: 0 height: 1 width: 1 type: radiobuttons channel: mybuttons content: mouse 0: 'mouse_id=0' mouse 1: 'mouse_id=1' mouse 2: 'mouse_id=2' myslider: x: 1 y: 0 height: 1 width: 1 type: slider channel: myslider route: /testtest restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse q = dj.U('mouse_id') & Mouse return dict(query=q, fetch_args=[]) Example table (conditional row coloring): # yaml allows keys with spaces! route: /weuroiewjqroiew x: 0 y: 2 height: 6 width: 1 type: antd-table channel: myantd-table channels: [mybuttons] restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=Mouse, fetch_args=[]) tableplots: route: /plot1d type: plot:plotly:stored_json x: 1 y: 2 height: 6 width: 1 channels: [myslider] restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): MousePlots = test_group1_simple.MousePlots return dict(query=MousePlots, fetch_args=['plot']) Metadata: route: /metadata grids: grid2: type: fixed columns: 6 row_height: 233 components: comp: type: metadata route: /metadata1 x: 1 y: 1 height: 1 width: 1 restriction: > def restriction(**kwargs): return dict(**kwargs, b_id=19) dj_query: > def dj_query(test_group1_simple): TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) return dict(query=(TableA * TableB), fetch_args=[]) desc: type: markdown x: 3 y: 0 height: 3 width: 3 text: | # This is a metadata component it is not very useful by itself but when combined with the dynamic component generator it can provide a useful description of what the other components are. Dynamic Grid: route: /dynamicGrid grids: dropdownGrid: type: fixed columns: 1 row_height: 80 components: mydropdown: x: 1 y: 0 height: 1 width: 1 type: dropdown-static channel: testtest content: none: '' jeff: mouse_id=0 splinter: mouse_id=1 dgrid: route: /dgrid type: dynamic channels: [testtest] columns: 1 row_height: 600 restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse.proj()), fetch_args=[]) component_templates: comp2: route: /myMeta type: metadata restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse), fetch_args=[]) comp1: route: /myPlot type: plot:plotly:stored_json restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): MousePlots = test_group1_simple.MousePlots return dict(query=(MousePlots), fetch_args=['plot']) Dynamic Form: route: /dynamicForm grids: grid1: type: fixed columns: 2 row_height: 375 components: Table A: route: /insert1 x: 0 y: 0 height: 1 width: 1 type: form tables: - test_group1_simple.TableA Table B: route: /insert2 x: 1 y: 0 height: 1 width: 1 type: form tables: - test_group1_simple.TableB presets: > def presets(): return {'preset 1': {'b_id': 14}} Table C: route: /insert3 x: 0 y: 1 height: 1 width: 1 type: form tables: - test_group1_simple.TableC B and C with mapping: route: /insert4 x: 1 y: 1 height: 1 width: 1 type: form tables: - test_group1_simple.TableB - test_group1_simple.TableC presets: > def presets(test_group1_simple): return {r['preset_name']: r['preset_dict'] for r in test_group1_simple.PresetTable} map: - type: attribute input: B Id destination: b_id - type: attribute input: B Number destination: b_number - type: table input: Table A destination: test_group1_simple.TableA map: - type: attribute input: A Id destination: a_id - type: attribute input: C Id destination: c_id B and C with mapping except table map: route: /insert5 x: 0 y: 2 height: 1 width: 1 type: form tables: - test_group1_simple.TableB - test_group1_simple.TableC map: - type: attribute input: B Id destination: b_id - type: attribute input: B Number destination: b_number - type: table input: Table A destination: test_group1_simple.TableA - type: attribute input: C Id destination: c_id B and C with no mapping: route: /insert6 x: 1 y: 2 height: 1 width: 1 type: form tables: [test_group1_simple.TableB, test_group1_simple.TableC] All supported input types: route: /insert7 x: 0 y: 3 height: 3 width: 1 type: form tables: - test_group1_simple.TableD booleans: - a_bool presets: > def presets(test_group1_simple): return {r['preset_name']: r['preset_dict'] for r in test_group1_simple.PresetTable} All Supported Input Types Table: route: /all_support_types_table x: 1 y: 3 height: 3 width: 1 type: antd-table restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): TableD = test_group1_simple.TableD return dict(query=TableD, fetch_args=[]) Buttons: route: /formButtons x: 0 y: 6 height: 1 width: 1 type: radiobuttons channel: formButtons content: Table A: 'table=TableA' Table B: 'table=TableB' Table C: 'table=TableC' One-One Channeled Form: route: /insert8 x: 1 y: 6 height: 1 width: 1 type: form channels: [formButtons] tables: - 'test_group1_simple.{table}' Dropdown: route: /formDropdown x: 0 y: 7 height: 1 width: 1 type: dropdown-static channel: formDropdown content: Schema 1: 'schema=test_group1_simple' Schema 2: 'schema=test_group2_simple' Many-One Channeled Form: route: /insert9 x: 1 y: 7 height: 1 width: 1 type: form channels: [formButtons, formDropdown] tables: - '{schema}.{table}' Buttons2: route: /formButtons2 x: 0 y: 8 height: 1 width: 1 type: radiobuttons channel: formButtons2 content: Table A: 'table=test_group1_simple.TableA' Table B: 'table=test_group1_simple.TableB' Table C: 'table=test_group1_simple.TableC' Table A2: 'table=test_group2_simple.TableA' Table B2: 'table=test_group2_simple.TableB' Table C2: 'table=test_group2_simple.TableC' Buttons3: route: /formButtons3 x: 0 y: 9 height: 1 width: 1 type: radiobuttons channel: formButtons3 content: Table B: 'table2=test_group1_simple.TableB' Table C: 'table2=test_group1_simple.TableC' Table A2: 'table2=test_group2_simple.TableA' Table B2: 'table2=test_group2_simple.TableB' Table C2: 'table2=test_group2_simple.TableC' Buttons4: route: /formButtons4 x: 0 y: 10 height: 1 width: 1 type: radiobuttons channel: formButtons4 content: Table C: 'table3=test_group1_simple.TableC' Table A2: 'table3=test_group2_simple.TableA' Table B2: 'table3=test_group2_simple.TableB' Table C2: 'table3=test_group2_simple.TableC' Channeled Multi Form: route: /insert10 x: 1 y: 8 height: 3 width: 1 type: form channels: [formButtons2, formButtons3, formButtons4] tables: - '{table}' - '{table2}' - '{table3}' Datetime FPK Form: route: /insert11 x: 0 y: 11 height: 1 width: 1 type: form tables: - test_group1_simple.TableU Part A: route: /insert12 x: 1 y: 11 height: 1 width: 1 type: form tables: - test_group1_simple.TableA.PartA map: - type: table destination: test_group1_simple.TableA input: TableA Big FK Dropdown: route: /insert13 x: 0 y: 12 height: 1 width: 1 type: form tables: - test_group1_simple.TableW Slideshow: route: /slideShow grids: grid1: type: fixed columns: 1 row_height: 680 components: mydatetime: x: 0 y: 0 height: 1 width: 1 type: daterangepicker channel: testtest myslideshow: x: 0 y: 1 height: 1 width: 1 type: slideshow route: /slideshowtest batch_size: 3 chunk_size: 50 buffer_size: 30 max_FPS: 50 channels: [testtest] restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): # SOME QUERY THAT RETURNS ONLY ONE RECORD ONE COLUMN THAT IS THE VIDEO NAME TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) q = ((TableA * TableB).proj( ..., #_sciviz_font='IF(a_name = "Raphael", "rgb(255, 0, 0)", NULL)', _sciviz_background='IF(a_name = "Raphael", "rgba(50, 255, 0, 0.16)", "NULL")', )) return {'query': q, 'fetch_args': {'order_by': '_sciviz_background ASC'}} IFrame: route: /iFrame grids: grid1: type: fixed columns: 3 row_height: 500 components: IFrame Example: route: /iFrameExample x: 1 y: 0 height: 1 width: 1 type: iframe url: https://guzman-raphael-streamlit-examp-authenticated-appsapp1app-3jm4w7.streamlit.app/?embedded=true Hidden Page: route: /hiddenpage hidden: True grids: dgrid: route: /dgridasdawdd type: dynamic columns: 3 row_height: 600 restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse.proj()), fetch_args=[]) component_templates: comp2: route: /myMetakkljj type: metadata restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse), fetch_args=[]) mygrid: type: fixed columns: 3 row_height: 600 components: Example table (conditional row coloring): # yaml allows keys with spaces! route: /nvoihfoewo x: 0 y: 0 height: 1 width: 1 type: antd-table channel: mytable restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) q = ((TableA * TableB).proj( ..., #_sciviz_font='IF(a_name = "Raphael", "rgb(255, 0, 0)", NULL)', _sciviz_background='IF(a_name = "Raphael", "rgba(50, 255, 0, 0.16)", "NULL")', )) return {'query': q, 'fetch_args': {'order_by': '_sciviz_background ASC'}} Mouse metadata: route: /dawdgar x: 1 y: 0 height: 1 width: 1 type: metadata link: /hiddenpage restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse), fetch_args=[]) testplot: type: plot:plotly:stored_json x: 0 y: 0 height: 1 width: 1 route: /someplotroute restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): MousePlots = test_group1_simple.MousePlots return dict(query=(MousePlots), fetch_args=['plot']) picture: type: file:image:attach route: /picture height: 1 width: 1 x: 2 y: 0 restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): MousePics = test_group1_simple.MousePics return dict(query=MousePics, fetch_args=['image_payload']) Nested Linked Table: route: /nestedlinked x: 0 y: 0 height: 1 width: 1 type: antd-table link: /hiddenpage2 restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) q = ((TableA * TableB).proj( ..., #_sciviz_font='IF(a_name = "Raphael", "rgb(255, 0, 0)", NULL)', _sciviz_background='IF(a_name = "Raphael", "rgba(50, 255, 0, 0.16)", "NULL")', )) return {'query': q, 'fetch_args': {'order_by': '_sciviz_background ASC'}} Hidden Page2: route: /hiddenpage2 hidden: True grids: dgrid: route: /dgridasdawddsfsdf type: dynamic columns: 3 row_height: 600 restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse.proj()), fetch_args=[]) component_templates: comp2: route: /myMetakkljjsdfsd type: metadata restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse), fetch_args=[]) mygrid: type: fixed columns: 3 row_height: 600 components: Example table (conditional row coloring): # yaml allows keys with spaces! route: /nvoihfoewosdfsf x: 0 y: 0 height: 1 width: 1 type: antd-table channel: mytable restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): TableA, TableB = (test_group1_simple.TableA, test_group1_simple.TableB) q = ((TableA * TableB).proj( ..., #_sciviz_font='IF(a_name = "Raphael", "rgb(255, 0, 0)", NULL)', _sciviz_background='IF(a_name = "Raphael", "rgba(50, 255, 0, 0.16)", "NULL")', )) return {'query': q, 'fetch_args': {'order_by': '_sciviz_background ASC'}} Mouse metadata: route: /dawdgarsdfsdf x: 1 y: 0 height: 1 width: 1 type: metadata link: /hiddenpage2 restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): Mouse = test_group1_simple.Mouse return dict(query=(Mouse), fetch_args=[]) testplot: type: plot:plotly:stored_json x: 0 y: 0 height: 1 width: 1 route: /someplotroutesdfsdf restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): MousePlots = test_group1_simple.MousePlots return dict(query=(MousePlots), fetch_args=['plot']) picture: type: file:image:attach route: /picturesdfsd height: 1 width: 1 x: 2 y: 0 restriction: > def restriction(**kwargs): return dict(**kwargs) dj_query: > def dj_query(test_group1_simple): MousePics = test_group1_simple.MousePics return dict(query=MousePics, fetch_args=['image_payload'])
#include <stdio.h> #include <Python.h> /** * print_python_bytes - Prints bytes information * * @s: Python Object * Return: no return */ void print_python_bytes(PyObject *s) { char *k; long int size, i, limit; printf("[.] bytes object info\n"); if (!PyBytes_Check(s)) { printf(" [ERROR] Invalid Bytes Object\n"); return; } size = ((PyVarObject *)(s))->ob_size; k = ((PyBytesObject *)s)->ob_sval; printf(" size: %ld\n", size); printf(" trying string: %s\n", k); if (size >= 10) limit = 10; else limit = size + 1; printf(" first %ld bytes:", limit); for (i = 0; i < limit; i++) if (k[i] >= 0) printf(" %02x", k[i]); else printf(" %02x", 256 + k[i]); printf("\n"); } /** * print_python_list - Prints list information * * @s: Python Object * Return: no return */ void print_python_list(PyObject *s) { long int size, i; PyListObject *k; PyObject *obj; size = ((PyVarObject *)(s))->ob_size; k = (PyListObject *)s; printf("[*] Python list info\n"); printf("[*] Size of the Python List = %ld\n", size); printf("[*] Allocated = %ld\n", k->allocated); for (i = 0; i < size; i++) { obj = ((PyListObject *)s)->ob_item[i]; printf("Element %ld: %s\n", i, ((obj)->ob_type)->tp_name); if (PyBytes_Check(obj)) print_python_bytes(obj); } }
<script setup lang="ts"> import SearchField from '@/components/SearchField.vue' import MainInfo from '@/components/MainInfo.vue' import DataTable from '@/components/DataTable.vue' import AppModal from '@/components/AppModal.vue' import TheFooter from '@/components/TheFooter.vue' import { ref, computed, watch } from 'vue' import { usePackagesStore } from '@/stores/packages' import { storeToRefs } from 'pinia' import { useDebounce } from '@/composables/helpers' import type { DataTableHeaders } from '@/types' const appModal = ref<InstanceType<typeof AppModal> | null>(null) const packagesStore = usePackagesStore() const { getPackageByName } = packagesStore const { packageName, packages, packageLoading } = storeToRefs(packagesStore) const tableHeaders: DataTableHeaders = [{ title: 'Version', sortable: false, key: 'version' }] const searchPackageByName = useDebounce(getPackageByName, 1000) const noDataText = computed<string>(() => { if (!packageName.value && !packages.value) return 'Data not found, please enter the package name in the search' else return `${packageName.value} package not found` }) watch(packageName, newValue => { if (!packageLoading.value) packageLoading.value = true searchPackageByName(newValue) }) function openAppModal (item: any, row: any): void { appModal.value?.openModal(row.item.version) } </script> <template> <div class="home bg-background-main pa-8"> <div class="home__search"> <SearchField v-model="packageName" /> </div> <MainInfo /> <DataTable :headers="tableHeaders" :items="packages?.versions" :no-data-text="noDataText" :loading="packageLoading" @on-row-click="openAppModal" /> <AppModal ref="appModal" /> </div> <TheFooter /> </template> <style lang="sass"> .home display: flex flex-direction: column min-height: calc(100vh - 120px) &__search width: 100% max-width: 560px align-self: center </style>
import { AnimatePresence, motion, useReducedMotion, Variants, } from 'framer-motion' import { useInView } from 'react-intersection-observer' import React, { Children, ComponentProps, FC, useMemo } from 'react' const wrapVariants: Variants = { show: { transition: { staggerChildren: 0.14, }, }, } // simple float up animation export const childVariants: Variants = { hidden: { translateY: -100, opacity: 0, }, show: { opacity: 1, translateY: 0, transition: { duration: 0.35, }, }, } /** * The IO children, must be wrapped with AnimatedInView first * https://codesandbox.io/s/framer-motion-intersection-observer-scale-qmtyb?from-embed */ export const AnimatedIOView: FC< ComponentProps<typeof motion.div> & { duration?: number delayOrder?: number disableScale?: boolean once?: boolean } > = ({ children, duration = 0.15, delayOrder = 0, disableScale = false, once, ...rest }) => { const { inView, ref } = useInView({ triggerOnce: once, }) const shouldReduceMotion = useReducedMotion() const transition = useMemo( () => ({ duration, delay: Math.min(delayOrder * 0.04, 0.15) / Math.min(Children.count(children) || 1, 3), }), [duration, delayOrder, children], ) const variants = { hidden: { scale: disableScale ? 1 : 0, translateY: -100, opacity: 0, transition, }, show: { scale: 1, translateY: 0, opacity: 1, transition, }, } return ( <motion.div ref={ref} initial={shouldReduceMotion ? 'show' : 'hidden'} animate={inView ? 'show' : 'hidden'} exit={shouldReduceMotion ? 'show' : 'hidden'} variants={variants} {...rest} > {children} </motion.div> ) } // variant of above // without IO, uses AnimatePresence instead // variant needs show and hidden keys export const AnimatedInPlainViewParent: FC< ComponentProps<typeof motion.div> & { exitBeforeEnter?: boolean } > = ({ children, exitBeforeEnter = false, ...rest }) => { const shouldReduceMotion = useReducedMotion() return useMemo( () => ( <AnimatePresence exitBeforeEnter={exitBeforeEnter}> <motion.div initial={shouldReduceMotion ? 'show' : 'hidden'} animate={'show'} exit={shouldReduceMotion ? 'show' : 'hidden'} variants={wrapVariants} {...rest} > {children} </motion.div> </AnimatePresence> ), [shouldReduceMotion, children, exitBeforeEnter, rest], ) } // a child for the parent ^ that animates in accordion fashion export const AnimatedInViewChildDiv: FC< ComponentProps<typeof motion.div> > = ({ children, variants = childVariants, ...rest }) => ( <motion.div variants={variants} {...rest}> {children} </motion.div> )
import axios from 'axios'; import { useParams } from 'react-router-dom'; import {useState,useEffect} from 'react'; import styles from './cards.module.css'; const Detail = () => { const {id} = useParams(); const [character, setCharacter] = useState({}); useEffect(() => { axios(`https://rickandmortyapi.com/api/character/${id}`) .then(({ data }) => { if (data.name) { setCharacter(data); } else { window.alert('No hay personajes con ese ID'); } }); return setCharacter({}); }, [id]); return ( <div className={styles.detail}> <h2>{character.name && character.name}</h2> <p>{character.status && character.status}</p> <h3>{character.gender && character.gender}</h3> <p>{character.origin?.name && character.origin.name}</p> <img src={character.image && character.image} alt='asd' width= '300px'></img> </div> ) } export default Detail
#postgresql Podemos divir esta tarefa em 3 etapas ### Primeira etapa Primeiro fazemos o PostgreSQL ouvir conexões externas. Para isso precisamos abrir o arquivo `postgresql.conf`: ```bash sudo nano /etc/postgresql/9.6/main/postgresql.conf ``` **NOTA**: 9.6 representa a versão do PostgreSQL instalado. Substitua a seguinte linha do arquivo ```bash listen_addresses = 'localhost' ``` por ```bash listen_addresses = '*' ``` ### Segunda etapa Permitir o PostgreSQL receber conexões externas. Abra o arquivo `pg_hba.cong` ```bash /etc/postgresql/9.6/main/pg_hba.conf ``` **NOTA**: 9.6 representa a versão do PostgreSQL instalado. Adicione a seguinte regra no arquivo: ```bash host all all 0.0.0.0/0 md5 ``` Isso permite qualquer IP de se logar no PostgreSQL através da senha definida do usuario do banco. ### Terceira etapa Reiniciar o PostgreSQL com o comando: ```bash sudo /etc/init.d/postgresql restart ```
# MachineLearning ## Overview Welcome to the MachineLearning repository! Here, you'll find a treasure trove of Jupyter Notebooks showcasing the implementation of fundamental machine learning algorithms from scratch. No shortcuts, no black boxes - just pure, unadulterated code crafted by a passionate learner and practitioner of the art and science of machine learning. ## What's Inside 1. **Linear Regression:** Dive deep into the heart of predictive modeling with our custom implementation of Linear Regression. Understand the core concepts of regression analysis and witness how we build a predictive model step by step. 2. **Naive Bayes:** Explore the elegant simplicity of the Naive Bayes algorithm for classification tasks. We break down the math behind Bayes' theorem and demonstrate how to apply it to real-world data. 3. **Perceptron:** Unravel the mysteries of neural networks by building a Perceptron model from scratch. Learn about activation functions, weight optimization, and the power of single-layer networks. 4. **KNN (K-Nearest Neighbors):** Get hands-on with the KNN algorithm and understand its intuitive approach to classification. Discover how to find similarities between data points and make predictions based on the nearest neighbors. 5. **Forward Propagation:** Take a journey through the forward pass of a neural network. Witness how input data flows through the network, undergoes transformations, and produces an output. 6. **Back Propagation:** Delve into the backpropagation algorithm, the cornerstone of training neural networks. Learn how to adjust weights and biases to minimize errors and improve model performance. ## Why This Repository Matters In an era where machine learning libraries like scikit-learn dominate the landscape, this repository stands out as a testament to genuine understanding and mastery of the underlying principles. By eschewing convenience in favor of comprehension, we've gained a deeper insight into how these algorithms work under the hood. ## What Sets Me Apart - **Passion for Learning:** Every line of code in this repository reflects a burning passion for understanding and mastering machine learning. - **Commitment to Excellence:** I don't settle for "good enough." I strive for excellence in every aspect of my work, constantly refining and improving my algorithms. - **Problem-Solving Skills:** Beyond just implementing algorithms, I possess a keen problem-solving mindset, able to tackle complex challenges with creativity and resourcefulness. ## Join Me on This Journey If you're a recruiter seeking someone who's not just proficient with machine learning libraries but truly understands the principles behind them, then you've come to the right place. Dive into this repository, explore the code, and see for yourself the depth of knowledge and dedication I bring to the table. ## Let's Connect Feel free to reach out to me via email at [gsevprasad2004@gmail.com] or connect with me on LinkedIn [(https://www.linkedin.com/in/g-srinivasa-eswara-vara-prasad-10962a229/)]. I'm always eager to discuss exciting opportunities and collaborations in the field of machine learning. ## Together, Let's Shape the Future of AI! Thank you for taking the time to explore my MachineLearning repository. I look forward to the possibility of working together and contributing to the advancement of artificial intelligence and machine learning.
{% set footer = 'footer' %} {% set page = 'menu' %} {% set front = 'front' %} {% extends 'templates/app.twig' %} {% block content %} <section id="pageTitle" class="row"> <div class="row m0 pageTitle"><span>Items Cart</span></div> <div class="row m0 breadcrumbRow"> <ul class="list-inline"> <li><a href="{{path_for('home')}}">home</a></li> <li><a href="{{path_for('menu')}}"><i class="fa fa-arrow-circle-right"></i> Part Details</a></li> <li><i class="fa fa-arrow-circle-right"></i>Cart</li> </ul> </div> </section> <!--Page Title--> <section id="blogPosts" class="row contentSection"> <div class="container"> <div class="row m_30"> <div class="col-sm-8"> {% if basket.itemCount %} <div class="well"> <table class="table table-striped table-condensed"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> </tr> </thead> <tbody> {% for item in basket.all %} <tr> <td><a href="{{ path_for('product.get', {slug:item.slug})}}">{{ item.title}}</a></td> <td>${{item.price | number_format(2) }}</td> <td> <form action="{{ path_for('cart.update', {slug:item.slug})}}" method="post" class="form-inline"> <select name="quantity" class="form-control input-sm"> {% for num in 1..item.stock %} <option value="{{num}}" {% if num == item.quantity %}selected {% endif %}>{{num }}</option> {% endfor %} <option value="0">None</option> </select> {{ csrf.field | raw }} <input type="submit" class="btn btn-default btn-sm" value="save"> </form> </td> </tr> {% endfor %} </tbody> </table> <a href="{{ path_for('menu')}}">Add more items</a> </div> {% else %} <p>You have not items in your cart. <a href="{{ path_for('menu') }}">Start Shopping</a></p> {% endif %} </div> {% if basket.itemCount %} <div class="col-sm-4 sidebar"> <div class="categories"> <div class="well"> {% if basket.all and basket.subTotal %} <h4>Cart summary</h4> <hr> {% include 'cart/partials/summary.twig' %} <a href="{{ path_for('order.index') }}" class="btn btn-primary">Checkout</a> {% endif %} </div> </div> </div> {% endif %} </div> </div> </section> <!--Blog Posts--> {% endblock %}
<div class="row justify-content-center"> <div class="col-8"> <form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm"> <h2 id="jhi-siba-account-form-heading" jhiTranslate="formfillerApp.sibaAccountForm.home.createOrEditLabel">Create or edit a Siba Account Form</h2> <div> <jhi-alert-error></jhi-alert-error> <div class="form-group" [hidden]="!sibaAccountForm.id"> <label for="id" jhiTranslate="global.field.id">ID</label> <input type="text" class="form-control" id="id" name="id" [(ngModel)]="sibaAccountForm.id" readonly /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.registerDate" for="field_registerDate">Register Date</label> <div class="input-group"> <input id="field_registerDate" type="text" class="form-control" name="registerDate" ngbDatepicker #registerDateDp="ngbDatepicker" [(ngModel)]="sibaAccountForm.registerDate" /> <span class="input-group-append"> <button type="button" class="btn btn-secondary" (click)="registerDateDp.toggle()"><fa-icon [icon]="'calendar-alt'"></fa-icon></button> </span> </div> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.registrationNumber" for="field_registrationNumber">Registration Number</label> <input type="text" class="form-control" name="registrationNumber" id="field_registrationNumber" [(ngModel)]="sibaAccountForm.registrationNumber" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.registrationPlace" for="field_registrationPlace">Registration Place</label> <input type="text" class="form-control" name="registrationPlace" id="field_registrationPlace" [(ngModel)]="sibaAccountForm.registrationPlace" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.registrationCapital" for="field_registrationCapital">Registration Capital</label> <input type="text" class="form-control" name="registrationCapital" id="field_registrationCapital" [(ngModel)]="sibaAccountForm.registrationCapital" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.activityType" for="field_activityType">Activity Type</label> <input type="text" class="form-control" name="activityType" id="field_activityType" [(ngModel)]="sibaAccountForm.activityType" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.longTime" for="field_longTime">Long Time</label> <input type="text" class="form-control" name="longTime" id="field_longTime" [(ngModel)]="sibaAccountForm.longTime" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.boardManagementLong" for="field_boardManagementLong">Board Management Long</label> <input type="text" class="form-control" name="boardManagementLong" id="field_boardManagementLong" [(ngModel)]="sibaAccountForm.boardManagementLong" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.phoneNumber1" for="field_phoneNumber1">Phone Number 1</label> <input type="text" class="form-control" name="phoneNumber1" id="field_phoneNumber1" [(ngModel)]="sibaAccountForm.phoneNumber1" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.phoneNumber2" for="field_phoneNumber2">Phone Number 2</label> <input type="text" class="form-control" name="phoneNumber2" id="field_phoneNumber2" [(ngModel)]="sibaAccountForm.phoneNumber2" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.faxNumber" for="field_faxNumber">Fax Number</label> <input type="text" class="form-control" name="faxNumber" id="field_faxNumber" [(ngModel)]="sibaAccountForm.faxNumber" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.zipCode" for="field_zipCode">Zip Code</label> <input type="text" class="form-control" name="zipCode" id="field_zipCode" [(ngModel)]="sibaAccountForm.zipCode" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.emailAddress" for="field_emailAddress">Email Address</label> <input type="text" class="form-control" name="emailAddress" id="field_emailAddress" [(ngModel)]="sibaAccountForm.emailAddress" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.plainAddress" for="field_plainAddress">Plain Address</label> <input type="text" class="form-control" name="plainAddress" id="field_plainAddress" [(ngModel)]="sibaAccountForm.plainAddress" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.accountRegistrationPurpose" for="field_accountRegistrationPurpose">Account Registration Purpose</label> <input type="text" class="form-control" name="accountRegistrationPurpose" id="field_accountRegistrationPurpose" [(ngModel)]="sibaAccountForm.accountRegistrationPurpose" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.fullName1" for="field_fullName1">Full Name 1</label> <input type="text" class="form-control" name="fullName1" id="field_fullName1" [(ngModel)]="sibaAccountForm.fullName1" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.fullName2" for="field_fullName2">Full Name 2</label> <input type="text" class="form-control" name="fullName2" id="field_fullName2" [(ngModel)]="sibaAccountForm.fullName2" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.fullName3" for="field_fullName3">Full Name 3</label> <input type="text" class="form-control" name="fullName3" id="field_fullName3" [(ngModel)]="sibaAccountForm.fullName3" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.fullName4" for="field_fullName4">Full Name 4</label> <input type="text" class="form-control" name="fullName4" id="field_fullName4" [(ngModel)]="sibaAccountForm.fullName4" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.fullName5" for="field_fullName5">Full Name 5</label> <input type="text" class="form-control" name="fullName5" id="field_fullName5" [(ngModel)]="sibaAccountForm.fullName5" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.fullName6" for="field_fullName6">Full Name 6</label> <input type="text" class="form-control" name="fullName6" id="field_fullName6" [(ngModel)]="sibaAccountForm.fullName6" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.customerNumber1" for="field_customerNumber1">Customer Number 1</label> <input type="text" class="form-control" name="customerNumber1" id="field_customerNumber1" [(ngModel)]="sibaAccountForm.customerNumber1" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.customerNumber2" for="field_customerNumber2">Customer Number 2</label> <input type="text" class="form-control" name="customerNumber2" id="field_customerNumber2" [(ngModel)]="sibaAccountForm.customerNumber2" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.customerNumber3" for="field_customerNumber3">Customer Number 3</label> <input type="text" class="form-control" name="customerNumber3" id="field_customerNumber3" [(ngModel)]="sibaAccountForm.customerNumber3" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.customerNumber4" for="field_customerNumber4">Customer Number 4</label> <input type="text" class="form-control" name="customerNumber4" id="field_customerNumber4" [(ngModel)]="sibaAccountForm.customerNumber4" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.customerNumber5" for="field_customerNumber5">Customer Number 5</label> <input type="text" class="form-control" name="customerNumber5" id="field_customerNumber5" [(ngModel)]="sibaAccountForm.customerNumber5" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.customerNumber6" for="field_customerNumber6">Customer Number 6</label> <input type="text" class="form-control" name="customerNumber6" id="field_customerNumber6" [(ngModel)]="sibaAccountForm.customerNumber6" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.sendingBillCycle" for="field_sendingBillCycle">Sending Bill Cycle</label> <input type="text" class="form-control" name="sendingBillCycle" id="field_sendingBillCycle" [(ngModel)]="sibaAccountForm.sendingBillCycle" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.howToSendBill" for="field_howToSendBill">How To Send Bill</label> <input type="text" class="form-control" name="howToSendBill" id="field_howToSendBill" [(ngModel)]="sibaAccountForm.howToSendBill" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.otherServices" for="field_otherServices">Other Services</label> <input type="text" class="form-control" name="otherServices" id="field_otherServices" [(ngModel)]="sibaAccountForm.otherServices" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.accountType" for="field_accountType">Account Type</label> <input type="text" class="form-control" name="accountType" id="field_accountType" [(ngModel)]="sibaAccountForm.accountType" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.letterNumber" for="field_letterNumber">Letter Number</label> <input type="text" class="form-control" name="letterNumber" id="field_letterNumber" [(ngModel)]="sibaAccountForm.letterNumber" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.letterDate" for="field_letterDate">Letter Date</label> <input type="text" class="form-control" name="letterDate" id="field_letterDate" [(ngModel)]="sibaAccountForm.letterDate" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.letterOrganization" for="field_letterOrganization">Letter Organization</label> <input type="text" class="form-control" name="letterOrganization" id="field_letterOrganization" [(ngModel)]="sibaAccountForm.letterOrganization" /> </div> <div class="form-group"> <label class="form-control-label" jhiTranslate="formfillerApp.sibaAccountForm.customer" for="field_customer">Customer</label> <select class="form-control" id="field_customer" name="customer" [(ngModel)]="sibaAccountForm.customer" > <option [ngValue]="null"></option> <option [ngValue]="customerOption.id === sibaAccountForm.customer?.id ? sibaAccountForm.customer : customerOption" *ngFor="let customerOption of customers; trackBy: trackCustomerById">{{customerOption.id}}</option> </select> </div> </div> <div> <button type="button" id="cancel-save" class="btn btn-secondary" (click)="previousState()"> <fa-icon [icon]="'ban'"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span> </button> <button type="submit" id="save-entity" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary"> <fa-icon [icon]="'save'"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Save</span> </button> </div> </form> </div> </div>
import clsx from "clsx"; import { Link, useNavigate } from "@remix-run/react"; import type { Gallery } from "@gs/types"; import Accordion from "@gs/ui/Accordion"; import Button from "@gs/ui/Button"; import { assetTransformationOptions, generateAssetTransformedUrl, } from "@gs/utils/asset-transformer"; import type { Command } from "./commands"; import useSearch from "./context"; export interface SearchResultGroupProps { label: string; items?: SearchResultItemProps[]; setPreviewProps: (content: SearchResultItemProps) => void; } export function SearchResultGroup({ label, items = [], setPreviewProps, }: SearchResultGroupProps): JSX.Element | null { if (items.length === 0) { return null; } return ( <Accordion summary={<strong>{label}</strong>} open summaryClassName="sticky top-0" className="flex flex-col gap-4" > {items.map((item) => ( <SearchResultItem key={item.id} {...item} setPreviewProps={setPreviewProps} /> ))} </Accordion> ); } export interface SearchResultItemProps { id: string; title: string; subtitle?: string; icon?: string; cover?: string; linkUrl?: string; tags?: string[]; gallery?: Gallery; description?: string; setPreviewProps?: (content: SearchResultItemProps) => void; } export function SearchResultItem({ setPreviewProps, ...props }: SearchResultItemProps): JSX.Element | null { const { id, title, subtitle, icon, cover, linkUrl } = props; const to = new URL(linkUrl || id, "https://guptasiddhant.com"); const { closeSearch } = useSearch(); const navigate = useNavigate(); const handleInteraction = () => setPreviewProps?.(props); const handleKeyDown = (e: React.KeyboardEvent<HTMLAnchorElement>) => { if (e.ctrlKey) { if (e.key === "e" || e.key === "E") { e.preventDefault(); closeSearch(); navigate(`${to}/edit`); } } }; const iconUrl = generateAssetTransformedUrl( icon || cover, assetTransformationOptions.ICON, ); return ( <Link to={to} id={`search-result-${id}`} onClick={closeSearch} onMouseEnter={handleInteraction} onFocus={handleInteraction} onKeyDown={handleKeyDown} className={clsx( "mx-2 grid grid-cols-[2rem_1fr] items-center gap-4 py-2 px-4 ", "rounded bg-transparent hocus:bg-secondary", )} > <div className="h-8 w-8"> {iconUrl ? ( <img src={iconUrl} alt={id} className="h-full w-full rounded-sm bg-inverse object-cover" loading="lazy" /> ) : null} </div> <div className="flex flex-col"> <span className="text-base font-bold">{title}</span> <span className="text-sm">{subtitle}</span> </div> </Link> ); } export function CommandItem(command: Command): JSX.Element | null { const { id, title, onClick } = command; const { closeSearch } = useSearch(); const handleClick = () => { closeSearch(); onClick(); }; return ( <Button data-testid={id} onClick={handleClick} className={"p-2"}> {title} </Button> ); }
/** * Projet de première année à l'IUT de Paris - Rive de Seine * Jeu de Crazy Circus par Dominique Ehrhard * @author Clothilde PROUX, Suyi LYN * @file Joueur.java * Joueurs de la partie */ package test; public class Joueur { private static int nbJoueursJoue = 0; private final String pseudo; private int score; private int rang; private boolean aJoue; /** * Constructeur à partir d'un nom * @param pseudo → pseudo donné au joueur pour s'identifier */ public Joueur (String pseudo) { this.pseudo = pseudo; this.score = 0; this.aJoue = false; } /** * Teste si le joueur existe ou non * @param nom → le nom entré par le joueur * @return null si le joueur n'existe pas ; le joueur sinon */ public Joueur reconnaitJoueur(String nom) { if (this.pseudo.equals(nom)) return this; return null; } public static int getNbJoueursJoue() { return nbJoueursJoue; } public static void setNbJoueursJoue(int nbJoueursJoue) { Joueur.nbJoueursJoue = nbJoueursJoue; } public void setScore() { this.score++; } public int getScore() { return score; } public void setAJoue(boolean bool) { this.aJoue = bool; } public boolean isAJoue() { return aJoue; } public void setRang(int rang) { this.rang = rang; } public int getRang() { return rang; } public String toString() { return this.pseudo; } }
import os import discord import requests from discord import app_commands from discord.ext import commands from discord import Embed import asyncio import random # Set up the Discord client and intents bot = commands.Bot(command_prefix='s!', intents=discord.Intents.all()) def random_color(): return random.randint(0, 0xFFFFFF) @bot.event async def on_ready(): print('{0.user} is ready!'.format(bot)) await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.users)} users!")) try: synced = await bot.tree.sync() print(f'Synced {len(synced)} commands') except Exception as e: print(f'Failed to sync commands: {e}') @bot.tree.command(name='chkbtc', description='Checks the status of a Bitcoin transaction and provides Blockchain information.') async def chkbtc(interaction: discord.Interaction, txid: str): try: response = requests.get(f'https://mempool.space/api/tx/{txid}') data = response.json() embed = Embed(title=f'Blockchain information for', description=f'**{txid}**', color=discord.Color.from_rgb(255,191,0)) embed.add_field(name='Confirmed', value=data['status']['confirmed']) embed.add_field(name='Using Coinbase', value=data['vin'][0]['is_coinbase']) embed.set_footer(text='Information Provided By Crypto Bot') await interaction.response.send_message(embed=embed) except Exception as e: print(f"An error occurred: {str(e)}") embed = Embed(title=f'Error', color=discord.Color.from_rgb(231,76,60)) embed.add_field(name='Invalid txid', value='TXID not found') embed.set_footer(text='Try a different TXID') await interaction.response.send_message(embed=embed) @bot.tree.command(name='alertbtc', description='Sends a DM when a Bitcoin transaction has been confirmed.') async def alert_btc(interaction: discord.Interaction, txid: str): try: url = f"https://mempool.space/api/tx/{txid}" response = requests.get(url).json() confirmed = response.get("status", {}).get("confirmed") if confirmed: embed = Embed(title=f'Blockchain information for', description=f'**{txid}**', color=discord.Color.from_rgb(46,204,113)) embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/853999284520484885.gif?size=240&quality=lossless") embed.add_field(name='Confirmed', value=confirmed) embed.add_field(name='Using Coinbase', value=response['vin'][0]['is_coinbase']) embed.set_footer(text='Information Provided By Crypto Bot') await interaction.response.send_message(embed=embed) else: embed = Embed(title='Waiting for confirmation', color=discord.Color.from_rgb(255,191,0)) embed.add_field(name='Transaction ID', value=txid) embed.set_footer(text='Information Provided By Crypto Bot') await interaction.response.send_message(embed=embed) while True: response = requests.get(url).json() confirmed = response.get("status", {}).get("confirmed") if confirmed: embed = Embed(title=f'Blockchain information for', description=f'**{txid}**', color=discord.Color.from_rgb(46,204,113)()) embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/853999284520484885.gif?size=240&quality=lossless") embed.add_field(name='Confirmed', value=confirmed) embed.add_field(name='Using Coinbase', value=response['vin'][0]['is_coinbase']) embed.set_footer(text='Information Provided By Crypto Bot') await interaction.followup.send(embed=embed) break else: await asyncio.sleep(30) except Exception as e: print(f"An error occurred: {str(e)}") embed = Embed(title=f'Error', color=discord.Color.from_rgb(231,76,60)()) embed.add_field(name='Invalid txid', value='TXID not found') embed.set_footer(text='Try a different TXID') await interaction.response.send_message(embed=embed) # Start the client bot.run("token")
package com.goit.dev10.entities; import java.math.BigDecimal; import java.sql.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class Worker { private Long workerId; private String name; private Date birthday; private String level; private BigDecimal salary; public Worker() { } public Worker(String name, Date birthday, String level, BigDecimal salary) { this.name = name; this.birthday = birthday; this.level = level; this.salary = salary; } public Long getWorkerId() { return workerId; } public void setWorkerId(Long workerId) { this.workerId = workerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public void setBirthday(String birthday) throws ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); this.birthday = new Date(simpleDateFormat.parse(birthday).getTime()); } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } @Override public String toString() { return "Worker{" + "workerId=" + workerId + ", name='" + name + '\'' + ", birthday=" + birthday + ", level='" + level + '\'' + ", salary=" + salary + '}'; } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Account; use App\Services\MakeTransaction; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use RealRashid\SweetAlert\Facades\Alert; class SendMoneyController extends Controller { private $transactionService; public function __construct(MakeTransaction $transactionService) { $this->transactionService = $transactionService; } public function index() { $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return view('frontend.operations.sendingOptions', ['credit' => $credit]); } public function viaEmail() { $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return view('frontend.operations.sendViaEmail', ['credit' => $credit]); } public function viaMobile() { $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return view('frontend.operations.sendViaMobile', ['credit' => $credit]); } public function viaAccount() { $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return view('frontend.operations.sendViaAccount', ['credit' => $credit]); } public function pay(Request $request) { $request->validate([ 'amount' => 'required', // 'surName' => 'required|max:25', 'email' => 'required', 'pin' => 'required|exists:pins,pin', ], [ 'pin.required' => '*Required', 'pin.exists:pins,pin' => '*Pin invalid', ]); $userEmail = Auth::user()->email; $user = DB::table('users') ->leftJoin('accounts as a', 'a.user_id', '=', 'users.id') ->where(['email' => $userEmail])->get(); // dd($user); $faccount = Account::where(['account_number' => $user[0]->account_number])->first(); // dd($status); $targetEmail = $request['email']; $targetUser = DB::table('users') ->leftJoin('accounts as a', 'a.user_id', '=', 'users.id') ->where(['email' => $targetEmail])->get(); $taccount = Account::where(['account_number' => $targetUser[0]->account_number])->first(); // dd($status); $data = ['taccount' => $taccount->id, 'faccount' => $faccount->id, 'amount' => $request['amount']]; $response = $this->transactionService->make($data, 3); if ($response['status'] == 'failed') { Alert::success('Failed!', $response['message']); $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return redirect()->route('client.dashboard')->with(['credit' => $credit, 'error' => $response['message']]); } Alert::success('Successfull!', 'Money transferred successfully.'); $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return redirect()->route('client.dashboard')->with(['credit' => $credit, 'message' => 'Money transferred successfully.']); } public function payMobile(Request $request) { $request->validate([ 'amount' => 'required', // 'surName' => 'required|max:25', 'phone_no' => 'required|integer|digits_between: 1,15', 'pin' => 'required|exists:pins,pin', ], [ 'pin.required' => '*Required', 'pin.exists:pins,pin' => '*Pin invalid', ]); $user = DB::table('users')->leftJoin('accounts as a', 'a.user_id', '=', 'users.id') ->where(['users.id' => Auth::user()->id])->get(); // dd($user); $faccount = Account::where(['account_number' => $user[0]->account_number])->first(); // dd($status); $targetMobile = $request['phone_no']; $targetUser = DB::table('users') ->leftJoin('accounts as a', 'a.user_id', '=', 'users.id') ->where(['phone_no' => $targetMobile])->get(); $taccount = Account::where(['account_number' => $targetUser[0]->account_number])->first(); // dd($status); $data = ['taccount' => $taccount->id, 'faccount' => $faccount->id, 'amount' => $request['amount']]; $response = $this->transactionService->make($data, 3); if ($response['status'] == 'failed') { Alert::success('Failed!', $response['message']); $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return redirect()->route('client.dashboard')->with(['credit' => $credit, 'error' => $response['message']]); } Alert::success('Successfull!', 'Money transferred successfully.'); $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return redirect()->route('client.dashboard')->with(['credit' => $credit, 'message' => 'Money transferred successfully.']); } public function payAccount(Request $request) { $request->validate([ 'amount' => 'required', // 'surName' => 'required|max:25', 'account_number' => 'required|integer|digits_between: 1,15', 'pin' => 'required|exists:pins,pin', ], [ 'pin.required' => '*Required', 'pin.exists:pins,pin' => '*Pin invalid', ]); $user = DB::table('users')->leftJoin('accounts as a', 'a.user_id', '=', 'users.id') ->where(['users.id' => Auth::user()->id])->get(); // dd($user); $faccount = Account::where(['account_number' => $user[0]->account_number])->first(); // dd($status); $targetAccount = $request['account_number']; $targetUser = DB::table('users') ->leftJoin('accounts as a', 'a.user_id', '=', 'users.id') ->where(['account_number' => $targetAccount])->get(); $taccount = Account::where(['account_number' => $targetUser[0]->account_number])->first(); // dd($status); $data = ['taccount' => $taccount->id, 'faccount' => $faccount->id, 'amount' => $request['amount']]; $response = $this->transactionService->make($data, 3); if ($response['status'] == 'failed') { Alert::success('Failed!', $response['message']); $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return redirect()->route('client.dashboard')->with(['credit' => $credit, 'error' => $response['message']]); } Alert::success('Successfull!', 'Money transferred successfully.'); $credit = Account::where(['user_id' => Auth::user()->id])->first()->credit; return redirect()->route('client.dashboard')->with(['credit' => $credit, 'message' => 'Money transferred successfully.']); } }
import React from 'react'; import { NavLink, useNavigate } from 'react-router-dom'; import styled from 'styled-components'; import { useCart } from '../Context/CartContext'; const Wrapper = styled.div` display: flex; justify-content: center; align-items: center; height: 80vh; form { background-color: #f5f5f5; padding: 20px; border-radius: 8px; box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.1); width: 300px; /* Make the signup container slightly longer */ height: 340px; display: flex; flex-direction: column; justify-content: space-between; } h2 { text-align: center; margin-bottom: 20px; } input { width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } button { width: 100%; padding: 10px; background-color: black; color: #fff; border: none; border-radius: 4px; cursor: pointer; margin-bottom: 10px; transition: background-color 0.3s ease; } button:hover { background-color: #333; } p { text-align: center; margin-bottom: 0; } a { text-decoration: none; color: #007bff; cursor: pointer; } a:hover { text-decoration: underline; } `; const SignUp = () => { const navigate = useNavigate(); const { setIsLoggedIn } = useCart(); const handleSignUp=()=>{ // setIsLoggedIn(true); // Redirect to login pagee navigate('/login'); } return ( <Wrapper> <form action="" onSubmit={handleSignUp} className='signup_form'> <h2>Sign Up</h2> <input type="text" placeholder="Username" required/> <input type="email" placeholder="Email" required/> <input type="password" placeholder="Password" required minLength={5}/> <button type="submit" name="signup_btn">Signup</button> <p>Already have an account? <NavLink to="/login">Login</NavLink></p> </form> </Wrapper> ); } export default SignUp;
DIRECTION_STEPS = { "R": (1, 0), "U": (0, 1), "L": (-1, 0), "D": (0, -1), } def run(input_path): input = open(input_path, "r") head_pos = (0, 0) tail_pos = (0, 0) tail_visited = set([tail_pos]) for line in input.readlines(): line = line.strip() direction, distance = line.split(" ") step = DIRECTION_STEPS[direction] for _ in range(int(distance)): head_pos = (head_pos[0] + step[0], head_pos[1] + step[1]) tail_pos = move_tail(head_pos, tail_pos) tail_visited.add(tail_pos) return len(tail_visited) def move_tail(head_pos, tail_pos): # Distance from tail to head dx = head_pos[0] - tail_pos[0] dy = head_pos[1] - tail_pos[1] # Check that head and tail are in a valid position assert abs(dx) <= 2 and abs(dy) <= 2 assert not (abs(dx) == 2 and abs(dy) == 2) # Check if tail is within one space of head if abs(dx) <= 1 and abs(dy) <= 1: # If so, tail does not move return tail_pos # Straight to left or right if abs(dx) == 2 and abs(dy) == 0: return (tail_pos[0] + dx // 2, tail_pos[1]) # Straight above or below if abs(dx) == 0 and abs(dy) == 2: return (tail_pos[0], tail_pos[1] + dy // 2) # Diagonally more to left or right than to top or bottom if abs(dx) == 2 and abs(dy) == 1: return (tail_pos[0] + dx // 2, tail_pos[1] + dy) # Diagonally more to top or bottom than left or right if abs(dx) == 1 and abs(dy) == 2: return (tail_pos[0] + dx, tail_pos[1] + dy // 2) # This should cover all cases assert False if __name__ == "__main__": assert run("9-test.txt") == 13 assert run("9-real.txt") == 5960
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import * as _ from 'lodash'; import { MediaChange, MediaObserver } from '@angular/flex-layout'; import { UnitsService } from '../../services/units.service'; @Component({ selector: 'app-pareto', templateUrl: './pareto.component.html', styleUrls: ['./pareto.component.scss'] }) export class ParetoComponent implements OnChanges { @Input() name = 'name'; @Input() value = 'value'; @Input() occurances = 'occurances'; @Input() topItems = 0; @Input() barWidth = 100; @Input() barHeight = 20; @Input() data = []; @Input() type; units; vm; constructor(private unitsService: UnitsService, public media: MediaObserver) { this.units = this.type; } calculateParetoVm() { // Create a standardized data array using the provided accessor names let tempValues = this.data.map((o) => { return { name: o[this.name], value: o[this.value], occurances: o[this.occurances] }; }); //console.log(tempValues); // Sort the array by descending value /*global _ */ _.sortBy(tempValues, (o) => { return -1 * o.value; }); // Initialize the view model let vm = []; let other = { count: 0, total: 0, combinedNames: '' }; this.units = this.unitsService.getUserUnits(this.type); for (let i = 0; i < tempValues.length; i++) { let newValue: any = tempValues[i]; if (newValue.value < 0) { continue; } newValue.value = this.unitsService.convertUnits(newValue.value, this.type, 1, this.units); if (i < this.topItems) { //todo:format from service for ffi&fdi? newValue.toolTipText = newValue.value.toFixed(1) + ' ' + this.units; vm.push(newValue); //console.log(newValue); } else { other.total += newValue.value; other.count++; if (other.combinedNames !== '') { other.combinedNames += ', '; } other.combinedNames += newValue.name + ': ' + newValue.value.toFixed(1); } } if (other.count > 0) { vm.push({ name: 'Other (' + other.count + ')', value: other.total, toolTipText: other.combinedNames }); } // Find the max and total value let maxValue = Math.max.apply(Math, tempValues.map((o) => { return o.value; })); /*global _ */ // lodash version required by angular-dc doesn't support _sum let sumValues = _.reduce(tempValues, (sum, val) => { return sum + val.value; }); // Add percentages vm = vm.map((o) => { o.valuePercent = o.value / sumValues; o.barPercent = o.value / maxValue; return o; }); return vm; } ngOnChanges(changes: SimpleChanges): void { if (changes.data && changes.data.currentValue) { this.vm = this.calculateParetoVm(); } } }
import React, { useEffect } from "react"; import { connect } from "react-redux"; import { IState } from "src/initialload/state-interface"; import { Dispatch } from "redux"; import { Avatar, Dialog, DialogContent, DialogTitle, IconButton, ImageList, ImageListItem, List, ListItem, Menu, MenuItem, MuiThemeProvider, Paper, Tab, Tabs, Toolbar, Tooltip, Typography } from "@material-ui/core"; import { menuListAction } from "../menulists/menulists-reducer"; import MUIDataTable from "mui-datatables"; import { history } from "src/helper/history"; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import AddIcon from '@material-ui/icons/Add'; import { TextFieldView } from "src/component/textfield-view"; import { DropDownView } from "src/component/dropdown-view"; import { DatePickerView } from "src/component/datepicker-view"; import { apiActions } from "src/action/action"; import { ImageView } from "src/component/image-view"; import moment from "moment"; import { createMuiTheme } from "@material-ui/core/styles"; import { Browser } from "src/helper/browser"; import { CategoryTypeView } from "../mastercomponent/categorytype-view"; import { BankDetailsView } from "../mastercomponent/bank-view"; import EqualizerIcon from '@material-ui/icons/Equalizer'; import { Aggregates } from "src/helper/Aggregates"; import { isNullOrUndefinedOrEmpty, number2FormatFn } from "src/common"; import { alertAction } from "../alert/alert-reducer"; import { COMMONAPI, RECEIPTUPLOADAPI } from "src/apiurl"; import { ButtonView } from "src/component/button-view"; import { TabPanel, tabProps } from "src/component/tab-view"; import { listStyles } from "src/commontheme-css"; import ArrowRightAltIcon from '@material-ui/icons/ArrowRightAlt'; import EditIcon from '@material-ui/icons/Edit'; import SaveIcon from '@material-ui/icons/Save'; function Receiptupload(props: any) { const SPACED_DATE_FORMAT = "DD MMM YYYY"; let gridObj = {billDate: new Date(), categoryUuid: '', categoryTypeName: '', bankUuid: '', bankName: '', spentTypeUuid: '', spentType: '', amount: 0, image: '', description: '', transferType: '', transferTypeUuid: '', transferId: '' }; const [state, setState] = React.useState({ gridData: [], isNewReceipt: false, isImageView: false, imageData: '', isInitial: true, isCategoryType: false, monthlyExpenseTemplateSource: [], dropDownSource: [], isBankName: false, bankDropDownSource: [], isSummary: null, monthlyExpenseTemplate: '', monthlyExpenseTemplateUuid: '', monthExpenseObj: {}, ...gridObj, totalAmount: 0, creditAmt: 0, monthlyTotalAmount: 0, remainingAmount: 0, debitAmt: 0, tabIndex: 0, summaryTabIndex: 0, receiptUuid: '' }); const handleChange = (field: any, value: any) => { if (typeof value === 'object' && field !== 'billDate' && field !== 'isSummary') { setState(prevState => ({ ...prevState, ...value })); } else { setState(prevState => ({ ...prevState, [field]: value })); } }; const options: any = { filter: true, selectableRows: false, filterType: 'dropdown', responsive: 'stacked', rowsPerPage: 10, tableBodyHeight: window.innerHeight - 262, customToolbar: () => { return (<> <Tooltip title={"Add New"}> <IconButton onClick={() => { if (isNullOrUndefinedOrEmpty(state.monthlyExpenseTemplateUuid)) { props.dispatch(alertAction.error('Please Create Monthly Expense For This Month')); } else { handleChange('isNewReceipt', {...gridObj, isNewReceipt: true}) } }}> <AddIcon /> </IconButton> </Tooltip> </>); } }; const columns: any = [ { label: 'Bill Date', name: 'billDate', options: { sortDirection: 'desc', customBodyRender: (value: any) => moment(new Date(value)).format(SPACED_DATE_FORMAT) } }, { label: 'Category Type', name: 'categoryTypeName' }, { label: 'Bank Name', name: 'bankName' }, { label: 'Amount', name: 'amount', options: { customBodyRender: function (value: number) { return number2FormatFn(value); } }}, { label: 'Image', name: 'image', options: { customBodyRender: (image: any) => { return ( <Avatar variant="rounded" src={image} onClick={() => { if (image) { handleChange('isImageView', {isImageView: true, imageData: image}); } else { props.dispatch(alertAction.error('There is No Image')); } }}></Avatar> ); } }, }, { label: 'Description', name: 'description' } ]; useEffect(() => { if (state.isInitial) { props.dispatch(apiActions.methodAction('get', COMMONAPI('receiptUpload', null).RECEIPTRELATEDMASTER, {}, (res: any) => { // let validMonthExpense = res.monthlyExpenseData.filter((line: any) => { // let currentDate = new Date(new Date().setHours(0, 0, 0, 0)).getTime(); // if (new Date(new Date(line.fromDate).setHours(0, 0, 0, 0)).getTime() <= currentDate && // currentDate <= new Date(new Date(line.toDate).setHours(0, 0, 0, 0)).getTime()) { // return line; // } // }); let filterCredit = res.receiptData.filter((line: any) => +line.transferId === 1); let creditAmt = Aggregates.sum(filterCredit, 'amount'); let filterDebit = res.receiptData.filter((line: any) => +line.transferId !== 1); let debitAmt = Aggregates.sum(filterDebit, 'amount'); let currentMonthData = res.monthlyExpenseData.filter((line: any) => +line.expenseMonth === new Date().getMonth()); let currentMonthDataObj = currentMonthData[0] || {}; let totalAmount = (currentMonthDataObj['totalAmount'] || 0) + (creditAmt || 0); let expenseAmount = (+state.monthExpenseObj['expenseAmount'] || 0) + (debitAmt || 0); handleChange('gridData', { dropDownSource: res.categoryData, bankDropDownSource: res.bankData, gridData: res.receiptData, monthlyExpenseTemplateUuid: currentMonthDataObj.uuid, monthlyExpenseTemplate: currentMonthDataObj.templateName, monthlyExpenseTemplateSource: res.monthlyExpenseData, isInitial: false, monthExpenseObj: currentMonthDataObj, monthlyTotalAmount: (currentMonthDataObj['totalAmount'] || 0), totalAmount: totalAmount, creditAmt: (creditAmt || 0), debitAmt: (debitAmt || 0), remainingAmount: ((+totalAmount || 0) - (+expenseAmount || 0)) }); })); } let descriptionText = state.categoryTypeName + ' - ' + state.bankName + ' - ' + state.spentType + ' - ' + state.transferType + ' - ' + state.amount; handleChange('description', descriptionText); }, [state.categoryTypeName, state.bankName, state.spentType, state.amount]); const receiptupload = () => { let getCategoryList = state.gridData.filter((line: any) => line.categoryUuid === state.categoryUuid); let categoryAmt = Aggregates.sum(getCategoryList, 'amount') + (+state.amount || 0); let monthCategoryTypes = JSON.parse(state.monthExpenseObj['categoryTypes'] || `[]`).filter((category: any) => category.uuid === state.categoryUuid); let monthCategoryAmt = Aggregates.sum(monthCategoryTypes, 'amount'); let calcCategoryAmt = monthCategoryAmt - categoryAmt; let postData = { billDate: moment(new Date(state.billDate)).format("YYYY-MM-DD h:mm:ss"), monthlyExpenseTemplate: state.monthlyExpenseTemplate, monthlyExpenseTemplateUuid: state.monthlyExpenseTemplateUuid, categoryUuid: state.categoryUuid, categoryTypeName: state.categoryTypeName, bankUuid: state.bankUuid, bankName: state.bankName, spentTypeUuid: state.spentTypeUuid, spentType: state.spentType, transferTypeUuid: state.transferTypeUuid, transferType: state.transferType, transferId: state.transferId, amount: +state.amount || 0, image: state.image, description: state.description }; if (isNullOrUndefinedOrEmpty(postData.categoryUuid)) { props.dispatch(alertAction.error('Please Choose Category Type')); } else if (isNullOrUndefinedOrEmpty(postData.bankUuid)) { props.dispatch(alertAction.error('Please Choose Bank Type')); } else if (isNullOrUndefinedOrEmpty(postData.amount) || postData.amount === 0) { props.dispatch(alertAction.error('Please Enter Amount')); } else if (isNullOrUndefinedOrEmpty(postData.spentTypeUuid)) { props.dispatch(alertAction.error('Please Choose Spent Type')); } else if (isNullOrUndefinedOrEmpty(postData.transferTypeUuid)) { props.dispatch(alertAction.error('Please Choose Transfer Type')); } else { if (+calcCategoryAmt < 0) { props.dispatch(alertAction.error('Amount Greater than the Allocated Amount')); } if (state.receiptUuid) { postData['uuid'] = state.receiptUuid; props.dispatch(apiActions.methodAction('put', RECEIPTUPLOADAPI().PUT, postData, (res: any) => { let gridData = state.gridData.map((line: any) => { if (line.uuid === state.receiptUuid) { return postData; } return line; }); gridRefresh(gridData); })); } else { props.dispatch(apiActions.methodAction('post', RECEIPTUPLOADAPI().POST, postData, (res: any) => { let gridData = state.gridData.concat([res.data]); gridRefresh(gridData); })); } } }; const gridRefresh = (gridData: any) => { let filterCredit = gridData.filter((line: any) => +line.transferId === 1); let creditAmt = Aggregates.sum(filterCredit, 'amount'); let filterDebit = gridData.filter((line: any) => +line.transferId !== 1); let debitAmt = Aggregates.sum(filterDebit, 'amount'); let totalAmount = (state.monthlyTotalAmount || 0) + (creditAmt || 0); let expenseAmount = (+state.monthExpenseObj['expenseAmount'] || 0) + (debitAmt || 0); handleChange('isNewReceipt', { isNewReceipt: false, gridData: gridData, totalAmount: totalAmount, creditAmt: (creditAmt || 0), debitAmt: (debitAmt || 0), remainingAmount: ((+totalAmount || 0) - (+expenseAmount || 0)) }); } const allocatedTemplate = () => { return <div className="bg-white col-sm-12 p-0 pt-2"> <div className="row m-0"> <div className="col-6 col-sm-6 pb-2">Total Amount</div> <div className="col-6 col-sm-6 pb-2" align="right">{state.monthlyTotalAmount || 0}</div> </div> <div className="row m-0"> <div className="col-6 col-sm-6 pb-2">Credited Amount</div> <div className="col-6 col-sm-6 pb-2" align="right">{state.creditAmt || 0}</div> </div> <div className="row m-0"> <div className="col-6 col-sm-6 pb-2">Debited Amount</div> <div className="col-6 col-sm-6 pb-2" align="right">{state.debitAmt || 0}</div> </div> <div className="row m-0 pb-2 fw-bold text-secondary"> <div className="col-6 col-sm-6">Expense Amount</div> <div className="col-6 col-sm-6" align="right">{state.monthExpenseObj['expenseAmount'] || 0}</div> </div> <div className="row m-0 py-2 border-top border-bottom"> <div className="col-6 col-sm-6">Saving Amount</div> <div className="col-6 col-sm-6" align="right">{state.remainingAmount || 0}</div> </div> </div>; } const categorySummaryTemplate = () => { return <div className="col-sm-12 p-0"> <List className={listClasses.root + ' p-0'}> {state.dropDownSource.map((types: any, ind: number) => { let monthCategoryTypes = JSON.parse(state.monthExpenseObj['categoryTypes'] || `[]`).filter((category: any) => category.uuid === types.uuid); let monthCategoryTypesObj = monthCategoryTypes[0] || {}; let geFilterData = state.gridData.filter((type: any) => type.categoryUuid === types.uuid); let sumCreditAmt = geFilterData.filter((type: any) => +type.transferId === 1); let sumDebitAmt = geFilterData.filter((type: any) => +type.transferId !== 1); let sumCreditVal = Aggregates.sum(sumCreditAmt, 'amount'); let sumDebitVal = Aggregates.sum(sumDebitAmt, 'amount'); let sumVal = ((+sumCreditVal || 0) - (+sumDebitVal || 0)); let remainAmt = (+monthCategoryTypesObj.amount || 0) + (sumVal || 0); overallCategoryRemainAmt += +remainAmt || 0; overallCategorySpentAmt += +sumDebitVal || 0; return <ListItem className="border-bottom" style={+remainAmt < 0 ? {background: 'lavenderblush'} : {background: 'white'}}> <div className={'col-12 col-sm-12'}> <div className="col-sm-12">{types.categoryTypeName}</div> <div className="row m-0"> <div className="col-6 col-sm-6 p-0"> <span className="text-secondary">Alloc: </span> <span>{number2FormatFn(monthCategoryTypesObj.amount || 0)}</span> </div> <div className="col-6 col-sm-6 p-0" align="right"> <span className="text-secondary">Remain: </span> <span>{remainAmt || 0}</span> </div> </div> <div className="row m-0"> {+sumCreditVal > 0 ? <div className="col-6 col-sm-6 p-0" style={{color: 'green'}}> <span>Ct: {number2FormatFn(sumCreditVal || 0)}</span> <ArrowRightAltIcon style={{transform: `rotate(270deg)`}} /> </div> : sumDebitVal > 0 ? <div className="col-6 col-sm-6 p-0" style={{color: 'red'}}> <span>Dt: {number2FormatFn(sumDebitVal || 0)}</span> <ArrowRightAltIcon style={{transform: `rotate(90deg)`}} /> </div> : <></>} </div> </div> </ListItem> })} </List> {/* <div className="row m-0 pb-2 a-fw-md"> <div className="col-sm-4">Category Type</div> <div className="col-sm-2">Allocated</div> <div className="col-sm-2">Credit</div> <div className="col-sm-2">Spend</div> <div className="col-sm-2 text-end">Remaining</div> </div> <div className="col-sm-12 pb-2"> {state.dropDownSource.map((types: any) => { let monthCategoryTypes = JSON.parse(state.monthExpenseObj['categoryTypes'] || `[]`).filter((category: any) => category.uuid === types.uuid); let monthCategoryTypesObj = monthCategoryTypes[0] || {}; let geFilterData = state.gridData.filter((type: any) => type.categoryUuid === types.uuid); let sumCreditAmt = geFilterData.filter((type: any) => +type.transferId === 1); let sumDebitAmt = geFilterData.filter((type: any) => +type.transferId !== 1); let sumCreditVal = Aggregates.sum(sumCreditAmt, 'amount'); let sumDebitVal = Aggregates.sum(sumDebitAmt, 'amount'); let sumVal = ((+sumCreditVal || 0) - (+sumDebitVal || 0)); let remainAmt = (+monthCategoryTypesObj.amount || 0) + (sumVal || 0); overallCategoryRemainAmt += +remainAmt || 0; overallCategorySpentAmt += +sumDebitVal || 0; let diffAmt = ((monthCategoryTypesObj.amount || 0) + (sumVal || 0)) < 0 ? true : false; return <div className={"row m-0 py-2 " + (diffAmt ? 'text-danger' : '')}> <div className="col-sm-4">{types.categoryTypeName}</div> <div className="col-sm-2">{monthCategoryTypesObj.amount || 0}</div> <div className="col-sm-2"> <span>{sumCreditVal || 0}</span> <ArrowRightAltIcon style={{color: 'green', transform: `rotate(270deg)`}} /> </div> <div className="col-sm-2"> <span>{sumDebitVal || 0}</span> <ArrowRightAltIcon style={{color: 'red', transform: `rotate(90deg)`}} /> </div> <div className="col-sm-2 fw-bold text-end">{remainAmt || 0}</div> </div> })} </div> */} <div className={"row m-0 py-3 border-bottom"} style={overallCategoryRemainAmt < 0 ? {background: 'lavenderblush'} : {background: '#d3efd3'}}> <div className="col-8 col-sm-6 fw-bold">Category Expense Amount</div> <div className="col-4 col-sm-6 fw-bold" align="right">{overallCategoryRemainAmt}</div> </div> <div className={"row m-0 py-2 border-bottom d-none " + (((+state.remainingAmount) > (+state.totalAmount - (+overallCategorySpentAmt || 0))) ? 'text-danger' : '')}> <div className="col-6 col-sm-6">Overall Saving Amount</div> <div className={"col-6 col-sm-6 fw-bold"} align="right"> {(+state.totalAmount || 0) - (+overallCategorySpentAmt || 0)} </div> </div> </div>; } const bankSummaryTemplate = () => { return <div className="col-sm-12 p-0"> <List className={listClasses.root + ' p-0'}> {state.bankDropDownSource.map((types: any, ind: number) => { let monthBankTypes = JSON.parse(state.monthExpenseObj['bankNames'] || `[]`).filter((bank: any) => bank.uuid === types.uuid); let monthBankTypesObj = monthBankTypes[0] || {}; let geFilterData = state.gridData.filter((type: any) => type.bankUuid === types.uuid); let sumCreditAmt = geFilterData.filter((type: any) => +type.transferId === 1); let sumDebitAmt = geFilterData.filter((type: any) => +type.transferId !== 1); let sumCreditVal = Aggregates.sum(sumCreditAmt, 'amount'); let sumDebitVal = Aggregates.sum(sumDebitAmt, 'amount'); let sumVal = ((+sumCreditVal || 0) - (+sumDebitVal || 0)); let remainAmt = (+monthBankTypesObj.amount || 0) + (sumVal || 0); overallBankRemainAmt += +remainAmt || 0; overallBankSpentAmt += +sumDebitVal || 0; return <ListItem className="border-bottom" style={+remainAmt < 0 ? {background: 'lavenderblush'} : {background: 'white'}}> <div className={'col-12 col-sm-12'}> <div className="col-sm-12">{types.bankName}</div> <div className="row m-0"> <div className="col-6 col-sm-6 p-0"> <span className="text-secondary">Alloc: </span> <span>{number2FormatFn(monthBankTypesObj.amount || 0)}</span> </div> <div className="col-6 col-sm-6 p-0" align="right"> <span className="text-secondary">Remain: </span> <span>{remainAmt || 0}</span> </div> </div> <div className="row m-0"> <div className="col-6 col-sm-6 p-0" style={{color: 'green'}}> <span>Ct: {number2FormatFn(sumCreditVal || 0)}</span> <ArrowRightAltIcon style={{transform: `rotate(270deg)`}} /> </div> <div className="col-6 col-sm-6 p-0" style={{color: 'red'}} align="right"> <span>Dt: {number2FormatFn(sumDebitVal || 0)}</span> <ArrowRightAltIcon style={{transform: `rotate(90deg)`}} /> </div> </div> </div> </ListItem> })} </List> {/* <div className="row m-0 pb-2 a-fw-md"> <div className="col-sm-4">Bank Name</div> <div className="col-sm-2">Allocated</div> <div className="col-sm-2">Credit</div> <div className="col-sm-2">Spend</div> <div className="col-sm-2 text-end">Remaining</div> </div> <div className="col-sm-12 pb-2"> {state.bankDropDownSource.map((types: any) => { let monthBankTypes = JSON.parse(state.monthExpenseObj['bankNames'] || `[]`).filter((bank: any) => bank.uuid === types.uuid); let monthBankTypesObj = monthBankTypes[0] || {}; let geFilterData = state.gridData.filter((type: any) => type.bankUuid === types.uuid); let sumCreditAmt = geFilterData.filter((type: any) => +type.transferId === 1); let sumDebitAmt = geFilterData.filter((type: any) => +type.transferId !== 1); let sumCreditVal = Aggregates.sum(sumCreditAmt, 'amount'); let sumDebitVal = Aggregates.sum(sumDebitAmt, 'amount'); let sumVal = ((+sumCreditVal || 0) - (+sumDebitVal || 0)); let remainAmt = (+monthBankTypesObj.amount || 0) + (sumVal || 0); overallBankRemainAmt += +remainAmt || 0; overallBankSpentAmt += +sumDebitVal || 0; let diffAmt = ((monthBankTypesObj.amount || 0) + (sumVal || 0)) < 0 ? true : false; return <div className={"row m-0 " + (diffAmt ? 'text-danger' : '')}> <div className="col-sm-4">{types.bankName}</div> <div className="col-sm-2">{monthBankTypesObj.amount || 0}</div> <div className="col-sm-2">{sumCreditVal || 0}</div> <div className="col-sm-2">{sumDebitVal || 0}</div> <div className="col-sm-2 fw-bold text-end">{remainAmt || 0}</div> </div> })} </div> */} <div className={"row m-0 py-3 border-bottom"} style={overallBankRemainAmt < 0 ? {background: 'lavenderblush'} : {background: '#d3efd3'}}> <div className="col-8 col-sm-6 fw-bold">Bank Expense Amount</div> <div className="col-4 col-sm-6 fw-bold" align="right">{overallBankRemainAmt}</div> </div> <div className={"row m-0 py-2 border-bottom d-none " + (((+state.remainingAmount) > (+state.totalAmount - (+overallBankSpentAmt || 0))) ? 'text-danger' : '')}> <div className="col-6 col-sm-6">Overall Saving Amount</div> <div className={"col-6 col-sm-6 fw-bold"} align="right"> {(+state.totalAmount || 0) - (+overallBankSpentAmt || 0)} </div> </div> </div>; } const getMuiTheme = createMuiTheme({ overrides: { MUIDataTableBodyCell: { cellStackedSmall: { display: 'none' } }, MUIDataTableHeadCell: { toolButton: { color: 'black', fontWeight: 700 } }, MUIDataTableToolbar: { root: { borderBottom: '1px solid rgba(224, 224, 224, 1)', position: 'sticky', // top: '64px', zIndex: 101, background: 'white' } }, MuiTableCell: { root: { borderBottom: Browser.isDeviceScreen ? 'unset' : '1px solid rgba(224, 224, 224, 1)' } }, MuiList: { root: { width: '300px' } }, MuiListItem: { root: { "&:not(:last-child)": { borderBottom: '2px solid whitesmoke' } } }, MuiTableHead: { root: { zIndex: 0 } } } }); let compareHistoryMoveDate = new Date(new Date(props.loginCurrentUser.historyMovedDate).setHours(0, 0, 0, 0)).getTime() === new Date(new Date().setHours(0, 0, 0, 0)).getTime(); let overallCategoryRemainAmt = 0; let overallBankRemainAmt = 0; let overallCategorySpentAmt = 0; let overallBankSpentAmt = 0; const listClasses = listStyles(); return (<> <div className="col-sm-12 bg-light h-100"> <div className="a-appbar"> <Toolbar className="border-bottom bg-white a-sticky-t0-z101"> <IconButton edge="start" color="inherit" aria-label="menu" onClick={() => { props.dispatch(menuListAction.menuSelection(false)); history.push('/\home'); }}> <ArrowBackIcon /> </IconButton> <div className="col py-2" style={{lineHeight: '16px'}}> <Typography variant="h6" className="flex-grow-1">Receipt Upload</Typography> {compareHistoryMoveDate && <div className="text-danger fw-bold pb-2">Last Month Record Moved to Receipt History</div>} </div> </Toolbar> </div> <div className="position-relative" style={{zIndex: 1}}> <Paper square elevation={0} className="border-bottom"> <Tabs value={state.tabIndex} indicatorColor="primary" textColor="primary" onChange={(event: any, value: number) => handleChange('tabIndex', value)}> <Tab label="Summary" className="w-50" {...tabProps(0)} /> <Tab label="Receipt List" className="w-50" {...tabProps(1)} /> </Tabs> </Paper> </div> <div className="col-12 col-sm-12 row m-0 p-0 overflow-auto" style={{height: 'calc(100% - 113px)'}}> <TabPanel value={state.tabIndex} index={0} className='p-0'> {Browser.isDeviceScreen ? <> <div className="position-sticky" style={{zIndex: 1, top: '1px'}}> <Paper square elevation={0} className="border-bottom"> <Tabs value={state.summaryTabIndex} indicatorColor="primary" textColor="primary" onChange={(event: any, value: number) => handleChange('summaryTabIndex', value)}> {/* <Tab label="Allocated Amount" {...tabProps(0)} /> */} <Tab label="Category Expense" className="col-6" {...tabProps(0)} /> <Tab label="Bank Expense" className="col-6" {...tabProps(1)} /> </Tabs> </Paper> </div> {/* <TabPanel value={state.summaryTabIndex} index={0} className='p-0'> {allocatedTemplate()} </TabPanel> */} <TabPanel value={state.summaryTabIndex} index={0} className='p-0'> {categorySummaryTemplate()} </TabPanel> <TabPanel value={state.summaryTabIndex} index={1} className='p-0'> {bankSummaryTemplate()} </TabPanel> </> : <div className="p-2"> <div className="col-sm-12 row m-0"> <div className="col-12 col-sm-4 p-0 h-100"> <div className="bg-white col-sm-12 p-0 pt-2"> <div className="row m-0"> <div className="a-fw-md col-sm-12 pb-3 fw-bold">Allocated Amount</div> </div> {allocatedTemplate()} </div> </div> <div className="col-12 col-sm-4 row m-0 h-100"> <div className="bg-white col-sm-12 p-0 pt-2"> <div className="a-fw-md col-sm-12 px-3 fw-bold">Category Wise List</div> {categorySummaryTemplate()} </div> </div> <div className="col-12 col-sm-4 p-0 row m-0 h-100"> <div className="bg-white col-sm-12 p-0 pt-2"> <div className="a-fw-md col-sm-12 px-3 fw-bold">Bank Wise List</div> {bankSummaryTemplate()} </div> </div> </div> </div>} </TabPanel> <TabPanel value={state.tabIndex} index={1} className='p-0'> {Browser.isDeviceScreen ? <> <div className="p-2" align="right"> <ButtonView className='text-primary' onClick={() => { if (isNullOrUndefinedOrEmpty(state.monthlyExpenseTemplateUuid)) { props.dispatch(alertAction.error('Please Create Monthly Expense For This Month')); } else { handleChange('isNewReceipt', {...gridObj, isNewReceipt: true}) } }} startIcon={<AddIcon></AddIcon>}>Add New</ButtonView> </div> <List className={listClasses.root + (state.gridData.length ? ' d-block' : ' d-none')}> {state.gridData.map((line: any, ind: number) => { return <ListItem className="border-bottom"> <div className={'col-12 col-sm-12 row m-0'}> <Avatar variant="rounded" src={line.image} onClick={() => { if (line.image) { handleChange('isImageView', {isImageView: true, imageData: line.image}); } else { props.dispatch(alertAction.error('There is No Image')); } }}></Avatar> <div className="col"> <div>{line.categoryTypeName}</div> <div className="text-secondary">{moment(new Date(line.billDate)).format(SPACED_DATE_FORMAT)}</div> <div className="fw-bold">{number2FormatFn(line.amount)}</div> </div> <div style={{width: '24px'}} className="p-0" onClick={() => handleChange('isNewReceipt', {...line, receiptUuid: line.uuid, isNewReceipt: true})}> <EditIcon fontSize={'medium'} className="text-secondary"></EditIcon> </div> </div> </ListItem> })} </List> </> : <div className="p-2"> <MuiThemeProvider theme={getMuiTheme}> <MUIDataTable columns={columns} data={state.gridData} title={ <Tooltip title={"Summary Details"}> <IconButton onClick={(event: any) => { if (state.gridData.length === 0) { props.dispatch(alertAction.error('There is No Receipt Records')); } else { handleChange('isSummary', event.currentTarget); } }}> <EqualizerIcon></EqualizerIcon> </IconButton> </Tooltip> } options={options} /> </MuiThemeProvider> </div>} </TabPanel> </div> </div> <Dialog aria-labelledby="simple-dialog-title" open={state.isNewReceipt} className={'a-dialog-full'}> <DialogTitle id="simple-dialog-title" className="p-0"> <Toolbar className="border-bottom bg-white pe-0"> <IconButton edge="start" color="inherit" aria-label="menu" onClick={() => handleChange('isNewReceipt', false)}> <ArrowBackIcon /> </IconButton> <Typography variant="h6" className="flex-grow-1">New Receipt Upload</Typography> <ButtonView color="inherit" className='justify-content-end' onClick={() => receiptupload()} startIcon={<SaveIcon></SaveIcon>}> <span className="px-1 pt-1 d-none d-sm-block">Save</span> </ButtonView> </Toolbar> </DialogTitle> <DialogContent> <div className="col-sm-12"> <DatePickerView format={"dd/MM/yyyy"} label="From Date" className="col-12 col-sm-12" value={state.billDate} onChange={handleChange} field={'billDate'}></DatePickerView> </div> <div className="col-sm-12 mb-4"> <DropDownView field={'categoryUuid'} label={'Category Type'} value={state.categoryUuid} required className="col-12 col-sm-12" onChange={(field: string, value: any, obj: any) => handleChange(field, {categoryUuid: obj.uuid, categoryTypeName: obj.categoryTypeName})} dataSource={state.dropDownSource} fields={{ text: 'categoryTypeName', value: 'uuid' }} footerTemlate={() => { return <div className="text-primary" onClick={() => handleChange('isCategoryType', {isCategoryType: true, categoryUuid: '', categoryTypeName: ''})}> <MenuItem value={'addNew'}> <AddIcon></AddIcon> <span className="px-1">{'Add New'}</span> </MenuItem> </div>; }}></DropDownView> </div> <div className="col-sm-12 mb-4"> <DropDownView field={'bankName'} label={'Bank Type'} value={state.bankName} className="col-12 col-sm-12" onChange={(field: string, value: any, obj: any) => handleChange(field, {bankUuid: obj.uuid, bankName: obj.bankName})} dataSource={state.bankDropDownSource} fields={{ text: 'bankName', value: 'bankName' }} footerTemlate={() => { return <div className="text-primary" onClick={() => handleChange('isBankName', {isBankName: true, bankUuid: '', bankName: ''})}> <MenuItem value={'addNew'}> <AddIcon></AddIcon> <span className="px-1">{'Add New'}</span> </MenuItem> </div>; }}></DropDownView> </div> <div className="col-sm-12 mb-4"> <DropDownView field={'spentType'} label={'Spent Type'} value={state.spentType} required className="col-12 col-sm-12" onChange={(field: string, value: any, obj: any) => handleChange(field, {spentTypeUuid: obj.uuid, spentType: obj.spentType})} dataSource={props.spentType} fields={{ text: 'spentType', value: 'spentType' }}> </DropDownView> </div> <div className="col-sm-12 mb-4"> <DropDownView field={'transferType'} label={'Transfer Type'} value={state.transferType} required className="col-12 col-sm-12" onChange={(field: string, value: any, obj: any) => handleChange(field, {transferTypeUuid: obj.uuid, transferType: obj.transferType, transferId: obj.transferId})} dataSource={props.transferType} fields={{ text: 'transferType', value: 'transferType' }}> </DropDownView> </div> <div className="col-sm-12 mb-4"> <TextFieldView label="Amount" type={'number'} field={'amount'} className="col-12 col-sm-12" required value={state.amount} onChange={handleChange} /> </div> <div className="col-sm-12 mb-4"> <ImageView value={state.image} field={'image'} onChange={handleChange}></ImageView> </div> <div className="col-sm-12 mb-4"> <TextFieldView label="Description" className="col-12 col-sm-12" value={state.description} onChange={handleChange} id="filled-multiline-static" multiline rows={4} type={'text'} field={'description'} /> </div> </DialogContent> </Dialog> <Dialog aria-labelledby="simple-dialog-title" open={state.isImageView} className={'a-dialog-md'}> <DialogTitle id="simple-dialog-title" className="p-0"> <Toolbar className="border-bottom bg-white"> <IconButton edge="start" color="inherit" aria-label="menu" onClick={() => handleChange('isImageView', false)}> <ArrowBackIcon /> </IconButton> <Typography variant="h6">Image View</Typography> </Toolbar> </DialogTitle> <DialogContent> <ImageList rowHeight={160} cols={3} className={'a-center-align pb-2'}> <ImageListItem key={state.imageData} cols={1}> <img src={state.imageData} /> </ImageListItem> </ImageList> </DialogContent> </Dialog> {state.isCategoryType && <CategoryTypeView dropDownSource={state.dropDownSource} refresh={(res: any) => { let dropDownSource = state.dropDownSource.concat([res.data]); handleChange('isCategoryType', {isCategoryType: false, dropDownSource: dropDownSource, categoryUuid: res.data.uuid, categoryTypeName: res.data.categoryTypeName}); }} onClose={() => handleChange('isCategoryType', false)}></CategoryTypeView>} {state.isBankName && <BankDetailsView dropDownSource={state.bankDropDownSource} refresh={(res: any) => { let bankDropDownSource = state.bankDropDownSource.concat([res.data]); handleChange('isBankName', {isBankName: false, bankDropDownSource: bankDropDownSource, bankUuid: res.data.uuid, bankName: res.data.bankName}); }} onClose={() => handleChange('isBankName', false)}></BankDetailsView>} <MuiThemeProvider theme={getMuiTheme}> <Menu anchorEl={state.isSummary} keepMounted open={Boolean(state.isSummary)} onClose={() => handleChange('isSummary', null)} anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }} getContentAnchorEl={null}> {state.dropDownSource.map((categoryList: any, index: number) => { let filterData = state.gridData.filter((line: any) => line.categoryUuid === categoryList.uuid); let sumVal = Aggregates.sum(filterData, 'amount'); return <MenuItem className="col-12 row m-0" key={index}> <div className="col-6 p-0 text-secondary">{categoryList.categoryTypeName}</div> <div className="col-6 p-0 fw-bold" align="right">{number2FormatFn(sumVal)}</div> </MenuItem>; })} </Menu> </MuiThemeProvider> </>); } const mapStateToProps = function(state: IState) { return { spentType: state.commonReducer.spentType, transferType: state.commonReducer.transferType, loginCurrentUser: state.loginUser.loginCurrentUser }; }; const mapDispatchToProps = function(dispatch: Dispatch) { return { dispatch: dispatch }; }; export const ReceiptuploadView = connect(mapStateToProps, mapDispatchToProps)(Receiptupload);
#In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. #For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. #The twin sum is defined as the sum of a node and its twin. #Given the head of a linked list with even length, return the maximum twin sum of the linked list. #exercise 2130 from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def pairSum(self, head: Optional[ListNode]) -> int: slow, fast = head, head reverse = None while fast and fast.next:#this is other way to find the middle of the list fast = fast.next.next #this will continue untill the end reverse, reverse.next, slow = slow, reverse, slow.next #on last executation, reverse will be in the middle of the list inverted first = reverse #first half of the original list, reversed second = slow #2nd half of the original list max_sum = -math.inf while first: if first.val + second.val > max_sum: max_sum = first.val + second.val #we are at the middle, so with first we advance untill reach its end (head of the original list) and untill the second reaches to the end first = first.next second = second.next return max_sum
<template> <div :class="$style.mypageMenu"> <div :class="$style.menuContiner"> <div :class="$style.menuBox" v-for="(menu, index) in menuList" :key="index" > <div :class="$style.menuTitle">{{ menu.title }}</div> <div :class="$style.menuItem" v-for="listItem in menu.list" :key="listItem.listNum" > <span :class="$style.listItem" @click="clickMenuList(listItem)">{{ listItem.name }}</span ><br /> </div> <div :class="$style.divideLine"></div> </div> <div :class="$style.info"> <span :class="$style.centerName">고객센터</span> <p :class="$style.phoneNum">051-000-0000</p> <span :class="$style.time">평일 09:00 ~ 18:00</span><br /> <span :class="$style.time">점심시간 12:00 ~ 13:00</span><br /> <span :class="$style.dayOff">주말, 공휴일 휴무</span> </div> </div> </div> </template> <script setup> const emit = defineEmits(["menuItem"]); const menuList = { order: { title: "주문내역", list: [ { name: "주문조회", listNum: 0 }, { name: "취소/교환/환불 내역", listNum: 1 }, ], }, ask: { title: "문의내역", list: [ { name: "1:1문의", listNum: 2 }, { name: "리뷰", listNum: 3 }, ], }, userInfo: { title: "회원 정보", list: [ { name: "회원정보 수정", listNum: 4 }, { name: "회원탈퇴", listNum: 5 }, // { name: '배송지 관리', listNum: 5 }, ], }, }; const clickMenuList = (listItem) => { emit("menuItem", listItem); }; </script> <style src="@/assets/css/layouts/MyPageMenu.css" module></style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="one"> </div> <script> var element = document.getElementById("one"); var object = { language: "bangla" }; Object.defineProperty(object, "f", { get: function() { return this.language.toUpperCase(); } } ); element.innerHTML += object.f + "<br>"; Object.defineProperty(object, "g", { set: function(x) { this.language = x; } } ); object.g = "english"; element.innerHTML += object.f + "<br>"; </script> </body> </html>
import React from 'react'; import { View, Text, Touchable, TouchableOpacity } from 'react-native'; import Background from './Background'; import Btn from './Btn'; import { darkGreen } from './Constants'; import Field from './Field'; const Login = (props) => { return ( <Background> <View style={{ alignItems: 'center', width: '156%' }}> <Text style={{ color: 'white', fontSize: 60, fontWeight: 'bold', marginVertical: 30, }}> Login </Text> <View style={{ backgroundColor: 'white', height: '100%', width: '70%', borderTopLeftRadius: 100, paddingTop: 30, alignItems: 'center', }}> <Text style={{ fontSize: 35, color: darkGreen, fontWeight: 'bold' }}> Welcome Back </Text> <Text style={{ color: 'grey', fontSize: 19, fontWeight: 'bold', marginBottom: 20, }}> Login to your account </Text> <Field placeholder="Email / Username" keyboardType={'email-address'} /> <Field placeholder="Password" secureTextEntry={true} /> <View style={{ alignItems: 'flex-end', width: '68%', paddingRight: 16, marginBottom: 200 }}> <Text style={{ color: darkGreen, fontWeight: 'bold', fontSize: 16 }}> Forgot Password ? </Text> </View> <Btn textColor='white' bgColor={darkGreen} btnLabel="Login" Press={() => alert("Logged In")} /> <View style={{ display: 'flex', flexDirection: 'row', justifyContent: "center" }}> <Text style={{ fontSize: 16, fontWeight: "bold" }}>Don't have an account ? </Text> <TouchableOpacity onPress={() => props.navigation.navigate("Signup")}> <Text style={{ color: darkGreen, fontWeight: 'bold', fontSize: 16 }}>Signup</Text> </TouchableOpacity> </View> </View> </View> </Background> ); }; export default Login;
/* 35) Elaborar um programa em linguagem Java que apresente ao operador o menu abaixo e execute as funções descritas nele: A- Inserir Nó na Árvore (Acesso Pré-Ordenado); B- Apresentar Árvore; B- Eliminar Nó da Árvore (Digitado o Conteúdo do Nó); C- Sair. Observação: O item C deve solicitar a digitação de um Nó, que se existir na árvore, será ser eliminado. Informar todas as possibilidades em tela. Quando eliminar um nó pai que tenha apenas um dos dois nós filhos, esse nó filho assumirá o lugar do nó pai. Quando eliminar um nó pai que tenha os dois nós filhos, o nó filho da direita assumirá o lugar do nó pai e o nó filho da esquerda deverá ser alocado corretamente ao novo nó pai. */ package ArvoreBinaria; import java.util.Scanner; // Definição da classe para o Nó da Árvore Binária class No { int valor; No esquerda; No direita; public No(int valor) { this.valor = valor; esquerda = null; direita = null; } } // Classe para a Árvore Binária class ArvoreBinaria { No raiz; public ArvoreBinaria() { raiz = null; } // Método para inserir um valor na árvore private No inserirRecursivo(No no, int valor) { if (no == null) { return new No(valor); } if (valor < no.valor) { no.esquerda = inserirRecursivo(no.esquerda, valor); } else if (valor > no.valor) { no.direita = inserirRecursivo(no.direita, valor); } return no; } public void inserir(int valor) { raiz = inserirRecursivo(raiz, valor); } // Método para apresentar a árvore em pré-ordem private void apresentarPreOrdemRecursivo(No no) { if (no != null) { System.out.print(no.valor + " "); apresentarPreOrdemRecursivo(no.esquerda); apresentarPreOrdemRecursivo(no.direita); } } public void apresentarPreOrdem() { apresentarPreOrdemRecursivo(raiz); System.out.println(); } // Método para buscar um valor na árvore private boolean buscarRecursivo(No no, int valor) { if (no == null) { return false; } if (valor == no.valor) { return true; } if (valor < no.valor) { return buscarRecursivo(no.esquerda, valor); } else { return buscarRecursivo(no.direita, valor); } } public boolean buscar(int valor) { return buscarRecursivo(raiz, valor); } // Método para eliminar um nó da árvore private No encontrarMinimo(No no) { while (no.esquerda != null) { no = no.esquerda; } return no; } private No removerRecursivo(No no, int valor) { if (no == null) { return null; } if (valor == no.valor) { if (no.esquerda == null && no.direita == null) { return null; } if (no.esquerda == null) { return no.direita; } if (no.direita == null) { return no.esquerda; } No sucessor = encontrarMinimo(no.direita); no.valor = sucessor.valor; no.direita = removerRecursivo(no.direita, sucessor.valor); return no; } if (valor < no.valor) { no.esquerda = removerRecursivo(no.esquerda, valor); return no; } no.direita = removerRecursivo(no.direita, valor); return no; } public void remover(int valor) { raiz = removerRecursivo(raiz, valor); } } // Classe principal que contém o método main public class ex35 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArvoreBinaria arvore = new ArvoreBinaria(); char opcao; do { System.out.println("\nMenu:"); System.out.println("A- Inserir Nó na Árvore (Acesso Pré-Ordenado)"); System.out.println("B- Apresentar Árvore"); System.out.println("C- Eliminar Nó da Árvore (Digitado o Conteúdo do Nó)"); System.out.println("D- Sair"); System.out.print("Escolha uma opção: "); opcao = scanner.next().charAt(0); switch (opcao) { case 'A': case 'a': System.out.print("Digite o valor a ser inserido: "); int valorInserir = scanner.nextInt(); arvore.inserir(valorInserir); break; case 'B': case 'b': System.out.println("Árvore:"); arvore.apresentarPreOrdem(); break; case 'C': case 'c': System.out.print("Digite o valor a ser removido: "); int valorRemover = scanner.nextInt(); if (arvore.buscar(valorRemover)) { arvore.remover(valorRemover); System.out.println("O nó com valor " + valorRemover + " foi removido."); } else { System.out.println("O valor " + valorRemover + " não está na árvore."); } break; case 'D': case 'd': System.out.println("Encerrando o programa..."); break; default: System.out.println("Opção inválida! Por favor, escolha novamente."); } } while (opcao != 'D' && opcao != 'd'); scanner.close(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>创建和删除标签</title> </head> <body> <ul id="city"> <li id="bj">北京</li> <li id="sh">上海</li> <li id="sz">深圳</li> <li id="gz">广州</li> </ul> <script> //目标1: 在城市列表的最后添加一个子标签 <li id="cs">长沙</li> //1. 创建一个li标签 <li></li> var liElement = document.createElement("Li"); //2. 给创建的li标签设置id属性和文本 <li id="cs">长沙</li> liElement.id = "cs"; liElement.innerText = "长沙"; //3. 将创建的li标签添加到城市列表中(ul) var cityUI = document.getElementById("city"); //父.appendChild(子)将子标签添加到父标签的最后面 // cityUl.appendChild(liElement) //目标2:在城市列表的深圳之前添加一个子标签 <li id="cs">长沙</li> //获取到深圳这个标签 var szElement = document.getElementById("sz"); //父.insertBefore(新标签,参照标签) cityUI.insertBefore(liElement,szElement); //目标3: 在城市列表中添加一个子标签替换深圳 <li id="cs">长沙</li> //父.replaceChild(新标签,被替换的标签) cityUI.replaceChild(liElement,szElement) //目标4: 在城市列表中删除深圳 szElement.remove(); //目标5: 清除城市列表中的所有城市,保留城市列表标签ul cityUI.innerHTML = ""; </script> </body> </html>
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:velvet_framework/kernel/exceptions/kernel_is_already_running_exception.dart'; import 'package:velvet_framework/kernel/providers/kernel_bootstrap_provider.dart'; import 'package:velvet_framework/kernel/widgets/kernel_loading_widget.dart'; import 'package:velvet_framework/kernel/widgets/kernel_widget.dart'; import 'package:velvet_framework/kernel/widgets/kerner_error_widget.dart'; typedef Create<T, R extends Ref> = T Function(R ref); class Kernel { Widget? appWidget; KernelErrorWidget? errorWidget; KernelLoadingWidget? loadingWidget; /// A bag of services that will be bootstrapped final List<Create<FutureOr, FutureProviderRef>> _bootstrapServices = []; /// The kernel running status bool _isRunning = false; /// A bag of Riverpod's [ProviderObserver] that will be used by the [ProviderScope] final List<ProviderObserver> _riverpodObservers = []; /// A bag of Riverpod's [Override] that will be used to override the original providers final List<Override> _riverpodOvverides = []; /// Indicates if the kernel is running bool get isRunning => _isRunning; /// Bind a new provider to the list of providers. /// This will override the original provider with the new one. /// /// Useful for replace a service with another one for more scalable implementations or testing. /// /// Internally, this method uses Riverpod's [overrideWith] method. /// /// ```dart /// Kernel() /// ..bind(firebaseProvider, (ref) => FirebaseService()) /// // ... other configurations /// ..run(); /// ``` void bind<T>( Provider<T> original, Create<T, ProviderRef<T>> create, ) { _throwIfRunning(); _riverpodOvverides.add(original.overrideWith(create)); } /// Bind a new provider to the list of providers. /// This will override the original provider with the new one. /// /// Useful for replace a service with another one for more scalable implementations or testing. /// /// Internally, this method uses Riverpod's [overrideWith] method. /// /// ```dart /// Kernel() /// ..bind(firebaseProvider, (ref) => FirebaseService()) /// // ... other configurations /// ..run(); /// ``` void bindAsync<T>( FutureProvider<T> original, Create<FutureOr<T>, FutureProviderRef<T>> create, ) { _throwIfRunning(); _riverpodOvverides.add(original.overrideWith(create)); } /// Add a new service to the list of services that will be bootstrapped /// /// ```dart /// Kernel() /// ..boot(firebaseBootstrap) /// // ... other configurations /// ..run(); /// ``` boot(Create<FutureOr, FutureProviderRef> create) { _throwIfRunning(); _bootstrapServices.add(create); } /// Add a list of services to the list of services that will be bootstrapped /// Internally, this method uses the [boot] method /// /// ```dart /// Kernel() /// ..bootMany([firebaseBootstrap, deviceOrientationBootstrap]) /// // ... other configurations /// ..run(); /// ``` bootMany(List<Create<FutureOr, FutureProviderRef>> creates) { _throwIfRunning(); _bootstrapServices.addAll(creates); } /// Add a new observer to the list of observers /// that will be used by the [ProviderScope] /// /// Coupled with Riverpod's [ProviderObserver] /// /// ```dart /// Kernel() /// ..observe(TalkerRiverpodObserver(talker: talkerGlobalInstance)) /// // ... other configurations /// ..run(); /// ``` void observe(ProviderObserver observer) { _throwIfRunning(); _riverpodObservers.add(observer); } // Set the initialization's error widget of the application /// If not set, the default error widget will be used /// /// IMPORTANT: The widget must return a MaterialApp at its root void usingError(KernelErrorWidget errorWidget) { _throwIfRunning(); this.errorWidget = errorWidget; } /// Set the initialization's loading widget of the application /// If not set, the default loading widget will be used /// /// IMPORTANT: The widget must return a MaterialApp at its root void usingLoading(KernelLoadingWidget loadingWidget) { _throwIfRunning(); this.loadingWidget = loadingWidget; } /// Run the application /// /// This method should be called at the end of the configuration /// /// ```dart /// Kernel() /// ..boot(firebaseBootstrap) /// ..observe(TalkerRiverpodObserver(talker: talkerGlobalInstance)) /// ..run(); /// ``` /// /// This will initialize the application with the provided configuration. void run() { _throwIfRunning(); _setAsRunning(); WidgetsFlutterBinding.ensureInitialized(); runApp( ProviderScope( observers: _riverpodObservers, overrides: [ ..._riverpodOvverides, kernelBootstrapProvider.overrideWith((ref) async { for (var service in _bootstrapServices) { service(ref); } }), ], child: KernelWidget( errorWidget: errorWidget, loadingWidget: loadingWidget, ), ), ); } /// Check if the kernel is running. /// If it is, throw a [KernelIsAlreadyRunningException] /// to prevent the user from changing the configuration /// while the application is already running. _throwIfRunning() { if (isRunning) { throw KernelIsAlreadyRunningException(); } } /// Set the kernel as running void _setAsRunning() { _isRunning = true; } }
const jsBackgroundWaves = document.getElementById("js-background-waves"); const jsStartButton = document.getElementById("js-start-button"); const jsWelcomeMessage = document.getElementById("js-welcome-message"); const jsScoreCounter = document.getElementById("js-score-counter"); const jsContainer = document.getElementById("js-container"); const jsShark = document.getElementById("js-shark"); const jsGameOverMessage = document.getElementById("js-game-over-message"); let userReady = false; let fishArray = []; function spawnFish() { let fish = document.createElement("div"); fish.classList.add("fish"); fish.style.backgroundColor = "yellow"; fish.style.position = "absolute"; fish.style.left = "0"; fishHeight = jsContainer.clientHeight * 0.15; fish.style.top = `${ Math.random() * (jsContainer.clientHeight - fishHeight) }px`; jsContainer.appendChild(fish); fishArray.push(fish); } function moveFish() { for (let i = fishArray.length - 1; i >= 0; i--) { let fish = fishArray[i]; let fishLeftPosition = parseInt(fish.style.left, 10); let leftMovementRange = jsContainer.clientWidth / 25; fish.style.left = `${ fishLeftPosition + Math.random() * leftMovementRange }px`; let fishHeight = parseInt(fish.offsetHeight, 10); let fishTopPosition = parseInt(fish.style.top, 10); let topMovementRange = ((Math.random() - 0.5) * jsContainer.clientHeight) / 15; let newTopPosition = fishTopPosition + topMovementRange; if (newTopPosition > jsContainer.clientHeight - fishHeight) { newTopPosition = jsContainer.clientHeight - fishHeight; } if (newTopPosition < 0) { newTopPosition = 0; } fish.style.top = `${newTopPosition}px`; if (fishSharkCollision(fish, jsShark)) { console.log(`Collision with fish ${i}`); jsContainer.removeChild(fish); fishArray.splice(i, 1); } else if (fishLeftPosition >= jsContainer.clientWidth) { console.log(`Fish off screen at index ${i}`); jsContainer.removeChild(fish); fishArray.splice(i, 1); } } } let score = 0; function fishSharkCollision(fish, jsShark) { let fishBCRect = fish.getBoundingClientRect(); let jsSharkBCRect = jsShark.getBoundingClientRect(); if ( fishBCRect.x + fishBCRect.width > jsSharkBCRect.x && fishBCRect.x < jsSharkBCRect.x + jsSharkBCRect.width && fishBCRect.y + fishBCRect.height > jsSharkBCRect.y && fishBCRect.y < jsSharkBCRect.y + jsSharkBCRect.height ) { score++; console.log(`Score: ${score}`); jsScoreCounter.innerHTML = `Score: ${score}`; return true; } else { return false; } } function gameStart() { if (counter >= 1 || score >= 1) { resetGame(); } jsWelcomeMessage.style.display = "none"; jsScoreCounter.style.display = "block"; jsGameOverMessage.style.display = "none"; userReady = true; spawnTimer = setInterval(spawnFish, 1000); movementTimer = setInterval(moveFish, 250); countdownTimer = setInterval(countdown, 100); } function resetGame() { counter = 0; score = 0; jsScoreCounter.innerHTML = "Score: 0"; fishArray.forEach((fish) => { jsContainer.removeChild(fish); }); fishArray = []; } const jsStartButtons = document.querySelectorAll(".start-button"); jsStartButtons.forEach(function (button) { button.addEventListener("click", gameStart); }); let counter = 0; function countdown() { counter++; console.log(`Timer: ${counter}`); if (counter >= 15) { stopGame(); } } const jsResultNumber = document.getElementById("js-result-number"); const jsPlayerScore = document.getElementById("js-player-score"); function stopGame() { userReady = false; //moveShark function cannot be moved anymore. Shark //object cannot be moved by player. preventDefault() also disabled so //text input field in gameOverScreen takes keydown inputs. clearInterval(spawnTimer); clearInterval(movementTimer); clearInterval(countdownTimer); jsScoreCounter.style.display = "none"; gameOverScreen(); } function gameOverScreen() { jsGameOverMessage.style.display = "block"; jsResultNumber.innerHTML = `${score}`; jsResultNumber.style.fontSize = "1.5rem"; jsPlayerScore.value = `${score}`; } const scoreForm = document.getElementById("scoreform"); scoreForm.addEventListener("submit", function (e) { e.preventDefault(); const scoreFormData = new FormData(scoreform); const playerName = scoreFormData.get("playername"); scoreForm.innerHTML = `<div class="loading-box"> <img src="img/loading.svg" class="loading" alt="loading"> <p>Submitting your score</p> </div>`; setTimeout(function () { scoreForm.innerHTML = `<p>Thanks for playing ${playerName}. Score submitted!</p>`; }, 2000); }); /* Move Shark Up and Down ====== */ function moveShark(event) { event.preventDefault(); let step = 15; let currentPosition = parseInt(jsShark.style.top, 10) || 0; switch (event.key) { case "ArrowUp": currentPosition = Math.max(currentPosition - step, 0); break; case "ArrowDown": currentPosition = Math.min( currentPosition + step, jsContainer.clientHeight - jsShark.clientHeight ); break; } jsShark.style.top = currentPosition + "px"; } window.addEventListener("keydown", (event) => { if (userReady === true) { moveShark(event); } });
import 'package:flutter/material.dart'; import '../../../app/extensions.dart'; class FadeInAnimWidget extends StatefulWidget { const FadeInAnimWidget( {super.key, required this.child, required this.durationMilliSec, this.delayMilliSec = 0, this.curve = Curves.linear}); final Widget child; final int durationMilliSec; final int delayMilliSec; final Curve curve; @override State<FadeInAnimWidget> createState() => _FadeInAnimWidgetState(); } class _FadeInAnimWidgetState extends State<FadeInAnimWidget> with SingleTickerProviderStateMixin { late final AnimationController _animationController; late final CurvedAnimation _curvedAnimation; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: widget.durationMilliSec.getMilliSec()); _curvedAnimation = CurvedAnimation(parent: _animationController, curve: widget.curve); Future.delayed(widget.delayMilliSec.getMilliSec()).then((value) { if (mounted) _animationController.forward(); }); } @override void dispose() { _curvedAnimation.dispose(); _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _animationController, builder: (context, child) { return Opacity( opacity: _curvedAnimation.value, child: child, ); }, child: widget.child, ); } }
// nextjs import { getServerSession } from "next-auth"; import { NextRequest } from "next/server"; // auth import authOptions from "../../auth/[...nextauth]/authOptions"; // helpers import { ResponseFormating } from "@/lib/helpers/helpers"; // validation request import { ExamAnswerInputValidation } from "@/lib/validation/request"; // types import { SessionType } from "@/lib/types/ResultTypes"; import { ExamAnswerSearchParamType } from "@/lib/types/InputTypes"; // services import { SaveExamAnswer, GetExamAnswer } from "@/lib/services/mysql/examAnswer"; /** * Get Exam Answer * ------------------------- */ export async function GET(request: NextRequest) { // session const session = (await getServerSession(authOptions)) as SessionType; // url params const { searchParams } = new URL(request.url); const examSearch: ExamAnswerSearchParamType = { page: searchParams.get("page") ?? "", limit: searchParams.get("limit") ?? "", keyword: searchParams.get("keyword") ?? "", id_exam: searchParams.get("id_exam") ?? "", id_user: searchParams.get("id_user") ?? "", }; // logic const res = await GetExamAnswer(examSearch, session); // response api const data = { totalRow: res.totalRow, totalPage: res.totalPage, data: res.data, }; return ResponseFormating.json(res.message, res.code, data); } /** * Save Exam Answer * ------------------------- */ export async function POST(request: NextRequest) { // session const session = (await getServerSession(authOptions)) as SessionType; // json const req = await request.json(); // validation const validationResult = ExamAnswerInputValidation.safeParse(req); if (!validationResult.success) { return ResponseFormating.json( "validation failed", 400, ResponseFormating.zodErrors(validationResult.error) ); } // logic const res = await SaveExamAnswer(req, session); // response api return ResponseFormating.json(res.message, res.code, res.data); }
<template> <van-button class="border-radius-10" size="mini" type="primary" :disabled="disables || time > 0" @click="run" > {{ btnText }} </van-button> </template> <script> import { Button } from "vant"; import api from "@/api"; import Vue from "vue"; // 谷歌验证 import { VueReCaptcha } from "vue-recaptcha-v3"; Vue.use(VueReCaptcha, { siteKey: "6LchlZ0UAAAAAB-69cFKResZKh-9mlrwPuVPNQVX", loaderOptions: { useRecaptchaNet: true } }); export default { components: { vanButton: Button }, props: { second: { type: Number, default: 60 }, phone: { required: true, default: null }, purpose: { type: String, required: true } }, data() { return { time: 0, disables: false }; }, computed: { btnText() { return this.time > 0 ? this.time + `s 重新发送` : "获取验证码"; } }, methods: { run() { const self = this; if (!self.phone || self.phone.length != 11) { self.$Toast({ message: "电话号码错误,请重新输入!" }); return; } self.start(); self.setDisabled(true); this.getSmscode(); }, getSmscode() { const self = this; api .sendVerifyCode({ mobile: self.phone, userType: 3 }) .then(res => { if (res.success) { self.$Toast({ message: res.msg }); } else { self.$Toast({ message: res.msg || "发送失败" }); } }); }, start() { this.time = this.second; this.timer(); }, setDisabled(val) { this.disables = val; }, timer() { if (this.time > 0) { this.time--; setTimeout(this.timer, 1000); } else { this.setDisabled(false); } } } }; </script>
const { SlashCommandBuilder, EmbedBuilder } = require("discord.js"); const { sendTradeRequest, acceptTradeRequest, } = require("../../../game/game.js"); const execute = async (interaction) => { const userToTrade = interaction.options.getUser("user"); const embed = new EmbedBuilder().setAuthor({ name: interaction.member.displayName, iconURL: interaction.member.displayAvatarURL(), }); if (userToTrade.bot) { embed.setDescription("You can't trade with bots"); } else if (userToTrade.id === interaction.user.id) { embed.setDescription("You can't trade with yourself"); } else { const cardsToTrade = JSON.parse(interaction.options.getString("away")); const cardsToReceive = JSON.parse(interaction.options.getString("for")); const trade = sendTradeRequest( interaction.user.id, userToTrade.id, cardsToTrade, cardsToReceive ); if (trade.success) { embed.setTitle("Trade sent successfully").addFields([ { name: "You are trading away", value: cardsToTrade .map((card) => `${card.name} (${card.count})`) .join("\n"), inline: true, }, { name: "You are trading for", value: cardsToReceive .map((card) => `${card.name} (${card.count})`) .join("\n"), inline: true, }, ]); userToTrade.createDM().then(async (channel) => { const tradeRequestEmbed = new EmbedBuilder() .setAuthor({ name: interaction.member.displayName, iconURL: interaction.member.displayAvatarURL(), }) .setTitle(`Trade request from ${interaction.member.displayName}`) .addFields([ { name: "You are trading away", value: cardsToReceive .map((card) => `${card.name} (${card.count})`) .join("\n"), inline: true, }, { name: "You are trading for", value: cardsToTrade .map((card) => `${card.name} (${card.count})`) .join("\n"), inline: true, }, ]) .setFooter({ text: "✅ to accept, ❎ to decline" }); const message = await channel.send({ embeds: [tradeRequestEmbed] }); Promise.all([message.react("✅"), message.react("❎")]); message .awaitReactions({ filter: (reaction) => ["✅", "❎"].includes(reaction.emoji.name), max: 1, time: 60000, errors: ["time"], }) .then(async (collected) => { const reaction = collected.first(); if (reaction.emoji.name === "✅") { const tradeResult = acceptTradeRequest(trade.id); if (tradeResult.success) { await message.edit( new EmbedBuilder() .setAuthor({ name: interaction.member.displayName, iconURL: interaction.member.displayAvatarURL(), }) .setTitle( `Trade request from ${interaction.member.displayName}` ) .setDescription("Trade accepted") ); } else { await message.edit( tradeRequestEmbed .setDescription("Trade unsuceessful") .addFields([ { name: "Reason", value: tradeResult.message, inline: false, }, ]) ); } } else { await message.edit( tradeRequestEmbed.setDescription("Trade declined") ); } }); }); } else { embed .setTitle("Trade request unsuccessful") .setDescription(tradeResult.message); } } await interaction.reply({ embeds: [embed] }); }; module.exports = { data: new SlashCommandBuilder() .setName("trade") .setDescription("Trade cards with other users") .addUserOption((option) => option .setName("user") .setDescription("User to trade with") .setRequired(true) ) .addStringOption((option) => option .setName("away") .setDescription("Cards to trade away") .setRequired(true) ) .addStringOption((option) => option .setName("for") .setDescription("Cards to trade for") .setRequired(true) ), execute: execute, };
import React, { useRef } from "react"; import "./SideBar.css"; import Input from "../UI/Input/Input"; // Assuming Input component is defined export default function NewsletterSignUp() { const emailRef = useRef(null); const InvalidMsg = () => { const emailInput = emailRef.current; if (emailInput.value === "") { emailInput.setCustomValidity("Required email address"); } else if (emailInput.validity.typeMismatch) { emailInput.setCustomValidity("Please enter a valid email address"); } else { emailInput.setCustomValidity(""); } }; const handleFormSubmit = (event) => { event.preventDefault(); InvalidMsg(); if (emailRef.current.checkValidity()) { console.log("Form submitted with email:", emailRef.current.value); } }; return ( <div className="newsletter__container"> <div className="newsletter__container-title"> <h3>Newsletter</h3> </div> <div className="newsletter__container__input-title"> <h3>Design News to your inbox</h3> </div> <div className="newsletter__container__input"> <form onSubmit={handleFormSubmit}> <Input ref={emailRef} className="mb-2" type="email" placeholder="Email Address" required /> <button type="submit"> Sign Up </button> </form> </div> </div> ); }
import 'package:flutter/material.dart'; import 'package:smart_training_kits/helper/shared_files.dart'; import 'package:smart_training_kits/helper/styles.dart'; import 'text_field.dart'; class TextFieldContainer extends StatelessWidget { TextEditingController textEditingController; TextInputType? keyboardType; bool readOnly; bool isLastField; IconData? icon; String? hint; void Function()? onTap; Function(String)? onChanged; Function()? onToggle; bool? showText; TextFieldContainer({ Key? key, required this.textEditingController, this.keyboardType, this.readOnly = false, this.isLastField = false, this.hint, this.onChanged, this.onTap, this.icon, this.onToggle, this.showText, }) : super(key: key); @override Widget build(BuildContext context) { return Opacity( opacity: readOnly ? 0.7 : 1, child: GestureDetector( onTap: onTap, child: Container( // height: 50, margin: EdgeInsets.only(bottom: AppMethods.DEFAULT_PADDING / 2), decoration: BoxDecoration( color: Theme.of(context).canvasColor, border: Border.all( color: Theme.of(context).dividerColor, ), borderRadius: BorderRadius.circular( 8, ), ), padding: const EdgeInsets.symmetric( vertical: 8, horizontal: 20, ), child: IgnorePointer( ignoring: onTap != null, child: Row( children: [ Expanded( child: AppTextField( textEditingController: textEditingController, // icon: icon, isLastField: isLastField, key: key, onChanged: onChanged, onTap: onTap, keyboardType: keyboardType, hint: hint, readOnly: readOnly, showText: showText, style: textStyle( context: context, fontSize: FontSize.H4, // isBold: true, color: Theme.of(context).shadowColor, ), hintStyle: textStyle( context: context, fontSize: FontSize.H4, color: Theme.of(context).splashColor, ), ), ), ], ), ), ), ), ); } }
package com.example.blooddonationsystem.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ControllerExceptionHandler { @ExceptionHandler(value = UserEmailExistsException.class) public ResponseEntity<?> userEmailExistsException(){ return new ResponseEntity<>("Korisničko ime je zauzeto", HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = InvalidDataException.class) public ResponseEntity<?> invalidDataException() { return new ResponseEntity<>("Neispravni podaci", HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = UserNotFoundException.class) public ResponseEntity<?> userNotFoundException(){ return new ResponseEntity<>("Korisnik nije pronađen", HttpStatus.NOT_FOUND); } @ExceptionHandler(value = BloodCenterNotFoundException.class) public ResponseEntity<?> bloodCenterNotFoundException(){ return new ResponseEntity<>("Centar nije pronađen", HttpStatus.NOT_FOUND); } @ExceptionHandler(value = ChangeImageException.class) public ResponseEntity<?> changeImageException() { return new ResponseEntity<>("Neuspješna izmjena slike", HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(value = NotEligibleToDonateBloodException.class) public ResponseEntity<?> notEligibleToDonateBloodException() { return new ResponseEntity<>("Nije prošao odgovarajući vremenski period od prethodnog davanja krvi." + " Interval između davanja krvi je 3 mjeseca za muškarce i 4 mjeseca za žene.", HttpStatus.CONFLICT); } @ExceptionHandler(value = NoFreeAppointmentsException.class) public ResponseEntity<?> noFreeAppointmentsException() { return new ResponseEntity<>("Nema slobodnih termina za odabrani datum", HttpStatus.CONFLICT); } @ExceptionHandler(value = PasswordIncorrectException.class) public ResponseEntity<?> passwordIncorrectException() { return new ResponseEntity<>("Neispravan unos stare lozinke", HttpStatus.BAD_REQUEST); } }
--- Egg collector --- Written by Sander Alsema for the 10-liner competition 2018. Language: Commodore 64 Basic v2 Category: PUR-80 I prefer VICE, but you can use any emulator that works with *.d64 files. If you haven't installed it yet, it can be downloaded from their website. Here's how to use it: Click : File -> Attach disk image -> Drive 8 Select: Egg collector.d64 Click : Attach Now, just as you would with a normal Commodore 64, you can type: LOAD"$",8 (to load the directory) LOAD"EGG COLLECTOR",8 (to load the game) LIST (to view the directory or game listing) RUN (to run the game) Be aware that you are now using a virtual Commodore 64 keyboard. Therefore the keys will differ slightly from your physical keyboard. Use <SHIFT> '2' to display quotation marks. --- In this game you work on a farm, and it's your job to collect freshly laid goose eggs. The goose, however, is loose!!! It will not come down from the ceiling, but continues to lay eggs. You have no other option but to try to catch them in a little nest. You can move the nest: to the left by pressing '<' to the right by pressing '>' If you move the nest offscreen, it will reappear in the center. When you have dropped five eggs, the game is over. --- Line 0: Clear the horizontal and vertical 'orientation' strings. Make sure that a clear screen is the first thing that is displayed. Build the orientation strings with cursor movements, right and down. Set the nest to begin in the center. Set the goose to begin in the center. Set the goose's destination to begin in the same place. No eggs falling yet. Clear the number of eggs caught. Line 1: Read the goose-string and the clear-goose-string from somewhere else in the program to make efficient use of available space. Clear the number of eggs dropped. Set the border colour to purple. Set the background colour to blue. Line 2: Build the 'position' string for the nest, by making use of parts of the orientation strings. Build the 'position' string for the goose, by making use of parts of the orientation strings. Clear the old goose. Display the new goose. Display the nest. (without carriage return) Line 3: If the goose has reached its destination: - Randomly choose a new destination. - If no egg is currently falling then start laying an egg. - If five eggs have been dropped, then jump to line 9. Line 4: If the falling egg has reached the level of the nest, and the nest is actually there: - Stop the egg from falling. - Clear the egg. - Increase the number of eggs caught. Line 5: If the egg is falling: - Display the egg, by making use of parts of the orientation strings. (without carriage return) - The next egg will be one screen line lower. - If the egg has reached the bottom, then stop the egg from falling and increase the number of eggs dropped. Line 6: Read the keyboard. If the pressed key was ',' or '.' (meaning '<' or '>'): - Clear the nest. - Calculate the new position of the nest using the ascii value of the pressed key. - If the nest goes offscreen then reposition it in the center. Line 7: If the goose is not at its destination, then move one step towards it. Line 8: Set the position string for clearing the old goose to the current position string of the goose. Jump to line 2. This line also holds the data for the goose string and its clearing string. Line 9: Display "GAME OVER" and the number of eggs caught. Wait a little while. Restart the game. ---
/* eslint-disable @typescript-eslint/no-explicit-any */ import TypedEvent from './TypedEvent'; import { isTypedMessage } from './TypedMessage'; type ListenerSignature<L> = { [E in keyof L]: (...args: any[]) => any; }; type DefaultListener = { [k: string]: (...args: any[]) => any; }; // interface TypedEventTarget<L extends ListenerSignature<L> = DefaultListener> { // on<U extends keyof L>(event: U, listener: L[U]): this; // off<U extends keyof L>(event: U, listener: L[U]): this; // dispatchEvent<U extends keyof L>(event: U, ...args: Parameters<L[U]>): boolean; // } interface TypedEventListener { (event: TypedEvent): void; } type ListenerPair<T = unknown> = readonly [T, TypedEventListener]; export default class TypedEventTarget< L extends ListenerSignature<L> = DefaultListener, > extends EventTarget { #listeners: { [P in keyof L]?: ListenerPair<L[P]>[] } = {}; constructor(readonly target: string) { super(); window.addEventListener('message', this.#eventListener); } #eventListener = (e: MessageEvent): void => { const { data, source } = e; if (source !== window || !isTypedMessage(data, this.target)) return; this.dispatchEvent(new TypedEvent(data.type, data.payload)); }; on<U extends keyof L>(event: U, listener: L[U], once = false): this { const eventListener: TypedEventListener = e => listener(e.payload); if (!this.#listeners[event]) { this.#listeners[event] = []; } const listeners = this.#listeners[event]; listeners?.push([listener, eventListener]); this.addEventListener(event as string, eventListener, { once }); return this; } once<U extends keyof L>(event: U, listener: L[U]): this { return this.on(event, listener, true); } off<U extends keyof L>(event: U, listener: L[U]): this { const listeners = this.#listeners[event]; if (listeners) { const index = listeners.findIndex(item => item[0] === listener); if (index !== -1) { const [[, eventListener]] = listeners.splice(index, 1); this.removeEventListener(event as string, eventListener); } } return this; } release(): void { Object.entries(this.#listeners).forEach(([event, listeners]) => { (listeners as ListenerPair[]).forEach(([, eventListener]) => this.removeEventListener(event, eventListener), ); }); this.#listeners = {}; window.removeEventListener('message', this.#eventListener); } }
#include <gtest/gtest.h> #include <AllegroFlare/Testing/ErrorAssertions.hpp> #include <AllegroFlare/Testing/WithAllegroRenderingFixture.hpp> #include <AllegroFlare/Color.hpp> class AllegroFlare_Elements_TextTest : public ::testing::Test {}; class AllegroFlare_Elements_TextTestWithAllegroRenderingFixture : public AllegroFlare::Testing::WithAllegroRenderingFixture {}; #include <AllegroFlare/Elements/Text.hpp> TEST_F(AllegroFlare_Elements_TextTest, can_be_created_without_blowing_up) { AllegroFlare::Elements::Text text; } TEST_F(AllegroFlare_Elements_TextTest, render__without_allegro_initialized__raises_an_error) { AllegroFlare::Elements::Text text; std::string expected_error_message = "Text::render: error: guard \"al_is_system_installed()\" not met"; ASSERT_THROW_WITH_MESSAGE(text.render(), std::runtime_error, expected_error_message); } TEST_F(AllegroFlare_Elements_TextTestWithAllegroRenderingFixture, render__without_a_font_bin__will_throw_an_error) { AllegroFlare::Elements::Text text; std::string expected_error_message = "Text::obtain_font: error: guard \"font_bin\" not met"; ASSERT_THROW_WITH_MESSAGE(text.render(), std::runtime_error, expected_error_message); } TEST_F(AllegroFlare_Elements_TextTestWithAllegroRenderingFixture, CAPTURE__render__will_draw_the_text_to_the_screen) { AllegroFlare::FontBin &font_bin = get_font_bin_ref(); AllegroFlare::Elements::Text text(&font_bin); text.render(); al_flip_display(); } TEST_F(AllegroFlare_Elements_TextTestWithAllegroRenderingFixture, fit_placement_width_and_height_to_text__will_set_the_placement_width_and_height_to_the_dimensions_of_the_text) { AllegroFlare::FontBin &font_bin = get_font_bin_ref(); AllegroFlare::Elements::Text text(&font_bin); text.fit_placement_width_and_height_to_text(); EXPECT_EQ(192, text.get_placement().size.x); EXPECT_EQ(48, text.get_placement().size.y); } TEST_F(AllegroFlare_Elements_TextTestWithAllegroRenderingFixture, CAPTURE__render__with_customizations_on_color_font_identifier_and_font_size__will_render_as_expected) { AllegroFlare::FontBin &font_bin = get_font_bin_ref(); AllegroFlare::Elements::Text text(&font_bin); text.fit_placement_width_and_height_to_text(); text.set_text("This is Custom Text"); text.set_font_identifier("plantin-mt-light.ttf"); text.set_font_size(-120); text.set_color(AllegroFlare::Color::Aquamarine); text.get_placement_ref().position.x = 1920/2; text.get_placement_ref().position.y = 1080/2; text.render(); al_flip_display(); }
const express = require("express"); const cors = require('cors'); const mongoose = require("mongoose"); require("dotenv").config(); const app = express(); const PORT = process.env.PORT || 5000; // Middleware app.use(cors()); app.use(express.json()); // Connect to MongoDB const connectDB = require("./config/db"); connectDB(); // Routes app.get("/", (req, res) => { res.send("Library Management System API"); }); // Use the books route const booksRouter = require("./routes/books"); app.use("/api/books", booksRouter); // Use the members route const membersRouter = require("./routes/members"); app.use("/api/members", membersRouter); // Use the issues route const issuesRouter = require("./routes/issues"); app.use("/api/issues", issuesRouter); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
--- title: QT5 C++11 Lambda Error date: 2020-07-10 16:20:08 tags: [QT, C/C++, CODE, SUMMERTERM, ERROR] description: "An unexpected error of Lambda Expression when using connect in QT5 C++11" --- {% note warning %} # QT Lambda 表达式在 connect 时 error 依旧在这个折磨人的小学期 第一次接触到 **Lambda** 表达式,以及它在 QT 的 `connect` 函数中的运用 但是当自己写的时候,却发现不是那回事 ## 我的情况 我在将一个 button 连接,但是我希望只有在 button 点击的时候,才在相应的位置上 new 这样我就可以只定义二维指针数组,而不需要立即为他们分配内存 在 h 文件中,有他们的二维指针数组 ```cpp class Gmae : public QWidget { ... private: QPushButton *mapButton[12][7]; Tower *tower[12][7]; }; ``` 在 cpp 中,`mapButton` 已经 `new` 过了 ```cpp // j, i 是因为 ij 是二维数组式的行列下标,而 QT 中为 xy connect(mapButton[j][i], SIGNAL(click(bool)), [=]() { tower[j][i] = new Tower(this); }); ``` 然后就 error 了😭,会告诉你没有合适的 **candidate** ## 问题原因 出现这个问题,根据我的最终解决方案和推测,是这样的 QT 从 5 开始,才支持 C++11 的 **Lambda** 表达式,而同时,QT5 对 `connect` 稍有修改 由原来的 ```qt connect(*sender, SIGNAL(senderSignal()), *receiver, SLOT(receiverSlot())); ``` 修改为了 ```cpp connect(*sender, &SenderClass::signal, *receiver, &ReceiverClass::slot); ``` 但是同时,兼容旧版的 `connect` 函数 但是 `Lambda` 表达式的 `connect` 函数并不支持旧版 当参数中用了 `Lambda` 表达式,会自动以 5 之后的标准看待这个 `connect` 函数 ## 解决 所以解决方案也很简单 ```cpp connect(mapButton[j][i], &QPushButton::click, [=]() { tower[j][i] = new Tower(this); }); ``` 我觉得对于这个问题,与下一篇的 `#pragma once` 放在一起看,会对新旧标注以及兼容性有一点自己的想法吧 {% endnote %}
package types import "strings" type Enum struct { fields []string } func NewEnum(fields ...string) *Enum { return &Enum{fields} } func (t *Enum) Equals(other Type) bool { if t2 := AsPrimitive(other); t2 != nil { return t2.kind == KindAny } if t2 := AsEnum(other); t2 != nil { if len(t2.fields) != len(t.fields) { return false } for i := range t.fields { if t.fields[i] != t2.fields[i] { return false } } return true } return false } func (t *Enum) Underlying() Type { return t } func (t *Enum) String() string { buf := strings.Builder{} buf.WriteString("enum{") first := true for _, field := range t.fields { if !first { buf.WriteString("; ") } buf.WriteString(field) first = false } buf.WriteByte('}') return buf.String() } func (t *Enum) Fields() []string { return t.fields } func IsEnum(t Type) bool { return AsEnum(t) != nil } func AsEnum(t Type) *Enum { if t != nil { if e, _ := t.Underlying().(*Enum); e != nil { return e } } return nil }
/* * Copyright 2022 Tadashi G. Takaoka * * 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. */ #include <Arduino.h> #include <AUnit.h> #include <libcli/fake/FakeStream.h> using FakeStream = libcli::fake::FakeStream; test(printTest, empty) { FakeStream stream; assertEqual(stream.printerLength(), 0); assertEqual(stream.printerText(), ""); stream.flush(); } test(printTest, writeChar) { FakeStream stream; assertEqual((int)stream.write('c'), 1); assertEqual(stream.printerText(), "c"); assertEqual((int)stream.write('x'), 1); assertEqual(stream.printerText(), "cx"); assertEqual((int)stream.println(), 2); assertEqual(stream.printerText(), "cx\r\n"); stream.flush(); assertEqual(stream.printerLength(), 0); assertEqual(stream.printerText(), ""); } test(printTest, writeText) { FakeStream stream; assertEqual((int)stream.write((const uint8_t *)"abcde", 3), 3); assertEqual(stream.printerText(), "abc"); assertEqual((int)stream.write((const uint8_t *)"xyzw", 4), 4); assertEqual(stream.printerText(), "abcxyzw"); stream.flush(); assertEqual(stream.printerLength(), 0); assertEqual(stream.printerText(), ""); } test(streamTest, empty) { FakeStream stream; assertEqual(stream.available(), 0); assertEqual(stream.peek(), -1); assertEqual(stream.read(), -1); } test(streamTest, letter) { FakeStream stream; stream.setInput('A'); assertEqual(stream.available(), 1); assertEqual(stream.peek(), (int)'A'); assertEqual(stream.read(), (int)'A'); assertEqual(stream.available(), 0); stream.setInput('x'); assertEqual(stream.available(), 1); assertEqual(stream.peek(), (int)'x'); assertEqual(stream.read(), (int)'x'); assertEqual(stream.available(), 0); } test(streamTest, text) { FakeStream stream; { char text[] = {'a', 'b', 'c', 0}; stream.setInput(text); } assertEqual(stream.available(), 3); assertEqual(stream.peek(), (int)'a'); assertEqual(stream.read(), (int)'a'); assertEqual(stream.available(), 2); assertEqual(stream.peek(), (int)'b'); assertEqual(stream.read(), (int)'b'); assertEqual(stream.available(), 1); assertEqual(stream.peek(), (int)'c'); assertEqual(stream.read(), (int)'c'); assertEqual(stream.available(), 0); assertEqual(stream.peek(), -1); assertEqual(stream.read(), -1); assertEqual(stream.available(), 0); assertEqual(stream.peek(), -1); assertEqual(stream.read(), -1); } test(streamTest, text_P) { FakeStream stream; stream.setInput(PSTR("abc")); assertEqual(stream.available(), 3); assertEqual(stream.peek(), (int)'a'); assertEqual(stream.read(), (int)'a'); assertEqual(stream.available(), 2); assertEqual(stream.peek(), (int)'b'); assertEqual(stream.read(), (int)'b'); assertEqual(stream.available(), 1); assertEqual(stream.peek(), (int)'c'); assertEqual(stream.read(), (int)'c'); assertEqual(stream.available(), 0); assertEqual(stream.peek(), -1); assertEqual(stream.read(), -1); assertEqual(stream.available(), 0); assertEqual(stream.peek(), -1); assertEqual(stream.read(), -1); } test(streamTest, text_F) { FakeStream stream; stream.setInput(F("abc")); assertEqual(stream.available(), 3); assertEqual(stream.peek(), (int)'a'); assertEqual(stream.read(), (int)'a'); assertEqual(stream.available(), 2); assertEqual(stream.peek(), (int)'b'); assertEqual(stream.read(), (int)'b'); assertEqual(stream.available(), 1); assertEqual(stream.peek(), (int)'c'); assertEqual(stream.read(), (int)'c'); assertEqual(stream.available(), 0); assertEqual(stream.peek(), -1); assertEqual(stream.read(), -1); assertEqual(stream.available(), 0); assertEqual(stream.peek(), -1); assertEqual(stream.read(), -1); } void setup() {} void loop() { aunit::TestRunner::run(); } // Local Variables: // mode: c++ // c-basic-offset: 4 // tab-width: 4 // End: // vim: set ft=cpp et ts=4 sw=4:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> * { padding: 0px; margin: 0px; } .banner { width: 600px; margin: auto; border: 1px solid green; height: 350px; position: relative; overflow: hidden; } .imgList img { width: 600px; height: 350px; } .imgList { /* 绝对定位 */ position: absolute; /* left:-600px; */ /* width: 2600px; */ } .imgList li { float: left; margin-right: 20px; list-style: none; } .circle { position: absolute; bottom: 15px; left: 50%; transform: translateX(-50%); } .circle a { width: 15px; height: 15px; background: green; display: block; border-radius: 50%; opacity: .8; float: left; margin-right: 10px; } .circle a.hover { background: black; opacity: .7; } </style> </head> <body> <div class="banner"> <ul class="imgList"> <li><img src="img/flex1.jpg" /></li> <li><img src="img/flex2.jpg" /></li> <li><img src="img/flex1.jpg" /></li> <li><img src="img/flex2.jpg" /></li> </ul> <div class="circle"> <!-- <a href="javascript:;"></a> <a href="javascript:;"></a> --> </div> </div> <!-- 实现 点击小圆点 图片滑动 小圆点样式改变 --> <script type="text/javascript"> // 确定ul的宽度 动态的创建小圆点 var imgList = document.querySelector('.imgList'); var circle = document.querySelector('.circle'); var circleA = circle.children; // thisIndex默认索引值是0 var thisIndex = 0; // console.log(imgList.children.length); // window.onload延迟加载函数 window.onload = function () { //给ui标签设置宽度 imgList.style.width = imgList.children.length * 620 + 'px'; //下面动态创建a标签 for (var i = 0; i < imgList.children.length; i++) { var aNode = document.createElement('a'); //我们在这里创建index属性来记录索引值 aNode.setAttribute('index', i); circle.appendChild(aNode); } //给小圆点加点击事件 circle.addEventListener('click', function (e) { //这里给a标签点击事件有个小bug 就是我们鼠标点击到.circle标签时候图片也滑动了 //解决上面小bug的方法 if (e.target.nodeName != 'A') { return false; } // e.target指向的是a标签 console.log(e.target); // console.log(e.target.nodeName); // 获得索引值 thisIndex = e.target.getAttribute('index'); // console.log(thisIndex); //图片移动的规则 0索引值 ->0 1 ->-1*620 2 ->-2*620 imgList.style.left = -thisIndex * 620 + 'px'; //调用小圆点改变样式的函数 circlechange(); }) function circlechange() { //先清除样式 再添加样式 for (var i = 0; i < circleA.length; i++) { circleA[i].className = ''; } circleA[thisIndex].className = 'hover'; } // 自动轮播 setInterval(function () { thisIndex++; if (thisIndex >= imgList.children.length) { thisIndex = 0; } imgList.style.left = -thisIndex * 620 + 'px'; circlechange(); }, 1000); } </script> </body> </html>
package com.study.springboot.entity; import jakarta.persistence.*; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDate; @Entity @Table(name="member_security") @Getter @NoArgsConstructor public class MemberEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String user_name; private String user_role; @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate join_date; @Builder public MemberEntity(LocalDate join_date, String user_role, String user_name, String password, String username, Long id) { this.join_date = join_date; this.user_role = user_role; this.user_name = user_name; this.password = password; this.username = username; this.id = id; } }
package com.rachma.datapasien.room import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase // Untuk menjadikan data class Note yang akan digunakan sebagai database, dan versi databasenya adalah 1 @Database( entities = [Note::class], version = 1 ) // Untuk membuat abstract class NoteDB yang akan mewarisi fungsi dari class RoomDatabase abstract class NoteDB : RoomDatabase() { abstract fun noteDao(): NoteDao companion object { @Volatile private var instance: NoteDB? = null private val LOCK = Any() operator fun invoke(context: Context) = instance ?: synchronized(LOCK){ instance ?: buildDatabase(context).also{ instance = it } } // Untuk membuat fungsi buildDatabase untuk membuat database note12345.db sebagai tempat penyimpanan data private fun buildDatabase(context: Context)= Room.databaseBuilder( context.applicationContext, NoteDB::class.java, "note12345.db" ).build() } }
import { Component, Input, OnInit, EventEmitter, Output, OnChanges } from '@angular/core'; import { CommonModule, DatePipe } from '@angular/common'; import { FormGroup, FormControl } from '@angular/forms'; class MonthViewEventInfo { constructor(public type: MonthViewEventType, public data: any) { } } enum MonthViewEventType { UserInfo = "UserInfo", Attendance = "Attendance" } @Component({ selector: 'month-view', templateUrl: './month-view.component.html', styleUrls: ['./month-view.component.scss'] }) export class MonthViewComponent implements OnInit, OnChanges { public years:Array<number>; public months:Array<string>; public selectedDate:Date; public monthYearSelector:FormGroup; public eventList:any; // event list which is used to bind the control public datesList:any; // Dates in format 20181220 [YearMonthDay] public daysInMonth:number; @Input() resourceData: any; @Output() resourceRowClicked = new EventEmitter(); @Output() monthAndYearChanged = new EventEmitter(); constructor(private datePipe:DatePipe) { this.selectedDate = new Date(); } ngOnInit() { if(!this.resourceData) { this.resourceData = []; } this.initialize(); } ngOnChanges(){ if(this.resourceData){ this.initialize(); } } public onResourceClicked(event:any, data:any){ event.preventDefault(); let eventInfo = new MonthViewEventInfo(MonthViewEventType.UserInfo, data); this.resourceRowClicked.emit(eventInfo); } public onResourceAttendanceCellClicked(event:any, eventData:any, date:Date){ eventData.eventDate = date; eventData.attendanceType = this.getCellValue(eventData, date); let eventInfo = new MonthViewEventInfo(MonthViewEventType.Attendance, eventData); this.resourceRowClicked.emit(eventInfo); } public getCellValue(events:any, date:any):string { date = this.datePipe.transform(date,"yyyyMMdd"); return events.events[date] && events.events[date].value ? events.events[date].value : ""; } public getDayOfTheWeek(date:Date): string { let days = ["SU", "MO", "TU", "WE", "TH","FR", "SA"]; let index = date.getDay(); index = index % 7; return days[index]; } public isAnOffDay(date:Date): Boolean { let isAnOffDay:Boolean; let day = this.getDayOfTheWeek(date);// TODO: Include Holidays from holiday list if(day == "FR" || day == "SA"){ isAnOffDay = true; } return isAnOffDay; } public onMonthYearChanged(event:any){ this.selectedDate = new Date(this.monthYearSelector.get("yearSelector").value, this.monthYearSelector.get("monthSelector").value, 1); this.datesList = this.generateDatesList(); this.daysInMonth = this.daysInThisMonth(); this.eventList = this.getEventList(); let dateInfo = this.monthYearSelector.value; this.monthAndYearChanged.emit({ "month" : parseInt(dateInfo.monthSelector, 10) + 1, "year": dateInfo.yearSelector }); } private getEventList() { return this.resourceData; // this.prepareTestEvents } private initialize(){ this.monthYearSelector = new FormGroup({ monthSelector : new FormControl(), yearSelector : new FormControl() }); this.generateYears(); this.generateMonths(); this.datesList = this.generateDatesList(); this.daysInMonth = this.daysInThisMonth(); this.eventList = this.getEventList(); } private generateDatesList(){ let arr = new Array(); let date = this.selectedDate; let yr = date.getFullYear(); let mo = date.getMonth(); var firstDay = new Date(yr, mo, 1); var lastDay = new Date(yr, mo + 1, 0); while (firstDay <= lastDay) { arr.push(new Date(firstDay)); firstDay.setDate(firstDay.getDate() + 1); } return arr; } private daysInThisMonth() { var now = this.selectedDate; return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate(); } private prepareTestEvents(){ return [{ "id": 1, "resource": "John Doe", "events": { "20181201": { "value": "1" }, "20181202": { "value": "1" }, "20181203": { "value": "1" }, "20181204": { "value": "1" }, "20181205": { "value": "1" }, "20181206": { "value": "1" }, "20181207": { "value": "1" }, "20181208": { "value": "1" }, "20181209": { "value": "1" }, "20181109": { "value": "1" } } }, { "id": 2, "resource": "Smith Doe", "events": { "20181201": { "value": "1" }, "20181202": { "value": "1" }, "20181203": { "value": "1" }, "20181204": { "value": "1" }, "20181205": { "value": "1" }, "20181206": { "value": "1" }, "20181207": { "value": "1" }, "20181208": { "value": "1" }, "20181209": { "value": "1" } } }]; } private generateYears(){ let num = 0; this.years = new Array<number>(); let yr = new Date().getFullYear(); this.years.push(yr); for(let index=0; index < num; index++) { this.years.push(--yr); } this.monthYearSelector.patchValue({ "yearSelector": this.selectedDate.getFullYear()}); } private generateMonths(){ this.months = new Array<string>(); this.months.push("January"); this.months.push("February"); this.months.push("March"); this.months.push("April"); this.months.push("May"); this.months.push("June"); this.months.push("July"); this.months.push("August"); this.months.push("September"); this.months.push("October"); this.months.push("November"); this.months.push("December"); this.monthYearSelector.patchValue({ "monthSelector": this.selectedDate.getMonth() }); } }
<?php /** * Lian Options Panel */ if ( ! defined( 'ABSPATH' ) ) exit; use Lian\DynamicCodes; use Lian\ApiHelper; if ( ! class_exists( 'LIAN_Theme_Dashboard' ) ) { class LIAN_Theme_Dashboard { public function __construct() { if ( is_admin() ) { add_action( 'admin_menu', array( 'LIAN_Theme_Dashboard', 'add_admin_menu' ) ); add_action( 'admin_init', array( 'LIAN_Theme_Dashboard', 'register_settings' ) ); } } public static function get_lian_options() { return get_option( 'lian_options' ); } public static function get_theme_option( $id ) { $options = self::get_lian_options(); if ( isset( $options[$id] ) ) { return $options[$id]; } } public static function add_admin_menu() { $menu_name = "Lian"; $lian_new_version = !empty(get_option('lian_new_version')) ? get_option( 'lian_new_version') : LIAN_VERSION; if(version_compare(LIAN_VERSION,$lian_new_version,'<')){ $menu_name .= '<span title="Update Available" class="update-plugins count-1"><span class="update-count">1</span></span>'; } add_menu_page( $menu_name, $menu_name, 'manage_options', 'lian-dashboard', array( 'LIAN_Theme_Dashboard', 'lian_dashboard_page' ), 'dashicons-plus', 4 ); add_submenu_page( 'lian-dashboard', __( 'Elementor Editor', 'lian' ), __( 'Elementor Editor', 'lian' ), 'manage_options', 'lian-elementor', array( 'LIAN_Theme_Dashboard', 'lian_elementor_editor_page' ), 2 ); add_submenu_page( 'lian-dashboard', __( 'Settings', 'lian' ), __( 'Settings', 'lian' ), 'manage_options', 'lian-settings', array( 'LIAN_Theme_Dashboard', 'lian_admin_page' ), 7 ); } public static function register_settings() { register_setting( 'lian_options', 'lian_options', array( 'LIAN_Theme_Dashboard', 'sanitize' ) ); // Generate CSS & JS file $css_codes = DynamicCodes::lian_dynamic_css(); if(function_exists('lian_core_dynamic_css_create_file')){ lian_core_dynamic_css_create_file($css_codes); } $js_codes = DynamicCodes::lian_dynamic_js(); if(function_exists('lian_core_dynamic_js_create_file')){ lian_core_dynamic_js_create_file($js_codes); } } public static function sanitize( $options ) { return $options; } /** * Lian Elementor Editor Page * @author Alireza Dr. */ public static function lian_dashboard_page(){ ?> <div class="lian-wrap"> <div class="container lian-dashboard"> <div class="row"> <div class="col"> <div class="col-content mb-16"> <b><?php echo sprintf( __('Welcome to Lian Version %s, enjoy!', 'lian'), LIAN_VERSION); ?></b> <p><?php _e( 'Unlock the potential of Lian to turn your dreams into a digital masterpiece!', 'lian' ); ?></p> </div> </div> <div class="col"> <div class="col-content mb-16 revert-colors elementor-box"> <b><img src="<?php echo LIAN_ASSETS_URI . 'img/elementor-logo-w.png';?>" width="200"></b> <p><?php _e( 'Change headers, footers, pages and everything with Elementor. Are yo ready?', 'lian'); ?></p> <a href="?page=lian-elementor" class="btn btn-primary dib mt-16"><?php _e('Elementor Editor', 'lian' ); ?></a> </div> </div> <div class="col"> <div class="col-content mb-16"> <b><?php _e( 'Lian Settings', 'lian' ); ?></b> <p><?php _e('The most comprehensive settings are provided so that the template is in your hands.', 'lian'); ?></p> <a href="?page=lian-settings" class="btn btn-primary dib mt-16"><?php _e('Theme Settings', 'lian'); ?></a> </div> </div> </div> <div class="row"> <div class="col"> <div class="col-content mb-16 <?php echo esc_attr($update_available_class); ?>"> <b><?php _e( 'Updates', 'lian' ); ?></b> <?php $theme_information = new ApiHelper(); $lian_new_version = $theme_information->get_lian_theme_version(); if(!$lian_new_version || LIAN_VERSION >= $lian_new_version): ?> <p><?php _e( 'Your theme is up to date. Enjoy!', 'lian' ); ?></p> <?php else: ?> <p><?php _e( 'Version', 'lian' ); ?> <?php echo esc_attr($lian_new_version); ?> <?php _e( 'is now Available!!', 'lian' ); ?></p> <?php endif; ?> </div> </div> <div class="col"> <div class="col-content mb-16"> <b><?php _e( 'Support', 'lian' ); ?></b> <p><?php _e( 'You can request support and send a ticket at any hour of the day and night so that the first operator will check your problem and answer you as soon as possible.', 'lian' ); ?></p> <a href="<?php _e('https://wipna.com/dashboard/', 'lian'); ?>" class="btn btn-primary dib mt-16"><?php _e( 'Send a Request', 'lian' ); ?></a> </div> </div> </div> <div class="row"> <div class="col"> <div class="col-content mb-16"> <b><?php _e( 'Documentation', 'lian' ); ?></b> <p><?php _e( 'The Documentation is a comprehensive resource that can significantly enhance your proficiency with the Lian theme, guiding you on how to customize it to suit your specific needs and work more effectively with it.', 'lian' ); ?></p> <a href="<?php _e('https://docs.wipna.com/lian/', 'lian'); ?>" class="btn btn-primary dib mt-16" target="_blank"><?php _e( 'See Online Documentation', 'lian' ); ?></a> </div> </div> </div> </div> </div> <?php } /** * Lian Elementor Editor Page * @author Alireza Dr. */ public static function lian_elementor_editor_page(){ ?> <div class="lian-wrap" style="margin-top:20px;"> <div class="lian-overlay-options"></div> <div class="lian-save" style="display:none"> <div class="doing" style="display:none"><span><?php echo _e('Saving...','lian'); ?></span></div> <div class="succ" style="display:none"><span><?php echo _e('Saved!','lian'); ?></span></div> <div class="fail" style="display:none"><span><?php echo _e('Failed!','lian'); ?></span></div> </div> <form method="post" action="options.php"> <?php settings_fields( 'lian_options' ); ?> <div class="lian-options"> <div class="lian-options-sidebar"> <center style=" padding-bottom: 15px; "> <div style="width: 100%;"> <embed src="<?php echo esc_url(get_template_directory_uri() . '/inc/options/assets/img/logo.png'); ?>"/> <span class="version"><?php echo 'v'.LIAN_VERSION; ?></span> </div> </center> <ul> <li class="active"><i class="dashicons dashicons-table-row-before"></i><?php _e( 'Header', 'lian' ); ?></li> <li><i class="dashicons dashicons-table-row-after"></i><?php _e( 'Footer', 'lian' ); ?></li> <li><i class="dashicons dashicons-schedule"></i><?php _e( 'Pages', 'lian' ); ?></li> <li><i class="dashicons dashicons-menu-alt3"></i><?php _e( 'Mega Menu', 'lian' ); ?></li> </ul> </div> <div class="lian-options-content"> <?php if(lian_is_core_activated() && lian_is_elementor_activated()): ?> <ul class="lian-elementor-posts"> <?php include 'elementor-editor/frontend/header.php'; ?> <?php include 'elementor-editor/frontend/footer.php'; ?> <?php include 'elementor-editor/frontend/pages.php'; ?> <?php include 'elementor-editor/frontend/megamenu.php'; ?> </ul> <?php else: ?> <div> <?php if(!lian_is_core_activated()): ?> <div class="notice lian-notice"> <?php _e('<a href="https://wipna.com/lian-core/" target="_blank">Lian Core</a> plugin is required for this section. <a href="https://wipna.com/lian-core/" target="_blank">Click Here to get the Lian Core plugin right now!</a>','lian'); ?> </div> <?php endif; ?> <?php if(!lian_is_elementor_activated()): ?> <div class="notice lian-notice"> <?php _e('Free Elementor plugin is required for this section. Please install and activate the Elementor plugin through Plugins » Add Plugin.','lian'); ?> </div> <?php endif; ?> </div> <?php endif; ?> </div> </div> </form> </div> <?php } /** * Lian Settings Page * @author Alireza Dr. */ public static function lian_admin_page() { ?> <div class="lian-wrap" style="margin-top:20px;"> <div class="lian-overlay-options"></div> <div class="lian-save" style="display:none"> <div class="doing" style="display:none"><span><?php echo _e('Saving...','lian'); ?></span></div> <div class="succ" style="display:none"><span><?php echo _e('Saved!','lian'); ?></span></div> <div class="fail" style="display:none"><span><?php echo _e('Failed!','lian'); ?></span></div> </div> <form method="post" action="options.php"> <?php settings_fields( 'lian_options' ); ?> <div class="lian-options"> <div class="lian-options-sidebar"> <center style=" padding-bottom: 15px; "> <div style="width: 100%;"> <embed src="<?php echo esc_url(get_template_directory_uri() . '/inc/options/assets/img/logo.png'); ?>"/> <span class="version"><?php echo 'v'.LIAN_VERSION; ?></span> </div> </center> <ul> <li class="active"><i class="dashicons-before dashicons-dashboard"></i><?php _e( 'General', 'lian' ); ?></li> <li><i class="dashicons-before dashicons-admin-appearance"></i><?php _e( 'Style', 'lian' ); ?></li> <li><i class="dashicons-before dashicons-editor-textcolor"></i><?php _e( 'Typography', 'lian' ); ?></li> <li><i class="dashicons-before dashicons-schedule"></i><?php _e( 'Header', 'lian' ); ?></li> <li><i class="dashicons-before dashicons-layout"></i><?php _e( 'Footer', 'lian' ); ?></li> <li><i class="dashicons-before dashicons-format-aside"></i><?php _e( 'Blog / Archive - Single', 'lian' ); ?></li> <li><i class="dashicons-before dashicons-portfolio"></i><?php _e( 'Portfolio / Archive - Single', 'lian' ); ?></li> <li><i class="dashicons-before dashicons-info-outline"></i><?php _e( '404 page', 'lian' ); ?></li> </ul> <p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e('Save Options','lian'); ?>"></p> </div> <div class="lian-options-content"> <ul> <?php include 'settings/frontend/options-general.php'; ?> <?php include 'settings/frontend/options-style.php'; ?> <?php include 'settings/frontend/options-typography.php'; ?> <?php include 'settings/frontend/options-header.php'; ?> <?php include 'settings/frontend/options-footer.php'; ?> <?php include 'settings/frontend/options-blog.php'; ?> <?php include 'settings/frontend/options-portfolio.php'; ?> <?php include 'settings/frontend/options-notfound.php'; ?> </ul> </div> </div> </form> </div> <?php } } } new LIAN_Theme_Dashboard; // to return a value function lian_options( $id = '' ) { return LIAN_Theme_Dashboard::get_theme_option( $id ); }
use std::collections::HashMap; fn get_grid_size(input: &str) -> (i64, i64, i64, i64) { input.replace("\n", " -> ").split(" -> ").fold( (i64::MAX, i64::MIN, i64::MAX, i64::MIN), |acc, line| { let (y_min, y_max, x_min, x_max) = acc; let points = line .split(",") .map(|s| s.parse::<i64>().unwrap()) .collect::<Vec<i64>>(); let x = points[0]; let y = points[1]; (y_min.min(y), y_max.max(y), x_min.min(x), x_max.max(x)) }, ) } fn get_grid(input: &str, x_size: i64, y_size: i64, x_offset: i64) -> Vec<Vec<char>> { let mut grid = vec![vec!['.'; x_size as usize]; y_size as usize]; input.lines().for_each(|line| { let points = line .split(" -> ") .map(|point| { let points = point .split(",") .map(|s| s.parse::<i64>().unwrap()) .collect::<Vec<i64>>(); (points[0] - x_offset, points[1]) }) .collect::<Vec<(i64, i64)>>(); points.windows(2).for_each(|points| { let p1 = points[0]; let p2 = points[1]; if p1.0 == p2.0 { for i in p1.1.min(p2.1)..=p2.1.max(p1.1) { grid[i as usize][p1.0 as usize] = '#'; } } if p1.1 == p2.1 { for i in p1.0.min(p2.0)..=p2.0.max(p1.0) { grid[p1.1 as usize][i as usize] = '#'; } } }) }); grid } fn simulate_sand(grid: &mut Vec<Vec<char>>, sand_source: (i64, i64)) -> i64 { let mut sand_counter = 0; let dirs: Vec<(i64, i64)> = vec![(1, 0), (1, -1), (1, 1)]; 'new_sand: loop { let mut sand_target = sand_source; 'moving_sand: loop { for dir in dirs.iter() { let target = (sand_target.0 + dir.0, sand_target.1 + dir.1); if target.0 < 0 || target.0 >= grid.len() as i64 || target.1 < 0 || target.1 >= grid[0].len() as i64 { break 'new_sand; } if grid[target.0 as usize][target.1 as usize] == '.' { sand_target = target; continue 'moving_sand; } } break 'moving_sand; } sand_counter += 1; grid[sand_target.0 as usize][sand_target.1 as usize] = 'o'; } sand_counter } fn run_a(input: &str) { let (_, y_max, x_min, x_max) = get_grid_size(input); let x_size = x_max - x_min + 1; let y_size = y_max + 1; let mut grid = get_grid(input, x_size, y_size, x_min); let sand_source = (0 as i64, 500 - x_min); let result = simulate_sand(&mut grid, sand_source); println!("a: {}", result); } fn simulate_infinite_sand( grid: &mut HashMap<(i64, i64), char>, sand_source: (i64, i64), y_max: i64, ) -> i64 { let mut sand_counter = 0; let dirs: Vec<(i64, i64)> = vec![(1, 0), (1, -1), (1, 1)]; 'new_sand: loop { let mut sand_target = sand_source; 'moving_sand: loop { for dir in dirs.iter() { let target = (sand_target.0 + dir.0, sand_target.1 + dir.1); if target.0 >= y_max + 2 { break 'moving_sand; } if grid.get(&target) == None { sand_target = target; continue 'moving_sand; } } break 'moving_sand; } sand_counter += 1; grid.insert(sand_target, 'o'); if sand_target == sand_source { break 'new_sand; } } sand_counter } fn get_infinite_grid(input: &str, x_offset: i64) -> HashMap<(i64, i64), char> { let mut grid = HashMap::new(); input.lines().for_each(|line| { let points = line .split(" -> ") .map(|point| { let points = point .split(",") .map(|s| s.parse::<i64>().unwrap()) .collect::<Vec<i64>>(); (points[0] - x_offset, points[1]) }) .collect::<Vec<(i64, i64)>>(); points.windows(2).for_each(|points| { let p1 = points[0]; let p2 = points[1]; if p1.0 == p2.0 { for i in p1.1.min(p2.1)..=p2.1.max(p1.1) { grid.insert((i, p1.0), '#'); } } if p1.1 == p2.1 { for i in p1.0.min(p2.0)..=p2.0.max(p1.0) { grid.insert((p1.1, i), '#'); } } }) }); grid } fn run_b(input: &str) { let (_, y_max, x_min, _) = get_grid_size(input); let mut grid: HashMap<(i64, i64), char> = get_infinite_grid(input, x_min); let sand_source = (0 as i64, 500 - x_min); let result = simulate_infinite_sand(&mut grid, sand_source, y_max); println!("b: {}", result); } pub fn run() { let input = include_str!("../inputs/day-14.txt"); run_a(input); run_b(input); }
import React, { useState } from 'react'; import styled from 'styled-components'; const ModalOverlay = styled.div` position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; `; const ModalContent = styled.div` background: #fff; padding: 20px; border-radius: 10px; width: 400px; box-shadow: 0 0 10px rgba(0,0,0,0.1); `; const FormGroup = styled.div` margin-bottom: 20px; `; const Label = styled.label` display: block; margin-bottom: 5px; font-weight: bold; `; const Input = styled.input` width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 5px; `; const ButtonGroup = styled.div` display: flex; justify-content: flex-end; button { margin-left: 10px; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; transition: background 0.3s; } .cancel { background: #ccc; &:hover { background: #bbb; } } .save { background: #4caf50; color: white; &:hover { background: #45a049; } } `; const Modal = ({ onSave, onClose }) => { const [name, setName] = useState(''); const [price, setPrice] = useState(0); const [dosage, setDosage] = useState(''); const [instruction, setInstruction] = useState(''); const [quantity, setQuantity] = useState(0); const [amount, setAmount] = useState(0); const handleSave = () => { onSave({ name, price, dosage, instruction, quantity, amount }); }; return ( <ModalOverlay> <ModalContent> <h2>Add Medicine</h2> <FormGroup> <Label>Name</Label> <Input type="text" value={name} onChange={(e) => setName(e.target.value)} /> </FormGroup> <FormGroup> <Label>Price</Label> <Input type="number" value={price} onChange={(e) => setPrice(e.target.value)} /> </FormGroup> <FormGroup> <Label>Dosage</Label> <Input type="text" value={dosage} onChange={(e) => setDosage(e.target.value)} /> </FormGroup> <FormGroup> <Label>Instruction</Label> <Input type="text" value={instruction} onChange={(e) => setInstruction(e.target.value)} /> </FormGroup> <FormGroup> <Label>Quantity</Label> <Input type="number" value={quantity} onChange={(e) => setQuantity(e.target.value)} /> </FormGroup> <FormGroup> <Label>Amount</Label> <Input type="number" value={amount} onChange={(e) => setAmount(e.target.value)} /> </FormGroup> <ButtonGroup> <button className="cancel" onClick={onClose}>Cancel</button> <button className="save" onClick={handleSave}>Save</button> </ButtonGroup> </ModalContent> </ModalOverlay> ); }; export default Modal;
<!DOCTYPE html> <html lang="en"> {% load static %} {% load crispy_forms_tags %} <head> {% if user.is_authenticated %} <title>ASN ANALYSIS</title> {% else %} <title>-------</title> {% endif %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" /> <link rel="stylesheet" href="{% static 'myStyle.css' %}" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css"> <script src="https://use.fontawesome.com/cc5e99677f.js"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <!-- Header --> <div class="navbar-div"> <nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #859F41;"> <div class="container-fluid"> {% if user.is_authenticated %} <a class="navbar-brand" href="{% url 'home' %}">Dashboard</a> <a class="navbar-brand" href="{% url 'asn_analysis' %}">ASN Analysis</a> {% if filter %} <div class="hidden-filter-icon"> <button class="btn submit-button" type="button">&nbsp;<i class="fa fa-filter filter-icon fa-1x">filter</i>&nbsp;&nbsp;</button> </div> {% endif %} <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> {% comment %} <li class="nav-item"> <a class="nav-link active" href="{% url 'home' %}"> Home </a> </li> {% endcomment %} <!-- <li> <form class="forn-inline" action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="number" name="name"> <input type="submit" name="submit" value="Search" style="background-color: whitesmoke; color: #859F41; border-radius: 25px;"> </form> </li> --> </ul> <ul class="navbar-nav ml-auto"> {% block navbar %} {% endblock %} <li class="nav-item dropdown"> <a class="nav-link active dropdown-toggle" href="" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tshoot Tool </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'list_peers' %}">List Peers</a> {% if is_noc %} <a class="dropdown-item" href="{% url 'list_switches' %}">List Switches</a> <a class="dropdown-item" href="{% url 'update_switches' %}">Update Params</a> {% endif %} </div> </li> <li class="nav-item dropdown"> <a class="nav-link active dropdown-toggle" href="" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> ASN Details </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'list_asns' %}">MEMBERS BGP ANALYSIS</a> <a class="dropdown-item" href="{% url 'list_unique_asns_behind' %}">INDIRECTLY CONNECTED ASNS</a> <a class="dropdown-item" href="{% url 'list_asns_in_naija' %}">ALL ASNS IN NIGERIA</a> <a class="dropdown-item" href="{% url 'list_asns_not_dc' %}">ASNS IN NIGERIA BUT NOT PEERING DIRCTLY</a> <a class="dropdown-item" href="{% url 'list_asns_not_in_ixpn' %}">ASNS IN NIGRTIA BUT NOT AT IXPN</a> <a class="dropdown-item" href="{% url 'list_all_afrinic_asns' %}">ALL AFRINIC ASNS</a> </div> </li> {% if is_noc %} <li class="nav-item"> <a class="nav-link active" href="{% url 'dashboard_group' %}"> Dashboard Items </a> </li> {% endif %} <li class="nav-item"> <a class="nav-link active" href="{% url 'account_logout' %}">Logout</a> </li> <li class="nav-item"> <a class="nav-link active" href="{% url 'account_change_password' %}">Change Password</a> </li> {% else %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link active" href="{% url 'account_login' %}">Login</a> </li> </ul> </div> {% endif %} </div> </nav> </div> <div class="blank"> <br><br> </div> <div class="container-fluid"> <div class="messages"> <div class="animate__animated animate__zoomOutLeft animate__delay-5s"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="alert alert-{{ message.tags }}" {% else %} class="alert alert-primary" {% endif %}> <div role="alert">{{ message }}</div></li> {% endfor %} </ul> {% endif %} </div> </div> </div> {% if messages %} {% else %} <br><br> {% endif %} <br> <h3 id="caption">{{ caption }}</h3> <br> {% if updated %} <p class="list-asns">Last updated on {{ updated.update }}</p> {% endif %} <!-- The flexible grid (content) --> <div class="container-fluid"> <div class="row"> {% if filter %} <div class="side"> {% block side %}{% endblock %} </div> {% endif %} <div class="main"> {% block content %}{% endblock %} </div> </div> </div> <!-- Footer --> <div class="footer"> {% if user.is_authenticated %} <p>© Internet Exchange point of Nigeria {% now "Y" %}</p> {% else %} <p>© ABC {% now "Y" %}</p> {% endif %} </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script type="text/javascript" src="{% static 'myJs.js' %}"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script> <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script> </body> </html>
// Service worker installation and activation self.addEventListener('install', event => { console.log('Service worker installed'); self.skipWaiting(); // Activate service worker immediately }); self.addEventListener('activate', event => { console.log('Service worker activated'); }); // Push notification event handling self.addEventListener('push', event => { const payload = event.data ? event.data.text() : 'Default notification'; event.waitUntil( self.registration.showNotification('Travel Master', { body: payload, //icon: '/static/images/icon.png', // Path to your notification icon //badge: '/static/images/badge.png' // Path to your notification badge }) ); }); // Fetch event handling for caching static assets self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => { // Cache hit - return response from cache if (response) { return response; } // Clone the request because it's a one-time use const fetchRequest = event.request.clone(); return fetch(fetchRequest).then(response => { // Check if we received a valid response if (!response || response.status !== 200 || response.type !== 'basic') { return response; } // Clone the response because we need to put it in the cache const responseToCache = response.clone(); caches.open('static-cache-v1').then(cache => { cache.put(event.request, responseToCache); }); return response; }); }) ); });
import { Button, Flex, Form, Input, Modal, Popconfirm, Table, Tooltip, Typography, message } from 'antd'; import Hero from '../../../components/hero/Hero'; import API from '../../../services/apiAxios'; import React, { useEffect, useState } from 'react'; import { CustomAvatar } from '../../../components/CustomAvatar'; import dayjs from 'dayjs'; import { DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons'; import { useForm } from 'antd/es/form/Form'; const AdminAuthor = () => { const [authorData, setAuthorData] = useState([]); const [count, setCount] = useState(''); const [pageSize, setPageSize] = useState(10); const [currentPage, setCurrentPage] = useState(1); const [showModal, setShowModal] = useState(false); const [form] = useForm(); const handleFormSubmit = async (values) => { try { await API.post('api/v1/author', values); message.destroy(); message.success('Author Successfully created !'); fetchAuthors(); setShowModal(!showModal); form.resetFields(); } catch (error) { message.destroy(); message.success(error); } } const fetchAuthors = async () => { try { const response = await API.get(`api/v1/author?limit=${pageSize}&page=${currentPage}`); setAuthorData(response?.data?.data?.createdAuthor); setCount(response?.data?.data?.count); } catch (error) { message.destroy(); message.error(error?.response?.data?.message); } }; const deleteAuthor = async (id) => { await API.delete(`api/v1/author/${id}`).then(() => fetchAuthors()); } useEffect(() => { fetchAuthors(); }, [pageSize, currentPage]); const data = authorData?.map((row, index) => { return { id: row._id, s_no: index + 1, name: row.name, image_url: row.image, created_at: dayjs(row.created_at).format('DD/MM/YYYY (HH:MM)'), } }); const columns = [ { title: 'S.no.', dataIndex: 's_no', }, { title: 'Book', dataIndex: 'book', render: (_, render) => ( <CustomAvatar size="default" style={{ cursor: "pointer" }} name={render.name} /> ) }, { title: 'Name', dataIndex: 'name', key: 'name', }, { title: 'Created At', dataIndex: 'created_at', }, { title: 'Action', key: 'action', render: (_, record) => ( <Flex gap="small" horizontal> <Popconfirm title="Delete Author" description="Are you sure ?" onConfirm={() => deleteAuthor(record.id)} okText="Yes" cancelText="No" > <Tooltip title="Delete" placement='bottom'> <Button danger icon={<DeleteOutlined />} size={'small'} /> </Tooltip> </Popconfirm> </Flex> ), } ]; const formItemLayout = { labelCol: { xs: { span: 24, }, sm: { span: 7, }, }, wrapperCol: { xs: { span: 24, }, sm: { span: 16, }, }, }; return ( <div> <Hero heading="Authors" description="These are our Authors" /> <Flex justify='flex-end' className='mt-4 mr-4'> <Button type="primary" icon={<PlusCircleOutlined />} onClick={() => setShowModal(!showModal)} > Add Author </Button> </Flex> <div className='p-5'> <Table dataSource={data} columns={columns} pagination={{ total: count, showSizeChanger: true, pageSize: pageSize, pageSizeOptions: [2, 5, 10, 20, 100], onChange: (page, newPageSize) => { setCurrentPage(page) setPageSize(newPageSize) }, showTotal: (total) => ( <Typography.Title level={5}>Total : {total}</Typography.Title>), }} /> </div> <Modal title="Add Author" open={showModal} onCancel={() => setShowModal(!showModal)} width={400} footer="" > <Form {...formItemLayout} form={form} style={{ marginTop: '2rem' }} onFinish={handleFormSubmit} > <Form.Item name="name" label="Name" rules={[ { required: true, message: "Please enter name", }, ]} > <Input /> </Form.Item> <Form.Item name="image" label="Image URL" rules={[ { required: true, message: "Please enter image url", }, ]} > <Input /> </Form.Item> <Form.Item name="description" label="Description" rules={[ { required: true, message: "Please enter description", }, ]} > <Input.TextArea /> </Form.Item> <Form.Item wrapperCol={{ offset: 18, span: 16, }} > <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> </Modal> </div> ); }; export default AdminAuthor;
#' @title Fold change (\eqn{\Delta \Delta C_T} method) analysis of target genes using t-test #' #' @description t.test based analysis of the fold change expression for any number of target genes. #' #' @details The \code{qpcrTTEST} function applies a t.test based analysis to calculate #' fold change (\eqn{\Delta \Delta C_T} method) expression and returns related statistics for any number of #' target genes that have been evaluated under control and treatment conditions. Sampling may be paired or #' unpaired. One or two reference genes can be used. Unpaired and paired samples are commonly analyzed #' using unpaired and paired t-test, respectively. \strong{NOTE:} Paired samples in quantitative PCR refer to two sample #' data that are collected from one set of individuals #' at two different conditions, for example before and after a treatment or at two different time points. While #' for unpaired samples, two sets of individuals are used: one under untreated and the other set under treated #' condition. Paired samples allow to compare gene expression changes within the same individual, reducing #' inter-individual variability. #' @author Ghader Mirzaghaderi #' @export qpcrTTEST #' @import tidyr #' @import dplyr #' @import reshape2 #' @import ggplot2 #' @param x a data frame of 4 columns including Conditions, E (efficiency), Gene and Ct values (see examples below). Biological replicates needs to be equal for all Genes. Each Ct value is the mean of technical replicates. Complete amplification efficiencies of 2 is assumed here for all wells but the calculated efficienies can be used instead. See \href{../doc/vignette.html}{\code{vignette}} for details about "data structure and column arrangement". #' @param paired a logical indicating whether you want a paired t-test. #' @param var.equal a logical variable indicating whether to treat the two variances as being equal. If TRUE then the pooled variance is used to estimate the variance otherwise the Welch (or Satterthwaite) approximation to the degrees of freedom is used. #' @param numberOfrefGenes number of reference genes. Up to two reference genes can be handled. #' @return A list of two elements: #' \describe{ #' \item{Row_data}{The row data including Genes and weighed delta Ct (wDCt) values.} #' \item{Result}{Output table including the Fold Change values, lower and upper confidence interval, pvalue and standard error with the lower and upper limits.} #' } #' For more information about the test procedure and its arguments, #' refer \code{\link[stats]{t.test}}, and \code{\link[stats]{lm}}. #' If the residuals of the model do not follow normal distribution and variances between the two groups are not homoGene, \code{\link[stats]{wilcox.test}} procedure may be concidered #' #' @references Livak, Kenneth J, and Thomas D Schmittgen. 2001. Analysis of #' Relative Gene Expression Data Using Real-Time Quantitative PCR and the #' Double Delta CT Method. Methods 25 (4). doi:10.1006/meth.2001.1262. #' #' Ganger, MT, Dietz GD, and Ewing SJ. 2017. A common base method for analysis #' of qPCR data and the application of simple blocking in qPCR experiments. #' BMC bioinformatics 18, 1-11. #' #' Yuan, Joshua S, Ann Reed, Feng Chen, and Neal Stewart. 2006. #' Statistical Analysis of Real-Time PCR Data. BMC Bioinformatics 7 (85). #' doi:10.1186/1471-2105-7-85. #' #' @examples #' #' # See the sample data structure #' data_ttest #' #' # Getting t.test results #' qpcrTTEST(data_ttest, #' paired = FALSE, #' var.equal = TRUE, #' numberOfrefGenes = 1) #' #' #' #' qpcrTTEST(Taylor_etal2019, #' numberOfrefGenes = 2, #' var.equal = TRUE) #' #' #' qpcrTTEST <- function(x,numberOfrefGenes, paired = FALSE, var.equal = TRUE) { colnames(x)[1] <- "Condition" colnames(x)[2] <- "Gene" colnames(x)[3] <- "E" colnames(x)[4] <- "Ct" r <- nrow(x)/(2 * length(unique(x$Gene))) if(!all(r %% 1 == 0)) { stop("Error: Replicates are not equal for all Genes!") } else { x <- data.frame(x, wCt = log2(x$E) * x$Ct) if(numberOfrefGenes == 1) { x <- x } else { a <- (((2 * r) * (length(unique(x$Gene)) - 2)) + 1) b <- ((length(unique(x$Gene)) - 1) * 2 * r) mwCT <- (x$wCt[a:b] + x$wCt[(a+(2*r)):(b+(2*r))])/2 x$wCt[a:b] <- mwCT x <- x[-((a+(2*r)):(b+(2*r))),] } GENE <- x$Gene levels_to_compare <- unique(GENE)[-length(unique(GENE))] res <- matrix(nrow = length(levels_to_compare), ncol=7) colnames(res) <- c("Gene", "dif", "FC", "LCL", "UCL", "pvalue", "se") subset_df <- data.frame(group = character(), Gene = character(), wDCt = numeric()) ttest_result <- vector("list", length(levels_to_compare)) for (i in 1:length(levels_to_compare)) { subset_df <- rbind(subset_df, data.frame(group = x[GENE == levels_to_compare[i], "Condition"], Gene = levels_to_compare[i], wDCt = x[GENE == levels_to_compare[i], "wCt"] - x[GENE == utils::tail(unique(GENE), 1), "wCt"])) ttest_result[[i]] <- stats::t.test(subset_df$wDCt[(nrow(subset_df) - 2*r + 1):(nrow(subset_df) - r)], subset_df$wDCt[(nrow(subset_df) - r + 1):nrow(subset_df)], paired = paired, var.equal = var.equal) res[i, ] <- c(levels_to_compare[i], round(mean(subset_df$wDCt[(nrow(subset_df) - r + 1):nrow(subset_df)]) - mean(subset_df$wDCt[(nrow(subset_df) - 2*r + 1):(nrow(subset_df) - r)]), 4), round(2^-((mean(subset_df$wDCt[(nrow(subset_df) - r + 1):nrow(subset_df)]) - mean(subset_df$wDCt[(nrow(subset_df) - 2*r + 1):(nrow(subset_df) - r)]))), 4), round(2^(-ttest_result[[i]]$conf.int[2]), 4), round(2^(-ttest_result[[i]]$conf.int[1]), 4), round(ttest_result[[i]]$p.value, 4), round(stats::sd(subset_df$wDCt[(nrow(subset_df) - r + 1):nrow(subset_df)]) / sqrt(r), 4)) } res <- as.data.frame(res) res$FC <- as.numeric(res$FC) res$se <- as.numeric(res$se) res$dif <- NULL res <- data.frame(res, Lower.se = round(2^(log2(res$FC) - res$se), 4), Upper.se = round(2^(log2(res$FC) + res$se), 4)) res <- list(Raw_data = subset_df, Result = res) return(res) } }
<?php namespace Drupal\cgov_core; use Drupal\Core\Cache\CacheableDependencyInterface; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Language\LanguageManagerInterface; use Drupal\Core\Render\RendererInterface; use Drupal\file\Entity\File; use Drupal\views\ViewExecutable; use Drupal\Component\Utility\Html; use Symfony\Component\HttpFoundation\RequestStack; use Twig\TwigFunction; use Twig\Extension\AbstractExtension; use Drupal\Core\File\FileUrlGeneratorInterface; /** * Extend Drupal's AbstractExtension class. */ class CgovCoreTwigExtensions extends AbstractExtension { /** * Entity Type Manager. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** * The language manager. * * @var \Drupal\Core\Language\LanguageManagerInterface */ protected $languageManager; /** * The renderer. * * @var \Drupal\Core\Render\RendererInterface */ protected $renderer; /** * The request stack. * * @var \Symfony\Component\HttpFoundation\RequestStack */ protected $requestStack; /** * The current language ID. * * @var string */ protected $langid; /** * The file URL generator. * * @var \Drupal\Core\File\FileUrlGeneratorInterface */ protected $fileUrlGenerator; /** * Constructs a new CgovNavigationManager class. */ public function __construct(EntityTypeManagerInterface $entityTypeManager, LanguageManagerInterface $languageManager, RendererInterface $renderer, RequestStack $requestStack, FileUrlGeneratorInterface $file_url_generator) { $this->entityTypeManager = $entityTypeManager; $this->languageManager = $languageManager; $this->renderer = $renderer; $this->requestStack = $requestStack; // Get current language. $this->langid = $this->languageManager->getCurrentLanguage()->getID(); $this->fileUrlGenerator = $file_url_generator; } /** * {@inheritdoc} */ public function getName() { return 'cgov_core.CgovCoreTwigExtensions'; } /** * {@inheritdoc} */ public function getFunctions() { return [ new TwigFunction('get_blog_info', [$this, 'getBlogInfo'], ['is_safe' => ['html']]), new TwigFunction('get_enclosure', [$this, 'getEnclosure'], ['is_safe' => ['html']]), new TwigFunction('get_list_description', [$this, 'getListDescription'], ['is_safe' => ['html']]), new TwigFunction('get_translated_absolute_path', [$this, 'getTranslatedAbsolutePath'], [ 'is_safe' => ['html'], ]), new TwigFunction('strip_duplicate_leading_credit', [$this, 'stripDuplicateLeadingCredit'], [ 'is_safe' => ['html'], ]), new TwigFunction('has_content', [$this, 'hasContent'], ['is_safe' => ['html']]), // This is borrowed from 'sfc' module based on discussions in // https://www.drupal.org/project/drupal/issues/2660002. This should be // used when you are going to be digging around in entity reference // fields not using the field in the content variable. When you bypass // this, cache bubbling is skipped and thus Drupal cannot keep track of // what entities comprised the markup, and therefore cannot clear said // rendered content out of its render cache when changes are made to // the referenced entity. new TwigFunction('bubble_cache', [$this, 'cache']), ]; } /** * Determine whether any real text content exists. * * @param array $field_array * The field array. * * @return bool * Field has text content. */ public function hasContent(array $field_array) { $hasTextField = isset($field_array[0]['#text']); if ($hasTextField) { $content = $field_array[0]['#text']; $contentWithoutSpaces = str_replace("&nbsp;", "", $content); $doc = Html::load($contentWithoutSpaces); $nodeList = $doc->getElementsByTagName('body'); $elem = $nodeList[0]; $textContent = $elem->textContent; $trimmed = trim($textContent); $hasContent = strlen($trimmed) > 0; return $hasContent; } return FALSE; } /** * Strip migrated content of duplicate credit label. * * @param array $field_array * The unstripped string. * * @return array * The stripped string. */ public function stripDuplicateLeadingCredit(array $field_array) { $unsanitized_credit_string = $field_array[0]['#context']['value']; $sanitized_credit_string = preg_replace('/^(Credit\:?\s?|Crédito\:?\s?)/i', '', $unsanitized_credit_string); $field_array[0]['#context']['value'] = $sanitized_credit_string; return $field_array; } /** * Generate <enclosure url='x' length='9' type='mime/type' /> tag from NID. * * Call this function with {{ get_enclosure(nid) }} * * @param int $nid * Node ID to create enclosure tag from. * * @return string * generated enclosure tag. */ public function getEnclosure($nid) { $node = $this->getTranslatedNodeById($nid); if (!$node) { return NULL; } $enclosure = NULL; // Image style to use when rendering images. $thumbnail_image_style = 'cgov_thumbnail'; $media_image_file = $this->getNodeImageFile($nid); if ($media_image_file != NULL) { $image_info = $this->getImageData($media_image_file, $thumbnail_image_style); $enclosure = "<enclosure url='" . $image_info['absolute_uri'] . "' length='" . $image_info['filesize'] . "' type='" . $image_info['mimetype'] . "' />"; } return $enclosure; } /** * Return metadata about an Image Filefield. * * Get file URL, filesize and mimetype for an image field rendered to a * provided ImageStyle. The image's imagestyle file will be created on the * filesystem (which is required to determine the filesize properly). * * @param \Drupal\file\Entity\File $media_image_file * The File entity of an image field. * @param string $image_style * The Image Style to render the image with. * * @return array * Returns information about the image. */ public function getImageData(File $media_image_file, $image_style) { // Get URI of media image file (eg: public://2019-03/image.jpg). $image_uri = $media_image_file->getFileUri(); // Generate new derivative image from imagestyle. $imageStyle = $this->entityTypeManager->getStorage('image_style')->load($image_style); // Get thumbnail_uri // (eg: public://styles/cgov_thumbail/public/2019-03/image.jpg). $thumbnail_uri = $imageStyle->buildUri($image_uri); // Create the styled image on the filesystem // (needed to find final file size and mime type). $imageStyle->createDerivative($image_uri, $thumbnail_uri); // Convert 'public://path/image.jpg' // to '/sites/default/files/path/image.jpg'. $relative_imagestyle_uri = $this->fileUrlGenerator->generateString($thumbnail_uri); // Remove querystring, if present (eg: path/image.jpg?h=98765az) $relative_imagestyle_uri = strtok($relative_imagestyle_uri, '?'); // Add HTTP scheme (HTTP[S]) and hostname. $absolute_imagestyle_url = $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost() . $relative_imagestyle_uri; // Get the filesystem path (not web path) to the imagestyle // file so we can get filesize. $imagestyle_filename = urldecode(realpath(".") . $relative_imagestyle_uri); $styled_file_size = filesize($imagestyle_filename); $styled_mime_type = image_type_to_mime_type(exif_imagetype($imagestyle_filename)); $image_info['imagestyle'] = $image_style; $image_info['relative_uri'] = $relative_imagestyle_uri; $image_info['absolute_uri'] = $absolute_imagestyle_url; $image_info['filename'] = $imagestyle_filename; $image_info['filesize'] = $styled_file_size; $image_info['mimetype'] = $styled_mime_type; return($image_info); } /** * Select either the List Description or the Page/Meta Description. * * Call this function with {{ get_list_description (nid) }} * * @param int $nid * Node ID to load description from. * * @return string * Selected description. */ public function getListDescription($nid) { $node = $this->getTranslatedNodeById($nid); if (!$node) { return NULL; } $description = NULL; // Check for available descriptions to display. if ($node->hasField('field_page_description')) { $description = $node->field_page_description->value; } if ($node->hasField('field_list_description') && !$node->field_list_description->isEmpty()) { $description = $node->field_list_description->value; } return $description; } /** * Get the translated absolute path to the node. * * Call this function with {{ get_translated_path(nid) }}. * This is a workaround to the many Core issues about views not returning the * proper path for translations: * https://www.drupal.org/project/drupal/issues/2877994 * https://www.drupal.org/project/drupal/issues/2957917 * https://www.drupal.org/project/drupal/issues/2862511 * https://www.drupal.org/project/drupal/issues/2802311 * etc. * * @param int $nid * Node ID to load description from. * * @return string * Path to node. */ public function getTranslatedAbsolutePath($nid) { $node = $this->getTranslatedNodeById($nid); // Verify node was found. if (!$node) { return FALSE; } // Get translated absolute link. $link = $node->toUrl('canonical', ['absolute' => TRUE])->toString(); return $link; } /** * Get the translated version of entity, if available. */ private function getTranslationIfExists($entity) { if ($entity && $entity->hasTranslation($this->langid)) { $entity = $entity->getTranslation($this->langid); } return $entity; } /** * Get the translated node by NID. * * Load the translated version of a node by NID. Will not return node if * the current language's translation is not found. * * @param int $nid * Node ID to create enclosure tag from. * * @return \Drupal\node\Entity\Node * Node or NULL. */ public function getTranslatedNodeById($nid) { // Strip any theme debugging and cast to numeric. $nid = (int) strip_tags($nid); // Load the node's translation, if available. $node = $this->getTranslationIfExists($this->entityTypeManager->getStorage('node')->load($nid)); if ($node && $node->hasTranslation($this->langid)) { $node = $node->getTranslation($this->langid); } else { return NULL; } return $node; } /** * Get the Blog Information about Series and Topics. * * @param \Drupal\views\ViewExecutable $view * The current view being displayed. Uses Contextual Filters for details. * * @return array * Array containing information for the <channel><title>/<description> tags. */ public function getBlogInfo(ViewExecutable $view) { $base_url = $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost() . ltrim(base_path(), '/'); $series_nid = !empty($view->args) ? $view->args[0] : ''; $topic_tid = count($view->args) > 1 ? $view->args[1] : NULL; $series_name = NULL; $series_link = NULL; $series_desc = NULL; if ($series_nid) { if ($series_nid == 'all') { $series_name = 'All NCI Blogs'; $series_desc = 'All NCI Blog Posts'; $series_link = $base_url; } else { // Get Blog Series Name. $node = $this->getTranslatedNodeById($series_nid); if (!$node) { print "<!-- ERROR: No NID $series_nid with '{$this->langid}' Translation -->"; return NULL; } $series_name = $node->label(); $series_desc = $node->field_about_blog->value; $series_link = $node->toUrl('canonical', ['absolute' => TRUE])->toString(); } } if ($topic_tid) { // Get Blog Topics Name. $term = $this->entityTypeManager->getStorage('taxonomy_term')->load($topic_tid); $topic_name = $term->getName(); $topic_desc = $term->getDescription(); } else { $topic_name = NULL; $topic_desc = NULL; } // Figure out the proper Title/Description to use. if (!$series_nid && !$topic_tid) { // All posts for all blogs. $title = 'NCI Blogs'; $desc = 'All NCI Blog Posts'; $link = $base_url; } elseif ($series_nid && !$topic_tid) { // All posts for a blog, all topics. $title = $series_name; $desc = $series_desc; $link = $series_link; } elseif ((!$series_nid or $series_nid = 'all') && $topic_tid) { // All blog posts across all blogs for a Topic. $title = "All blogs on '$topic_name'"; $desc = "Posts on '$topic_desc'' across all NCI blogs"; $link = $base_url; } else { // All posts from a Single blog on a Single Topic. $title = "$series_name posts on '$topic_name'"; $desc = $series_name; $link = $series_link; } // Return metadata. $result['series'] = $series_name; $result['series_desc'] = $series_desc; $result['topic'] = $topic_name; $result['topic_desc'] = $topic_desc; $result['title'] = $title; $result['desc'] = $desc; $result['link'] = $link; return $result; } /** * Get Lead or Promo Image. * * Select the proper image file to display for a node * (either Lead Image or Promo Image or none). * * @param int $nid * Node ID to create enclosure tag from. * * @return \Drupal\file\Entity\File * The specified node or NULL */ public function getNodeImageFile($nid) { $node = $this->getTranslatedNodeById($nid); if (!$node) { return NULL; } // Check for available images to display. $media_image_file = NULL; // Check if there is a promotional image specified, if so use it. if ($node->hasField('field_image_promotional') && isset($node->field_image_promotional->entity)) { $media_entity = $node->field_image_promotional->entity; $promo_media_entity = $this->getTranslationIfExists($media_entity); if (isset($promo_media_entity->field_override_img_thumbnail->entity)) { $media_image_file = $promo_media_entity->field_override_img_thumbnail->entity; } elseif (isset($promo_media_entity->field_media_image->entity)) { // @todo Check if crop exist. $media_image_file = $promo_media_entity->field_media_image->entity; } } elseif ($node->hasField('field_image_article') && isset($node->field_image_article->entity)) { $media_entity = $node->field_image_article->entity; $lead_media_field = $this->getTranslationIfExists($media_entity); // Check if override image is present. if (isset($lead_media_field->field_override_img_thumbnail->entity)) { $media_image_file = $lead_media_field->field_override_img_thumbnail->entity; } elseif (isset($lead_media_field->field_media_image->entity)) { $media_image_file = $lead_media_field->field_media_image->entity; } } return($media_image_file); } /** * Allows component plugins to quickly add caching to templates. * * Use this to ensure that cache metadata gets bubbled when you * are referencing data instead of built fields. * Simple example usage: * @code * {{ node.label() }} * {{ bubble_cache(node) }} * @endcode * * A more complex example from a list template: * @code * {% if content.field_override_title|field_value %} * {% set title = content.field_override_title|field_value %} * {% else %} * {% set title = content.field_internal_link[0]["#node"].title.value %} * {{ bubble_cache(content.field_internal_link[0]["#node"]) }} * {% endif %} * @endcode * * You can also set other cache information as described in the * $type parameter. * * @param mixed $arg * String, Object or Array. * @param string $type * The type of metadata for string $args. Defaults to "tags". * Valid options are "contexts", "max-age", or "tags". * * @return mixed * The rendered output. */ public function cache($arg, $type = 'tags') { $build = []; $metadata = new CacheableMetadata(); $scalars = []; if (!is_array($arg)) { $arg = [$arg]; } foreach ($arg as $current) { if (is_scalar($current)) { $scalars[] = $current; } elseif ($current instanceof CacheableDependencyInterface) { $metadata = CacheableMetadata::createFromObject($current)->merge($metadata); } } if (!empty($scalars)) { switch ($type) { case 'contexts': $metadata->addCacheContexts($scalars); break; case 'max-age': $metadata->setCacheMaxAge($scalars[0]); break; default: $metadata->addCacheTags($scalars); } } $metadata->applyTo($build); return $this->renderer->render($build); } }
import sys def nearest_neighbor(graph): num_cities = len(graph) visited = [False] * num_cities tour = [] current_city = 0 tour.append(current_city) visited[current_city] = True for _ in range(num_cities - 1): nearest_city = None min_distance = sys.maxsize for city in range(num_cities): if not visited[city] and graph[current_city][city] < min_distance: nearest_city = city min_distance = graph[current_city][city] tour.append(nearest_city) visited[nearest_city] = True current_city = nearest_city # Return to the starting city to complete the tour tour.append(tour[0]) return tour # Example usage: if __name__ == "__main__": distance_matrix = [ [0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0] ] # Find the tour using the Nearest Neighbor Algorithm tour = nearest_neighbor(distance_matrix) print("Optimal Tour Sequence:", tour) # # The Traveling Salesman Problem (TSP) is a classic optimization problem in computer science and mathematics. The # problem can be defined as follows: Given a list of cities and the distances between each pair of cities, # the task is to find the shortest possible route that visits each city exactly once and returns to the original # city. The TSP is known to be NP-hard, meaning that there is no known efficient algorithm to solve it optimally for # large instances in polynomial time. Therefore, we often use approximation algorithms to find good solutions. # One common approach to solving the TSP is the Nearest Neighbor Algorithm, which is a simple and greedy heuristic # method. Here's an outline of the algorithm: # # ### Nearest Neighbor Algorithm for TSP: # # 1. Start at a randomly chosen city as the initial city. # 2. While there are unvisited cities: # a. Select the nearest unvisited city to the current city. # b. Add the selected city to the tour and mark it as visited. # c. Set the selected city as the current city. # 3. Return to the starting city to complete the tour. # # #### Complexity Analysis: # # 1. **General Complexity and Efficiency**: The TSP is known to be an NP-hard problem, which means that its # complexity grows exponentially with the number of cities. Therefore, finding the optimal solution for large # instances is not practically feasible. Instead, we often resort to approximation algorithms like the Nearest # Neighbor Algorithm, which provide reasonably good solutions quickly but may not always be optimal. # # 2. **Runtime Efficiency (Big O Notation)**: The runtime efficiency of the Nearest Neighbor Algorithm depends on the # number of cities (n). The algorithm iterates through all cities in each step, and for each city, it calculates # distances to all unvisited cities. Therefore, the time complexity of this algorithm is O(n^2) in the worst case. # However, this complexity can be improved using data structures like priority queues to find the nearest neighbor # more efficiently. # # 3. **Complexity Classification of the Algorithm**: The Nearest Neighbor Algorithm is a greedy algorithm, # which means it makes a series of locally optimal choices at each step without considering the global optimal # solution. As a result, it can find good solutions quickly but may not always find the best solution. The # algorithm's complexity classification is typically O(n^2), but with optimizations, it can be made more efficient. # # Keep in mind that the TSP is a well-studied problem, and there are various algorithms and techniques for solving # it, including exact algorithms like branch and bound, dynamic programming, and more sophisticated heuristics and # metaheuristics. The choice of algorithm depends on the problem size and the trade-off between solution quality and # computation time.
//libraries #include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> //formula declarations int key_check(int a, string b); string encipher(string key, string plaintext); //main int main(int argc, string argv[]) { //GET KEY int check = key_check(argc, argv[1]); //formula that checks that only 2 arguments in command line and key input by user is valid. if (check == 0) { //GET PLAINTEXT string plaintext = get_string("plaintext: "); //ENCIPHER & PRINT CIPHERTEXT string k = argv[1]; printf("ciphertext: %s\n", encipher(k, plaintext)); //carries out encipher function and prints ciphertext. } else { return 1; //returns 1 if wrong type of or no key given in command line argument. } } //formulas int key_check(int a, string b) { bool check1 = false; bool check2 = false; bool check3 = false; //CHECK 1: checks that only 2 arguments are in the command line. if (a == 2) { check1 = true; //if right number of command line arguments given. //CHECK 2: checks that string or 'key' characters are all letters. int i = 0; while (isalpha(b[i]) != 0) { i++; } if (i == 26 && strlen(b) == 26) { check2 = true; } //CHECK 3: checks that no duplicate letters are in key bool dup = false; int j = 0; while (b[j] != '\0') { for (int l = j + 1; b[l] != '\0'; l++) { if (b[j] == b[l]) { dup = true; } } j++; } if (dup == false) { check3 = true; } } //Final check to ensure all above checks are true. if (check1 == true && check2 == true && check3 == true) { return 0; } else if (check1 == true && check2 == false && check3 == true) { printf("Key must contain 26 characters.\n"); //prints this if key has too few characters. return 1; } else if (check1 == true && check2 == true && check3 == false) { printf("Key must not contain duplicate characters.\n"); //prints this if key has duplicate characters. return 1; } //If both checks not true then user is prompted for a new key. else { printf("Usage: ./substitution key\n"); //prints this if too many or too few command line arguments given. return 1; } } string encipher(string key, string plaintext) //formula to encipher a string of plaintext by an integer 'key'. { string ciphertext = plaintext; //ciphertext begins as copy of plaintext. int i = 0; while (plaintext[i] != '\0') //while loop to go through all chars of plaintext { char c = plaintext[i]; int alpha = isalpha(c); //checks if char is an alphabetical letter. int upper = isupper(c); //checks if char is an uppercase letter. if (alpha == 0) //if not an alphabetical letter then no change is made. i.e. punctuation and numbers stay as they are. { ciphertext[i] = c; //changes ciphertext array accordingly. } else //if alphabetical letter then following is undertaken. { if (upper != 0) //if uppercase letter { int l = c - 65; //65 used based an ASCII decimal chart ciphertext[i] = key[l]; if (isupper(ciphertext[i]) == 0) { ciphertext[i] = toupper(ciphertext[i]); } } else { int l = c - 97; //97 used based an ASCII decimal chart ciphertext[i] = key[l]; if (isupper(ciphertext[i]) != 0) { ciphertext[i] = tolower(ciphertext[i]); } } } i++; } return ciphertext; //returns string ciphertext which is dictated by key given. }
/* wc-l-syscall.c -- Simple "wc -l" command(system call version) */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> static void do_wc(const char *path); static void die(const char *s); int main(int argc, char const *argv[]) { if (argc < 2) { fprintf(stderr, "%s: file name not given\n", argv[0]); exit(1); } for (int i = 1; i < argc; i++) { do_wc(argv[i]); } exit(0); } #define BUFFER_SIZE 2048 static void do_wc(const char *path) { int fd; unsigned char buf[BUFFER_SIZE]; int n; fd = open(path, O_RDONLY); // ファイルを開く if (fd < 0) die(path); // ちゃんと開けたかチェック unsigned long count = 0; for (;;) { // ファイルディスクリプタfdが示すストリームにbufからバイト列を読み込む // 読み込むサイズは最大でもsizeof buf、つまりbuf配列のサイズまで // ただし、必ずしもこのサイズ一杯まで読まれる訳ではない // 実際に読まれたバイト数はread()の戻り値としてnに保持する n = read(fd, buf, sizeof buf); // 読み込みが成功したかチェック if (n < 0) die(path); // 最後まで読んだかチェック if (n == 0) break; for (int i = 0; i < n; i++) { if (buf[i] == '\n') { count++; } } } printf("%lu\n", count); if (close(fd) < 0) die(path); // ファイルを閉じる } static void die(const char *s) { perror(s); exit(1); }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* easyfind.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: framos-p <framos-p@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/01/09 14:43:34 by framos-p #+# #+# */ /* Updated: 2024/01/10 10:40:12 by framos-p ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef EASYFIND_HPP # define EASYFIND_HPP #include <iostream> #include <vector> struct ValueFoundException : public std::exception { const char *what() const throw() { return ("Value not found in container"); } }; template <typename T> typename T::iterator easyfind(T &container, int value) { typename T::iterator it = container.begin(); for (; it != container.end(); ++it) { if (*it == value) return (it); } throw ValueFoundException(); } #endif
import { useEffect, useState } from 'react'; import { FlatList, View, StyleSheet, Pressable } from "react-native"; import { Searchbar } from "react-native-paper"; import { useNavigation } from '@react-navigation/native'; import RecipeCard from './RecipeCard'; import RecipeCardPlaceholder from './RecipeCardPlaceholder'; import { useUser } from '@clerk/clerk-expo'; import recipeService from '../../services/recipeService' import EmptyList from './EmptyList'; import colors from '../../../colors.json'; // Collection of recipes created or saved by the user export default function CreatedRecipes(props) { // User object const { user } = useUser(); // State that provides navigation property const navigation = useNavigation(); // State for tracking user search input const [searchQuery, setSearchQuery] = useState(''); // States for listing recipes const [createdRecipes, setCreatedRecipes] = useState([]); const [isLoading, setIsLoading] = useState(true); // Gets recipes that user has created and sets state to response const loadCreatedRecipes = async() => { // Gets response from recipeService let response = await recipeService.getCreatedRecipes(user.id); setCreatedRecipes(response); setIsLoading(false); } // Renders recipes on component load & re-renders component when refreshValue is updated useEffect(() => { loadCreatedRecipes(); console.log('loaded createdRecipes.js'); }, [props.refreshValue1, props.refreshValue2]); return ( <View style={styles.container}> <Searchbar style={styles.searchbar} placeholder={"search recipes"} placeholderTextColor={"grey"} inputStyle={{paddingLeft: 0, alignSelf: 'center'}} showDivider={false} mode={'view'} onChangeText={query => setSearchQuery(query)} value={searchQuery} /> {!isLoading ? <FlatList style={{maxHeight: '90%'}} data={createdRecipes} renderItem={(item) => { if(item.item.Title.toLowerCase().includes(searchQuery.toLowerCase())){ return ( <Pressable key={item.item.RecipeId} onPress={() => navigation.navigate('Recipe', { recipe: item.item })}> <RecipeCard recipe={item.item}/> </Pressable> ) } }} ListEmptyComponent={() => <EmptyList/>} /> : <View> <RecipeCardPlaceholder/> <RecipeCardPlaceholder/> <RecipeCardPlaceholder/> <RecipeCardPlaceholder/> <RecipeCardPlaceholder/> </View> } </View> ); }; const styles = StyleSheet.create({ container: { margin: 20, minHeight: '100%' }, searchbar: { height: 35, width: '100%', marginVertical: 5, backgroundColor: colors['background2'] }, });
import { api } from "./api"; import { account, user } from "../urls"; import { buildClientRequestUrl } from "../../utils"; import { NotificationChangeFormType, OrderType, PasswordChangeFormType, UserType } from "@/types"; interface OrdersRequestType { limit?: number; page?: number; } interface GetOrdersResponse { total_count: number; page_count: number; data: OrderType[]; } export const accountApi = api.injectEndpoints({ endpoints: build => ({ getProfileInfo: build.query<any, void>({ query: () => buildClientRequestUrl(user.profile), transformResponse: (response: UserType) => response, providesTags: ["Profile"], }), updatePassword: build.mutation<void, PasswordChangeFormType>({ query: body => ({ url: buildClientRequestUrl(account.updatePassword), method: "POST", body, }), }), updateNotifications: build.mutation<void, NotificationChangeFormType>({ query: body => ({ url: buildClientRequestUrl(account.updateNotifications), method: "POST", body, }), }), getOrders: build.query<GetOrdersResponse, OrdersRequestType>({ query: params => ({ url: buildClientRequestUrl(`${account.orders}?limit=${params?.limit}&page=${params?.page}`), }), }), getLastActiveOrder: build.query<OrderType, void>({ query: () => ({ url: buildClientRequestUrl(`${account.lastActiveOrder}`), }), }), }), overrideExisting: true, }); export const { useGetProfileInfoQuery, useUpdatePasswordMutation, useUpdateNotificationsMutation, useGetOrdersQuery, useGetLastActiveOrderQuery, } = accountApi;
package net.radioapp.web.Network; import net.radioapp.commandController.actions.ActionHandler; import net.radioapp.WebHandler; import net.radioapp.commandController.actions.Action; import net.radioapp.web.Client; import net.radioapp.web.emisor.Emision; import net.radioapp.web.emisor.Emisora; import net.radioapp.web.emisor.Grupo; import net.radioapp.commandController.Colors; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class NetHandler implements WebHandler { private static final Path mainDir = Paths.get("./mainApp"); private static List<Path> groupsPaths = new ArrayList<>(); private static List<Path> emisorasPaths = new ArrayList<>(); private static List<Grupo> gruposList = new ArrayList<>(); private static List<Emisora> emisorasList = new ArrayList<>(); private static Grupo grupoActual; private static UDPRecibe recibidor; @Override public void initialize() throws IOException{ //TODO: Configurar grupo actual y tal groupsPaths.clear(); emisorasPaths.clear(); gruposList.clear(); emisorasList.clear(); checkIfHasStructure(); Stream<Path> paths = Files.list(mainDir); paths.filter(Files::isDirectory).forEach(groupsPaths::add); for(Path p : groupsPaths){ Stream<Path> emisoras = Files.list(p); emisoras.filter(Files::isDirectory).forEach(emisorasPaths::add); List<Emisora> temp = new ArrayList<>(); for(Path e: emisorasPaths){ Emisora emisor = new Emisora(e.getFileName().toString(), e); temp.add(emisor); emisorasList.add(emisor); emisor.readConfigFile(); } Grupo g = new Grupo(p.getFileName().toString(), p, temp); g.readConfigFile(); gruposList.add(g); } grupoActual = gruposList.getFirst(); recibidor = new UDPRecibe(); recibidor.start(); } public void checkIfHasStructure() throws IOException{ if (!Files.exists(mainDir)) { Files.createDirectory(mainDir); Files.createDirectory(Paths.get(mainDir+"/GrupoEjemplo")); Files.createDirectory(Paths.get(mainDir+"/GrupoEjemplo/EmisoraEjemplo")); } } @Override public void start() { if(!ClientHandler.isOnline()){ ClientHandler.setOnline(true); ActionHandler.log(Colors.Green.colorize("> Sistema iniciado"));} else {ActionHandler.log(Colors.Red.colorize(" El sistema ya está iniciado"));} for (Emisora e : emisorasList){ new Emision(e).start(); } } @Override public void stop() { if (ClientHandler.isOnline()) { ClientHandler.setOnline(false); ActionHandler.log(Colors.Green.colorize(" Sistema parado")); } else{ActionHandler.log(Colors.Red.colorize(" El sistema ya está parado"));} } @Override public void restart() { ClientHandler.setOnline(false); recibidor.setCanRun(false); try{initialize();} catch (Exception e){ActionHandler.handleException(e, " Error en el reinicio del servicio de red");} ClientHandler.setClientes(new ArrayList<>()); ClientHandler.setOnline(true); ActionHandler.log(Colors.Green.colorize(" Sistema reiniciado")); } @Override public void send(UDPDataArray arg, PackageTypes t) { for(Client c: ClientHandler.getClientes()){ new UDPEmitter(new UDPPacket(c, arg.getData(), t)).start(); } } public void send(UDPDataArray arg, PackageTypes t, Client c){ new UDPEmitter(new UDPPacket(c, arg.getData(), t)).start(); } @Override public void filterAction(Action action) { switch (action.getName().toLowerCase()) { case "start": start(); break; case "stop": stop(); break; case "restart": restart(); break; case "say": send(new UDPDataArray(action.getRes().getBytes()), PackageTypes.LOG); break; case "setfrecuency": try{ ClientHandler.moveAll(Double.parseDouble(action.getRes())); send(new UDPDataArray(action.getRes().getBytes()), PackageTypes.MOVER); ActionHandler.log("Todos los clientes han sido" + "cambiados a la frecuencia ");} catch(NumberFormatException e){ActionHandler.handleException(e, "La frecuencia debe de ser un número válido");} break; } } public void getState(){ StringBuilder r = new StringBuilder("Mostrando los clientes:\n"); for (Client c: ClientHandler.getClientes()){ r.append("> ").append(c.toString()).append("\n"); } ActionHandler.log(r.toString()); } }
import React, { useState, useEffect } from 'react'; import { View, DeviceEventEmitter } from 'react-native'; import { ScrollView, Select, Button, IconButton, TextArea, FormControl, Checkbox, Input, Stack, } from 'native-base'; import { Ionicons } from '@expo/vector-icons'; import { useMutation, useQuery, useApolloClient, } from '@apollo/client'; import { ADD_SUBTASK } from '../../../../queries/subtasks'; import { GET_TASK } from '../../../../queries/tasks'; import { useTranslation } from 'react-i18next'; export default function SubtaskAdd(props) { const { navigation, route } = props; const { users, newSubtaskOrder, taskId, addingTask, defaultAssignedUser, } = route.params; const { t } = useTranslation(); const client = useApolloClient(); const [addSubtask] = useMutation(ADD_SUBTASK); const [done, setDone] = React.useState(false); const [title, setTitle] = React.useState(''); const [quantity, setQuantity] = React.useState(''); const [assignedTo, setAssignedTo] = React.useState(null); React.useLayoutEffect(() => { navigation.setOptions({ headerRight: () => ( <View style={{ display: 'flex', flexDirection: 'row', }} > <IconButton onPress={() => { if (title.length > 0) { if (addingTask) { DeviceEventEmitter.emit( 'event.addSubtask', { title, done, quantity, assignedTo, } ); navigation.goBack(); } else { addSubtaskFunc({ title, done, quantity, assignedTo, }); } } }} variant="ghost" _icon={{ as: Ionicons, name: 'save', color: 'white', }} /> </View> ), }); }, [navigation, done, title, quantity, assignedTo]); useEffect(() => { setAssignedTo(defaultAssignedUser); }, [defaultAssignedUser]); const addSubtaskFunc = (work) => { // setSaving( true ); addSubtask({ variables: { title: work.title, done: work.done, quantity: isNaN(parseFloat(work.quantity)) ? 0 : parseFloat(work.quantity), assignedTo: work.assignedTo.id, order: newSubtaskOrder, approved: false, discount: 0, task: taskId, scheduled: null, fromInvoice: false, }, }) .then((response) => { updateCasheStorage( response.data.addSubtask, 'subtasks', 'ADD' ); navigation.goBack(); // setSaving( false ); }) .catch((err) => { console.log(err); // addLocalError( err ); // setSaving( false ); }); }; const updateCasheStorage = (response, key, type) => { const task = client.readQuery({ query: GET_TASK, variables: { id: taskId, }, }); let newTask = { ...task.task, }; newTask[key] = [...newTask[key]]; newTask[key].push(response); client.writeQuery({ query: GET_TASK, variables: { id: taskId, }, data: { task: newTask, }, }); }; return ( <ScrollView margin="5"> <FormControl> <Stack> <Checkbox accessibilityLabel="Completed" isChecked={done} onChange={() => { setDone(!done); }} > {t('completed')} </Checkbox> </Stack> </FormControl> <FormControl> <FormControl.Label> {t('subtasklInfo')} </FormControl.Label> <TextArea bgColor="white" placeholder={t('writeSubtaskDesc')} value={title} onChangeText={(text) => { setTitle(text); }} /> </FormControl> <FormControl> <Stack> <FormControl.Label> {t('quantity')} </FormControl.Label> <Input keyboardType="numeric" bgColor="white" type="text" value={quantity} onChangeText={(num) => { if (num[0] === '-') { setQuantity(num); } if ( num.length > 0 && isNaN(num) ) { return; } setQuantity(num); }} /> </Stack> </FormControl> <FormControl> <Stack> <FormControl.Label> {t('assignedUser')} </FormControl.Label> <Select defaultValue={ defaultAssignedUser.id } onValueChange={(itemValue) => { const user = users.find( (user) => user.id === itemValue ); setAssignedTo(user); }} > {users.map((user) => ( <Select.Item key={user.id} label={user.label} value={user.id} /> ))} </Select> </Stack> </FormControl> </ScrollView> ); }
import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; class DioHelper { static Dio? dio ; static init() { dio = Dio( BaseOptions( baseUrl: 'http://147.182.240.32:8000/' , //'https://famtam.herokuapp.com/', receiveDataWhenStatusError: true, followRedirects: false, validateStatus: (status) => true, ), ); } static Future <Response> getData({ required String url, Map<String, dynamic>?query, String lang = "ar", String? token, }) async { dio.options.headers = { "Content-Type": "application/json", "lang": lang, 'Authorization': token ?? '', }; return dio.get( url, queryParameters: query ); } static Future <Response> postData({ required String url, required Map<String, dynamic> data, Map<String, dynamic>? query, String lang = "ar", String? token, }) async { dio.options.headers = { "Content-Type": "application/json", 'lang': lang, "Authorization":"Token ${token ?? '' }" , // 'Authorization': token ?? '', }; return dio.post( url, queryParameters: query, data: data, ); } static Future <Response> putData({ required String url, required Map<String, dynamic> data, Map<String, dynamic>? query, String lang = "ar", String? token, }) async { dio.options.headers = { "Content-Type": "application/json", 'lang': lang, "Authorization":"Token ${token ?? '' }" , // 'Authorization': token ?? '', }; return dio.put( url, queryParameters: query, data: data, ); } }
import { createSlice } from "@reduxjs/toolkit"; import { TasksState } from "../../types/task"; import { fetchTasks, updateTask } from "./thunks"; const initialState: TasksState = { data: [], isLoading: false, error: null }; const tasksSlice = createSlice({ name: 'tasks', initialState, reducers: { }, extraReducers(builder) { // Fetch tasks builder .addCase(fetchTasks.pending, (state) => { state.isLoading = true; }) .addCase(fetchTasks.fulfilled, (state, action) => { state.isLoading = false; state.data = action.payload; }) .addCase(fetchTasks.rejected, (state, action) => { state.isLoading = false; state.error = action.error; }); // Update task builder .addCase(updateTask.pending, (state) => { state.isLoading = true; }) .addCase(updateTask.fulfilled, (state, action) => { const { id } = action.payload; const taskIndex = state.data.findIndex((task) => task.id === id); if (taskIndex !== -1) { state.data[taskIndex] = action.payload; } state.isLoading = false; }) .addCase(updateTask.rejected, (state, action) => { state.isLoading = false; state.error = action.error; }); } }); export const tasksReducer = tasksSlice.reducer;
var game 𝛑 = Math.PI addEventListener("DOMContentLoaded", () => { game = new Game(document.getElementById("main").getContext("2d"), { enemyLap: 1.75, projectileSpeed: 5.75, enemySpeed: 2.5, epl: 2 }) game.run() }) class Shooter { constructor(ctx, ppt) { this.ctx = ctx this.ppt = ppt } spawn() { this.x = this.ctx.canvas.width / 2 this.y = this.ctx.canvas.height / 2 this.ctx.beginPath() this.ctx.fillStyle = this.ppt.color this.ctx.arc(this.x, this.y, this.ppt.radius, 0, 2 * 𝛑) this.ctx.fill() this.ctx.closePath() } } class Projectile { constructor(ctx, ppt, coordinates, origin) { this.ctx = ctx this.ppt = ppt this.origin = origin this.coordinates = coordinates this.x = origin.x this.y = origin.y let perp = (this.coordinates.y - this.origin.y) let base = (this.coordinates.x - this.origin.x) let hyp = Math.sqrt(perp ** 2 + base ** 2) this.vx = (base / hyp) * this.ppt.speed this.vy = (perp / hyp) * this.ppt.speed } spawn() { this.ctx.beginPath() this.ctx.fillStyle = this.ppt.color this.ctx.arc(this.x, this.y, this.ppt.radius, 0, 2 * 𝛑) this.ctx.fill() // this.ctx.closePath() this.x += this.vx this.y += this.vy } } class Particles { constructor(ctx, ppt, coordinates, origin) { this.ctx = ctx this.ppt = ppt this.origin = origin this.coordinates = coordinates this.x = origin.x this.y = origin.y let perp = (this.coordinates.y - this.origin.y) let base = (this.coordinates.x - this.origin.x) let hyp = Math.sqrt(perp ** 2 + base ** 2) this.vx = (base / hyp) * this.ppt.speed this.vy = (perp / hyp) * this.ppt.speed } spawn() { this.ctx.beginPath() this.ctx.fillStyle = this.ppt.color this.ctx.arc(this.x, this.y, this.ppt.radius, 0, 2 * 𝛑) this.ctx.fill() // this.ctx.closePath() this.x += this.vx this.y += this.vy } } class Enemy { constructor(ctx, ppt, coordinates, origin) { this.ctx = ctx this.ppt = ppt this.origin = origin this.coordinates = coordinates this.x = coordinates.x this.y = coordinates.y let perp = (this.origin.x - this.coordinates.x) let base = (this.origin.y - this.coordinates.y) let hyp = Math.sqrt(perp ** 2 + base ** 2) this.vx = (perp / hyp) * this.ppt.speed this.vy = (base / hyp) * this.ppt.speed } spawn() { this.ctx.beginPath() this.ctx.fillStyle = this.ppt.color this.ctx.arc(this.x, this.y, this.ppt.radius, 0, 2 * 𝛑) this.ctx.fill() this.ctx.closePath() this.x += this.vx this.y += this.vy } } class Game { constructor(context, values) { this.context = context this.values = values this.projectiles = [] this.enemies = [] this.isGameRunning = false this.i = 0 this.aura = 0 this.icons = { pause: new Image() } this.icons.pause.src = 'https://dka-raj.github.io/space-shooter-game/play.png' } run() { this.context.canvas.addEventListener("mousedown", ({ sourceCapabilities, offsetX, offsetY }) => { if (sourceCapabilities.firesTouchEvents) return if (Math.hypot(this.shooter.x - offsetX, this.shooter.y - offsetY) < this.shooter.ppt.radius) this.pause() else { let projectile = this.regProjectile(offsetX, offsetY) this.projectiles.push(projectile) } }) this.context.canvas.addEventListener("touchstart", ({ touches }) => { Object.values(touches).forEach(({ clientX, clientY }) => { if (Math.hypot(this.shooter.x - clientX, this.shooter.y - clientY) < this.shooter.ppt.radius) this.pause() else { let projectile = this.regProjectile(clientX, clientY) this.projectiles.push(projectile) } }) }) window.addEventListener("keydown", ({ key }) => { if (key === " ") this.pause() else if (key === "8") this.boom() }) this.context.canvas.width = window.innerWidth this.context.canvas.height = window.innerHeight this.shooter = new Shooter(this.context, { color: "#fff", radius: 22 }) this.boomData = [ { x: this.shooter.x, y: this.shooter.y - this.shooter.ppt.radius }, { x: this.shooter.x - this.shooter.ppt.radius, y: this.shooter.y }, { x: this.shooter.x, y: this.shooter.y + this.shooter.ppt.radius }, { x: this.shooter.x + this.shooter.ppt.radius, y: this.shooter.y }, { x: this.shooter.x - this.shooter.ppt.radius, y: this.shooter.y - this.shooter.ppt.radius }, { x: this.shooter.x + this.shooter.ppt.radius, y: this.shooter.y + this.shooter.ppt.radius }, { x: this.shooter.x + this.shooter.ppt.radius, y: this.shooter.y - this.shooter.ppt.radius }, { x: this.shooter.x - this.shooter.ppt.radius, y: this.shooter.y + this.shooter.ppt.radius } ] this.animationId = requestAnimationFrame(this.animate.bind(this)) this.isGameRunning = true setTimeout(() => { this.pause() }, 1000); } animate() { this.context.fillStyle = `rgba(0,0,0,.2)` this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height) this.enemies.forEach((enemy, ie) => { enemy.spawn() let dist = Math.hypot(this.shooter.x - enemy.x, this.shooter.y - enemy.y) // over if (dist <= (enemy.ppt.radius + this.shooter.ppt.radius)) { alert("😭😭😭😭\nGame over!\nPress Ok to Play again!") this.enemies=[] } this.projectiles.forEach((projectile, ip) => { if (projectile.x <= 0 || projectile.y <= 0 || projectile.x >= this.context.canvas.width || projectile.y >= this.context.canvas.height) { this.projectiles.splice(ip, 1) } let dist = Math.hypot(projectile.x - enemy.x, projectile.y - enemy.y) // when projectile hits the enemy if (dist <= (enemy.ppt.radius + projectile.ppt.radius + projectile.ppt.aura)) { if (enemy.ppt.radius - 15 > 15) { gsap.to(enemy.ppt,{ radius: enemy.ppt.radius-15 }) setTimeout(() => { this.projectiles.splice(ip, 1) }) } else { setTimeout(() => { this.projectiles.splice(ip, 1) this.enemies.splice(ie, 1) }, 0); } } }) }) this.projectiles.forEach((projectile) => { projectile.spawn() }) this.shooter.spawn() if (this.i !== 60 * this.values.enemyLap) { this.i++ } else { for (let i = 0; i < this.values.epl; i++) { let enemy = this.regEnemy(this.eOrigin()) this.enemies.push(enemy) } this.i = 0 } this.animationId = requestAnimationFrame(this.animate.bind(this)) } boom() { this.boomData.forEach((coordinate) => { let projectile = new Projectile(this.context, { color: "green", radius: this.shooter.ppt.radius, speed: this.values.projectileSpeed * 10, aura: 50 }, coordinate, { x: this.shooter.x, y: this.shooter.y }) this.projectiles.push(projectile) }) } regProjectile(x, y) { return new Projectile(this.context, { color: this.shooter.ppt.color, radius: 10, speed: this.values.projectileSpeed, aura: 0 }, { x, y }, { x: this.shooter.x, y: this.shooter.y }) } regEnemy(coordinates) { return new Enemy(this.context, { color: `hsl(${Math.random() * 360}, 100%, 50%)`, radius: Math.random() * 20 + 7, speed: this.values.enemySpeed }, coordinates, { x: this.shooter.x, y: this.shooter.y }) } eOrigin() { let wall = Math.round(Math.random() * 3) + 1 let randNo = Math.random() let height = this.context.canvas.height, width = this.context.canvas.width let x = 0, y = 0 switch (wall) { case 1: x = 0 y = randNo * height break; case 2: x = width y = randNo * height break; case 3: x = randNo * width y = 0 break; case 1: x = randNo * width x = height break; default: x = y = 0 break; } return { x, y } } pause() { if (this.isGameRunning) { cancelAnimationFrame(this.animationId) this.isGameRunning = false let diameter = this.shooter.ppt.radius * 2 - 2 let x = this.shooter.x - this.shooter.ppt.radius + 1 let y = this.shooter.y - this.shooter.ppt.radius + 1 this.context.drawImage(this.icons.pause, x, y, diameter, diameter) } else { this.animationId = requestAnimationFrame(this.animate.bind(this)) this.isGameRunning = true } } }
import React, { useState } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; import { useDispatch } from 'react-redux'; import { addFavoriteAdvert, removeFavoriteAdvert } from '../../redux/favorites/favoritesSlices'; import { AdvertCardContainer, AdvertCardItem, AdvertCardImg, AdvertCardInfo, AdvertMainInfo, AdvertMainSection, AdvertPriceSection, AdvertPrice, AdvertSecondSection, AdvertReviewSection, AdvertRatingInfo, AdvertLocationSection, AdvertLocation, AdvertCardDescription, StyledFavoriteBorderIcon, StyledFavoriteIcon } from '../AdvertCard/AdvertCard.styled'; import { MainTitle, Button } from 'components/GlobalStyles'; import { IconLocation } from '../Icons/Icons'; import RatingStar from '../RatingStar/RatingStar'; import Modal from '../Modal/Modal'; import DetailsCard from '../DetailsCard/DetailsCard'; import AdvertDescriptionDetails from '../AdvertDescriptionDetails/AdvertDescriptionDetails'; const AdvertCard = ({ advert, isFavorite }) => { const dispatch = useDispatch(); const { isAuthenticated } = useAuth0(); const [isModalOpen, setIsModalOpen] = useState(false); const handleFavoriteToggle = () => { if (isFavorite) { dispatch(removeFavoriteAdvert(advert._id)); } else { dispatch(addFavoriteAdvert(advert._id)); } }; const openModal = () => { document.body.style.overflow = 'hidden'; setIsModalOpen(true); }; const closeModal = () => { document.body.style.overflow = 'auto'; setIsModalOpen(false); } return ( <AdvertCardContainer> <AdvertCardItem> <AdvertCardImg src={advert.gallery[0]} alt={advert.name} /> <AdvertCardInfo> <AdvertMainInfo> <AdvertMainSection> <MainTitle>{advert.name}</MainTitle> <AdvertPriceSection> <AdvertPrice>&#8364;{parseFloat(advert.price).toFixed(2)}</AdvertPrice> {isAuthenticated && ( <button type="button" onClick={handleFavoriteToggle}> {isFavorite ? <StyledFavoriteIcon /> : <StyledFavoriteBorderIcon />} </button> )} </AdvertPriceSection> </AdvertMainSection> <AdvertSecondSection> <AdvertReviewSection> <RatingStar /> <AdvertRatingInfo> <div>{advert.rating}</div> <div>&#x2772;{advert.reviews.length} Reviews&#x2773;</div> </AdvertRatingInfo> </AdvertReviewSection> <AdvertLocationSection> <IconLocation /> <AdvertLocation>{advert.location}</AdvertLocation> </AdvertLocationSection> </AdvertSecondSection> </AdvertMainInfo> <AdvertCardDescription> {advert.description}&#8230; </AdvertCardDescription> <AdvertDescriptionDetails advert={advert} order={1}/> <div> <Button type="button" onClick={openModal}>Show more</Button> </div> {isModalOpen && ( <Modal isCloseModal={closeModal}> <DetailsCard advert={advert} /> </Modal> )} </AdvertCardInfo> </AdvertCardItem> </AdvertCardContainer> ); }; export default AdvertCard;
@name StratifiedJS Language overview @type doclib @desc StratifiedJS executes code in logical units we call **strata**. Unlike normal JS code, strata are allowed to "block", i.e. the control flow is allowed to stop at a particular point to be picked up again later at the same point where it left off. An example would be the [::builtins::hold] function which blocks for a given period of time (but still allows other strata to be executed while it is blocking its own stratum). ### Concurrent strata While one stratum is blocked, other strata can execute. Strata are a bit like threads, but they are much more deterministic: Only one stratum is running at any one time and it is executed atomically up until the point where it either finishes or suspends. At that point the next pending stratum is executed until *it* finishes or suspends, and so forth. ## Base language StratifiedJS is based on the JavaScript language as originally defined in [ECMA-262 Edition 3][]. In addition, StratifiedJS supports many features defined in more recent standards, such as: [ECMA-262 Edition 3]: http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf - Rest parameters - Spread syntax - Destructuring ## Concurrency primitives: StratifiedJS contains language constructs for casting asynchronous logic into blocking form (`waitfor()`), constructs for orchestrating the execution of multiple strata (`waitfor/and`, `waitfor/or`, `waitfor/while`, `collapse`) in a structured way, as well as a facility for implementing more complex concurrency scenarios (`reifiedStratum`). ### Pausing execution - [::builtins::hold] The `hold` function can be called with a number argument `t` to suspend the current stratum for ~`t` milliseconds: hold(1000); // the next code will be executed after around 1s Calling `hold` with an `undefined` argument suspends the current stratum indefinitely. ### Suspending execution - [::syntax::waitfor-resume] The `waitfor()` construct suspends the current stratum until explicitly resumed. waitfor() { // ... "suspending code block" ... } // ... next code ... It is typically used to create a stratified wrapper around plain javascript functions that make use of callback parameters. ### Fork-join composition - [::syntax::waitfor-and] StratifiedJS offers several different constructs for running and coordinating multiple concurrent strata. One of the most straightforward ways is to use fork-join composition - which executes multiple branches of code concurrently and continues only once all branches have completed. This is achieved with SJS's `waitfor/and` construct: waitfor { ... some code ... } and { ... some other code ... } ... next code ... ### Alt composition - [::syntax::waitfor-or] Alt ('alternatives') composition explores a set of alternatives concurrently, and resumes as soon as any code path completes. It is expressed with SJS's `waitfor/or` construct: waitfor { ... some code ... } or { ... some other code ... } ... next code ... ### Collapsing alternatives - [::syntax::collapse] The `collapse` keyword can be used to prematurely collapse the strata in a `waitfor/or` construct. ### Asymmetric composition - [::syntax::waitfor-while] In asymmetric composition, the lifetime of one stratum is controlled by the lifetime of another, but not the other way around. ### Cancellation There are a number of situations under which suspended code gets cancelled, e.g. when another branch in a `waitfor/or` construct finishes first, or when a branch in a `waitfor/and` returns early: function foo() { waitfor { ...some suspending code... } and { ... return; } } Here, if `some suspending code` is still suspended by the time of the `return` call in the other branch, it will be cancelled. Cancellation means that a suspended `waitfor()`-construct will not wait for a call to its corresponding `resume` any more. Also, a `hold(t)` will not wake up any more. Any code in the cancelled stratum coming after the aborted suspended code will not be executed any more. ### Handling retraction - [::syntax::try-catch-retract-finally] Cancellation can be "caught" much like exceptions using `try/retract`: try { ... some suspending code ... } retract { console.log("'some suspending code' has been cancelled!"); } ### Accessing strata under the hood - [./syntax::reifiedStratum] StratifiedJS contains many higher-level concurrency primitives (such as dispatchers, semaphores, conditions, ...), all built on top of the structured concurrency language features detailed above. For more complicated concurrency scenarios that cannot easily be implemented with these facilities, StratifiedJS has the `reifiedStratum` keyword, which can be used within a function to access its [./builtins::Stratum] object. ## Syntax enhancements over JavaScript On top of the base JavaScript language, StratifiedJS supports a number of syntactic additions. Unlike the core stratified constructs, most of these (with the notable exception of blocklambdas) are *syntactic sugar* - they don't add anything the language couldn't already do, but they provide a convenient and readable syntax for constructs that can otherwise be cumbersome to express. ### String interpolation - [::syntax::string-interpolation] *using the same syntax as Ruby and CoffeeScript* String interpolation allows you to insert the value of an expression into a string literal. It can only be used inside double-quotes: console.log("Hello, #{name}!"); // equivalent to: console.log("Hello, " + name + "!"); ### Quasi quotes - [::syntax::quasi-quote] *a simplified version of the ECMAScript Harmony [Quasi-Literal / Template String](http://wiki.ecmascript.org/doku.php?id=harmony:quasis) proposal* Quasi-quotes ("quasis") look like strings, but are delimited by backticks (\`) instead of single or double quotes. Within a quasi, you can insert interpolated expressions by placing them inside `${ ... }`. Unlike string interpolation, a quasi-quoted value is a rich object. It maintains the embedded values alongside the literal portions, allowing the recipient to choose how embedded values are converted. ### Function chaining - [::syntax::double-dot] *created for SJS; although we later discovered [elixir](http://elixir-lang.org/)'s `|>` pipe operator was created independently with the same functionality* The double-dot operator allows you to chain function calls in a way similar to a pipeline or a sequence of method invocations in a [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface). var numbers = [1,2,3,4,5]; var even = x -> x % 2 == 0; numbers .. filter(even) .. each(console.log); // prints out: // 2 // 4 ### Blocklambda syntax - [::syntax::blocklambda] *adopted from the [block lambda revival](http://wiki.ecmascript.org/doku.php?id=strawman:block_lambda_revival) proposal for ECMAScript* Blocklambdas are a cross between anonymous functions and the builtin block syntax for conditional statements, loops, function bodies, etc. They are commonly used with the [sequence::] module, e.g: items .. each {|item| if (item.id == id) { console.log("found it!"); break; } } ### Arrow Function Syntax - [::syntax::arrow-function] *adopted from the proposed ECMA-262 Edition 6 arrow syntax and CoffeScript's arrow syntax* Arrow syntax is a shorthand for a function that only consists of a single expression and which returns the result of this expression. var add = (x, y) -> x + y; // equivalent to: var add = function(x, y) { return x + y; }; You can also bind the current value of `this` by using the "fat arrow" variant: var addOne = (x) => this.add(x, 1); // equivalent to: var x = function(x) { return this.add(x, 1); }.bind(this);
"""Import required libraries""" %matplotlib inline import numpy as np import tensorflow.compat.v1 as tf tf.disable_eager_execution() from sklearn import datasets as ds import matplotlib.pyplot as plt """Import dataset""" boston = ds.load_boston() x_raw = boston.data[:,np.argwhere(boston.feature_names == 'RM')[0,0]] y_raw = boston.target """Prepare and split the data""" total_count = x_raw.shape[0] split = int(total_count * 0.6) # Shuffle the data to avoid any ordering bias.. np.random.seed(0) shuffle = np.random.permutation(total_count) x = x_raw[shuffle] y = y_raw[shuffle] x_train_unnormalised = x[:split] y_train_unnormalised = y[:split] x_test_unnormalised = x[split:] y_test_unnormalised = y[split:] print('Training set size:', x_train_unnormalised.shape[0]) print('Test set size:', x_test_unnormalised.shape[0]) """Define a visulisation function""" def plot_data(x, y): plt.figure(figsize=[10,8]) plt.plot(x, y, 'b+') plt.grid(True) plt.xlabel('Average number rooms per dwelling') plt.ylabel('Mean value of home') plot_data(x_train_unnormalised, y_train_unnormalised) plt.title('Plot of the Training Data') """Normalising function and checks to ensure the data is normalised""" def normalise_data(x_unnormalised): b = x_unnormalised.mean(axis=0) a = x_unnormalised.std(axis=0) x_normalised = (x_unnormalised - b) / a return x_normalised, a, b def unnormalise_data(x_normalised, a, b): x_unnormalised = a * x_normalised + b return x_unnormalised try: x_train, x_norm_a, x_norm_b = normalise_data(x_train_unnormalised) y_train, y_norm_a, y_norm_b = normalise_data(y_train_unnormalised) x_test, _, _ = normalise_data(x_test_unnormalised) y_test, _, _ = normalise_data(y_test_unnormalised) except Exception as err: print('Error during normalisation functions:', err) def checking_function(normalise_data, unnormalise_data, data_to_check): passes_check = False est_normalised_data, est_a, est_b = normalise_data(data_to_check) est_unnormalised_data = unnormalise_data(est_normalised_data, est_a, est_b) passes_check = np.all(np.isclose(est_unnormalised_data, data_to_check), axis=0) return passes_check try: if (checking_function(normalise_data, unnormalise_data, x_train_unnormalised) == True) and \ (checking_function(normalise_data, unnormalise_data, y_train_unnormalised) == True): print('Passes checking function :)') else: print('Failed to pass the checking function :(') except Exception as err: print('Error during checking function:', err) # Plot the data to make sure they are normalised.. try: plot_data(x_train, y_train) plt.title('Plot of the (Normalised) Training Data') except Exception as err: print('Error during ploting functions:', err) """Define a function to calculate least squares regression and checking function""" def least_squares_error(x, y, w, c): y_estimates = w*x + c a = np.square(y - y_estimates) squared_error = np.sum(a) return squared_error try: print('Squared error for w = 1.5, c = 0.5 is ', least_squares_error(x_train, y_train, w=1.5, c=0.5)) except Exception as err: print('Error during least squares calculation:', err) """Analytical solution with NumPy, checking funtion and visualise""" def least_squares_analytic_solution(x, y): x_mean = np.sum(x)/len(x) y_mean = np.sum(y)/len(y) n = len(x) w = (n*np.sum(x*y) - np.sum(x)*np.sum(x*y))/(n*np.sum(np.square(x)) - np.square(np.sum(x))) c = y_mean - w*x_mean return w, c try: w_opt, c_opt = least_squares_analytic_solution(x_train, y_train) print('Analytic solution:') print('Analytic w = ', w_opt) print('Analytic c = ', c_opt) except Exception as err: print('Error during least squares analytic solution:', err) def plot_estimated_y_for_input_x(w, c): y = w*x + c fig = plt.figure() ax = plt.axes() ax.plot(x, y) pass try: plot_data(x_train, y_train) plt.title('Analytic Linear Regression (Training Data)') plot_estimated_y_for_input_x(w_opt, c_opt) print('Mean least squares error on TRAINING data = ', least_squares_error(x_train, y_train, w_opt, c_opt) / x_train.shape[0]) plot_data(x_test, y_test) plt.title('Analytic Linear Regression (Testing Data)') plot_estimated_y_for_input_x(w_opt, c_opt) print('Mean least squares error on TEST data = ', least_squares_error(x_test, y_test, w_opt, c_opt) / x_test.shape[0]) except Exception as err: print('Error during plotting:', err) """Test TensorFlow against NumPy function""" tf.reset_default_graph() try: # Constants to hold the training data.. t_x_train = tf.constant(x_train, name='x_train') t_y_train = tf.constant(y_train, name='y_train') except Exception as err: print('Error defining training data:', err) # Initial values for optimisation.. w_initial_guess = 1.5 c_initial_guess = 0.5 # Variables to hold w and c t_w = tf.Variable(w_initial_guess, dtype=tf.float64, name='w') t_c = tf.Variable(c_initial_guess, dtype=tf.float64, name='c') try: t_least_squares_error = calculate_tf_least_squares_error(t_x_train, t_y_train, t_w, t_c) with tf.Session() as session: session.run(tf.global_variables_initializer()) t_gradient_wrt_w = tf.gradients(t_least_squares_error, t_w) t_gradient_wrt_c = tf.gradients(t_least_squares_error, t_c) tf_grad_w = session.run(t_gradient_wrt_w) tf_grad_c = session.run(t_gradient_wrt_c) print('Tensorflow gradient wrt w = ', tf_grad_w) print('Tensorflow gradient wrt c = ', tf_grad_c) except Exception as err: print('Error using calculate_tf_least_squares_error() to find gradients:', err) def calc_gradients_for_least_squares(x, y, w, c): grad_w = 0 grad_c = 0 for i in range(len(x)): grad_w += (2 * w * np.square(x[i])) + (2 * x[i] * c) - (2 * x[i] * y[i]) grad_c += (2 * w * x[i]) + (2 * c) - (2 * y[i]) return grad_w, grad_c try: numpy_grad_w, numpy_grad_c = calc_gradients_for_least_squares(x_train, y_train, w_initial_guess, c_initial_guess) print('Analytic gradient wrt w = ', numpy_grad_w) print('Analytic gradient wrt c = ', numpy_grad_c) # This should pass if they are the same to nummerical precision! assert(np.isclose(tf_grad_w, numpy_grad_w)) assert(np.isclose(tf_grad_c, numpy_grad_c)) except Exception as err: print('Error during calculation with calc_gradients_for_least_squares():', err) """Implement gradient descent optimisation and visualisation (TensorFlow)""" # Keep track of parameter values over iterations.. w_current = w_initial_guess c_current = c_initial_guess try: # Keep track of the error.. E_current = least_squares_error(x_train, y_train, w_current, c_current) except Exception as err: print('Error defining training data:', err) # Keep track of the step size.. current_step_size = 0.001 num_iterations = 20 converge_threshold = 1e-8 try: for iteration in range(num_iterations): def run_iteration(x_train, y_train, w_current, c_current, E_current, current_step_size, converge_threshold): # Set to True when converged.. converged = False grad_w, grad_c = calc_gradients_for_least_squares(x_train, y_train, w_current, c_current) w_new = w_current - grad_w * current_step_size c_new = c_current - grad_c * current_step_size E_new = least_squares_error(x_train, y_train, w_current, c_current) if E_new > E_current: current_step_size -= 0.01 E_diff = E_current - E_new if E_diff > 0 and E_diff < 0.000000000001: converged = True # Take the step w_current = w_new c_current = c_new E_current = E_new return w_current, c_current, E_current, current_step_size, converged w_current, c_current, E_current, current_step_size, converged = \ run_iteration(x_train, y_train, w_current, c_current, E_current, current_step_size, converge_threshold) print('iteration %4d, E = %f, w = %f, c = %f' % (iteration, E_current, w_current, c_current)) if converged: # Break out of iteration loop.. print('Converged!') break print('\nAfter gradient descent optimisation:') print('Optimised w = ', w_current) print('Optimised c = ', c_current) print('\nAnalytic solution:') print('Analytic w = ', w_opt) print('Analytic c = ', c_opt) except Exception as err: print('Error during run_iteration():', err)
import TableTennisWebComponent from "../../components/TableTennisWebComponent/TableTennisWebComponent" import MatchStatistics from "../../components/Matches/MatchStatistics/MatchStatistics" import "./Match.css" import React, { useEffect, useContext, useState, useRef } from 'react'; import { TechnologyContext } from "../../providers/TechnologyProvider"; import { useParams } from 'react-router-dom'; import axios from "axios"; // * Match page export default function Match() { // Get the loggedIn and accessToken state const { loggedIn, accessToken } = useContext(TechnologyContext); // Set state const [match, setMatch] = useState("") const [reloadPage, setReloadPage] = useState(false); // Get the match Id from the URL const { id } = useParams(); // Get matches info from matches api endpoint useEffect(() => { if (!loggedIn) { return; } axios.get(`http://localhost:5005/api/matches/${id}`, { headers: { authToken: `Bearer ${accessToken}` }, }) // Set header to Bearer to get access approved by the auth. .then((res) => { setMatch(res.data[0]); }) .catch((error) => console.log(error)); }, [loggedIn, reloadPage]); const handleFinishMatch = () => { setReloadPage(!reloadPage); } // console.log(matches); if (!loggedIn) { return null; } return ( <div className="match-container"> {match.finished === true ? ( <MatchStatistics props={match} /> ) : ( <TableTennisWebComponent handleFinishMatch={handleFinishMatch}/> )} </div> ) }
import { forwardRef } from 'react' import { cn } from '@/utils/cn' import type { ComponentPropsWithRef, ReactNode } from 'react' type IconButtonProps = Readonly< { variant?: 'default' | 'danger' | 'ghost' | 'rounded' | 'close' | 'base' disabled?: boolean onClick?: () => void label: string icon: ReactNode className?: string } & ComponentPropsWithRef<'button'> > export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>( ({ variant = 'default', disabled, className, onClick, label, icon }, ref) => { return ( <button ref={ref} type='button' aria-label={label} disabled={disabled} onClick={onClick} className={cn( 'inline-flex border-0 border-transparent transition-colors disabled:pointer-events-none disabled:opacity-50', { 'rounded-md p-1 text-gray-600 hover:bg-gray-100 hover:text-blue-500': variant === 'default', 'rounded-md p-1 text-red-600 hover:border-red-600 hover:bg-red-600/20': variant === 'danger', 'rounded-full bg-transparent p-3 hover:bg-brand-black4': variant === 'rounded', 'rounded-md bg-transparent px-4 py-2 hover:bg-brand-black4': variant === 'ghost', 'rounded-full p-1': variant === 'close', 'text-black/40 hover:text-black/50': variant === 'base', }, className )} > {icon} </button> ) } ) IconButton.displayName = 'IconButton'
/* */ // const login = (username, callback) => { // setTimeout(() => { // callback(username) // }, 1000) // } const login = (username) => { return new Promise((resolve, reject) => { setTimeout(() => { if (username) { resolve(username) } else { reject(new Error('아이디를 입력해주세요.')) } }, 1000) }) } login('chris').then((username) => { console.log(`${username}님 안녕하세요.`); }).catch((error) => { console.log(error); }) const addToCart = (product) => { return new Promise((resolve, reject) => { setTimeout(() => { if (product) { resolve(product) } else { reject(new Error('there is no product')) } }, 1000) }) } addToCart('potato').then((product) => { console.log(`${product}이 위시리스트에 담겼어요!`); }).catch((error) => { console.log(error); }) const payment = (cardNumber, product) => { const strCardNumber = cardNumber.toString() return new Promise((resolve, reject) => { setTimeout(() => { if (strCardNumber.length < 15) { reject(new Error('카드 번호 에러')) return; } if (!product) { reject(new Error('결제할 상품이 없습니다.')) return; } resolve(product) }, 1000) }) } payment('121321113', 'potato') .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }) login('') .catch(() => { return 'anonymous' }) .then((username) => { console.log(`${username}님 안녕하세요.`); return addToCart('sweet potato') }) .then(product => { console.log(`${product}이 위시리스트에 담겼어요!`); return payment('123213213213213', product) }) .then((product) => { console.log(`${product} 상품이 결제 완료 되었습니다.`); }) .catch((error) => { console.log(object); })
<template> <h3>Slide Bar</h3> <p>Slide Bar is used to slide value.</p> <h5>Demo:</h5> <div class="demo-wrapper"> <!-- normal slide bar --> <p>This is a normal Slide Bar with default percentage:</p> <span id="range-slider-1-value"></span> <SlideBar id="range-slider-1" :default-slide-value="80" text-position="float-text" @slide-change="slideChangeEvent" /> <!-- fixed text slide bar with custom number--> <p>This is a fixed text Slide Bar with custom number:</p> <span id="range-slider-2-value"></span> <SlideBar id="range-slider-2" :default-slide-value="0" :max-slide-value="256" range-type="number" text-position="fixed-text" @slide-change="slideChangeEvent" /> </div> <DataTable :table-props="tableProps"></DataTable> <h5>Usage:</h5> <h6>Insert component:</h6> <highlightjs language="html" :code="insertCode" /> <h6>Import:</h6> <highlightjs language="js" :code="importCode" /> <h6>Apply in template:</h6> <highlightjs language="js" :code="templateCode" /> <FooterMessage /> </template> <script> import { computed } from "vue"; import { SlideBar, DataTable } from "../src"; import FooterMessage from "./common/FooterMessage.vue"; export default { name: "SlideBarDemo", components: { SlideBar, DataTable, FooterMessage }, setup() { const insertCode = computed(() => { return ` <!-- normal slide bar --> <SlideBar id="range-slider-1" :default-slide-value="80" text-position="float-text" @slide-change="slideChangeEvent" /> <!-- fixed text slide bar with custom number--> <SlideBar id="range-slider-2" :default-slide-value="0" :max-slide-value="256" range-type="number" text-position="fixed-text" @slide-change="slideChangeEvent" /> `; }); const importCode = computed(() => { return ` import { SlideBar } from "air-vue""; `; }); const templateCode = computed(() => { return ` const slideChangeEvent = (event) => { // Do something with the event document.querySelector("#" + event.id + "-value").innerHTML = event.number; }; `; }); const tableProps = computed(() => { return { title: "Props/Events Guide", //optional tableHead: [ { label: "Name", field: "name", }, { label: "Type", field: "type", }, { label: "Required", field: "required", }, { label: "Default", field: "default", }, { label: "Description", field: "description", }, ], tableBody: [ { name: "id", type: "String", required: "true", default: "-", description: "identifier of component", }, { name: "default-slide-value", type: "Number", required: "false", default: "0", description: "default slide value", }, { name: "text-position", type: "String", required: "false", default: "fixed-text", description: "text position of bar", }, { name: "max-slide-value", type: "Number", required: "false", default: "100", description: "max value of bar", }, { name: "range-type", type: "String", required: "false", default: "percentage", description: "number or percentage", }, { name: "slide-change", type: "<Event>", required: "true", default: "-", description: "event when slide bar value changed", }, ], }; }); const slideChangeEvent = (event) => { // Do something with the event document.querySelector("#" + event.id + "-value").innerHTML = event.number; }; return { insertCode, importCode, templateCode, tableProps, slideChangeEvent, }; }, }; </script> <style lang="scss"> .demo-wrapper { > * { display: inline-block; margin-right: 50px; } } </style>
// ignore_for_file: file_names, non_constant_identifier_names import 'package:flutter/material.dart'; import 'package:miniproj/Functions/FindListFunc.dart'; import '../Lists/Cart.dart'; class CartWidget2 extends StatefulWidget { final VoidCallback updateTotal; final int? CartLength; const CartWidget2({ super.key, required this.updateTotal, this.CartLength, }); @override State<CartWidget2> createState() => _CartWidget2State(); } class _CartWidget2State extends State<CartWidget2> { int cartCount = 0; cartlength() { if (Cart.length > 3) { cartCount = 3; } else { cartCount = Cart.length; } return cartCount; } cartItemAdd(index) { Cart[index]["Qty"] += 1; widget.updateTotal(); setState(() {}); } cartItemRemove(index) { if (Cart[index]["Qty"] > 1) { Cart[index]["Qty"] -= 1; } else { final productNameToRemove = Cart[index]["Name"]; final productListName = Cart[index]["Category"]; List productList = FindList(productListName); final productIndex = productList .indexWhere((product) => product["Name"] == productNameToRemove); if (productIndex != -1) { productList[productIndex]["InCart"] = false; productList[productIndex]["Qty"] = 0; } Cart.remove(Cart[index]); } widget.updateTotal(); setState(() {}); } @override Widget build(BuildContext context) { return ListView.builder( itemCount: widget.CartLength ?? cartlength(), itemBuilder: ((context, index) { return Column( children: [ ListTile( leading: Image.asset( "assets/images/Image Icon2.png", color: const Color.fromARGB(255, 30, 34, 43), ), title: Text( Cart[index]["Name"], style: const TextStyle( fontSize: 14, fontWeight: FontWeight.w500, color: Color.fromARGB(255, 30, 34, 43), ), ), subtitle: Text( "\$${Cart[index]["Price"].toString()}", style: const TextStyle( fontSize: 14, fontWeight: FontWeight.w400, color: Color.fromARGB(255, 30, 34, 43), ), ), trailing: Row( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ IconButton( onPressed: () { cartItemRemove(index); }, icon: const Icon( Icons.remove_circle_outlined, color: Color.fromARGB(255, 204, 204, 204), )), Text( (Cart[index]["Qty"]).toString(), style: const TextStyle( fontSize: 14, fontWeight: FontWeight.w500, color: Color.fromARGB(255, 30, 34, 43), ), ), IconButton( onPressed: () { cartItemAdd(index); }, icon: const Icon( Icons.add_circle_outlined, color: Color.fromARGB(255, 204, 204, 204), )), ], ), ), Container( height: 1.5, width: MediaQuery.of(context).size.width * 0.85, color: const Color.fromARGB(255, 235, 235, 251), ) ], ); }), ); } }
import pandas as pd from urllib.parse import urlparse, parse_qs # 1. Load the CSV and Extract UTM Parameters click_data_path = 'clicks.csv' click_df = pd.read_csv(click_data_path, parse_dates=['timestamp']) def extract_utm_parameters(url): params = parse_qs(urlparse(url).query) return params.get('utm_source', [None])[0], params.get('utm_medium', [None])[0] click_df['utm_source'], click_df['utm_medium'] = zip(*click_df['url'].apply(extract_utm_parameters)) # 2. Define the timestamps when the links were sent out sent_times = { 'gain-urgent': pd.Timestamp('2023-10-25 15:16:00'), 'gain-noturgent': pd.Timestamp('2023-10-25 17:57:00'), 'neutral-urgent': pd.Timestamp('2023-10-18 18:30:00'), 'neutral-noturgent': pd.Timestamp('2023-10-25 17:33:00'), 'loss-urgent': pd.Timestamp('2023-10-25 15:16:00') } # 3. Filter records and calculate response times response_times = {} total_clicks = {} for key, sent_time in sent_times.items(): source, medium = key.split('-') filtered = click_df[(click_df['utm_source'] == source) & (click_df['utm_medium'] == medium) & (click_df['timestamp'] >= sent_time) & (click_df['timestamp'] <= sent_time + pd.Timedelta(hours=24))] time_diffs = (filtered['timestamp'] - sent_time).dt.total_seconds() / 60 # in minutes response_times[key] = time_diffs total_clicks[key] = len(time_diffs) print(total_clicks) # 4. Calculate descriptive statistics and click rates for each condition stats_data = { 'condition': [], 'mean_time': [], 'median_time': [], 'std_dev_time': [], 'click_rate': [] } total_links_sent = { 'gain-urgent': 232, 'neutral-urgent': 213, 'loss-urgent': 202 } total_sent = { 'gain-urgent': 232, 'neutral-urgent': 213, 'loss-urgent': 202, 'gain-noturgent': 201, 'neutral-noturgent': 211, } for condition, total_sent in total_sent.items(): stats_data['condition'].append(condition) stats_data['mean_time'].append(response_times[condition].mean()) stats_data['median_time'].append(response_times[condition].median()) stats_data['std_dev_time'].append(response_times[condition].std()) stats_data['click_rate'].append(total_clicks[condition] / total_sent) stats_df = pd.DataFrame(stats_data) print(stats_df) total_sent = { 'gain-urgent': 232, 'neutral-urgent': 213, 'loss-urgent': 202, 'gain-noturgent': 201, 'neutral-noturgent': 211, } clicked_counts = { 'gain-urgent': total_clicks.get('gain-urgent', 0), 'neutral-urgent': total_clicks.get('neutral-urgent', 0), 'loss-urgent': total_clicks.get('loss-urgent', 0), 'gain-noturgent': total_clicks.get('gain-noturgent', 0), 'neutral-noturgent': total_clicks.get('neutral-noturgent', 0) } not_clicked_counts = {key: total_sent[key] - clicked_counts[key] for key in clicked_counts.keys()} contingency_table = pd.DataFrame({ 'Condition': ['gain-urgent', 'neutral-urgent', 'loss-urgent'], 'Clicked': [clicked_counts['gain-urgent'], clicked_counts['neutral-urgent'], clicked_counts['loss-urgent']], 'Not-Clicked': [not_clicked_counts['gain-urgent'], not_clicked_counts['neutral-urgent'], not_clicked_counts['loss-urgent']] }) print(contingency_table) contingency_table.to_csv('contingency_table_h1.csv', index=False) from scipy.stats import chi2_contingency # Using the Clicked and Not-Clicked columns for the Chi-squared test observed = contingency_table[['Clicked', 'Not-Clicked']].values chi2, p, _, _ = chi2_contingency(observed) print(f"Chi2 value: {chi2}") print(f"P-value: {p}")
#ifndef LINKQUEUE_H #define LINKQUEUE_H #include <stdio.h> #include <stdlib.h> #include "../common.h" typedef int QElemType; typedef struct QNode { QElemType data; struct QNode *next; }QNode, *QueuePtr; typedef struct { QueuePtr front; QueuePtr rear; }LinkQueue; /* * 初始化链队列 */ Status InitQueue(LinkQueue *Q); /* * 销毁 */ Status DestroyQueue(LinkQueue *Q); /* * 清空 */ Status ClearQueue(LinkQueue *Q); /* * 判空 */ Status QueueEmpty(LinkQueue Q); /* * 队列长度 */ int QueueLength(LinkQueue Q); /* * 头部 */ Status GetHead(LinkQueue Q, QElemType *e); /* * 队尾插入元素 */ Status EnQueue(LinkQueue *Q, QElemType e); /* * 删除队头元素 */ Status DeQueue(LinkQueue *Q, QElemType *e); /* * 遍历队列 */ Status QueueTraverse(LinkQueue Q, void (Visit)(ElemType)); /* * 打印元素 */ void Visit(ElemType); #endif
<div fxLayout="column" fxLayout.gt-sm="row wrap"> <div fxFlex="100" class="flex-p"> <mat-card> <mat-card-content> <mat-accordion> <mat-expansion-panel [expanded]="false"> <mat-expansion-panel-header> <mat-panel-title> Filtros de busqueda </mat-panel-title> <mat-panel-description> </mat-panel-description> </mat-expansion-panel-header> <div> <form [formGroup]="form" class="form" (ngSubmit)="onSearch(form.value)" autocomplete="off"> <div fxLayout="row" fxLayout.xs="column wrap" fxLayoutGap="10px" fxFlexFill> <div fxFlex> <div fxLayout="row" fxLayout.xs="column wrap" fxLayoutGap="10px" fxFlexFill> <div fxFlex> <mat-form-field appearance="fill" class="form"> <mat-label>Tipo Documento Identidad</mat-label> <mat-select formControlName="tipoDocumentoIdentidadId" (selectionChange)="onSelectionTipoDocIdentidad($event.value)"> <mat-option *ngFor="let item of tipoDocumentoClientes" [value]="item.tipoDocumentoIdentidadId"> {{item.nombre}} </mat-option> </mat-select> </mat-form-field> </div> <div fxFlex> <mat-form-field appearance="fill"> <mat-label>Número Documento</mat-label> <input matInput formControlName="numeroDocumento" maxlength="12"> <button mat-button type="button" matSuffix mat-icon-button aria-label="Search" (click)="searchNroDoc()"> <mat-icon>search</mat-icon> </button> <mat-error *ngIf="form.controls.numeroDocumento.errors?.pattern"> Ingrese correctamente el número de documento </mat-error> <mat-error *ngIf="form.controls.numeroDocumento.errors?.maxlength"> El número documento no debe ser mayor a 12 caracteres </mat-error> </mat-form-field> </div> </div> </div> <div fxFlex> <mat-form-field appearance="fill"> <mat-label> Nombre Cliente</mat-label> <input matInput formControlName="clienteNombre" maxlength="200" readonly> </mat-form-field> </div> </div> <div fxLayout="row" fxLayout.xs="column wrap" fxLayoutGap="10px" fxFlexFill> <div fxFlex> <mat-form-field appearance="fill" class="form"> <mat-label>Tipo Recibo Ingreso</mat-label> <mat-select formControlName="tipoReciboIngresoId"> <mat-option *ngFor="let item of tipoReciboIngresos" [value]="item.tipoReciboIngresoId"> {{item.nombre}} </mat-option> </mat-select> </mat-form-field> </div> <div fxFlex="30"> <mat-form-field appearance="fill" class="form"> <mat-label>Estados</mat-label> <mat-select formControlName="estado"> <mat-option *ngFor="let item of estados" [value]="item.numero"> {{item.nombre}} </mat-option> </mat-select> </mat-form-field> </div> </div> <div fxLayout="row" fxLayoutAlign="center center"> <div fxFlex style="text-align: center;"> <div class="button-row"> <button color="accent" mat-raised-button>Buscar</button> <button type="button" (click)="onClean()" mat-raised-button>Limpiar</button> </div> </div> </div> </form> </div> </mat-expansion-panel> </mat-accordion> <br> <div fxLayout="row" fxLayoutAlign="end center"> <div fxFlex style="text-align: right;"> <div class="button-row"> <button type="button" *ngIf="onAccion(accionEnum.AGREGAR)" color="primary" (click)="openDialogNew()" mat-raised-button type="button">Nuevo</button> </div> </div> </div> <div style="padding-bottom: 10px;"></div> <mat-divider></mat-divider> <div style="padding-top: 10px;"></div> <div> <mat-progress-bar mode="indeterminate" *ngIf="dataSource.loading | async"></mat-progress-bar> <div class="table-container"> <div class="table-response"> <table mat-table [dataSource]="dataSource" matSort matSortDisableClear> <!-- Id Column --> <ng-container matColumnDef="index" sticky> <th mat-header-cell *matHeaderCellDef> Nro</th> <td mat-cell *matCellDef="let row;"> {{ row?.index}}</td> </ng-container> <!-- Numero Column --> <ng-container matColumnDef="numero" sticky> <th mat-header-cell *matHeaderCellDef> Número </th> <td mat-cell *matCellDef="let row; let i = index"> {{ row?.numero}} </td> </ng-container> <!-- Fecha Column --> <ng-container matColumnDef="fechaRegistro"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Fecha </th> <td mat-cell *matCellDef="let row"> {{row?.fechaRegistro | date:'dd-MM-yyyy'}} </td> </ng-container> <!-- Estado Column --> <ng-container matColumnDef="estado"> <th mat-header-cell *matHeaderCellDef> Estado</th> <td mat-cell *matCellDef="let row"> {{ row?.estadoNombre}} </td> </ng-container> <!-- Numero Documento Column --> <ng-container matColumnDef="tipoDocumentoIdentidad"> <th mat-header-cell *matHeaderCellDef> Tipo Doc. Identidad </th> <td mat-cell *matCellDef="let row"> {{row?.cliente?.tipoDocumentoNombre}} </td> </ng-container> <!-- Numero Documento Column --> <ng-container matColumnDef="numeroDocumento"> <th mat-header-cell *matHeaderCellDef> Número Documento </th> <td mat-cell *matCellDef="let row"> {{row?.cliente?.numeroDocumento}} </td> </ng-container> <!-- Nombre Cliente Column --> <ng-container matColumnDef="nombreCliente"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Nombre y Apellidos / Razón Social </th> <td mat-cell *matCellDef="let row"> {{row?.cliente?.nombre}} </td> </ng-container> <!-- Correo Column --> <ng-container matColumnDef="correo"> <th mat-header-cell *matHeaderCellDef> Correo electrónico </th> <td mat-cell *matCellDef="let row"> {{row?.cliente?.correo}} </td> </ng-container> <!-- Tipo Recibo Column --> <ng-container matColumnDef="tipoReciboIngreso"> <th mat-header-cell *matHeaderCellDef> Tipo recibo ingreso</th> <td mat-cell *matCellDef="let row">{{row?.tipoReciboIngreso?.nombre}} </td> </ng-container> <!-- Banco Column --> <ng-container matColumnDef="banco"> <th mat-header-cell *matHeaderCellDef> Banco</th> <td mat-cell *matCellDef="let row"> {{row?.banco?.nombre}} </td> </ng-container> <!-- Número Cuenta Corriente Column --> <ng-container matColumnDef="cuentaCorriente"> <th mat-header-cell *matHeaderCellDef> Cta. Cte.</th> <td mat-cell *matCellDef="let row">{{row?.cuentaCorriente?.numero}} </td> </ng-container> <!-- Nro Deposito Column --> <ng-container matColumnDef="numeroDeposito"> <th mat-header-cell *matHeaderCellDef> Número Depósito</th> <td mat-cell *matCellDef="let row"> {{row?.numeroDeposito}}</td> </ng-container> <!-- Monto Deposito Column --> <ng-container matColumnDef="importeDeposito"> <th mat-header-cell *matHeaderCellDef> Monto Depósito (S/.) </th> <td mat-cell *matCellDef="let row"> {{row?.importeDeposito| number:'.2-2'}}</td> </ng-container> <!-- Fecha Deposito Column --> <ng-container matColumnDef="fechaDeposito"> <th mat-header-cell *matHeaderCellDef> Fecha Depósito</th> <td mat-cell *matCellDef="let row"> {{row?.fechaDeposito | date:'dd-MM-yyyy'}}</td> </ng-container> <!-- ValidarDeposito Column --> <ng-container matColumnDef="validarDeposito"> <th mat-header-cell *matHeaderCellDef> Validado</th> <td mat-cell *matCellDef="let row"> <span *ngIf="row.validarDeposito==validaDepositoEnum.PENDIENTE"> Pendiente </span> <span *ngIf="row.validarDeposito==validaDepositoEnum.SI"> Si </span> <span *ngIf="row.validarDeposito==validaDepositoEnum.NO"> No </span> </td> </ng-container> <!-- Expediente SINAD Column --> <ng-container matColumnDef="expedienteESinad"> <th mat-header-cell *matHeaderCellDef> Reg. SINAD </th> <td mat-cell *matCellDef="let row">{{row?.expedienteESinad}} </td> </ng-container> <!-- Nro Oficio Column --> <ng-container matColumnDef="numeroOficio"> <th mat-header-cell *matHeaderCellDef> Nro Oficio</th> <td mat-cell *matCellDef="let row"> {{ row?.numeroOficio}}</td> </ng-container> <!-- Comp. Pago Column --> <ng-container matColumnDef="numeroComprobantePago"> <th mat-header-cell *matHeaderCellDef> Comp. Pago</th> <td mat-cell *matCellDef="let row"> {{ row?.numeroComprobantePago}}</td> </ng-container> <!-- Expediente Siaf Column --> <ng-container matColumnDef="expedienteSiaf"> <th mat-header-cell *matHeaderCellDef> SIAF Nro.</th> <td mat-cell *matCellDef="let row"> {{ row?.expedienteSiaf}}</td> </ng-container> <!-- Nro Resolucion Column --> <ng-container matColumnDef="numeroResolucion"> <th mat-header-cell *matHeaderCellDef> Nro Resolución</th> <td mat-cell *matCellDef="let row"> {{ row?.numeroResolucion}}</td> </ng-container> <!-- Actions Column --> <ng-container matColumnDef="actions" stickyEnd> <th mat-header-cell *matHeaderCellDef class="center"> Acciones </th> <td mat-cell *matCellDef="let row; let i = index" class="center"> <button mat-icon-button [matMenuTriggerFor]="menu"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #menu="matMenu"> <button mat-menu-item (click)="openDialogInfo(row)"> <mat-icon aria-label="Show">touch_app</mat-icon> <span>Ver Información</span> </button> <button mat-menu-item (click)="openDialogEdit(row)" *ngIf=" (row.estado == estadoRegLineaEnum.EMITIDO || row.estado == estadoRegLineaEnum.EN_PROCESO) && onAccion(accionEnum.MODIFICAR)"> <mat-icon aria-label="Edit">edit</mat-icon> <span>Editar</span> </button> <button mat-menu-item (click)="onProcess(row)" *ngIf="row.estado == estadoRegLineaEnum.EMITIDO && onAccion(accionEnum.APROBAR)"> <mat-icon aria-label="Aprobar">hourglass_empty</mat-icon> <span>En Proceso</span> </button> <button mat-menu-item (click)="onDerivar(row)" *ngIf="row.estado == estadoRegLineaEnum.EN_PROCESO && onAccion(accionEnum.DERIVAR)"> <mat-icon aria-label="Derivar">forward</mat-icon> <span>Derivar</span> </button> <button mat-menu-item (click)="onDesestimar(row)" *ngIf="row.estado == estadoRegLineaEnum.EN_PROCESO && onAccion(accionEnum.DESESTIMAR)"> <mat-icon aria-label="Desestimar">thumb_down_alt</mat-icon> <span>Desestimar</span> </button> <button mat-menu-item (click)="openDialogObservar(row)" *ngIf="row.estado == estadoRegLineaEnum.EN_PROCESO && onAccion(accionEnum.OBSERVAR)"> <mat-icon aria-label="Observar">report</mat-icon> <span>Observar</span> </button> <button mat-menu-item (click)="onAutorizar(row)" *ngIf="(row.estado == estadoRegLineaEnum.DERIVADO || row.estado == estadoRegLineaEnum.OBSERVADO) && onAccion(accionEnum.CONFIRMAR)"> <mat-icon aria-label="Autorizar">check_circle</mat-icon> <span>Autorizar</span> </button> <button mat-menu-item (click)="onEmitRI(row)" *ngIf="row.estado == estadoRegLineaEnum.AUTORIZAR && onAccion(accionEnum.REMITIR)"> <mat-icon aria-label="EmitRI">add_box</mat-icon> <span>Emitir R.I</span> </button> <button mat-menu-item (click)="onDelete(row)" *ngIf="row.estado == estadoRegLineaEnum.EMITIDO && onAccion(accionEnum.ELIMINAR)"> <mat-icon aria-label="Edit">delete_outline</mat-icon> <span>Eliminar</span> </button> </mat-menu> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"> </tr> </table> <div class="no-results" *ngIf="!(dataSource.loading | async)" [style.display]="dataSource.data.length === 0 ? '' : 'none'"> No se encontraron registros </div> </div> <mat-paginator [length]="dataSource.total" [pageSize]="10" [pageSizeOptions]="[5,10,20,50]" showFirstLastButtons> </mat-paginator> </div> </div> </mat-card-content> </mat-card> </div> </div>
# 07_如何构建经济学思维方式 张是之:个人如何通过自学构建经济学的思维方式 个人简介: 张是之 电子科学与技术硕士。《经济学家告诉你》特约撰稿人,10W+ 阅读量文章作者。爱好读书码 字、足球、摄影。 《共同成长社区》的分享,并不是 “私密” 的,我们不在乎分享内容是否流出去,事实上, 我们会主动拿出绝大多数的内容分享至社区之外 —— 因为所有的分享,最终传播得越广越有 价值。 若要进一步了解《共同成长社区》,请在后台点击 “收费社群” 的子按钮 “共同成长” …… 请注意:共同成长社区已停止接受直接加入,请参阅这篇文章。 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 大家好,我是张是之,很高兴能在这里跟大家分享自己经济学的学习过程。 我原来是学电子材料的,2012 年偶然接触到经济学,发现了经济学的大厦,深深被其解释世 界的洞察力所折服,于是开始自己钻研经济学。越是深入学习,越是体会到了经济学的乐趣 。系统阅读经济学积累了两年之后,从去年开始写文章锻炼思考,尝试以经济学理论解释日 常生活中的现象,发现写文章对自己重新梳理思路帮助非常大。 坚持写了一年多,2014 年开始陆续有文章被「凤凰财知道」等公众号发表或转载,唯一一篇 阅读量 10w+ 的文章是今年在《丁香园》发的《钟南山院士为什么错了?》,现在是《经济 学家告诉你》特约撰稿人。今天我分享的题目是: 个人如何通过自学构建经济学的思维方式。 一、为什么要学习经济学?也就是为什么要建立经济学的思维方式? 首先,什么是经济学的思维方式? 罗辑思维节目在讲《魔鬼经济学》的时候,讲到了一个概念,「机会成本」的概念。这个概 念非常重要,笑来说的学习就是要掌握概念,对这个概念的掌握情况就是很好的对经济学思 维方式的一个检验。 被经济学家熊彼特称为「有史以来最出色的经济新闻记者」,法国政评作家巴斯夏,他生前 耗时一年多写的最后一篇文章是《看得见的与看不见的》(“What Is Seen and What Is Not Seen”),在 1850 年发表,是一篇传世经典。文章系统驳斥了「破窗理论」、「公共工程」 、「贸易管制」等一系列有些今天还在流行的谬误。 通过反驳这些谬误,巴斯夏告诉我们一个好的经济学家和一个坏的经济学家的区别是什么? 坏经济学家仅仅局限于看到可以看得见的后果,好经济学家却能同时考虑可以看得见的 后果和那些只能推测到的后果。 这种区别很重要,因为一般情况都是,当时的结果看起来不错,但后续结果却很糟糕;或者 恰恰相反。 巴斯夏所说「看得见的和看不见的」,这是好经济学家与坏经济学家的区别。而实际上在我 看来,这是一个有没有经济学思维方式的人之间的区别。需要提醒注意的是,这个思维方式 不一定要学习了经济学才能具备,有些人通过生活经验的积累加上天赋,也可以具备这种能 力,比如优秀的企业家。但大多数人,仅凭经验积累是无法形成经济学的思维方式的。 我自己也属于平庸的大多数,只是一直以来坚持阅读,终于幸运地闯进了经济学的大厦,颠 覆了很多传统的认知思维模式,三观尽毁。为什么说是颠覆三观呢?因为我们的生活经验的 积累,大多数是基于看得见的、摸得着的事物和经历,在逻辑思维模式的形成过程中,往往 忽视了看不见的那一部分。 既看不见,又不曾经历过,是很难自我锻炼出经济学的思维方式的。这就需要我们站在巨人 的肩膀上,帮助我们建立起一个系统的经济学思维方式。如果回答开始的问题,什么是经济 学的思维方式?实际上是一种能力,就是透过现象看到逻辑,再透过逻辑看到你原先没有看 见的东西的,这样的一种能力。 眼见不一定为实,透过逻辑上的思考和锻炼,帮助我们更好地认识和理解这个世界,选择不 同的视角和层次去分析问题,经常会颠覆你原来既有的认知观念,这就是经济学毁三观的原 因。用经济学家薛兆丰所说的就是,改造「世界」,非经济学所长;但改造「世界观」,却 是经济学的强项。但经济学的作用并不仅仅局限于、停留在改变世界观,而是可以改变世界 。 经济学本身的三大作用: 解释世界; 评价世界; 改造世界。 解释世界、评价世界是基本职能,是经济学家的工作; 改造世界,则往往是企业家的特长,经济学家通常是通过影响和改变人们的认知观念来改变 世界的。 休谟: 所有的人类事务,也完全是由意见支配的。 凯恩斯: 事实上,这个世界就是由极少数思想统治的。 比如这些用观念在影响世界的经济学家“斯们”: 马克思、凯恩斯、米塞斯、科斯等等。 他们给我们带来的认知世界角度的变化,使我们更容易接近真理、接近事物的本质,也就更 容易提高效率。 举几个我们国家自己的例子,比如: 小岗村村民仅仅是为了种田打粮,当年却要签订「生死状」来搞土地承包; 当年农民能不能自己养鸡卖鸡蛋,却是关乎「姓社」还是「姓资」的问题争论; 直到 1997 年《刑法》才取消了「投机倒把罪」,直到 2009 年才从法律中彻底删去与 「投机倒把」有关的规定,而这个当年被认为是「犯罪」的行为实际上仅仅是为了赚个 差价而已。 如果用理工类做一个类比的话,牛顿定律是解释世界的,基于牛顿定律的工程设计,比如飞 机、汽车的设计则需要通过牛顿定律来检验设计的可行性,而最终的设计实现,实际上是改 变了世界。 类似的还有量子力学和电子计算机的发展应用,没有基础的对于世界的正确解释,在应用层 面的工程设计,进步是非常缓慢的。而经济学,则是在人类行动的底层上提供逻辑解释,当 人们对行动逻辑的理解越正确,人类协作的效率才会越高,科技进步、社会发展才会更好。 [](+/不确定性原理 ~/bin/.m2doc/note) 经济学上,在解释世界上要求客观中立,不做价值判断,仅仅回答「是什么」以及「为什么 」。但在评价世界的层面,比如我们要判断一项政策出台是好是坏,作为科学的经济学要严 格停留在科学的边界上,不做好坏判断,但作为个人的经济学家,是可以回答的,回答的依 据之一就是「政策的实施能否达到它自身所宣称的目的」,假如暂时抛开目的本身伦理上的 正义性,政策能够达到它自己说的目的,那这个政策可以说是好的,如果达不到目的,甚至 南辕北辙,有相反的作用,这个时候,我们是没法说一个政策是好的。 在基于正确的解释,和客观的评价上,做出改造世界的选择才不至于带来意想不到的不好的 结果。大可以到整个人类、国家,小可以到公司事务、自己的选择决定,这个解释、评价、 改造的方法,都可以给我们提供有力的思考依据。所以,我的建议是,每个人都应该懂点经 济学,学会用经济学的思维方式,去发现一般人所看不见的东西。不仅仅是寻找思考的乐趣 ,对我们日常工作和生活的帮助作用,也是很明显的。 二、经济学兴趣的挖掘和培养(荐书三本) 经济学所带来的思维上的乐趣,就像笑来说的跑步的乐趣,有些人快有些人慢,所以我的建 议是从易到难,不要想一上来就指望能搞懂整个经济学的知识架构,一上来就看非常专业的 经济学教科书,各种图表曲线。那样不好,容易吃坏了胃口。那样学习曲线比较陡峭,很多 人还没体会到乐趣,就放弃继续探索了。 我自己的阅读经历,还是要从小事,甚至是身边具体的例子入手,或者从书籍上看到一些生 活中的例子,看看别人是怎么用经济学的思维方式思考的,然后再去尝试搭建一个属于自己 的思维体系和知识架构。比如生活中的小例子,大家在工作中都会有一个体会,那就是分工 不明确的时候,工作容易出问题,而出问题之后又容易推诿扯皮,没有人为后果负责。应对 办法,那就是责任到人。比如海尔公司的每一块玻璃上都会有打上清洁人和检查人的编码, 分工到具体的人。 由于缺乏具体负责人而带来的不好的结果,以及没有人为此负责的这些案例,通过经济学家 前辈们的抽象总结,就是「公地悲剧」(the Common Tragedy)。而理解了公地悲剧这个概 念之后,再遇到类似的问题,我们就很容易找到问题的解决办法。有了经济学之「道」的基 础,管理类科学则是在其上之「术」,更容易驾驭和掌握。 再举几个不太容易让人接受的经济学思维方式的案例,我去年曾经写过一篇文章《世界就是 这么狗血》,说的是象牙问题: 国际社会都在通过禁令来保护大象,而实际上恰恰是禁令让大象蒙受灾难。这也是一个 「公地悲剧」的案例,正确的做法是让大象有主人,而且要允许主人通过大象来获利, 包括卖象牙,这样他才有保护的动机。 这样看上去太残忍,但实际上有利于大象种群繁衍的做法。 不过既无法得到那些环保主义者的认可,也无法在国际社会得到支持,所以我们看到每 年都会有组织或者部门出来作秀,打击盗猎组织、没收销毁象牙等等,但实际上每年的 作秀都是对之前工作的一种否定。 人们在分析社会问题的时候,是非常容易受到情感左右的。《世界就是这么狗血》一文中的 象牙,换做酒精制品、毒品,甚至买卖儿童的问题上,逻辑上依然成立。但当缺乏足够的思 维锻炼,我们的大脑被感情所支配的时候,一开始就会排斥这个问题的分析思路,更不用说 认真思考其中的逻辑链条了。 关于禁酒令的案例,罗辑思维节目在讲《魔鬼经济学》以及高晓松的《晓松奇谈》在 6 月 3 日那期都有讲过,还有美剧《大西洋帝国》,感兴趣的不妨看一看。在诺奖得主加里 · 贝克 尔(Garys Becker)开辟用经济学分析日常生活现象之后,经济学帝国主义之名开始崛起。 这类书籍现在有不少,对于兴趣的培养,是非常有帮助的,推荐十本不成问题,如果精选三 本的话,我建议是: 薛兆丰的《经济学通识》; 亨利·黑兹利特的《一课经济学》; 加里·贝克尔的《生活中的经济学》。 三、系统阅读,深入思考,理解概念(荐书三本) 市面上有很多写经济方面的书,微信上也有很多这方面的文章,这一类想看是怎么都看不完 的,因为每天都会有新的文章生产出来。这里存在一个问题,那就是,这些都是别人告诉我 们的,作者自己的观点,不是我们自己分析得出的。如果要在一个具体的事情上形成自己的 判断,那就要求形成自己的知识架构,有自己的分析思路。 整个经济学的大厦,实际上源于人类至少面临四项普遍约束: 人类种种制度安排,都是为了应付这些约束而衍生的。它们对应着四个规律: 东西不够; 生命有限; 人际依赖; 需要协调。 列个表是这样的,更清晰一些。 人类至少面临四 经济学家总结出 人类社会所产生出的制度(并非对应) 项普遍约束 的对应规律 1 东西不够 需求定律 a.用于降低交易费用的制度,如货币、期货市场 2 生命有限 利息理论 b.用于影响生产要素的所有者之间配置风险的制度, 如合约、公司、保险等 3 人际依赖 产业理论 c.用于提供职能组织与个人收入间的联系制度,如税 收 4 需要协调 宏观理论 d.用于确立公共品和服务的生产与分配的框架制度, 如高速公路、机场、学校等 而在这四个理论规律支撑之下,所构建起来的经济学体系,就是我们洞察社会万象的工具。 帮助我们抽丝剥茧,透过看得见的事物表面,去看清背后看不见的真相,这样才能正确合理 地评估真正的得与失。这也就是我们开头所说的经济学的思维方式。 我个人是从张五常教授的《经济解释》开始接触到经济学的,张五常是芝加哥学派出身的, 是新制度经济学的奠基人之一。他的《经济解释》我读了大概不下 5 遍,每一遍都有新的收 获。张五常是阿尔钦的学生,同时,阿尔钦也深刻影响着薛兆丰的学术思想,薛兆丰在北京 大学的授课贯穿着阿尔钦的影响。 如果是个人自学的话,我推荐从张五常的《经济解释》(四卷本)入手,不推荐萨缪尔森的 《经济学》、以及曼昆的《经济学原理》,虽然这两本书在销量和名气上可能超过《经济解 释》。第一遍看《经济解释》不要指望能够全部看懂,这套书好就好在谋篇布局上很合理, 从浅入深,学习曲线比较缓慢。 推荐的第二本书是保罗 · 海恩(Paul Heyne)等著的《经济学的思维方式》,史晨翻译的。 这本书既受到了阿尔钦的学术影响,同时还吸收了奥地利学派的思想,强调市场过程的动态 性和企业家的作用。另外一点,这本书中有些图表和案例帮助我们理解一些关系,相比于张 五常《经济解释》单纯用文字描述逻辑,图表曲线还是更直观一些。 推荐的第三本书,是一代宗师,奥地利学派的领军人物米塞斯(Mises)的长篇巨著《人的行 动》。上海世纪出版集团出版的余晖译本是译作《人的行动》,而上海社科院出版的是夏道 平版本的译本《人的行为》。我看的是前者,当时后者还没出版,从概念的准确性上来讲, 「人的行动」其实更准确一点,不过据说夏道平版本的翻译更好一些,这个版本也买了,但 是还没有开始看。 作为鸿篇巨著,当然是比较难啃的,所以建议在看完前两本之后再看。如果把前两本能啃下 来,米塞斯的这本《人的行动》看起来就不会那么吃力。米塞斯所代表的奥地利学派,与张 五常所代表的芝加哥学派还是有很大不同的,这个不同主要集中在方法论上,也就是分析方 法上不一样,虽然得出的结论有些是相同的。 对于个人自学者,如果对自己要求比较高的话,到后期还是可以精进一步,做深入研究探索 的。这里简单提一下两者在方法论上的区别。张五常在方法论上更像是借鉴了物理学的方法 论,公理假设、观察验证,并以卡尔·波普尔的可证伪性作为是否为科学的依据。 而在米塞斯这里,不是套用物理学的分析方法,而是用的几何学的推演方法。从公理出发, 推演出整个人的行动——有目的的行动。在米塞斯为代表的奥地利学派,这套推演因为逻辑自 洽,严谨完整,就像勾股定理一样存在着绝对正确。但如果现实与推演发生了偏差,怎么办 ?从现实中找问题,找出与推演不一致的原因所在,往往这些原因都是藏在事物背后,不容 易被轻易观察到,只有借助于逻辑推演,才能发现其中的问题。 举个例子说明吧。在欧式几何中,三角形内角和恒为 180°,这个不是测量的结果,而是从欧 式几何的公理出发推演出来的定理,这是没有问题的。我们并不需要去测量每一个三角形, 然后相加看是否等于180°,以此来检验这个定理。相反,如果你派一个下属去测量一个三角 形,下属呈上的报告三个角之和不为 180°,那么我们不是怀疑这个定理不对,也不需要亲自 再去测量,而是直接告诉下属他测量的数据不对,或者他操作有误,又或者测量工具出现了 问题。 另外,由罗伯特 · P · 墨菲(Robert P. Murphy)著,吴烽炜翻译的《人的行动》学习指南 ,可以帮助学习,只不过这本书还没有出版,有电子版的,稍后放上下载链接。 以上三本《经济解释》、《经济学的思维方式》,和《人的行动》都是我读过的。北京大学 出版社,去年出版了一本张维迎教授的《经济学原理》,我大概翻看了一下结构,也应该是 一本不错的入门书籍,同样推荐一下。 四、如何用写作帮助经济学的学习 学过一门知识、一个观点,最好的测试是不看书、不用其他的辅助工具,向一个门外汉解释 你知道的东西,能不能把问题讲清楚,让别人明白其中道理,这是一个很好的方法,能够证 明你是否真的懂了。只有经过了自己的思考和书写,或者经过自己的讲述,才能让自己的思 路更清晰。所谓「教是最好的学,书写是为了更好的思考」,学经济尤其如此,要跟自己辩 论、跟其他人辩论,然后自己总结下来,写出来,才能知道自己是不是真的懂了。 除非是老师,有着得天独厚的教学条件,一般人是没有太多机会通过教授知识来更好地掌握 知识的。不过也有办法,那就是讨论、或者辩论。当你逐步养成了经济学的思维方式来看待 问题的时候,有诸多的社会热点问题,你可能既不会同意传统媒体的看法,也不会同意来自 大众的声音。这就很有可能造成了你与周围朋友、同事的不同意见。这个时候其实是绝好的 锻炼机会。 这个时候,找那些能够理性思考、认真讨论问题的朋友,来讨论一下,跟他们交换一下不同 看法。记住,要找能认真思考、且具备逻辑思考能力的人,如果找一个感情用事、缺乏逻辑 思考能力的人讨论的话,多半是不欢而散,还伤及友情得不偿失。是讨论,或者是辩论,注 意不要变成了争论。要能够把控讨论的范围和节奏,在不破坏友情的前提下充分阐述自己的 思考和逻辑,虽然有时候你是在重复别人的逻辑,但这是很好、也是很有用的梳理自己思路 的锻炼方式。 另外一个锻炼方式,就是写作。把你想要表达的东西,落笔纸上。只有你能够清晰地表达出 自己的观点,说明才是真的懂了,而不是似是而非的明白。我在2014年读到了某专家关于支 持最低工资的言论,实在是看不下去,就有那种如鲠在喉、不吐不快的感觉。当晚没耽误, 从晚上十点写到凌晨一点多,然后发给了「凤凰财知道」栏目的编辑,没想到第二天接着就 录用发出了。这也给了我一定的鼓励,从此开始尝试用写作锻炼自己的思考。 不光自己写,在系统建构知识框架,打好理论基础之后,还要看别人怎么用通俗的语言阐述 深刻的经济学原理的。深入浅出的表达,与学习外语一样,是需要大量的输入,然后才能输 出的。2014年开始写,2015年慢慢写的更多了一点,今年年初给自己定下目标每周一篇,到 目前为止是32篇,超额完成了目标。在此过程中陆续在不同的地方刊出过文章,到现在成为 公众号《经济学家告诉你》的特约作者,算是对自己努力的一种肯定吧,当然离优秀还是有 很大距离的。 自学精进的途径,讨论和写作,注意投稿交流,以文会友,你自己慢慢的水平高了,才能认 识更高水平的朋友,看到更大的差距,也学到更多的东西。 五、如何利用小组来学习 笑来的「新生大学」,包括这个共同成长的群,大家都各有所长,都具备了很强的学习能力 。如何利用小组来学习,是我的一个简单的思考,还不成熟,分享出来。 具备一定自学能力的人,如何快速学习?特别是如何通过网络高效地来运作这个学习机制? 我的思考是大概以下三点: 1. 小组以周为单位指定书目的章节,共同阅读; 2. 每周固定一个时间,在小组内以文字形式提问; 3. 学习小组成员认领问题以作解答,认领问题之后每周固定一个时间作为共同的讨论和答 疑,先由认领问题的成员回答,最好是书面回答,然后由学习小组的负责人作补充解答 。 平时在规定时间内,可以自由讨论,这样的学习是互补式的,也是启发式的。一个人提出的 问题,也许是别人没想到的,而另外一个人的回答,也许同样是别人没想到的。一问一答的 来回,所有人在参与过程中都会有所收获。如此循环往复,只要能坚持往前走,即使不好啃 的书,我想很快也能拿下。如果群内成员有分析问题的文章,也可以在群内分享出来共同讨 论,如何提高。以上这些过程可以很方便地通过网络来完成。 如果可能,我计划写一本书,书名暂定《人人都是经济学家》,希望能够通过更通俗的讲解 ,让一个完全没有经济学基础的文科生、理科生们能够快速步入经济学的殿堂,体会到思考 的乐趣,发现更多的事实和真相。 最后,小结一下今天的内容: 经济学的思维方式,就是透过现象看到逻辑,再透过逻辑看到原先没有看见的东西的一 种能力,这种能力可以帮助我们更好地理解世界、评价世界和改造世界; 这种能力大多数人并不是天生具备,但同时是可以通过学习前辈大师们的著作,不断思 考锻炼,逐步构建起来的;如果感兴趣,不妨先看几本浅显的书籍培养兴趣,更精进一 步,则需要系统的掌握经济学主体框架,为己所用; 而让自己快速进步的方法是主动去讨论、写作以及小组学习。 有句话说: 人们总是相信他们选择相信的东西。 其实就是有什么样的世界观,就是有什么样的世界。你相信剥削理论,那就很容易感觉世道 不公,到处都是剥削;你相信没有买卖就没有杀害,就不容易跳出原有思维的误区。 只要你愿意,随着阅读和思考的深入,我们会逐渐纠正原先错误的观念和认识,这就是一种 进步吧。只要你愿意,人人都可以成为经济学家。
package endpoint import ( "github.com/a10networks/terraform-provider-thunder/thunder/axapi" "github.com/clarketm/json" ) //based on ACOS 6_0_2_P1-37 type ZoneLocalZoneCfg struct { Inst struct { LocalType int `json:"local-type"` Uuid string `json:"uuid"` Name string } `json:"local-zone-cfg"` } func (p *ZoneLocalZoneCfg) GetId() string{ return "1" } func (p *ZoneLocalZoneCfg) getPath() string{ return "zone/" +p.Inst.Name + "/local-zone-cfg" } func (p *ZoneLocalZoneCfg) Post(authToken string, host string, logger *axapi.ThunderLog) error { logger.Println("ZoneLocalZoneCfg::Post") headers := axapi.GenRequestHeader(authToken) payloadBytes, err := axapi.SerializeToJson(p) if err != nil { logger.Println("Failed to serialize struct as json", err) return err } logger.Println("payload:", string(payloadBytes)) _, _, err = axapi.SendPost(host, p.getPath(), payloadBytes, headers, logger) return err } func (p *ZoneLocalZoneCfg) Get(authToken string, host string, instId string, logger *axapi.ThunderLog) error { logger.Println("ZoneLocalZoneCfg::Get") headers := axapi.GenRequestHeader(authToken) _, axResp, err := axapi.SendGet(host, p.getPath(), "", nil, headers, logger) if err == nil { if len(axResp) > 0{ err = json.Unmarshal(axResp, &p) } if err != nil { logger.Println("json.Unmarshal() failed with error", err) } } return err } func (p *ZoneLocalZoneCfg) Put(authToken string, host string, logger *axapi.ThunderLog) error { logger.Println("ZoneLocalZoneCfg::Put") headers := axapi.GenRequestHeader(authToken) payloadBytes, err := axapi.SerializeToJson(p) if err != nil { logger.Println("Failed to serialize struct as json", err) return err } logger.Println("payload: " + string(payloadBytes)) _, _, err = axapi.SendPut(host, p.getPath(), "", payloadBytes, headers, logger) return err } func (p *ZoneLocalZoneCfg) Delete(authToken string, host string, instId string, logger *axapi.ThunderLog) error { logger.Println("ZoneLocalZoneCfg::Delete") headers := axapi.GenRequestHeader(authToken) _, _, err := axapi.SendDelete(host, p.getPath(), "", nil, headers, logger) return err }
const mongoose = require('mongoose'); const supertest = require('supertest'); const app = require('../app'); const api = supertest(app); const bcrypt = require('bcrypt'); const User = require('../models/user'); describe('User testit', () => { beforeEach(async () => { await User.deleteMany({}); const passwordHash = await bcrypt.hash('sekret', 10); const user = new User({ username: 'root', passwordHash }); await user.save(); }); test('userin luominen epäonnistuu jos username ei ole uniikki', async () => { const usersAtStart = await User.find({}); const newUser = { username: 'root', name: 'Superuser', password: 'salainen', }; const result = await api .post('/api/users') .send(newUser) .expect(400) .expect('Content-Type', /application\/json/); expect(result.body.error).toContain('username must be unique'); const usersAtEnd = await User.find({}); expect(usersAtEnd).toHaveLength(usersAtStart.length); }); test('username ja password oltava tarpeeksi pitkiä', async () => { const newUser = { username: 'ro', name: 'Superuser', password: 'sa', }; const result = await api .post('/api/users') .send(newUser) .expect(400) .expect('Content-Type', /application\/json/); expect(result.body.error).toContain('username and password must be at least 3 characters long'); }); afterAll(() => { mongoose.connection.close(); }); });
#include <bits/stdc++.h> using namespace std; typedef long long ll; vector<string> output; #define MAXSIZE 1000 ll label[MAXSIZE]; int number = 1; string LongToString(long long long_num) // converts a long long integer to string for output purposes { stack<char> stringStack; string signValue = ""; if (long_num < 0) { signValue = "-"; long_num = -long_num; } if (long_num == 0) { stringStack.push('0'); } while (long_num > 0) { char convertedDigit = long_num % 10 + '0'; stringStack.push(convertedDigit); long_num /= 10; } string long_to_string = ""; while (!stringStack.empty()) { long_to_string += stringStack.top(); stringStack.pop(); } return signValue + long_to_string; } void r_type(ll binary[]) { string instruction; ll funct_7 = 0; ll shift = 6; for (ll i = 0; i < 7; i++) { funct_7 += (binary[i]) << (shift); shift--; } ll rs_2 = 0; shift = 4; for (ll i = 7; i < 12; i++) { rs_2 += (binary[i]) << (shift); shift--; } ll rs_1 = 0; shift = 4; for (ll i = 12; i < 17; i++) { rs_1 += (binary[i]) << (shift); shift--; } ll funct_3 = 0; shift = 2; for (ll i = 17; i < 20; i++) { funct_3 += (binary[i]) << (shift); shift--; } // cout << funct_7 << " " << funct_3 << endl ; ll rd = 0; shift = 4; for (ll i = 20; i < 25; i++) { rd += (binary[i]) << (shift); shift--; } if (funct_7 == 0) { if (funct_3 == 0) { instruction = "add"; } else if (funct_3 == 1) { instruction = "sll"; } else if (funct_3 == 2) { instruction = "slt"; } else if (funct_3 == 3) { instruction = "sltu"; } else if (funct_3 == 4) { instruction = "xor"; } else if (funct_3 == 5) { instruction = "srl"; } else if (funct_3 == 6) { instruction = "or"; } else if (funct_3 == 7) { instruction = "and"; } } else if (funct_7 == 32) { if (funct_3 == 0) { instruction = "sub"; } else if (funct_3 == 5) { instruction = "sra"; } } // cout << instruction << " x" << rd << " x" << rs_1 << " x" << rs_2 << endl; string inst = instruction + " x" + LongToString(rd) + ", x" + LongToString(rs_1) + ", x" + LongToString(rs_2); output.push_back(inst); } void i_type(ll binary[], ll type) { string instruction; ll immediate = 0; ll shift = 11; ll val_imm = 0; for (ll i = 0; i < 12; i++) { immediate += (binary[i]) << (shift); shift--; } if (immediate > 2047) { immediate -= 4096; } ll check = 0; shift = 5; for (ll i = 0; i < 6; i++) { check += (binary[i]) << (shift); shift--; } shift = 5; for (ll i = 6 ; i < 12 ; i++) { val_imm += (binary[i]) << (shift); shift--; } ll rs_1 = 0; shift = 4; for (ll i = 12; i < 17; i++) { rs_1 += (binary[i]) << (shift); shift--; } ll funct_3 = 0; shift = 2; for (ll i = 17; i < 20; i++) { funct_3 += (binary[i]) << (shift); shift--; } ll rd = 0; shift = 4; for (ll i = 20; i < 25; i++) { rd += (binary[i]) << (shift); shift--; } if (type == 1) { if (funct_3 == 0) { instruction = "addi"; } else if (funct_3 == 1) { instruction = "slli"; } else if (funct_3 == 2) { instruction = "slti"; } else if (funct_3 == 3) { instruction = "sltiu"; } else if (funct_3 == 4) { instruction = "xori"; } else if (funct_3 == 5) { if (check == 0) instruction = "srli"; else if (check >= 16) instruction = "srai"; } else if (funct_3 == 6) { instruction = "ori"; } else if (funct_3 == 7) { instruction = "andi"; } // cout << instruction << " x" << rd << " x" << rs_1 << " " << immediate << endl; string inst; if (funct_3 != 1 && funct_3 != 5) inst = instruction + " x" + LongToString(rd) + ", x" + LongToString(rs_1) + ", " + LongToString(immediate); else inst = instruction + " x" + LongToString(rd) + ", x" + LongToString(rs_1) + ", " + LongToString(val_imm); output.push_back(inst); } else if (type == 2) { if (funct_3 == 0) { instruction = "lb"; } else if (funct_3 == 1) { instruction = "lh"; } else if (funct_3 == 2) { instruction = "lw"; } else if (funct_3 == 3) { instruction = "ld"; } else if (funct_3 == 4) { instruction = "lbu"; } else if (funct_3 == 5) { instruction = "lhu"; } else if (funct_3 == 6) { instruction = "lwu"; } // cout << instruction << " x" << rd << " x" << rs_1 << " " << immediate << endl; string inst = instruction + " x" + LongToString(rd) + ", " + LongToString(immediate) + "(x" + LongToString(rs_1) +")"; output.push_back(inst); } else if (type == 3) { if (funct_3 == 0) { instruction = "jalr"; } // cout << instruction << " x" << rd << " x" << rs_1 << " " << immediate << endl; string inst = instruction + " x" + LongToString(rd) + ", x" + LongToString(rs_1) + ", " + LongToString(immediate); output.push_back(inst); } else if (type == 4) { if (funct_3 == 0) { if (immediate == 0) instruction = "ecall"; else instruction = "ebreak"; } // cout << instruction << " x" << rd << " x" << rs_1 << " " << immediate << endl; string inst = instruction + " x" + LongToString(rd) + ", x" + LongToString(rs_1) + ", " + LongToString(immediate); output.push_back(inst); } } void s_type(ll binary[]) { string instruction; ll immediate = 0; ll shift = 11; for (ll i = 0; i < 7; i++) { immediate += (binary[i]) << (shift); shift--; } if (immediate > 2047) { immediate -= 4096; } ll rs_2 = 0; shift = 4; for (ll i = 7; i < 12; i++) { rs_2 += (binary[i]) << (shift); shift--; } ll rs_1 = 0; shift = 4; for (ll i = 12; i < 17; i++) { rs_1 += (binary[i]) << (shift); shift--; } ll funct_3 = 0; shift = 2; for (ll i = 17; i < 20; i++) { funct_3 += (binary[i]) << (shift); shift--; } shift = 4; for (ll i = 20; i < 25; i++) { immediate += (binary[i]) << (shift); shift--; } if (funct_3 == 0) { instruction = "sb"; } else if (funct_3 == 1) { instruction = "sh"; } else if (funct_3 == 2) { instruction = "sw"; } else if (funct_3 == 3) { instruction = "sd"; } // cout << instruction << " x" << rs_2 << " (" << immediate << ")" << rs_1 << " " << endl; string inst = instruction + " x" + LongToString(rs_2) + ", " + LongToString(immediate) + "(x" + LongToString(rs_1) + ") "; output.push_back(inst); } void b_type(ll binary[], ll i) { string instruction; ll immediate = 0; immediate += (binary[0]) << (12); ll shift = 10; for (ll i = 1; i < 7; i++) { immediate += (binary[i]) << (shift); shift--; } ll rs_2 = 0; shift = 4; for (ll i = 7; i < 12; i++) { rs_2 += (binary[i]) << (shift); shift--; } ll rs_1 = 0; shift = 4; for (ll i = 12; i < 17; i++) { rs_1 += (binary[i]) << (shift); shift--; } ll funct_3 = 0; shift = 2; for (ll i = 17; i < 20; i++) { funct_3 += (binary[i]) << (shift); shift--; } shift = 4; for (ll i = 20; i < 24; i++) { immediate += (binary[i]) << (shift); shift--; } immediate += binary[24] << (11); if (immediate > 2047) { immediate -= 4096 * 2; } if (funct_3 == 0) { instruction = "beq"; } else if (funct_3 == 1) { instruction = "bne"; } else if (funct_3 == 4) { instruction = "blt"; } else if (funct_3 == 5) { instruction = "bge"; } else if (funct_3 == 6) { instruction = "bltu"; } else if (funct_3 == 7) { instruction = "bgeu"; } if (label[i + immediate / 4] == 0) { label[i + immediate / 4] = number; number++; } // cout << immediate << " hello \n"; // cout << instruction << " x" << rs_1 << " x" << rs_2 << " L" << label[i+immediate/4] << endl; string inst = instruction + " x" + LongToString(rs_1) + ", x" + LongToString(rs_2) + ", L" + LongToString(label[i + immediate / 4]); output.push_back(inst); } void u_type(ll binary[], ll type) { ll immediate = 0; ll shift = 31; string instruction; for (ll i = 0; i < 20; i++) { immediate += (binary[i]) << (shift); shift--; } ll rd = 0; shift = 4; for (ll i = 20; i < 25; i++) { rd += (binary[i]) << (shift); shift--; } if (type == 1) { instruction = "lui"; } else if (type == 2) { instruction = "auipc"; } char hex[10]; sprintf(hex, "%llX", immediate); // convert number to hex string modified; for (int i = 0; i < hex[i] != '\0'; i++) modified.push_back(hex[i]); ll size = modified.length(); modified = modified.substr(0, size - 3); string inst = instruction + " x" + LongToString(rd) + ", 0x" + modified; output.push_back(inst); } void j_type(ll binary[], ll i) { ll immediate = 0; immediate += (binary[0]) << (20); ll shift = 10; for (ll i = 1; i < 11; i++) { immediate += (binary[i]) << (shift); shift--; } immediate += (binary[11]) << (11); shift = 19; for (ll i = 12; i < 20; i++) { immediate += (binary[i]) << (shift); shift--; } ll rd = 0; shift = 4; if (immediate > 1048576) { immediate -= 2 * 1048576; } for (ll i = 20; i < 25; i++) { rd += (binary[i]) << (shift); shift--; } if (label[i + immediate / 4] == 0) { label[i + immediate / 4] = number; number++; } // cout << immediate; // cout << "jal" << " x" << rd << " L" << label[i+immediate/4] << endl; string inst = "jal x" + LongToString(rd) + ", L" + LongToString(label[i + immediate / 4]); output.push_back(inst); } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); for (ll i = 0; i < MAXSIZE; i++) label[i] = 0; vector<string> input; string line; ll n = 0; while (getline(cin, line)) { input.push_back(line); n++; } // converting into an integer using stoi function for (ll i = 0; i < n; i++) { ll machine_code = stoll(input[i], 0, 16); ll binary[32]; // converting the number into binary form ll dummy = machine_code; for (ll i = 1; i <= 32; i++) { binary[32 - i] = (dummy % 2); dummy /= 2; } // find opcode ll opcode = (machine_code) & (127); if (opcode == stoll("0110011", 0, 2)) // RISCV-R format { // cout << "It is R type instruction" << endl; r_type(binary); } else if (opcode == stoll("0010011", 0, 2)) { // cout << "It is I type instruction" << endl; i_type(binary, 1); } else if (opcode == stoll("0000011", 0, 2)) { // cout << "It is I type instruction" << endl; i_type(binary, 2); } else if (opcode == stoll("1100111", 0, 2)) { // cout << "It is I type instruction" << endl; i_type(binary, 3); } else if (opcode == stoll("1110011", 0, 2)) { // cout << "It is I type instruction" << endl; i_type(binary, 4); } else if (opcode == stoll("0100011", 0, 2)) { // cout << "It is S type instruction" << endl; s_type(binary); } else if (opcode == stoll("1100011", 0, 2)) { // cout << "It is B type instruction" << endl; b_type(binary, i); } else if (opcode == stoll("0110111", 0, 2)) { // cout << "It is U type instruction" << endl; u_type(binary, 1); } else if (opcode == stoll("0010111", 0, 2)) { // cout << "It is U type instruction" << endl; u_type(binary, 2); } else if (opcode == stoll("1101111", 0, 2)) { // cout << "It is J type instruction" << endl; j_type(binary, i); } } for (int i = 0; i < output.size(); i++) { if (label[i]) { cout << "L" << label[i] << ": "; } cout << output[i] << "\n"; } }
{% extends "layout.html" %} {% block body %} <div class="container" style="padding-top:50px"> <h1> Dashboard </h1> <hr> {% if not car %} <div class="alert alert-warning">You haven't yet configured a car. <a href="{{url_for("car_profile")}}" class="alert-link">Please do so here!</a></div> {% endif %} <h2> Battery Charge over time </h2> <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div> <h2> Estimated km driven</h2> <table class="table table-bordered"> <tr> <th>Day</th> <th>Km driven</th> </tr> {% for day, km in entries %} <tr> <td>{{day}}</td> <td>{{km}} km</td> </tr> {% endfor %} </table> </div> <script> $(function () { $('#container').highcharts({ chart: { zoomType: 'x', spacingRight: 20 }, title: { text: 'Battery Charge Levels' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', maxZoom: 900, // 15 minutes title: { text: null } }, yAxis: { title: { text: 'Charge Level' } }, tooltip: { shared: true }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, lineWidth: 1, marker: { enabled: false }, shadow: false, states: { hover: { lineWidth: 1 } }, threshold: null } }, series: [{ type: 'area', name: 'Charge Level', pointInterval: 50000, {% if timestamp %} pointStart: Date.UTC({{timestamp.year}}, {{timestamp.month}}, {{timestamp.day}}, {{timestamp.hour}}, {{timestamp.minute}}), {% endif %} data: {{data}} }], lang: { // Custom language option noData: "There is not yet data to display" }, /* Custom options */ noData: { // Custom positioning/aligning options position: { //align: 'right', //verticalAlign: 'bottom' }, // Custom svg attributes attr: { //'stroke-width': 1, //stroke: '#cccccc' }, // Custom css style: { //fontWeight: 'bold', //fontSize: '15px', //color: '#202030' } } }); }); </script> {% endblock %}
package com.awakening.ui.game.states; import com.awakening.ui.framework.gamestates.GameState; import com.awakening.ui.framework.gamestates.GameStateManager; import com.awakening.ui.framework.gui.Sound; import com.awakening.ui.framework.gui.WindowManager; import com.awakening.ui.framework.resources.Resources; import com.awakening.ui.framework.utils.MathHelper; import com.awakening.ui.game.entities.Enemy; import com.awakening.ui.game.entities.Entity; import com.awakening.ui.game.entities.Player; import com.awakening.ui.game.world.Feature; import com.awakening.ui.game.world.Room; import com.awakening.ui.game.world.Tile; import com.awakening.ui.game.world.World; import com.awakening.ui.game.world.generator.LevelGenerator; import com.awakening.ui.game.world.generator.RoomData; import java.awt.*; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.HashSet; import java.util.Objects; public class PlayingState extends GameState { // creates instances of different classes and arrays to be used private final LevelGenerator generator; private final World world; public static Player player; public static ArrayList<String> message = new ArrayList<>(); public static ArrayList<Integer> messageCounter = new ArrayList<>(); public static Sound music = new Sound(); public static Sound se = new Sound(); // Constructor public PlayingState(GameStateManager manager) { super(manager); generator = new LevelGenerator(); player = new Player(); this.generator.intializeGridForRooms(); this.generator.generateFloor(); this.world = new World(this.generator.getRoomsData()); generateLevel(1); regenerateBlocks(); generateItemsAndEnemies(); } // loops the frames in the current state @Override protected void loop() { player.move(); this.world.changeRoom(player); // Room names set up String roomName = LevelGenerator.getRoomName(World.getCurrentX(), World.getCurrentY()); player.setPlayerLoc(roomName); this.collisions(); checkWinLose(); World.getRoom().featureInteraction(player); player.regenerateHealth(); this.playerAttacks(); } /* If the player has a master key, patient file, journal and make their way back to the Front Desk, the player wins the game */ private void checkWinLose() { //Game Lose Scenario -> if the player's hp is less than or equal to 0, the player loses the game if (this.player.getHp() <= 0) { se.playSE(7); super.gameStateManager.stackState(new GameLoseState(gameStateManager)); } //Game Win Scenario -> check if the master key, patient file and journal are already in the inventory boolean masteryKeyFound = false; boolean patientFileFound = false; boolean journalFound = false; for (int i = 0; i < Player.getPlayerInventory().size(); i++) { //if( this.player.getPlayerInventory().contains()) Entity e = Player.getPlayerInventory().get(i); if (!patientFileFound && Player.getPlayerInventory().get(i).getID() == Resources.PATIENT_FILE) { patientFileFound = true; } if (!masteryKeyFound && Player.getPlayerInventory().get(i).getID() == Resources.MASTER_KEY) { masteryKeyFound = true; } if (!journalFound && Player.getPlayerInventory().get(i).getID() == Resources.JOURNAL) { journalFound = true; } if (masteryKeyFound && patientFileFound && journalFound && player.getPlayerLoc().equalsIgnoreCase("Front Desk")) { se.playSE(12); super.gameStateManager.stackState(new GameWinState(gameStateManager)); break; } } } @Override protected void render(Graphics graphics) { // displays current state World.getRoom().render(graphics); player.render(graphics); // displays current player and weapon if (Player.currentWeapon != null) { graphics.drawImage(Resources.TEXTURES.get(Player.currentWeapon.getID()), player.getAttackBox().x, player.getAttackBox().y, player.getAttackBox().width, player.getAttackBox().height, null); } else { graphics.drawImage(Resources.TEXTURES.get(Resources.ATTACK), player.getAttackBox().x, player.getAttackBox().y, player.getAttackBox().width, player.getAttackBox().height, null); } // Display position of player's health, armour and gold throughout the game graphics.setColor(Color.WHITE); graphics.setFont(new Font("arial", Font.BOLD, 17)); graphics.drawImage(Resources.TEXTURES.get(Resources.HEART), 0, 0, Tile.SIZE * 2 / 3, Tile.SIZE * 2 / 3, null); graphics.drawString(this.player.getHp() + "/" + this.player.getMaxHp(), Tile.SIZE * 2 / 3 + 4, 20); graphics.drawImage(Resources.TEXTURES.get(Resources.ARMOR), 92, 0, Tile.SIZE * 2 / 3, Tile.SIZE * 2 / 3, null); graphics.drawString(this.player.getArmor() + "", Tile.SIZE * 2 / 3 + 96, 20); graphics.drawImage(Resources.TEXTURES.get(Resources.GOLD), 168, 0, Tile.SIZE * 2 / 3, Tile.SIZE * 2 / 3, null); graphics.drawString(this.player.getGold() + "", Tile.SIZE * 2 / 3 + 173, 20); // render player's current location/ rooms name graphics.setColor(Color.BLACK); graphics.setFont(graphics.getFont().deriveFont(Font.BOLD, 23f)); graphics.drawString(player.getPlayerLoc(), 7, Tile.SIZE); graphics.setColor(Color.WHITE); graphics.setFont(graphics.getFont().deriveFont(Font.BOLD, 23f)); graphics.drawString(player.getPlayerLoc(), 5, Tile.SIZE-2); drawMessage(graphics); } // adds a text to be displayed using the drawMessage method public static void addMessage(String text) { message.add(text); messageCounter.add(0); } // draws a message. Always running in the background of the Playing State public void drawMessage(Graphics graphics) { int messageX = WindowManager.WIDTH - 1100; int messageY = WindowManager.HEIGHT - 100; graphics.setFont(graphics.getFont().deriveFont(Font.BOLD, 38f)); for (int i = 0; i < message.size(); i++) { if (message.get(i) != null) { graphics.setColor(Color.BLACK); graphics.drawString(message.get(i), messageX + 2, messageY + 2); graphics.setColor(Color.WHITE); graphics.drawString(message.get(i), messageX, messageY); int counter = messageCounter.get(i) + 1; messageCounter.set(i, counter); if (messageCounter.get(i) > 180) { message.remove(i); messageCounter.remove(i); Room.itemPickedUp = false; } } } } // Keys to be used in the current State @Override protected void keyPressed(int keyCode) { switch (keyCode) { case KeyEvent.VK_W: case KeyEvent.VK_UP: player.setUp(true); break; case KeyEvent.VK_A: case KeyEvent.VK_LEFT: player.setLeft(true); break; case KeyEvent.VK_S: case KeyEvent.VK_DOWN: player.setDown(true); break; case KeyEvent.VK_D: case KeyEvent.VK_RIGHT: player.setRight(true); break; case KeyEvent.VK_Q: case KeyEvent.VK_SPACE: player.attack(); break; case KeyEvent.VK_ESCAPE: super.gameStateManager.stackState(new Options(gameStateManager)); break; case KeyEvent.VK_I: super.gameStateManager.stackState(new Inventory(gameStateManager)); break; case KeyEvent.VK_M: super.gameStateManager.stackState(new Map(gameStateManager)); break; case KeyEvent.VK_P: super.gameStateManager.stackState(new PauseState(gameStateManager)); break; case KeyEvent.VK_ENTER: openMasterDoor(); openDoor(); break; } } // Makes the player stop moving when the keys are released @Override protected void keyReleased(int keyCode) { switch (keyCode) { case KeyEvent.VK_W: case KeyEvent.VK_UP: player.setUp(false); break; case KeyEvent.VK_A: case KeyEvent.VK_LEFT: player.setLeft(false); break; case KeyEvent.VK_S: case KeyEvent.VK_DOWN: player.setDown(false); break; case KeyEvent.VK_D: case KeyEvent.VK_RIGHT: player.setRight(false); break; case KeyEvent.VK_ESCAPE: break; case KeyEvent.VK_I: break; case KeyEvent.VK_M: break; } } private void generateLevel(int floorNum) { if (floorNum == 2) { //second floor World.setCurrentX(7); World.setCurrentY(2); // stairs to First Floor this.world.getRoom(7, 2).placeFeature(new Feature(Resources.UPPER_STAIRS, () -> generateLevel(3))); } else if (floorNum == 1) { //first floor this.world.getRoom(2, 2).placeFeature(new Feature(Resources.STAIRS, () -> generateLevel(2))); } else { World.setCurrentX(2); World.setCurrentY(2); this.world.getRoom(2, 2).placeFeature(new Feature(Resources.STAIRS, () -> generateLevel(2))); } this.spawnPlayer(); } private void generateItemsAndEnemies() { //first floor //place items in the rooms per the requirement generateChestInRoom(1, 0); generateItemInRoom(1, 0, Resources.CAMERA); generateChestInRoom(1, 2); generateChestInRoom(0, 2); generateItemInRoom(0, 2, Resources.PAPER_CLIP); generateItemInRoom(0, 2, Resources.BATTERIES); generateChestInRoom(1, 2); generateItemInRoom(1, 2, Resources.BANDAGES); generateChestInRoom(2, 1); generateItemInRoom(2, 1, Resources.CELLPHONE); generateItemInRoom(2, 2, Resources.MASTER_DOOR); generateItemInRoom(2, 2, Resources.AXE); generateItemInRoom(1, 3, Resources.KEY); generateItemInRoom(3, 2, Resources.PATIENT_FILE); //place enemies in the room per the requirement generateEnemyInRoom(1, 0, 10); // Basement generateEnemyInRoom(1, 2, 10); // Emergency Room generateEnemyInRoom(1, 2, 10); // Emergency Room generateEnemyInRoom(0, 2, 10); // Office generateEnemyInRoom(2, 2, 10); // Hallway generateEnemyInRoom(2, 1, 10); // Keypad Room generateBatsInRoom(3, 2, 5); // Patient Room generateBatsInRoom(3, 2, 5); // Patient Room generateBatsInRoom(3, 2, 5); // Patient Room generateBatsInRoom(3, 2, 5); // Patient Room generateBatsInRoom(3, 2, 5); // Patient Room generateBatsInRoom(1, 1, 5); // Morgue generateBatsInRoom(1, 1, 5); // Morgue generateBatsInRoom(1, 3, 5); // Front Desk generateBatsInRoom(1, 3, 5); // Front Desk generateBatsInRoom(1, 3, 5); // Front Desk generateBatsInRoom(1, 3, 5); // Front Desk generateBatsInRoom(1, 3, 5); // Front Desk //second floor //place items in the rooms per the requirement generateChestInRoom(6, 1); //pharmacy generateItemInRoom(6, 1, Resources.FIRST_AID_KIT); generateItemInRoom(6, 1, Resources.PRESS_PASS); generateChestInRoom(6, 2); //fellowship room generateItemInRoom(6, 2, Resources.WOOD_CANE); generateChestInRoom(6, 3); generateItemInRoom(6, 3, Resources.BARBELL); generateChestInRoom(5, 2); generateItemInRoom(5, 2, Resources.MASTER_KEY); generateItemInRoom(6, 2, Resources.DOOR); generateChestInRoom(7, 2); generateItemInRoom(7, 2, Resources.FIRE_EXTINGUISHER); generateChestInRoom(8, 2); generateItemInRoom(8, 2, Resources.TYLENOL); generateItemInRoom(8, 2, Resources.JOURNAL); //place enemies in the room per the requirement generateEnemyInRoom(6, 1, 10); // Pharmacy generateEnemyInRoom(6, 2, 10); // Fellowship Room generateEnemyInRoom(6, 3, 10); // Gym generateMainGhostInRoom(5, 2, 20); // Janitor Closet generateEnemyInRoom(5, 2, 10); // Janitor Closet generateEnemyInRoom(5, 2, 10); // Janitor Closet generateEnemyInRoom(5, 2, 10); // Janitor Closet generateEnemyInRoom(7, 2, 10); // U. Hallway generateEnemyInRoom(8, 2, 10); // Finance } // these methods generate the different Entities in the rooms private void generateChestInRoom(int roomX, int roomY) { this.world.getRoom(roomX, roomY).placeFeature(new Feature(Resources.CHEST, this::givePlayerRandomLoot)); } private void generateItemInRoom(int roomX, int roomY, byte resource) { this.world.getRoom(roomX, roomY).placeFeature(new Feature(resource, this::pickUpItem)); } private void generateEnemyInRoom(int roomX, int roomY, int enemyHp) { this.world.getRoom(roomX, roomY).spawnEnemy(new Enemy(Resources.ENEMY, enemyHp, player)); } private void generateBatsInRoom(int roomX, int roomY, int enemyHp) { this.world.getRoom(roomX, roomY).spawnEnemy(new Enemy(Resources.BAT, enemyHp, player)); } private void generateMainGhostInRoom(int roomX, int roomY, int enemyHp) { this.world.getRoom(roomX, roomY).spawnEnemy(new Enemy(Resources.GHOST_MAIN1, enemyHp, player)); } private void spawnPlayer() { if (this.world.getRoom(1, 0).getData().getTileAt(player.x / Tile.SIZE, player.y / Tile.SIZE).getID() != Resources.FLOOR) { player.replaceRandomly(); this.spawnPlayer(); } } // used to handle collisions in the rooms private void collisions() { RoomData roomIn = World.getRoom().getData(); for (int i = 0; i < roomIn.getSizeX(); i++) { for (int j = 0; j < roomIn.getSizeY(); j++) { player.handleCollisionWith(roomIn.getTileAt(i, j)); for (Enemy enemy : World.getRoom().getEnemies()) { enemy.handleCollisionWith(roomIn.getTileAt(i, j)); } } } } // randomly gives the player different items from the chests private void givePlayerRandomLoot() { switch (MathHelper.randomInt(3)) { case 0: player.addArmor(MathHelper.randomInt(3, 5)); se.playSE(6); break; case 1: player.giveGold(MathHelper.randomInt(3, 7)); se.playSE(6); break; case 2: player.instantHeal(MathHelper.randomInt(2, 5)); se.playSE(6); break; } } // used as a place holder for the generate items private void pickUpItem() { String text; if (Player.playerInventory.size() != Player.inventorySize) { text = "You have picked up an item!"; } else { text = "You cannot carry any more items!"; } } // used to attack the enemies and for the enemies to attack the player private void playerAttacks() { player.decreaseTime(); for (int i = 0; i < World.getRoom().getEnemies().size(); i++) { World.getRoom().getEnemies().get(i).move(); // when the enemy attacks the player if (World.getRoom().getEnemies().get(i).intersects(player)) { if (World.getRoom().getEnemies().get(i).getID() == Resources.BAT_2 || World.getRoom().getEnemies().get(i).getID() == Resources.BAT) { se.playSE(13); } else { se.playSE(5); } player.damage(5 - 5 * Player.getArmor() / 100); } // when the player attacks the enemy if (World.getRoom().getEnemies().get(i).intersects(player.getAttackBox())) { se.playSE(1); if (Player.currentWeapon != null) { World.getRoom().getEnemies().get(i).damage(Player.currentWeapon.getAttackPoints(), player.getFacing()); } else { World.getRoom().getEnemies().get(i).damage(player.getAttackPoints(), player.getFacing()); } if (World.getRoom().getEnemies().get(i).getHp() <= 0) { World.getRoom().getEnemies().remove(i); player.giveGold(MathHelper.randomInt(2, 5)); } } } } // for opening the master door private void openMasterDoor() { if (Objects.equals(LevelGenerator.getRoomName(World.getCurrentX(), World.getCurrentY()), "Hallway")) { RoomData roomIn = World.getRoom().getData(); for (int i = 0; i < Player.playerInventory.size(); i++) { if (Player.playerInventory.get(i).getID() == Resources.MASTER_KEY && player.intersects(roomIn.getTileAt(14, 3))) { gameStateManager.stackState(new UseKey(gameStateManager)); } else if (Player.playerInventory.get(i).getID() == Resources.MASTER_KEY && player.intersects(roomIn.getTileAt(14, 4))) { gameStateManager.stackState(new UseKey(gameStateManager)); } else if (Player.playerInventory.get(i).getID() == Resources.MASTER_KEY && player.intersects(roomIn.getTileAt(14, 5))) { gameStateManager.stackState(new UseKey(gameStateManager)); } } } } // for opening the regular door private void openDoor() { if (Objects.equals(LevelGenerator.getRoomName(World.getCurrentX(), World.getCurrentY()), "Fellowship Room")) { RoomData roomIn = World.getRoom().getData(); for (int i = 0; i < Player.playerInventory.size(); i++) { if (Player.playerInventory.get(i).getID() == Resources.KEY && player.intersects(roomIn.getTileAt(1, 3))) { gameStateManager.stackState(new UseKey(gameStateManager)); } else if (Player.playerInventory.get(i).getID() == Resources.KEY && player.intersects(roomIn.getTileAt(1, 4))) { gameStateManager.stackState(new UseKey(gameStateManager)); } else if (Player.playerInventory.get(i).getID() == Resources.KEY && player.intersects(roomIn.getTileAt(1, 5))) { gameStateManager.stackState(new UseKey(gameStateManager)); } } } } // regenerates blocks when the player restarts the game. Used to replace the blocks when doors are opened. private void regenerateBlocks() { RoomData roomFellowship = World.getFellowshipRoom().getData(); RoomData roomHallway = World.getHallwayRoom().getData(); if (roomFellowship.getTileAt(0, 3).getID() == Resources.TILE) { roomFellowship.getTileAt(0, 3).setId(Resources.WALL); roomFellowship.getTileAt(0, 4).setId(Resources.WALL); roomFellowship.getTileAt(0, 5).setId(Resources.WALL); roomFellowship.getTileAt(0, 3).setWall(true); roomFellowship.getTileAt(0, 4).setWall(true); roomFellowship.getTileAt(0, 5).setWall(true); } if (roomHallway.getTileAt(15, 3).getID() == Resources.TILE) { roomHallway.getTileAt(15,3).setId(Resources.STONE); roomHallway.getTileAt(15,4).setId(Resources.STONE); roomHallway.getTileAt(15,5).setId(Resources.STONE); roomHallway.getTileAt(15, 3).setWall(true); roomHallway.getTileAt(15, 4).setWall(true); roomHallway.getTileAt(15, 5).setWall(true); } } }
<h1 align="center"> <a href="https://cs-space.vercel.app"><img src="../static/img/slash-introducing.png" alt="Computer Science - Space"></a> </h1> <h3 align="center"> <a href="https://github.com/Fire-Oceann/CS-Space/issues/new?assignees=&labels=bug&template=bug_report.yml&title=">Hata Bildir</a> <span> · </span> <a href="https://github.com/Fire-Oceann/CS-Space/issues/new?assignees=&labels=feature+request&template=feature_request.yml&title=">Özellik Talep Et</a> <span> · </span> <a href="https://github.com/Fire-Oceann/CS-Space/discussions">Bir soru sor</a> </h3> <div align="center"> <br /> <a herf="../LICENSE"><img alt="GitHub" src="https://img.shields.io/github/license/Fire-Oceann/BB-TR-Kaynak?style=for-the-badge"/></a> <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --> <a href="https://img.shields.io/badge/all_contributors-0-orange.svg?style=for-the-badge"><img alt="All Contributors" src="https://img.shields.io/badge/all_contributors-5-orange.svg?style=for-the-badge"/></a> <!-- ALL-CONTRIBUTORS-BADGE:END --> <a herf=".URL_"><img alt="Open Source - ❤️" src="https://img.shields.io/badge/Open_Source-❤️-00d59b?style=for-the-badge"/></a> <a href="https://github.com/Fire-Oceann/CS-Space/issues"><img alt="GitHub issues" src="https://img.shields.io/github/issues-raw/Fire-Oceann/BB-TR-Kaynak?color=%23F2625A&style=for-the-badge"/></a> <a href="https://prettier.io/"><img src="https://img.shields.io/badge/code%20style-prettier-%23d971de?style=for-the-badge" alt="Prettier" /></a> <a href="https://github.com/Fire-Oceann/CS-Space/pulls"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=for-the-badge" alt="PRs Welcome" /></a> </div> <kbd>[<img title="Türkçe" alt="Türkçe" src="https://cdn.staticaly.com/gh/hjnilsson/country-flags/master/svg/tr.svg" width="22">](./README-TR.md)</kbd> <kbd>[<img title="Française" alt="Française" src="https://cdn.staticaly.com/gh/hjnilsson/country-flags/master/svg/fr.svg" width="22">](./README-FR.md)</kbd> <kbd>[<img title="Deutsch" alt="Deutsch" src="https://cdn.staticaly.com/gh/hjnilsson/country-flags/master/svg/de.svg" width="22">](./README-DE.md)</kbd> <kbd>[<img title="Русский язык" alt="Русский язык" src="https://cdn.staticaly.com/gh/hjnilsson/country-flags/master/svg/ru.svg" width="22">](./README-RU.md)</kbd> <kbd>[<img title="Italiano" alt="Italiano" src="https://cdn.staticaly.com/gh/hjnilsson/country-flags/master/svg/it.svg" width="22">](./README-IT.md)</kbd> > Meraklılar için bir Bilgisayar Bilimi portalı. İyi yazılmış, iyi düşünülmüş ve iyi açıklanmış bilgisayar bilimi ve programlama makaleleri içerir. ## Önkoşullar Geliştirme makinenize aşağıdaki ön koşulların tümünü yüklediğinizden emin olun: - Git - [Download & Install Git](https://git-scm.com/downloads). OSX ve Linux makinelerinde genellikle bu zaten kuruludur. - Node.js - [Download & Install](https://nodejs.org/en/download/) Node.js ve npm paket yöneticisi. Herhangi bir sorunla karşılaşırsanız, bunu da kullanabilirsiniz. [GitHub Gist](https://gist.github.com/isaacs/579814) to install Node.js. ## Kurulum ve Kurulum ```bash git clone https://github.com/Fire-Oceann/CS-Space.git cd CS-Space npm install npm start ``` ## Proje yardımı Teşekkür etmek veya/ve aktif gelişimini desteklemek istiyorsanız `CS-SPACE`: - Projeye bir ⭐️ [GitHub Star](https://github.com/Fire-Oceann/CS-Space) ekleyin. - `CS-SPACE` hakkında tweet. - [Dev.to](https://dev.to/), [Medium](https://medium.com/) veya kişisel blogunuzda proje hakkında ilginç makaleler yazın. Birlikte, `CS-SPACE` daha iyi hale getirebiliriz! ## 🤝 Katkı Öncelikle, katkıda bulunmak için zaman ayırdığınız için teşekkürler! Katkılar, açık kaynak topluluğunu öğrenmek, ilham vermek ve yaratmak için harika bir yer yapan şeydir. Yaptığınız katkılar herkese fayda sağlayacak ve çok takdir edilecektir. [Davranış kurallarımız](../CODE_OF_CONDUCT.md) ve bize çekme talepleri gönderme süreciyle ilgili ayrıntılar için lütfen [katkı yönergelerimizi](../CONTRIBUTING.md) okuyun. ## Katkıda Bulunanlar ✨ Bu harika insanlara teşekkürler ([emoji key](https://allcontributors.org/docs/en/emoji-key)): <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore-start --> <!-- markdownlint-disable --> <table> <tr> <td align="center"><a href="https://github.com/ziarparvaiz"><img src="https://avatars.githubusercontent.com/u/50423368?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ZIAR Parvaiz</b></sub></a><br /><a href="https://github.com/Fire-Oceann/CS-Space/issues?q=author%3Aziarparvaiz" title="Bug reports">🐛</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=ziarparvaiz" title="Code">💻</a> <a href="#design-ziarparvaiz" title="Design">🎨</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=ziarparvaiz" title="Documentation">📖</a> <a href="#ideas-ziarparvaiz" title="Ideas, Planning, & Feedback">🤔</a> </td> <td align="center"><a href="https://github.com/Burak-Atak"><img src="https://avatars.githubusercontent.com/u/71793345?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Burak</b></sub></a><br /><a href="https://github.com/Fire-Oceann/CS-Space/commits?author=Burak-Atak" title="Code">💻</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=Burak-Atak" title="Documentation">📖</a></td> <td align="center"><a href="https://medium.com/@beyzatekinli"><img src="https://avatars.githubusercontent.com/u/64313175?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Beyzanur Tekinli</b></sub></a><br /><a href="#blog-b-tekinli" title="Blogposts">📝</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=b-tekinli" title="Code">💻</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=b-tekinli" title="Documentation">📖</a></td> <td align="center"><a href="https://github.com/TalhaAksoy"><img src="https://avatars.githubusercontent.com/u/56833887?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Talha Aksoy</b></sub></a><br /><a href="https://github.com/Fire-Oceann/CS-Space/commits?author=TalhaAksoy" title="Code">💻</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=TalhaAksoy" title="Documentation">📖</a></td> <td align="center"><a href="https://github.com/beyzanur-seyhan"><img src="https://avatars.githubusercontent.com/u/80166639?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Beyzanur Seyhan</b></sub></a><br /><a href="#blog-beyzanur-seyhan" title="Blogposts">📝</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=beyzanur-seyhan" title="Code">💻</a> <a href="https://github.com/Fire-Oceann/CS-Space/commits?author=beyzanur-seyhan" title="Documentation">📖</a></td> </tr> </table> <!-- markdownlint-restore --> <!-- prettier-ignore-end --> <!-- ALL-CONTRIBUTORS-LIST:END --> Bu proje, [tüm katkıda bulunanlar](https://github.com/all-contributors/all-contributors) spesifikasyonunu takip eder. Her türlü katkı hoş geldiniz! ## sürüm oluşturma Versiyonlama için [SemVer](https://semver.org/) kullanıyoruz. Mevcut sürümler için [bu depodaki etiketlere](https://github.com/Fire-Oceann/CS-Space/tags) bakın. ## Lisans Bu proje [CS-SPACE](https://github.com/Fire-Oceann/CS-Space) kapsamında lisanslanmıştır. Lisans - ayrıntılar için [LİSANS](../LICENSE) dosyasına bakın.
import { useState } from 'react' import PropTypes from 'prop-types' import './addTask.css' const AddTask = ({dispatch}) => { const resetTask = { name: "", dateTime: "", reminder: false } const [task, setTask] = useState(resetTask) //Add task const addTask = (e) => { e.preventDefault() if (!task.name.trim()) { alert("Enter task name") } else if (!task.dateTime.trim()) { alert("Enter date and time") } else { dispatch({type: "ADD_TASK", payload: {...task, id: new Date().getTime().toString()}}) setTask(resetTask) } } return ( <form onSubmit={addTask}> <div className="form-control"> <label htmlFor="task">Task Name</label> <input type="text" id="name" className='input-box' placeholder="Add Task" value={task.name} onChange={(e)=> setTask({...task, name: e.target.value})} required /> </div> <div className="form-control"> <label htmlFor="day-time">Due Day & Time</label> <input type="datetime-local" id="dateTime" className='input-box' placeholder="Add Day & Time" value={task.dateTime} onChange={(e)=> setTask({...task, dateTime: e.target.value})} required /> </div> <div className="form-control-checkbox"> <label htmlFor="reminder">Set Reminder</label> <input type="checkbox" id="reminder" checked={task.reminder} onChange={(e)=> setTask({...task, reminder: e.currentTarget.checked})} /> </div> <button type="submit">Save Task</button> </form> ) } AddTask.propTypes = { dispatch: PropTypes.func } export default AddTask
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Yoeca.Sql { public sealed class Select { public static Select<T> From<T>() where T : new() { return Select<T>.All(); } } public sealed class Select<T> : ISqlCommand<T> where T : new() { public readonly ImmutableList<Where> Constraints; public readonly int? Limit; public readonly ImmutableList<string> Parameters; public readonly string Table; public Select( string table, ImmutableList<string> values, ImmutableList<Where> constraints, int? limit) { Table = table; Parameters = values; Constraints = constraints; Limit = limit; } public T TranslateRow(ISqlFields fields) { var definition = new TableDefinition(typeof(T)); var result = new T(); int index = 0; foreach (var columnRetriever in definition.Columns) { columnRetriever.Set(fields.Get(index), result); index++; } return result; } public string Format(SqlFormat format) { var builder = new StringBuilder(); builder.AppendFormat("SELECT {0} ", string.Join(", ", Parameters)); builder.AppendFormat("FROM {0}", Table); foreach (var constraint in Constraints) { builder.AppendLine(); builder.Append(constraint.Format(format)); } if (Limit.HasValue) { builder.AppendLine(); builder.AppendFormat("LIMIT {0}", Limit.Value); } return builder.ToString(); } public SelectValue<T, TValue> Maximum<TValue>( Expression<Func<T, TValue>> expression) { var column = GetColumn(expression); return new SelectValue<T, TValue>(Table, column.Name, Constraints, ValueOperations.Maximum); } public SelectValue<T, TValue> Minimum<TValue>( Expression<Func<T, TValue>> expression) { var column = GetColumn(expression); return new SelectValue<T, TValue>(Table, column.Name, Constraints, ValueOperations.Minimum); } public static Select<T> All() { var definition = new TableDefinition(typeof(T)); var parameters = new List<string>(); foreach (var columnRetriever in definition.Columns) { parameters.Add(columnRetriever.Name); } return new Select<T>(definition.Name, parameters.ToImmutableList(), ImmutableList<Where>.Empty, null); } public Select<T> WhereEqual<TResult>( Expression<Func<T, TResult>> expression, TResult value) { var column = GetColumn(expression); string? formattedValue = column.Convert.ConvertToString(value); if (formattedValue == null) { throw new ArgumentException("Specified value cannot be converted to column value: " + value); } if (column.RequiresEscaping) { formattedValue = "'" + formattedValue + "'"; } return With(new WhereEqual(column.Name, formattedValue)); } public Select<T> WhereContains( Expression<Func<T, string>> expression, string value) { var column = GetColumn(expression); string formattedValue = "'%" + value + "%'"; return With(new WhereLike(column.Name, formattedValue)); } public Select<T> WhereStartsWith( Expression<Func<T, string>> expression, string value) { var column = GetColumn(expression); string formattedValue = "'" + value + "%'"; return With(new WhereLike(column.Name, formattedValue)); } public Select<T> WhereEndsWith( Expression<Func<T, string>> expression, string value) { var column = GetColumn(expression); string formattedValue = "'%" + value + "'"; return With(new WhereLike(column.Name, formattedValue)); } private Select<T> With( Where constraint) { return new Select<T>(Table, Parameters, Constraints.Add(constraint), Limit); } public Select<T> WhereNotEqual<TResult>( Expression<Func<T, TResult>> expression, TResult value) { var column = GetColumn(expression); string? formattedValue = column.Convert.ConvertToString(value); if (formattedValue == null) { throw new ArgumentException("Specified value cannot be converted to column value: " + value); } if (column.RequiresEscaping) { formattedValue = "'" + formattedValue + "'"; } return With(new WhereNotEqual(column.Name, formattedValue)); } public Select<T> Take(int maximumNumberOfRecords) { return new Select<T>(Table, Parameters, Constraints, maximumNumberOfRecords); } private static ColumnRetriever GetColumn<TResult>( Expression<Func<T, TResult>> expression) { var member = expression.Body as MemberExpression; if (member == null) { throw new InvalidOperationException("Not a valid lambda."); } var definition = new TableDefinition(typeof(T)); return definition.Columns.Single(x => x.Name == member.Member.Name); } } }
import { useState } from 'react' import { FormControl, FormGroup, InputLabel, Input, Typography, Button } from '@mui/material' import styled from '@emotion/styled' import { addUser } from '../service/api'; const Container = styled(FormGroup)` width: 50%; margin: 5% auto 0 auto ; & > div { margin-top: 20px; } `; const defaultValue = { name: '', username: '', email: '', phone: '' } const AddUser = () => { const [user, setuser] = useState(defaultValue); const onValueChange = (e) => { setuser({...user, [e.target.name]: e.target.value }) console.log(user); } const addUserDetails = async() => { await addUser(user); } return ( <Container> <Typography variant='h4'> Add User</Typography> <FormControl> <InputLabel> Name </InputLabel> <Input onChange={ (e) => onValueChange(e) } name='name' /> </FormControl> <FormControl> <InputLabel> Username </InputLabel> <Input onChange={ (e) => onValueChange(e) } name='username'/> </FormControl> <FormControl> <InputLabel> Email </InputLabel> <Input onChange={ (e) => onValueChange(e) } name='email'/> </FormControl> <FormControl> <InputLabel> Phone </InputLabel> <Input onChange={ (e) => onValueChange(e) } name='phone'/> </FormControl> <FormControl> <Button variant='contained' onClick={()=>addUserDetails()}> Add User </Button> </FormControl> </Container> ) } export default AddUser