text
stringlengths
184
4.48M
// <copyright file="ReadForkToRam.cs" company="INTV Funhouse"> // Copyright (c) 2014 All Rights Reserved // <author>Steven A. Orth</author> // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation, either version 2 of the License, or (at your // option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this software. If not, see: http://www.gnu.org/licenses/. // or write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA // </copyright> namespace INTV.LtoFlash.Model.Commands { /// <summary> /// Implements the command to instruct the file system on a Locutus device to copy the contents of a fork into RAM on the device. /// </summary> internal sealed class ReadForkToRam : ProtocolCommand { /// <summary> /// Default timeout for reading response data in milliseconds. /// </summary> public const int DefaultResponseTimeout = 10000; private ReadForkToRam(uint address, ushort globalForkNumber, uint offset, int length) : base(ProtocolCommandId.LfsCopyForkToRam, DefaultResponseTimeout, globalForkNumber, address, offset, (uint)length) { ProtocolCommandHelpers.ValidateDataBlockSizeAndAddress(address, (int)length); } /// <summary> /// Creates an instance of the ReadForkToRam command. /// </summary> /// <param name="address">The address in RAM to which to begin copying the fork's data.</param> /// <param name="globalForkNumber">The global fork number of the fork to read into RAM.</param> /// <param name="offset">The offset (in bytes) into the fork at which to begin reading data to place into RAM.</param> /// <param name="length">The number of bytes to read into RAM.</param> /// <returns>A new instance of the command.</returns> public static ReadForkToRam Create(uint address, ushort globalForkNumber, uint offset, int length) { return new ReadForkToRam(address, globalForkNumber, offset, length); } } }
import 'package:flutter/material.dart'; import 'package:konbini/config/theme.dart'; import 'package:konbini/models/user_model.dart'; class TopSectionUser extends StatefulWidget { const TopSectionUser({super.key}); @override State<TopSectionUser> createState() => _TopSectionUserState(); } class _TopSectionUserState extends State<TopSectionUser> { UserModel? user; @override void initState() { fetchUserData(); super.initState(); } fetchUserData() async { user = await UserModel().fetchUserDataUsingModel(); setState(() {}); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 15), child: SizedBox( height: 100, child: Row( children: [ (user != null && user!.userImage != null && user!.userImage!.isNotEmpty) ? CircleAvatar( radius: 30, backgroundImage: NetworkImage( user!.userImage.toString(), ), ) : CircleAvatar( backgroundColor: secondaryColor3, radius: 30, child: Text( user != null && user!.userName != null && user!.userName!.isNotEmpty ? user!.userName![0].toUpperCase() : 'U', style: TextStyle( color: baseColor, fontSize: 30, ), ), ), const SizedBox( width: 30, ), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ user != null ? Text(user!.userName.toString()) : const Text('blabala'), (user != null) ? Text( user!.userEmail.toString(), style: Theme.of(context) .textTheme .bodySmall! .copyWith(color: Colors.grey.shade400), ) : Text( "User Email", style: Theme.of(context) .textTheme .bodySmall! .copyWith(color: Colors.grey.shade400), ), ], ), ], ), ), ); } }
using InteractiveCodeExecution.ExecutorEntities; namespace InteractiveCodeExecution.Services { public class PoCAssignmentProvider : IExecutorAssignmentProvider { public readonly List<ExecutorAssignment> Assignments = new List<ExecutorAssignment>() { new ExecutorAssignment() { AssignmentId = "CSharpHello", AssignmentName = "Simple CSharp with dotnet 8", Image = "mcr.microsoft.com/dotnet/sdk:8.0", Commands = new List<ExecutorCommand>() { new() { Command = "dotnet run", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = true } }, InitialPayload = new() { new() { Content = "Console.WriteLine(\"Hello World!\");", ContentType = ExecutorFileType.Utf8TextFile, Filepath = "Program.cs" }, new() { Content = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> </Project>", ContentType = ExecutorFileType.Utf8TextFile, Filepath = "Project.csproj" } } }, new ExecutorAssignment() { AssignmentId = "CSharpTwoStep", AssignmentName = "Two-step CSharp with dotnet 8", Image = "mcr.microsoft.com/dotnet/sdk:8.0", Commands = new List<ExecutorCommand>() { new() { Command = "dotnet build", Stage = ExecutorCommand.ExecutorStage.Build, WaitForExit = true }, new() { Command = "dotnet run", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = true } }, InitialPayload = new() { new() { Content = "Console.WriteLine(\"Hello World!\");", ContentType = ExecutorFileType.Utf8TextFile, Filepath = "Program.cs" }, new() { Content = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> </Project>", ContentType = ExecutorFileType.Utf8TextFile, Filepath = "Project.csproj" } } }, new ExecutorAssignment() { AssignmentId = "PythonHello", AssignmentName = "Plain python 3.13", Image = "python:3.13-rc-bullseye", Commands = new List<ExecutorCommand>() { new() { Command = "python main.py", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = true }, }, InitialPayload = new() { new() { Content = "print(\"Hello World!\")", ContentType = ExecutorFileType.Utf8TextFile, Filepath = "main.py" }, } }, new ExecutorAssignment() { AssignmentId = "VNC Base", AssignmentName = "The VNC Base-image with Firefox", Image = "ghcr.io/alexandernorup/interactivecodeexecution/vnc_base_image:v1", // From the /VncDockerImages/VncBase.Dockerfile Commands = new List<ExecutorCommand>() { new() { Command = "/run_vnc.sh", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = false }, new() { // Sleep here is required because Firefox expects an X-server to immediately connect to // Ideally this should be a shell script that waits for an x-server exists at the :0 // But for a PoC this is good enough Command = "sleep 3", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = true }, new() { Command = "firefox", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = true }, }, ExecutorConfig = new() { EnvironmentVariables = new List<string>() { "RESOLUTION=854x480", "DISPLAY=:0" }, MaxMemoryBytes = 1024 * 1024 * 512L, MaxVCpus = 0.5, Timeout = TimeSpan.FromMinutes(5), MaxPayloadSizeInBytes = 300, HasVncServer = true }, InitialPayload = new () { new () { Content = "The example is ready. There are no files for this one, so this is a just a placeholder file!", ContentType = ExecutorFileType.Utf8TextFile, Filepath = "Hello.txt" }, } }, new ExecutorAssignment() { AssignmentId = "vop-f24_point-giving-activity-1", AssignmentName = "VOP-24 Point giving activity 1", Image = "ghcr.io/alexandernorup/interactivecodeexecution/vnc_java:22-javafx", // From the /VncDockerImages/Java22Vnc.Dockerfile Commands = new List<ExecutorCommand>() { new() { Command = "/run_vnc.sh", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = false }, new() { Command = "mvn javafx:run", Stage = ExecutorCommand.ExecutorStage.Exec, WaitForExit = true }, }, ExecutorConfig = new() { EnvironmentVariables = new List<string>() { "RESOLUTION=854x480", "DISPLAY=:0" }, MaxMemoryBytes = 1024 * 1024 * 512L, MaxVCpus = 0.5, Timeout = TimeSpan.FromMinutes(5), MaxPayloadSizeInBytes = 1024*1024*5, // 5 Megabytes HasVncServer = true }, InitialPayload = GetExecutorFilesFromDirectory(Path.Combine(AppContext.BaseDirectory, "point-giving-activity-1")) } }; public IEnumerable<ExecutorAssignment> GetAllAssignments() { return Assignments; } public bool TryGetAssignment(string assignmentId, out ExecutorAssignment? assignment) { assignment = Assignments.FirstOrDefault(x => x.AssignmentId == assignmentId); return assignment is not null; } private static List<ExecutorFile> GetExecutorFilesFromDirectory(string path) { if (!Directory.Exists(path)) { // We could throw here. // We don't because this is a PoC and the directory might legitimately not exist return new() { new() { Content = $"This deployment has not been configured for this assignment.\nI except a directory to be present at \"{path}\" that contains the files for this assignment.", ContentType = ExecutorFileType.Utf8TextFile, Filepath = "error.txt" } }; } var files = new List<ExecutorFile>(); RecurisvelyAddFilesFromDirectory(path, files); return files; } private static readonly HashSet<string> KnownBinaryFormats = new() { ".jpg", ".jpeg", ".png", ".gif", ".webp", ".mov", ".mp4", ".pdf", ".bin", ".jar", ".exe", ".tar", ".gz", ".zip" }; private static void RecurisvelyAddFilesFromDirectory(string path, List<ExecutorFile> files, string containerPath = "", int depth = 0) { if (depth > 50) { throw new InvalidDataException("Execute folder structure too deep!"); } foreach (var file in Directory.EnumerateFileSystemEntries(path)) { // This is the path inside the container. This does not use Path.Combine() because we always want to use "/" for separators in the container. var containerPathFile = containerPath + "/" + Path.GetFileName(file); if (Directory.Exists(file)) { RecurisvelyAddFilesFromDirectory(file, files, containerPathFile, depth + 1); continue; } else if (File.Exists(file)) { var pathWithoutLeadingSlash = containerPathFile.TrimStart('/'); if (KnownBinaryFormats.Contains(Path.GetExtension(file))) { files.Add(new() { Content = Convert.ToBase64String(File.ReadAllBytes(file)), ContentType = ExecutorFileType.Base64BinaryFile, Filepath = pathWithoutLeadingSlash, }); } else { files.Add(new() { Content = File.ReadAllText(file), ContentType = ExecutorFileType.Utf8TextFile, Filepath = pathWithoutLeadingSlash, }); } } } } } }
package main import ( "bufio" "fmt" "math" "os" "strconv" ) func main() { n := nextString() var out string for _, r := range n { switch r { case '1': out += string('9') case '9': out += string('1') } } fmt.Println(out) } // Input. ---------- var sc = bufio.NewScanner(os.Stdin) func init() { sc.Buffer([]byte{}, math.MaxInt64) sc.Split(bufio.ScanWords) } func nextInt() int { sc.Scan() i, err := strconv.Atoi(sc.Text()) if err != nil { panic(err) } return i } func nextString() string { sc.Scan() if err := sc.Err(); err != nil { panic(err) } return sc.Text() } // ---------- Input. // Util. ---------- func min(x, y int) int { return int(math.Min(float64(x), float64(y))) } func max(x, y int) int { return int(math.Max(float64(x), float64(y))) } // ---------- Util.
import { ScrollView, TabWidget, VerticalBox , HorizontalBox} from "std-widgets.slint"; struct Icon { on: image, off: image, auto_off: image, error: image, } struct AllIcons { fan: Icon, light: Icon, night: Icon, schedule: Icon, select: Icon, speaker: Icon, trumpet: Icon, tv: Icon, } struct ButtonData { title: string, state: string, image: image, color: color, text_color: color, id: int, } struct ButtonRowData { title: string, buttons: [ButtonData], } struct TagsData { yesterday: [string], today: [string], tomorrow: [string], } struct SequenceData { time: string, title: string, important: bool, status: int, tasks: [string], } struct ScheduleData { date: string, sequences: [SequenceData], } component RoboticaButton inherits Rectangle { callback clicked; in property<ButtonData> data; height: 80px; width: 80px; border-radius: 5px; background: data.color; animate background { duration: 200ms; } Image { source: data.image; x: parent.width/2 - self.width/2; y: 4px; width: 52px; height: 52px; } Text { text: data.title; x: 0px; y: parent.height - 20px - 4px; width: parent.width; // height: parent.height; color: data.text_color; font-size: 10px; horizontal-alignment: center; } Text { text: data.state; x: 0px; y: parent.height - 10px - 4px; width: parent.width; // height: parent.height; color: data.text_color; font-size: 10px; horizontal-alignment: center; } TouchArea { clicked => { // Delegate to the user of this element root.clicked(); } } } component Title inherits Rectangle { callback clicked; in property<string> title; height: 80px; width: 80px; border-radius: 5px; background: #202020; animate background { duration: 200ms; } Text { text: title; x: 0px; y: parent.height/2 - 10px/2; width: parent.width; // height: parent.height; color: white; font-size: 10px; horizontal-alignment: center; } } component Buttons inherits ScrollView { in property <[ButtonRowData]> rows: []; callback screen_reset; callback clicked_widget(int); in property<int> number_per_row; viewport-width: (80px + 10px) * number_per_row + 10px; viewport-height: (80px + 10px) * rows.length + 10px; VerticalLayout { padding: 10px; spacing: 10px; for row[i] in rows : HorizontalLayout { spacing: 10px; Title { title: row.title; clicked => { screen_reset(); } } for column[i] in row.buttons : RoboticaButton{ data: column; clicked => { screen_reset(); root.clicked_widget(column.id); } } for x in number_per_row - row.buttons.length : Rectangle { width: 80px; height: 80px; background: #202020; } } } } component InlineTags inherits Rectangle { in property <[string]> tags; for tag[i] in tags : Rectangle { Text { text: tag; color: white; font-size: 10px; horizontal-alignment: center; vertical-alignment: center; x: 10px; y: 10px; width: parent.width - 20px; height: parent.height - 20px; } background: green; width: 200px; height: 40px; border-radius: 5px; x: 0px + mod(i,3) * 210px; y: 0px + floor(i/3) * 50px; } width: 0px + 3 * 210px - 10px; height: 0px + ceil(tags.length/3) * 50px - 10px; } component Tags inherits VerticalLayout { in property <TagsData> tags; callback screen_reset; alignment: start; Text { text: "Yesterday"; color: white; font-size: 10px; horizontal-alignment: center; } InlineTags { tags: tags.yesterday; x: parent.width/2 - self.width/2; } Rectangle { height: 10px; } Text { text: "Today"; color: white; font-size: 10px; horizontal-alignment: center; } InlineTags { tags: tags.today; x: parent.width/2 - self.width/2; } Rectangle { height: 10px; } Text { text: "Tomorrow"; color: white; font-size: 10px; horizontal-alignment: center; } InlineTags { tags: tags.tomorrow; x: parent.width/2 - self.width/2; } } component Schedule inherits ScrollView { in property <[ScheduleData]> schedule_list; callback screen_reset; // viewport-width: 200px; // viewport-height: (90px + 10px) * schedule.length + 10px; VerticalLayout { padding: 10px; spacing: 10px; for schedule[i] in schedule_list : VerticalLayout { padding: 0px; spacing: 10px; Rectangle { Text { text: schedule.date; color: white; font-size: 20px; width: parent.width; horizontal-alignment: left; y: 20px; } height: 20px + 20px; } for entry[i] in schedule.sequences : Rectangle { property <bool> open; property <[string]> tasks; open: false; tasks: open ? entry.tasks : []; height: open ? 30px + 20px * entry.tasks.length : 30px; property <color> pending_color: entry.important ? green : grey; // 0 = pending (pending) // 1 = in progress (blue) // 2 = completed (black) // 3 = cancelled (red) background: entry.status == 0 ? pending_color : entry.status == 1 ? blue : entry.status == 2 ? black : red; Text { x: 10px; y: 10px; width: parent.width; font-size: 10px; text: entry.time + " " + entry.title; color: white; } for task[i] in tasks : Text{ x: 20px; y: 30px + 20px * i; width: parent.width - 40px; font-size: 10px; text: task; color: white; } TouchArea { clicked => { screen_reset(); parent.open = !parent.open; } } } } } } component Clock inherits VerticalLayout { in property<int> hour; in property<int> minute; in property<int> second; Text { text: "Clock"; color: white; horizontal-alignment: center; font-size: 20px; } Rectangle { background: black; // hour marks for hour in [1,2,3,4,5,6,7,8,9,10,11,12] : Path { viewbox-height: 100; viewbox-width: 100; width: parent.width; height: parent.height; stroke: white; stroke-width: 5px; MoveTo { x: 50 + sin(360deg*hour/12)*49; y: 50 - cos(360deg*hour/12)*49; } LineTo { x: 50 + sin(360deg*hour/12)*50; y: 50 - cos(360deg*hour/12)*50; } } // minute marks for minute in [ 1,2,3,4, 6,7,8,9, 11,12,13,14, 16,17,18,19, 21,22,23,24, 26,27,28,29, 31,32,33,34, 36,37,38,39, 41,42,43,44, 46,47,48,49, 51,52,53,54, 56,57,58,59 ] : Path { viewbox-height: 100; viewbox-width: 100; width: parent.width; height: parent.height; stroke: white; stroke-width: 1px; MoveTo { x: 50 + sin(360deg*minute/60)*49; y: 50 - cos(360deg*minute/60)*49; } LineTo { x: 50 + sin(360deg*minute/60)*50; y: 50 - cos(360deg*minute/60)*50; } } // clock face Path { viewbox-height: 100; viewbox-width: 100; width: parent.width; height: parent.height; stroke: white; stroke-width: 5px; MoveTo { x: 50; y: 0; } ArcTo { x: 50; y: 100; radius-x: 50; radius-y: 50; x-rotation:0; large-arc: true; sweep: true; } ArcTo { x: 50; y: 0; radius-x: 50; radius-y: 50; x-rotation:0; large-arc: true; sweep: true; } } // hour hand Path { viewbox-height: 100; viewbox-width: 100; width: parent.width; height: parent.height; stroke: red; stroke-width: 10px; MoveTo { x: 50; y: 50; } LineTo { x: 50 + sin(360deg*hour/12)*30; y: 50 - cos(360deg*hour/12)*30; } } // minute hand Path { viewbox-height: 100; viewbox-width: 100; width: parent.width; height: parent.height; stroke: green; stroke-width: 5px; MoveTo { x: 50; y: 50; } LineTo { x: 50 + sin(360deg*minute/60)*40; y: 50 - cos(360deg*minute/60)*40; } } // second hand Path { viewbox-height: 100; viewbox-width: 100; width: parent.width; height: parent.height; stroke: blue; stroke-width: 1px; MoveTo { x: 50; y: 50; } LineTo { x: 50 + sin(360deg*second/60)*50; y: 50 - cos(360deg*second/60)*50; } } } } export component AppWindow inherits Window { in-out property<int> number_per_row; in property<bool> screen_on; in property<string> msg_body; in property<string> msg_title; in property<bool> display_message; in property<int> hour; in property<int> minute; in property<int> second; in property <[ScheduleData]> schedule_list; callback clicked_widget(int); callback screen_reset; background: black; out property<AllIcons> all_icons: { fan: { on: @image-url("images/fan_on.svg"), off: @image-url("images/fan_off.svg"), auto_off: @image-url("images/fan_auto.svg"), error: @image-url("images/fan_error.svg") }, light: { on: @image-url("images/light_on.svg"), off: @image-url("images/light_off.svg"), auto_off: @image-url("images/light_auto.svg"), error: @image-url("images/light_error.svg") }, night: { on: @image-url("images/night_on.svg"), off: @image-url("images/night_off.svg"), auto_off: @image-url("images/night_auto.svg"), error: @image-url("images/night_error.svg") }, schedule: { on: @image-url("images/schedule_on.svg"), off: @image-url("images/schedule_off.svg"), auto_off: @image-url("images/schedule_auto.svg"), error: @image-url("images/schedule_error.svg") }, select: { on: @image-url("images/select_on.svg"), off: @image-url("images/select_off.svg"), auto_off: @image-url("images/select_auto.svg"), error: @image-url("images/select_error.svg") }, speaker: { on: @image-url("images/speaker_on.svg"), off: @image-url("images/speaker_off.svg"), auto_off: @image-url("images/speaker_auto.svg"), error: @image-url("images/speaker_error.svg") }, trumpet: { on: @image-url("images/trumpet_on.svg"), off: @image-url("images/trumpet_off.svg"), auto_off: @image-url("images/trumpet_auto.svg"), error: @image-url("images/trumpet_error.svg") }, tv: { on: @image-url("images/tv_on.svg"), off: @image-url("images/tv_off.svg"), auto_off: @image-url("images/tv_auto.svg"), error: @image-url("images/tv_error.svg") }, }; in property <[ButtonRowData]> buttons: []; in property <TagsData> tags: { yesterday: [], today: [], tomorrow: [], }; TouchArea { clicked => { screen_reset(); } } TabWidget { x: 0px; y: 0px; width: parent.width; height: parent.height; Tab { title: "Clock"; Clock { hour: hour; minute: minute; second: second; } } Tab { title: "Buttons"; Buttons { rows: buttons; number_per_row: number_per_row; screen_reset => { root.screen_reset(); } clicked_widget(i) => { root.clicked_widget(i); } } } Tab { title: "Tags"; Tags { tags: root.tags; screen_reset => { root.screen_reset(); } } } Tab { title: "Schedule"; Schedule { schedule_list: root.schedule_list; screen_reset => { root.screen_reset(); } } } } if display_message : Rectangle { x: 0px; y: 0px; width: parent.width; height: parent.height; background: black; opacity: 0.9; VerticalLayout { Text { text: msg_title; color: white; horizontal-alignment: center; font-size: 30px; wrap: word-wrap; } Text { text: msg_body; color: white; horizontal-alignment: center; font-size: 40px; wrap: word-wrap; } } } if !screen_on : Rectangle { x: 0px; y: 0px; width: parent.width; height: parent.height; background: black; opacity: 0.9; } if !screen_on || display_message : TouchArea { clicked => { screen_reset(); } } }
package com.example.tezmarket.data.repositoryimpl import com.example.tezmarket.data.remote.TezMarketApi import com.example.tezmarket.data.remote.model.favorites.FavoriteProducts import com.example.tezmarket.data.remote.model.favorites.FavoritesToggle import com.example.tezmarket.domain.FavoriteRepository import com.example.tezmarket.utils.Resource import com.example.tezmarket.utils.SafeApiCall import kotlinx.coroutines.flow.Flow import javax.inject.Inject class FavoriteRepositoryImpl @Inject constructor(private val tezMarketApi: TezMarketApi) : FavoriteRepository, SafeApiCall() { override suspend fun getFavoritesProducts(): Flow<Resource<FavoriteProducts>> = call { tezMarketApi.getFavoriteProducts() } override suspend fun favoritesToggle( productId: Int, productType: String ): Flow<Resource<FavoritesToggle>> = call { tezMarketApi.favoritesToggle(productId = productId, productType = productType) } }
# Write your code here :-) import pycubed_rfm9x import board import digitalio import busio import time import wifi from secrets import secrets import socketpool import adafruit_requests import rtc import adafruit_minimqtt.adafruit_minimqtt as MQTT import ssl CS = digitalio.DigitalInOut(board.D5) CS.switch_to_output(True) RST = digitalio.DigitalInOut(board.D6) RST.switch_to_output(True) print('hello') RADIO_FREQ_MHZ = 437.4 node = const(0xfb) destination = const(0xfa) rfm9x = pycubed_rfm9x.RFM9x(board.SPI(), CS, RST, 437.4) rfm9x.spreading_factor = 8 rfm9x.node = node rfm9x.destination = destination def main1(): while True: packet = rfm9x.receive(timeout=10) #print('hi') if packet is not None: print(packet) print(rfm9x.last_rssi) def main2(): print('in main2') while True: current_time = time.time() path =f'/Volumes/CIRCUITPY/received_images/{current_time}.jpg' packet = rfm9x.receive() with open(path, "wb+") as stream: while True: data = rfm9x.receive() if data is None: break stream.write(data) print('done') def attempt_wifi(): # TODO: Move wifi pass and id to config # try connecting to wifi print("Connecting to WiFi...") try: wifi.radio.connect(ssid=secrets["wifi"]["ssid"], password=secrets["wifi"]["password"]) # wifi.radio.connect(ssid="Stanford") # open network print("Signal: {}".format(wifi.radio.ap_info.rssi)) # Create a socket pool pool = socketpool.SocketPool(wifi.radio) # sync out RTC from the web synctime(pool) except Exception as e: print("Unable to connect to WiFi: {}".format(e)) return None else: return pool def synctime(pool): try: requests = adafruit_requests.Session(pool) TIME_API = "http://worldtimeapi.org/api/ip" the_rtc = rtc.RTC() response = None while True: try: print("Fetching time") # print("Fetching json from", TIME_API) response = requests.get(TIME_API) break except (ValueError, RuntimeError) as e: print("Failed to get data, retrying\n", e) continue json1 = response.json() print(json1) current_time = json1['datetime'] the_date, the_time = current_time.split('T') year, month, mday = [int(x) for x in the_date.split('-')] the_time = the_time.split('.')[0] hours, minutes, seconds = [int(x) for x in the_time.split(':')] # We can also fill in these extra nice things year_day = json1['day_of_year'] week_day = json1['day_of_week'] is_dst = json1['dst'] now = time.struct_time( (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)) the_rtc.datetime = now except Exception as e: print('[WARNING]', e) def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. print("Connected to MQTT broker!") client.subscribe(secrets['mqtt']['codetopic']) def mqtt_message(client, topic, payload): print("[{}] {}".format(topic, payload)) def subscribe(mqtt_client, userdata, topic, granted_qos): # This method is called when the mqtt_client subscribes to a new feed. print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) def set_up_mqtt(pool): mqtt_client = MQTT.MQTT( broker=secrets["mqtt"]["broker"], port=secrets['mqtt']["port"], username=secrets["mqtt"]["username"], password=secrets['mqtt']["password"], socket_pool=pool, is_ssl = True, ssl_context=ssl.create_default_context() ) mqtt_client.on_connect = connected mqtt_client.on_message = mqtt_message mqtt_client.on_subscribe = subscribe mqtt_client.connect() print("connected") return mqtt_client pool = attempt_wifi() mqtt_client = set_up_mqtt(pool) while True: mqtt_client.loop() time.sleep(3) #main2()
// intersection types 83. type Person = { name: string; age: number; }; type Employee = { name: string; title: string; }; type Info = Person & Employee; // interface Person { // name: string; // age: number; // } // interface Employee { // name: string; // title: string; // } // interface Info extends Person, Employee {} type NumStr = string | number; type Numeric = number | boolean; type Universal = NumStr & Numeric; const person1: Employee = { name: "Jeffrey", title: "job", }; const myInfo: Info = { name: "Jeffrey", age: 22, title: "Developer", }; function checkField(data: Person | Employee, key: string = ""): void { if (key in data) console.log(data[key as keyof typeof data]); } // checkField(person1, "title"); interface Bird { type: "bird"; flyingSpeed: number; } interface Horse { type: "horse"; runningSpeed: number; } type Animal = Bird | Horse; function moveAnimal(animal: Animal) { let speed; switch (animal.type) { case "bird": speed = animal.flyingSpeed; break; case "horse": speed = animal.runningSpeed; } console.log("Moving at: " + speed); } // moveAnimal({ type: "bird", flyingSpeed: 80 }); // Index Properties interface ErrorCtn { [prop: string]: string; } const emailError: ErrorCtn = { email: "not a valid email!", }; // function overload type Combinable = string | number; function add(a: number, b: number): number; function add(a: string, b: string): string; function add(a: Combinable, b: Combinable) { if (typeof a === "string" || typeof b === "string") { return `${a}${b}`; } return a + b; } const result = add("Max", "Schwarz").split(""); // Optional Chaining const fetchData: { id: string; name: string; desc?: any } = { id: "1", name: "Jefrey", }; // console.log(fetchData.desc?.title); // Nullish Coalesing // console.log(null ?? "default"); //------- const Advanced = () => { return <p id="p">{fetchData?.desc}</p>; }; export default Advanced;
// // UserNameViewController.swift // instagram_ios // // Created by 김태형 on 2023/01/30. // import Foundation import UIKit class UserNameViewController : UIViewController { var textCnt : Int = 0 var userNameData : String = "" @IBOutlet weak var userNameText: UITextField! @IBOutlet weak var nextButton : UIButton! @IBAction func onClickConfirm() { if textCnt > 0 { let singleton = UserInfoSingleton.shared singleton.userName = userNameData guard let confirmVC = self.storyboard?.instantiateViewController(identifier: "ConfirmViewController") else {return} confirmVC.modalPresentationStyle = .fullScreen self.present(confirmVC, animated: true) } } override func viewDidLoad() { super.viewDidLoad() nextButton.tintColor = .facebook_uncheck DispatchQueue.main.async { self.CountText() } } func CountText() { userNameText.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged) // 텍스트 필드 실시간 데이터 변경 이벤트 감지 } // MARK: - [실시간 텍스트 필드 값 변경 감지] @objc private func textFieldDidChange(_ textField: UITextField) { // [실시간 입력 값 체크 실시] if let text = textField.text { if text.count > 0 { nextButton.tintColor = .facebook_check textCnt = text.count userNameData = text } else { nextButton.tintColor = .facebook_uncheck textCnt = text.count } } } }
const { PrismaClient } = require('@prisma/client'); const { getLogger } = require('../core/logging'); const prisma = new PrismaClient(); async function initializeData() { const logger = getLogger(); logger.info('Initializing connection to the database'); prisma.$connect(); // Check the connection try { await prisma.$executeRaw`SELECT 1+1 AS result`; } catch (error) { logger.error(error.message, {error}); throw new Error('Could not initialize the data layer'); } logger.info('Succesfully connected to the database'); } async function shutdownData() { getLogger().info('shutting down database connection'); prisma.$disconnect(); getLogger().info('shutting down database connection'); } module.exports = {initializeData, shutdownData };
#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> struct Info { int id; double a; double b; double c; }; struct mymsgbuf { long mtype; struct Info info; }mybuf; int main() { int msqid; /* IPC дескриптор для очереди сообщений */ char pathname[] = "server.c"; /* Имя файла, использующееся для генерации ключа. Файл с таким именем должен существовать в текущей директории */ //struct Info info; key_t key; /* IPC ключ */ int len; int size = sizeof(mybuf); printf("%d!!!\n", size); printf("%d!!!\n", sizeof(double)); printf("%d!!!\n", sizeof(int)); printf("%d!!!\n", sizeof(long)); /* Ниже следует пользовательская структура для сообщения */ /* Генерируем IPC ключ из имени файла 09-1a.c в текущей директории и номера экземпляра очереди сообщений 0. */ if((key = ftok(pathname,0)) < 0){ printf("Can\'t generate key\n"); exit(-1); } /* Пытаемся получить доступ по ключу к очереди сообщений, если она существует, или создать ее, если она еще не существует, с правами доступа read & write для всех пользователей */ if((msqid = msgget(key, 0666 | IPC_CREAT)) < 0){ printf("Can\'t get msqid\n"); exit(-1); } int result; result = fork(); /* Часть, принимающая числа с консоли и отправлющая на сервер */ if (result == 0) { printf ("Enter the numbers\n"); int ref = scanf("%lf%lf", &mybuf.info.a,&mybuf.info.b); assert(ref == 2); mybuf.mtype = 1; mybuf.info.id = getppid(); printf ("\n!!%d!!\n", getppid()); if (msgsnd(msqid, &mybuf, sizeof(struct Info), 0) < 0){ printf("Can\'t send message to queue\n"); printf ("%d", errno); if (errno == EINVAL) printf("EAGAIN"); msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL); exit(-1); } } /* Часть, принимающая ответ с сервера */ if (result > 0) { if((len = msgrcv(msqid, &mybuf, sizeof(struct Info), getpid(), 0)) < 0){ printf("Can\'t receive message from queue\n"); exit(-1); } //msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL); printf("%lf\n", mybuf.info.c); } return 0; msgctl(msqid, IPC_RMID, (struct msqid_ds *) NULL); }
package net.codejava.hibernateForeign; import java.util.Date; import javax.persistence.*; @Entity @Table(name = "BOOK") public class Book { @Id @Column(name = "BOOK_ID") @GeneratedValue private long id; private String title; private String description; @Temporal(TemporalType.DATE) @Column(name= "PUBLISHED") private Date publishedDate; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "AUTHOR_ID") private Author author; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getPublishedDate() { return publishedDate; } public void setPublishedDate(Date publishedDate) { this.publishedDate = publishedDate; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } }
package controller; import java.util.ArrayList; import dao.Pelaaja; import model.Ruutu; import model.NappulanTyyppi; import model.NappulanVari; /** * MVC-mallin mukainen kontrolleri rajapinta, joka mahdollistaa modelin * ja viewin kommunikoinnin keskenään. * @author Elmo Vahvaselkä 27.1.2022 */ public interface IKontrolleri { /** * Metodia kutsumalla shakkipeli alkaa. * @param tilastoitu Booleanarvo joka ilmoittaa, että onko kyseessä tilastoitu peli. True mikäli kyseessä tilastoitu, muuten false * @return palauttaa booleanin sen mukaan onnistuiko pelin aloittaminen. */ public boolean aloitaPeli(boolean tilastoitu); /** * Metodi palauttaa vallitsevan pelitilanteen. * @return Kaksiulotteinen taulukkon, joka koostuu Ruutu olioista. */ public Ruutu[][] getPelitilanne(); /** * Hakee tietyssä ruudussa olevan nappulan mahdolliset siirrot. * @param x Siirrettävän nappulan x-koordinaatti. * @param y Siirrettävän nappulan y-koordinaatti. * @return Ruutu olioista koostuvan ArrayListin. Jokainen Ruutu edustaa mahdollista paikkaa, johon nappulan voi liikuttaa. */ public ArrayList<Ruutu> getSiirrotNappulalle(int x, int y); /** * Siirtää nappulaa pelilaudalla. * @param mistaX Siirron lähtökoordinaatti x-akselilla, kokonaisluku väliltä 1-7. * @param mistaY Siirron lähtökoordinaatti y-akselilla, kokonaisluku väliltä 1-7. * @param mihinX Siirron kohdekoordinaatti x-akselilla, kokonaisluku väliltä 1-7. * @param mihinY Siirron kohsekoordinaatti y-akselilla, kokonaisluku väliltä 1-7. * @return palauttaa true, jos siirto onnistui, muuten false. */ public boolean teeSiirto(int mistaX, int mistaY, int mihinX, int mihinY); /** * Metodin kutsutaan, jos siirto aiheutti shakin. */ public void siirtoAiheuttiShakin(); /** * Metodia kutsutaan, mikäli vuorossa oleva pelaaja haluaa luovuttaa pelin. */ public void luovuta(); /** * Metodi jolla ilmoitetaan pelin voittaja. * @param pelaaja Pelin voittunt pelaaja Pelaaja oliona. */ public void pelinvoitti(Pelaaja pelaaja); /** * Metodi jolla sotilas korotetaan. * @return NappulanTyyppi enumina, johon sotilas halutaan korottaa. */ public NappulanTyyppi korota(); /** * Palauttaa vuorossa olevan pelaajan värin. * @return Vuorossa olevan pelaajan väri NappulanVari enumina. */ public NappulanVari getVuoro(); /** * Getteri valkoiselle pelaajalle. * @return Palauttaa valkoisen pelaajan Pelaaja oliona. */ public Pelaaja getValkoinenPelaaja(); /** * Getteri mustalle pelaajalle. * @return Palauttaa mustan pelaajan Pelaaja oliona. */ public Pelaaja getMustaPelaaja(); }
import { Component, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { AdminService } from '../admin.service'; import { AuthService } from '../auth.service'; import { AdminDialogComponent } from './admin-dialog/admin-dialog.component'; export interface Admin { adminId: number; firstName: string; lastName: string; adminRole: string; username: string; password: string; } @Component({ selector: 'app-admin', templateUrl: './admin.component.html', styleUrls: ['./admin.component.scss'], }) export class AdminComponent implements OnInit { constructor( public dialog: MatDialog, private service: AdminService, public authService: AuthService ) {} displayedColumns: string[] = [ 'firstName', 'lastName', 'adminRole', 'username', 'delete', 'edit', ]; dataSource: any; ngOnInit(): void { this.refreshList(); } refreshList() { this.service.getAdmin().subscribe((data) => { this.dataSource = data; }); } addNewAdmin() { this.dialog .open(AdminDialogComponent, { width: '50vw' }) .afterClosed() .subscribe((result) => { this.refreshList(); }); } deleteAdmin(adminId: number) { this.service.deleteAdmin(adminId).subscribe((admin) => { this.refreshList(); }); } editAdmin(admin: Admin) { this.dialog .open(AdminDialogComponent, { data: admin, width: '50vw' }) .afterClosed() .subscribe((result) => { this.refreshList(); }); } }
import React, { useState, useEffect } from "react"; import { Container, Row, Col, Button, FormControl } from "react-bootstrap"; import "./summary.css"; const PlacedOrder = () => { return ( <div> <Container> <h2>Summary of Your Order</h2> <Row className="mt-3"> <Col md={6}> <div className="mb-3"> <h3>Order Details</h3> {cartItems.length > 0 ? ( cartItems.map((itemArray, index) => ( <Row className="product-row" key={index}> {itemArray.map((product, productIndex) => ( <React.Fragment key={productIndex}> <Col xs={4}> <img src={product.photo} alt={product.title} className="cartImage" /> </Col> <Col xs={8}> <div className="title">{product.title}</div> <div>Quantity: <FormControl type="number" defaultValue={1} min={1} readOnly /></div> <div>Price: ${product.price}</div> </Col> </React.Fragment> ))} </Row> )) ) : ( <div>No products in cart.</div> )} </div> </Col> <Col md={6}> <div className="mb-3"> <div className="address-details"> <h3>Address Details</h3> <p><strong>First Name:</strong> {addressDetails.firstName}</p> <p><strong>Last Name:</strong> {addressDetails.lastName}</p> <p><strong>Phone:</strong> {addressDetails.phone}</p> <p><strong>Email:</strong> {addressDetails.email}</p> <p><strong>Address:</strong> {`${addressDetails.address}, ${addressDetails.city}, ${addressDetails.county}`}</p> <p><strong>Additional Info:</strong> {addressDetails.additionalInfo || "N/A"}</p> </div> </div> <button className="submit-order-button" onClick={submitOrder}> Submit Order </button> </Col> </Row> </Container> </div> ); }; export default PlacedOrder;
package com.org.jadwal_beacons import android.os.Handler import android.os.Looper import android.os.RemoteException import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.EventChannel.EventSink import org.altbeacon.beacon.BeaconManager import org.altbeacon.beacon.RangeNotifier import org.altbeacon.beacon.Region class JadwalRangingHandler(private val beaconManager: BeaconManager) { private val handler = Handler(Looper.getMainLooper()) private var regionRanging: MutableList<Region>? = null private var rangingEventSink: EventSink? = null val rangingStreamHandler: EventChannel.StreamHandler = object : EventChannel.StreamHandler { override fun onListen(o: Any, eventSink: EventSink) { startRanging(o, eventSink) } override fun onCancel(o: Any) { stopRanging() } } private fun startRanging(o: Any, eventSink: EventSink) { if (o is List<*>) { val list = o as List<*> regionRanging = mutableListOf() for (obj in list) { if (obj is Map<*, *>) { val map = obj as Map<*, *> val region = JadwalUtils.mapToRegion(map) if (region != null) { regionRanging!!.add(region) } } } } else { eventSink.error("Beacon", "invalid object for ranging", null) return } rangingEventSink = eventSink startRanging() } private fun startRanging() { if (regionRanging == null || regionRanging?.isEmpty() == true) { return } beaconManager.removeAllRangeNotifiers() beaconManager.addRangeNotifier(rangeNotifier) for (region in regionRanging!!) { beaconManager.startRangingBeacons(region) } } fun stopRanging() { if (regionRanging != null && !regionRanging!!.isEmpty()) { try { for (region in regionRanging!!) { beaconManager.stopRangingBeacons(region) } beaconManager.removeRangeNotifier(rangeNotifier) } catch (ignored: RemoteException) { } } rangingEventSink = null } private val rangeNotifier = RangeNotifier { collection, region -> if (rangingEventSink != null) { val map: MutableMap<String, Any> = emptyMap<String, Any>().toMutableMap() for (beacon in collection) { map[beacon.id1.toString()] = JadwalUtils.beaconToMap(beacon) } map["region"] = JadwalUtils.regionToMap(region) handler.post { rangingEventSink?.success(map) } } } }
"use client"; import React from "react"; import styled from "styled-components"; import Image from "next/image"; import { comforter_Brush } from "@/app/fonts"; import styles from "./styles.module.css"; import Link from "next/link"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faFacebook, faInstagram, faXTwitter, faLinkedin, faSpotify, faTwitter, } from "@fortawesome/free-brands-svg-icons"; const FooterContainer = styled.div` background-color: #301c03; color: #fdf4e7; `; function Footer() { return ( <> <FooterContainer> <section className="border-b px-6 lg:px-52 flex flex-col lg:flex-row gap-16 pt-32 pb-16 "> <div className="gap-4 flex flex-col lg:w-1/2"> <div className="flex gap-8 text-2xl "> <Image src="/logo-white.png" alt="header Logo" width={128} height={128} priority={false} /> <div className="flex gap-0.5 items-center"> <span className={styles.brandCafe}>Café</span> <span className={comforter_Brush.className}>delicia</span> </div> </div> <p className="text-5xl "> El secreto de un café rico es tomarselo entre{" "} <span className={comforter_Brush.className}>amigos</span> </p> </div> <div className="flex flex-col gap-8 lg:items-end lg:w-1/2 lg:justify-center"> <div className="flex flex-col gap-4 lg:justify-center"> <Link className="text-start" href="/nosotros"> Nosotros </Link> <Link href="/cafe">Café</Link> <Link href="/panaderia">Panadería</Link> <Link href="/bistro">Bistro</Link> <Link href="/testimonios">Testimonios</Link> <Link href="/historia">Historia</Link> <Link href="/contacto">Contacto</Link> </div> </div> </section> <section className="lg:px-52 lg:justify-start lg:w-1/2 py-16 px-8 flex gap-8 text-2xl justify-between "> <FontAwesomeIcon icon={faFacebook} /> <FontAwesomeIcon icon={faInstagram} /> <FontAwesomeIcon icon={faTwitter} /> <FontAwesomeIcon icon={faLinkedin} /> <FontAwesomeIcon icon={faSpotify} /> </section> </FooterContainer> </> ); } export default Footer;
// react-error-boundaryを使わないエラーバウンダリー、hooksが呼べない。 // https://zenn.dev/longbridge/articles/0c7c9ce5c60487 // https://marsquai.com/745ca65e-e38b-4a8e-8d59-55421be50f7e/f83dca4c-79db-4adf-b007-697c863b82a5/1df35b56-cba0-472f-8393-813e16a861c7/ // Next.jsだとサーバー側に自動的にエラーを送信する、TypeScriptの場合はランタイムエラーをコンパイルエラーにするので検証時注意。 import React, { ErrorInfo, ReactNode } from 'react' type Props = { children: ReactNode } type State = { hasError: boolean } class ErrorBoundary extends React.Component<Props, State> { constructor(props: Props) { super(props) this.state = { hasError: false } } public static getDerivedStateFromError(error: Error): State { return { hasError: true } } public componentDidCatch(error: Error, errorInfo: ErrorInfo) { // エラーハンドリングロジック if (process.env.NODE_ENV !== 'production') { console.error('Uncaught error:', error, errorInfo) } } public render() { const { hasError } = this.state const { children } = this.props if (hasError) { // // publicのhtmlを返す // window.location.href = '/error.html' // // pages/_error.tsxを返す // const router = useRouter() // router.push('/_error') return ( <> <h1>Something went wrong.</h1> <p> React標準のエラーバウンダリー(クラスコンポーネント)によるメッセージ </p> </> ) } return children } } export default ErrorBoundary
import argparse from PIL import Image from transformers import Blip2Processor, Blip2ForConditionalGeneration import torch def generate_caption(image_path, processor, model, device, prompt): try: raw_image = Image.open(image_path).convert('RGB') except FileNotFoundError: print(f'File not found: {image_path}') return None inputs = processor(images=raw_image, text=prompt, return_tensors="pt").to(device, torch.float16) out = model.generate(**inputs) return processor.decode(out[0], skip_special_tokens=True) def main(image_path, model_name, prompt): device = "cuda" if torch.cuda.is_available() else "cpu" processor = Blip2Processor.from_pretrained(model_name) model = Blip2ForConditionalGeneration.from_pretrained(model_name, torch_dtype=torch.float16) model.to(device) caption = generate_caption(image_path, processor, model, device, prompt) if caption: print(f"Generated Caption: {caption}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run BLIP2 model on an image.") parser.add_argument("--image_path", type=str, default='/workspace/data/images/xl_results.jpg', help="Path to the image file.") parser.add_argument("--model_name", type=str, default="Salesforce/blip2-opt-2.7b", help="Name of the model to use.") parser.add_argument("--prompt", type=str, default='The photo of ', help="Prompt to use for the model.") args = parser.parse_args() main(args.image_path, args.model_name, args.prompt)
import { useParams } from 'react-router-dom'; import { useState, useEffect } from 'react'; import './ReadBook.css'; import { Link } from 'react-router-dom'; import Client from '../../services/api'; import Nav from '../../components/Nav' const ReadBook = () => { let { id: storyId } = useParams(); const [snippet, setSnippet] = useState({}); const [allSnippets, setAllSnippets] = useState([]); const [isLoading, setIsLoading] = useState(true); const getAllSnippets = async (storyId) => { try { const res = await Client.get(`/snippets/story/${storyId}`); if (res.data && res.data.length > 0) { return res.data; } else { console.log("No data found"); return []; } } catch (err) { console.error(err); return []; } }; const getChildSnippets = async (snippetId) => { try { const res = await Client.get(`/snippets/snippet/${snippetId}`); if (res.data && res.data.length > 0 && res.data[0].children) { return res.data[0].children; } else { return []; } } catch (err) { console.error(err); return []; } }; const GetSnippet = async (snippetId) => { try { const snippets = await getAllSnippets(storyId); if (snippets && snippets.length > 0) { // Find the snippet with the specified ID const snippet = snippets.find(snippet => snippet.id === snippetId); setSnippet(snippet); const children = await getChildSnippets(snippet.id); setAllSnippets(children); } else { console.log("No snippets found"); } } catch (err) { console.error(err); } }; useEffect(() => { const fetchData = async () => { try { setIsLoading(true); const snippets = await getAllSnippets(storyId); if (snippets && snippets.length > 0) { const firstSnippet = snippets.sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0]; setSnippet(firstSnippet); const children = await getChildSnippets(firstSnippet.id); setAllSnippets(children); } else { console.log("No snippets found"); } } catch (err) { console.error(err); } finally { setIsLoading(false); } }; fetchData(); }, [storyId]); useEffect(() => { }, [snippet]); useEffect(() => { }, [allSnippets]); return ( <div><Nav /> <div className="readBook-container"> {isLoading ? ( <h1>Loading...</h1> ) : ( <> <img src={snippet.image} alt="" className="readBook-image" /> <h2>{snippet.header}</h2> {/* <h2>{snippet.id}</h2> */} {snippet && <p className="readBook-content" dangerouslySetInnerHTML={{ __html: snippet.content ? snippet.content.replace(/\n/g, '<br />') : '' }}></p>} {allSnippets && allSnippets.length > 0 && ( <div className="readBook-buttons"> {allSnippets.map((child) => ( <button key={child.id} onClick={() => GetSnippet(child.id)} className="readBook-btn"> {child.header} </button> ))} </div> )} </> )} <div className="backBtn"> <Link to={'/home'} className="backLink"> <p>Back to home</p> </Link> </div> </div> </div> ); }; export default ReadBook;
# frozen_string_literal: true module ActiveFields module Field class DecimalArray < ActiveFields.config.field_base_class store_accessor :options, :min_size, :max_size, :min, :max # attribute :min_size, :integer # attribute :max_size, :integer # attribute :min, :decimal # attribute :max, :decimal validates :min_size, comparison: { greater_than_or_equal_to: 0 }, allow_nil: true validates :max_size, comparison: { greater_than_or_equal_to: ->(r) { r.min_size || 0 } }, allow_nil: true validates :max, comparison: { greater_than_or_equal_to: :min }, allow_nil: true, if: :min %i[min_size max_size].each do |column| define_method(column) do Casters::IntegerCaster.new.deserialize(super()) end define_method(:"#{column}=") do |other| super(Casters::IntegerCaster.new.serialize(other)) end end %i[min max].each do |column| define_method(column) do Casters::DecimalCaster.new.deserialize(super()) end define_method(:"#{column}=") do |other| super(Casters::DecimalCaster.new.serialize(other)) end end private def set_defaults; end end end end
El proyecto "Universo Marvel" es una aplicación web sofisticada diseñada para brindar acceso integral a información sobre el vasto universo de Marvel Comics. Esta aplicación sirve como una plataforma interactiva para explorar cómics, series, personajes, historias y creadores asociados con Marvel. A continuación, se presenta una descripción estructurada y mejorada del proyecto: **Componentes Principales:** 1. **MarvelAPIService**: Este servicio es el núcleo de la aplicación, actuando como un puente entre la aplicación y la API de Marvel Comics. Facilita varias operaciones, como la búsqueda de cómics, obtención de detalles de series, personajes y eventos. 2. **MarvelController**: Gestiona las solicitudes HTTP y coordina la interacción entre la interfaz de usuario y MarvelAPIService. Por ejemplo, en una búsqueda de cómics, invoca el método `searchComics` de MarvelAPIService, procesa los datos recibidos y los presenta a través de la interfaz de usuario. 3. **FavoriteController**: Maneja las funcionalidades relacionadas con los favoritos en la aplicación, permitiendo a los usuarios agregar o eliminar elementos de sus favoritos y visualizar su lista de favoritos. **Funcionalidades Clave:** 1. **Página de Inicio**: Exhibe personajes, cómics y series destacadas de Marvel. 2. **Navegación**: Permite a los usuarios explorar diferentes secciones: personajes, cómics, series, historias, creadores y favoritos. 3. **Búsquedas Específicas**: Incluye búsqueda de personajes, cómics, series, historias y creadores, proporcionando detalles exhaustivos para cada categoría. 4. **Gestión de Favoritos**: Los usuarios registrados pueden gestionar su contenido favorito, añadiendo o eliminando elementos de su lista de favoritos. 5. **Autenticación de Usuarios**: Funciones de registro, inicio y cierre de sesión para una experiencia personalizada. 6. **Manejo de Errores**: Proporciona respuestas claras y útiles ante situaciones de error. 7. **Paginación**: Optimiza la visualización de grandes volúmenes de datos. **Integración Técnica:** - **API de Marvel**: Se utiliza para acceder a información actualizada del universo Marvel, requiriendo claves de autenticación pública y privada almacenadas en el archivo `.env`. Ejemplo de Claves: ```plaintext MARVEL_API_PUBLIC_KEY=2ec454ae867fe9610140383667a13382 MARVEL_API_PRIVATE_KEY=9a55cda0bc2ea68fa863f367174199b7bdeeb85d MARVEL_API_BASE_URL=https://gateway.marvel.com/v1/public ``` - **Base de Datos MySQL**: Almacena datos locales relevantes para el funcionamiento del sitio web. Detalles de Conexión: ```plaintext DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=marvel DB_USERNAME=root DB_PASSWORD=abcd1234 ``` En resumen, el proyecto "Universo Marvel" representa una solución tecnológica completa, estructurada y eficiente para los aficionados de Marvel, brindando una experiencia de usuario enriquecedora y accesible para explorar el fascinante mundo de Marvel Comics.
import { getRandomElement } from "./Utils"; import "./GamePanel.css"; const GamePanel = (props) => { const {currentRound, totalRounds, place, question, score, answerPlace, showNext, gameOver, onNext, onReset} = props; const answered = answerPlace !== null; const correctAnswer = answered && place.name === answerPlace.name; const nextButtonText = gameOver ? "Game Over" : showNext ? (answered ? "Next Round" : "Skip Round") : "End Game"; const correctAnswerText = getRandomElement(["Awesome!", "You got it!", "Way to go!", "Great job!"]); const wrongAnswerText = getRandomElement(["Close but no cigar!", "Sorry!", "Oh no!"]); const correctAnswerEmoji = getRandomElement(["😊", "😇", "😎", "😁"]); const wrongAnswerEmoji = getRandomElement(["🤕", "🤧", "😵", "🙁", "😢", "😭", "😞", "😫"]) const gameOverEmoji = getRandomElement(["🎲", "🎮", "👾", "🕹️"]); const wikiLink = "https://wikipedia.org/wiki/" + place.wikiLink; return ( <div id="game-panel"> <div className="pure-g"> <div className="pure-u-1-2 bold"> Round {currentRound}/{totalRounds} </div> <div className="pure-u-1-2 bold scoreboard"> Score {score} </div> <div className="pure-u-1-1"> <button disabled={gameOver} className="pure-button pure-button-primary next-button" onClick={onNext}>{nextButtonText}</button> </div> <div id="question" className="pure-u-1-1"> {question.text} {question.type === "image" && question.imageType === "emoji" && <div className="emoji"> {question.imageSrc} </div> } </div> {answered && <div id="answer-feedback" className="pure-u-1-1 animate"> {correctAnswer && <> <div className="emoji">{correctAnswerEmoji}</div> <div className="heading">{correctAnswerText}</div> <p>Read more about <a target="_blank" rel="noopener noreferrer" href={wikiLink}>{place.name}</a> on Wikipedia.</p> </> } {!correctAnswer && <> <div className="emoji">{wrongAnswerEmoji}</div> <div className="heading">{wrongAnswerText}</div> <div>That is incorrect.</div> </> } </div> } {gameOver && <div id="game-over" className="pure-u-1-1"> <div className="emoji"> {gameOverEmoji} </div> <div className="heading"> {score > 0 ? "Good job" : "Sorry"} </div> <div className="score-blurb"> You scored {score} points. </div> <button className="pure-button pure-button-primary" onClick={onReset}>Play again</button> </div> } </div> </div> ); } export default GamePanel;
#scope_module /* A Target is the final presenter of a rendered image. For instance, WindowTarget displays an image to an OS window. Not available yet, but FileTarget would be able to write a rendered image to a PNG file. To display anything to a target, you need to bind a renderer to the target. For instance, a Camera or a PostProcessRenderer. */ Target :: struct { Kind :: enum { None :: 0; Window; Vr; } Options :: struct { Filter :: enum { Linear :: 0; Nearest; } // How the renderer's output should be mapped to the final window. filter : Filter; } kind := Kind.None; engine : *Engine; options : Options; allocator : Allocator; } destroy_target :: (target : *Target) { if target.kind == .Window { window_target_cleanup(cast(*WindowTarget) target, resetMemory = false); } else if target.kind == .Vr { vr_target_cleanup(cast(*VrTarget) target, resetMemory = false); } if target.allocator.proc != null { Basic.free(target, target.allocator); } } target_cleanup :: (target : *Target) { if target.kind == Target.Kind.Window { window_target_cleanup(cast(*WindowTarget) target); } else if target.kind == .Vr { vr_target_cleanup(cast(*VrTarget) target); } } target_update :: (target : *Target) { if target.kind == .Window { window_target_update(cast(*WindowTarget) target); } else if target.kind == .Vr { vr_target_update(cast(*VrTarget) target); } } target_bind :: (target : *Target, rendererOutput : RendererOutput, bindIndex : u8 = 0) { if target.kind == .Window { window_target_bind(cast(*WindowTarget) target, rendererOutput, bindIndex); } else if target.kind == .Vr { vr_target_bind(cast(*VrTarget) target, rendererOutput, bindIndex); } } // ----- WindowTarget :: struct { using #as target : Target; target.kind = Target.Kind.Window; extent : Chamber.uvec2; rendererOutput : RendererOutput; using windowTargetImpl : WindowTargetImpl; } // Allocate, init and register a new window target. create_window_target :: (engine : *Engine, windowHandle : Chamber.WindowHandle, options := Target.Options.{}) -> *WindowTarget { windowTarget := cast(*WindowTarget) Basic.New(WindowTarget); Basic.remember_allocators(windowTarget); window_target_init(windowTarget, engine, windowHandle, options); engine_register(engine, windowTarget); return windowTarget; } window_target_init :: (windowTarget : *WindowTarget, engine : *Engine, windowHandle : Chamber.WindowHandle, options := Target.Options.{}) { Basic.assert(cast(bool) engine.options.features & .Window); _target_init(windowTarget, engine, options); impl_window_target_init(windowTarget, windowHandle); } window_target_cleanup :: (windowTarget : *WindowTarget, resetMemory := true) { impl_window_target_cleanup(windowTarget); if resetMemory { windowTarget.* = WindowTarget.{}; } } window_target_update :: (windowTarget : *WindowTarget) -> bool { // Nothing to do return true; } window_target_bind :: (windowTarget : *WindowTarget, rendererOutput : RendererOutput, bindIndex : u8) { windowTarget.rendererOutput = rendererOutput; } // ----- #if VR_ENABLED { #load "openxr/vr-target.jai"; } else { #load "dummy/vr-target.jai"; } _target_init :: (target : *Target, engine : *Engine, options : Target.Options) { target.options = options; target.engine = engine; }
# 리스트 자료 구조 # 1 list 생성 > list <- list("star", "sun", "moon") > list [[1]] [1] "star" [[2]] [1] "sun" [[3]] [1] "moon" # 2 리스트를 벡터 구조로 변경 > unlist <- unlist(list) > uliist 에러: 객체 'uliist'를 찾을 수 없습니다 > unlist [1] "star" "sun" "moon" > # 3 key와 value로 생성 > family <- list(name = c("star","sun", "moon"), age= c(13, 7, 3), + address = c("jeju", "seoul", "busan"), gender = c("M", "W", "W"), + htype = c("apt", "apt","house")) > family $name [1] "star" "sun" "moon" $age [1] 13 7 3 $address [1] "jeju" "seoul" "busan" $gender [1] "M" "W" "W" $htype [1] "apt" "apt" "house" # 4 name의 첫번째 값 출력 > family$name[1] [1] "star" # 5 htype의 첫번째 값 출력 > family$htype[1] [1] "apt" # 6 htype의 두번째 값을 "office"로 변경 > family$htype[2] <- "office" > family$htype [1] "apt" "office" "house" # 7 gender 원소 제거 > family$gender <- NULL > family $name [1] "star" "sun" "moon" $age [1] 13 7 3 $address [1] "jeju" "seoul" "busan" $htype [1] "apt" "office" "house" # 8 다차원 리스트 객체 생성 > multi_family = list(c1 = list("star", "sun", "moon"), + c2 = list("earth", "mars", "venus"), + c3 = list("saturn","neptun","pluto")) > multi_family $c1 $c1[[1]] [1] "star" $c1[[2]] [1] "sun" $c1[[3]] [1] "moon" $c2 $c2[[1]] [1] "earth" $c2[[2]] [1] "mars" $c2[[3]] [1] "venus" $c3 $c3[[1]] [1] "saturn" $c3[[2]] [1] "neptun" $c3[[3]] [1] "pluto" # 9 다차원 리스트를 열 단위로 바인딩 # 리스트 자료가 열단위로 묶여서 matrix 객체가 생성 > do.call(cbind, multi_family) c1 c2 c3 [1,] "star" "earth" "saturn" [2,] "sun" "mars" "neptun" [3,] "moon" "venus" "pluto"
import {Component, Input} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {ConfigService} from "../../shared/services/config.service"; import {ToastrService} from "ngx-toastr"; import {ModalService} from "../../shared/services/modal.service"; import {SystemConfigModel} from "../../shared/models/system-config.model"; import {ExercisetypeEnum} from "../../shared/enums/exercisetype.enum"; import {NgbActiveModal} from "@ng-bootstrap/ng-bootstrap"; import {ExerciseService} from "../../shared/services/exercise.service"; import {ExerciseModel} from "../../shared/models/exercise.model"; @Component({ selector: 'app-form-exercise', templateUrl: './form-exercise.component.html', styleUrls: ['./form-exercise.component.css'] }) export class FormExerciseComponent { @Input() exercise: ExerciseModel; @Input() patientId: number; exerciseForm: FormGroup; constructor(private formBuilder: FormBuilder, public activeModal: NgbActiveModal, private toastr: ToastrService, private modalService: ModalService, private exerciseService: ExerciseService) { } ngOnInit(): void { this.inicializeForm(); } private inicializeForm() { this.exerciseForm = this.formBuilder.group({ exerciseSeriesName: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(100)]], description: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(1000)]], timesPerWeek: ['', [Validators.required, Validators.min(1), Validators.pattern(/^\d+(\.\d{1,2})?$/)]], dateCreated: [''], timeCreated: [''], exerciseType: ['', [Validators.required]], }) this.exerciseForm.patchValue(this.exercise); } onSubmit(): void { if(this.exercise){ return } let exercise: ExerciseModel = this.exerciseForm.value; exercise.patientId = this.patientId; exercise.dateCreated = new Date().toISOString(); exercise.timeCreated = new Date().toLocaleTimeString('pt-BR', {timeZone: 'America/Sao_Paulo'}).slice(0, 5) + ':00'; this.exerciseService.createExercise(exercise).subscribe({ next: () => { this.toastr.success("Exercício criado com sucesso") this.activeModal.close() }, error: err => this.toastr.error(err.message) }) } onUpdate(): void { let exercise: ExerciseModel = this.exerciseForm.value; exercise.id = this.exercise.id; exercise.patientId = this.patientId; exercise.status = this.exercise.status; this.exerciseService.updateExercise(exercise).subscribe({ next: () => { this.toastr.success("Exercício atualizado com sucesso") this.activeModal.close() }, error: err => this.toastr.error(err.message) }) } onDelete() { this.exerciseService.deleteExercise(this.exercise.id).subscribe({ next: () => { this.toastr.success("Exercício excluído com sucesso") this.activeModal.close() }, error: err => this.toastr.error(err.message) }) } checkIfInputIsUsed(inputName: string): boolean { return this.exerciseForm.controls[inputName].dirty || this.exerciseForm.controls[inputName].touched } returnValidationClassForInput(inputName: string): string { if (this.checkIfInputIsUsed(inputName)) return this.exerciseForm.controls[inputName].invalid ? 'is-invalid' : 'is-valid' return '' } protected readonly ExercisetypeEnum = ExercisetypeEnum; protected readonly Object = Object; }
package dev.mmaksymko.users.models; import jakarta.persistence.*; import lombok.*; import org.hibernate.annotations.ColumnTransformer; import org.hibernate.annotations.CreationTimestamp; import java.time.LocalDateTime; @Entity @Table(name = "blog_user") @SecondaryTable(name = "user_pfp", pkJoinColumns = @PrimaryKeyJoinColumn(name = "user_id")) @Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(of = {"id"}) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") private Long id; @Column(name = "first_name", nullable = false) private String firstName; @Column(name = "last_name", nullable = false) private String lastName; @Column(name = "email", unique = true, nullable = false) private String email; @Enumerated(EnumType.STRING) @ColumnTransformer(write="?::USER_ROLE_DOMAIN") @Column(columnDefinition = "USER_ROLE_DOMAIN", name = "role", nullable = false) private UserRole role; @CreationTimestamp @Column(name = "registered_at", updatable = false) private LocalDateTime registeredAt; @Column(name = "pfp_url", table = "user_pfp") private String pfpUrl; }
<template> <q-page class=""> <q-layout-header :reveal="$store.state.device !== 'P'"> <q-toolbar color="black" inverted > <q-btn flat round dense icon="fast_rewind" @click="goBack" /> <q-toolbar-title>🔥 핫 딜 🔥</q-toolbar-title> <q-btn flat round dense icon="search" @click="goSearch" /> <!-- <q-select inverted-light color="white" v-model="selectedOrderBy" :options="selectedOrderByOptions" style="width:120px" /> --> </q-toolbar> </q-layout-header> <!-- 2. 상품 리스트 --> <q-pull-to-refresh :handler="refresher" pull-message="땡기라~더땡기라~" release-message="놔라~이제점놔라~" refresh-message="온다온다~" > <q-infinite-scroll :handler="loadMore" ref="infiniteScroll"> <q-card-separator /> <div style="padding:0px 0px 0px 0px" v-for="item in productList" :key="item.seq"> <q-item @click.native="goProductDetail(item.seq)" style="padding:0px 0px 0px 0px"> <table border="0" style="width: 95%" cellpadding="0" cellspacing="0" align="center"> <tr> <td colspan="4" align="center">&nbsp;</td> </tr> <tr> <td colspan="4" align="center">&nbsp;</td> </tr> <tr> <td colspan="4" align="center"><font size="2" color="grey"><div v-html="setHtml(item.subtitle)" style="word-break:keep-all; word-wrap:break-word;"></div></font></td> </tr> <tr> <td colspan="4" align="center"><font size="3" color="black"><div v-html="setHtml(item.title)" style="word-break:keep-all; word-wrap:break-word;"></div></font></td> </tr> <tr> <td colspan="4" align="center">&nbsp;</td> </tr> <tr> <td colspan="4" align="center"><img :src="item.image_url" :width="`${widthRate}%`" style="display: block; border-radius: 5px;"></td> </tr> <tr> <td colspan="4" align="center">&nbsp;</td> </tr> <tr> <td :width="`${(100 - widthRate) / 2}%`"></td> <td :width="`${(widthRate) / 5 * 3}%`" align="left"><font size="3" color="black" style="font-weight:bold;">&nbsp;{{ addComma(item.price) }}&nbsp;원</font></td> <td :width="`${(widthRate) / 5 * 2}%`" align="right"><font size="2" color="black">{{ addComma(item.reward_coin) }} <img src="statics/images/logo/logocoin.png" style="width: 9px">&nbsp;</font></td> <td :width="`${(100 - widthRate) / 2}%`"></td> </tr> <tr> <td colspan="4" align="center">&nbsp;</td> </tr> <tr> <td colspan="4" align="center">&nbsp;</td> </tr> </table> </q-item> <q-card-separator /> <q-card-separator /> <q-card-separator /> <q-card-separator /> <q-card-separator /> <q-card-separator /> <q-card-separator /> <q-card-separator /> <q-card-separator /> <q-card-separator /> </div> <br> <div style="text-align:center;"><q-spinner-hearts slot="message" :size="100" color="primary"></q-spinner-hearts></div> </q-infinite-scroll> </q-pull-to-refresh> <br> <br> <br> <br> </q-page> </template> <style> </style> <script> import Vue from 'vue' export default { name: 'new-product-list', data () { return { refresherDone: '', widthRate: 50, // 레이아웃 너비 % - PC화면 대응 pageSize: 15, lastPageNum: 1, // 마지막 페이지 selectedOrderBy: '', selectedOrderByOptions: [ {label: '최신순', value: '11'}, {label: '인기순', value: '21'}, {label: '판매순', value: '31'}, {label: '원더 ↑', value: '41'}, {label: '원더 ↓', value: '42'}, {label: '가격 ↑', value: '51'}, {label: '가격 ↓', value: '52'} ], productList: [] } }, components: { }, created: function () { if (this.$store.state.device === 'P') { // PC인 경우 this.widthRate = 25 // 화면 너비 50% } this.selectedOrderBy = '11' this.selectListMax() // 마지막페이지 조회 }, methods: { refresher (done) { // done - Function to call when you made all necessary updates. // DO NOT forget to call it otherwise the refresh message // will continue to be displayed // make some Ajax call then call done() this.refresherDone = done // load가 끝나면 로딩메세지 종료 this.$refs.infiniteScroll.reset() // index 초기화 this.$refs.infiniteScroll.resume() // stop에서 다시 재생 this.$refs.infiniteScroll.loadMore() // loadMore로 검색 }, loadMore: function (index, done) { // index - called for nth time // done - Function to call when you made all necessary updates. // DO NOT forget to call it otherwise your loading message // will continue to be displayed. Has optional boolean // parameter that invokes stop() when true console.log('index: ' + index) // make some Ajax call then call done() // this.pageNum = index setTimeout(() => { // alert(index) console.log('loadMore called index: ' + index) if (index <= this.lastPageNum) { this.selectList(index, done) if (index === this.lastPageNum) { this.$refs.infiniteScroll.stop() } // refresher 로딩메세지 처리 if (this.refresherDone != null && this.refresherDone !== '') { this.refresherDone() // 로딩메세지 종료 this.refresherDone = '' // 로딩메세지 초기화 } } }, 500) }, // 상품 리스트 마지막 페이지 조회 selectListMax () { this.$axios.get(this.$store.state.apiServerIp + '/api/product/selectHotdealProductListLastPageNum', {params: {pageSize: this.pageSize}}) .then((result) => { // console.log(JSON.stringify(result.data)) this.lastPageNum = result.data }) .catch((err) => { console.log(err) }) }, // 상품 리스트 조회 selectList (idx, done) { this.$axios.get(this.$store.state.apiServerIp + '/api/product/selectHotdealProductList', {params: {pageNum: idx, pageSize: this.pageSize}}) .then((result) => { // console.log(JSON.stringify(result.data)) if (idx === 1) { // 첫번째 load인 경우 this.productList = [] // 리스트 초기화 } this.productList = this.productList.concat(result.data) done() }) .catch((err) => { console.log(err) done() }) }, // 상품 상세 화면으로 이동 goProductDetail (seqProduct) { this.$router.push('/productDetail?seq=' + seqProduct) }, addComma (num) { return Vue.prototype.$addComma(num) }, setHtml (str) { return Vue.prototype.$setHtml(str) }, goSearch () { this.$router.push('/search') }, goBack () { // 라우터 백 패스 설정 let path = this.$store.state.ROUTER_FROM_PATH[this.$store.state.ROUTER_FROM_PATH.length - 1] // 라우터 백 패스 1개 삭제 this.$store.state.ROUTER_FROM_PATH.splice(this.$store.state.ROUTER_FROM_PATH.length - 1, 1) // 뒤로가기 여부 - true일 경우 라우터 패스를 저장 안함, goBack() 함수 내에서 true로 설정, 라우터에서 false로 초기화 this.$store.state.ROUTER_IS_MOVE_BACK = true // 라우터 백 패스로 이동 this.$router.push(path) } } } </script>
import axios from "axios"; import React from "react"; const api = axios.create({ baseURL: "http://localhost:8080/" }); class TodoForm extends React.Component { state = { title: "", dueDate: "", userId: Number(localStorage.getItem("user_id")), }; handleSubmit = async () => { if (this.state.title !== "" && this.state.dueDate !== "") { try { let res = await api.post("todo", this.state); if (res.status === 200) { this.props.data(this.props.secId); document.getElementsByClassName("AddTodo-text")[0].value = ""; document.getElementsByClassName("AddTodo-date")[0].value = ""; } } catch (error) { console.log(error); } } }; handleTodoText = (e) => { this.setState({ title: e.target.value }); e.preventDefault(); }; handleDueDate = (e) => { let dts = e.target.value.split("-"); let date = new Date(dts[0], dts[1] - 1, dts[2]); this.setState({ dueDate: date.getTime() }); e.preventDefault(); }; render() { return ( <div className="AddTodo"> <input type="text" className="AddTodo-text" placeholder="What's next?" onChange={this.handleTodoText} /> <input type="date" className="AddTodo-date" onChange={this.handleDueDate} /> <button className="AddTodo-button" onClick={this.handleSubmit}> Add </button> </div> ); } } export default TodoForm;
The dl_iterate_phdr() function allows an application to inquire at run time to find out which shared objects it has loaded, and the order in which they were loaded. The dl_iterate_phdr() function walks through the list of an application's shared objects and calls the function callback once for each object, until either all shared objects have been processed or callback returns a nonzero value. Each call to callback receives three arguments: info, which is a pointer to a structure containing information about the shared object; size, which is the size of the structure pointed to by info; and data, which is a copy of whatever value was passed by the calling program as the second argument (also named data) in the call to dl_iterate_phdr(). The info argument is a structure of the following type: struct dl_phdr_info { ElfW(Addr) dlpi_addr; /* Base address of object */ const char *dlpi_name; /* (Null-terminated) name of object */ const ElfW(Phdr) *dlpi_phdr; /* Pointer to array of ELF program headers for this object */ ElfW(Half) dlpi_phnum; /* # of items in dlpi_phdr */ /* The following fields were added in glibc 2.4, after the first version of this structure was available. Check the size argument passed to the dl_iterate_phdr callback to determine whether or not each later member is available. */ unsigned long long int dlpi_adds; /* Incremented when a new object may have been added */ unsigned long long int dlpi_subs; /* Incremented when an object may have been removed */ size_t dlpi_tls_modid; /* If there is a PT_TLS segment, its module ID as used in TLS relocations, else zero */ void *dlpi_tls_data; /* The address of the calling thread's instance of this module's PT_TLS segment, if it has one and it has been allocated in the calling thread, otherwise a null pointer */ }; (The ElfW() macro definition turns its argument into the name of an ELF data type suitable for the hardware architecture. For example, on a 32-bit platform, ElfW(Addr) yields the data type name Elf32_Addr. Further information on these types can be found in the <elf.h> and <link.h> header files.) The dlpi_addr field indicates the base address of the shared object (i.e., the difference between the virtual memory address of the shared object and the offset of that object in the file from which it was loaded). The dlpi_name field is a null-terminated string giving the pathname from which the shared object was loaded. To understand the meaning of the dlpi_phdr and dlpi_phnum fields, we need to be aware that an ELF shared object consists of a number of segments, each of which has a corresponding program header describing the segment. The dlpi_phdr field is a pointer to an array of the program headers for this shared object. The dlpi_phnum field indi‐ cates the size of this array. These program headers are structures of the following form: typedef struct { Elf32_Word p_type; /* Segment type */ Elf32_Off p_offset; /* Segment file offset */ Elf32_Addr p_vaddr; /* Segment virtual address */ Elf32_Addr p_paddr; /* Segment physical address */ Elf32_Word p_filesz; /* Segment size in file */ Elf32_Word p_memsz; /* Segment size in memory */ Elf32_Word p_flags; /* Segment flags */ Elf32_Word p_align; /* Segment alignment */ } Elf32_Phdr; Note that we can calculate the location of a particular program header, x, in virtual memory using the formula: addr == info->dlpi_addr + info->dlpi_phdr[x].p_vaddr; Possible values for p_type include the following (see <elf.h> for further details): #define PT_LOAD 1 /* Loadable program segment */ #define PT_DYNAMIC 2 /* Dynamic linking information */ #define PT_INTERP 3 /* Program interpreter */ #define PT_NOTE 4 /* Auxiliary information */ #define PT_SHLIB 5 /* Reserved */ #define PT_PHDR 6 /* Entry for header table itself */ #define PT_TLS 7 /* Thread-local storage segment */ #define PT_GNU_EH_FRAME 0x6474e550 /* GCC .eh_frame_hdr segment */ #define PT_GNU_STACK 0x6474e551 /* Indicates stack executability */ #define PT_GNU_RELRO 0x6474e552 /* Read-only after relocation */
import { axiosPrivate } from './axios' import { useEffect } from 'react' // import { Coockies } from 'js-cookie' import Coockies from 'js-cookie' import { userRefreshToken } from '../hooks/userRefreshToken' export const useAxiosPrivate = () => { const refresh = userRefreshToken() useEffect(() => { const requestInstance = axiosPrivate.interceptors.request.use( (config) => { const access = Coockies.get('access') config.headers.Authorization = `Bearer ${access}` return config }, (error) => Promise.reject(error) ) const responseInstance = axiosPrivate.interceptors.response.use( (response) => { return response }, async (error) => { const prvRequest = error?.config if (error.response?.status == 401 && !prvRequest?.sent) { prvRequest.sent = true const access = await refresh() // const access = Coockies.get('access') prvRequest.headers['Authorization'] = `Bearer ${access}` console.log(prvRequest) return await axiosPrivate(prvRequest) } return Promise.reject(error) } ) return () => { axiosPrivate.interceptors.response.eject(responseInstance) axiosPrivate.interceptors.request.eject(requestInstance) } }, [refresh]) return axiosPrivate }
package org.example.photo.usecases; import org.example.album.adapters.out.gateways.ds.entities.AlbumEntity; import org.example.album.adapters.out.gateways.ds.repositories.AlbumRepository; import org.example.photo.adapters.out.gateways.ds.entities.PhotoEntity; import org.example.photo.usecases.ports.in.PhotoRestUseCase; import org.example.photo.adapters.out.gateways.ds.repositories.PhotoRepository; import org.example.photo.usecases.models.PhotoRequest; import org.example.photo.usecases.models.PhotoResponse; import org.example.role.domains.RoleName; import org.example.shared.ApiResponse; import org.example.auth.usecases.models.PagedResponse; import org.example.shared.exceptions.ResourceNotFoundException; import org.example.shared.exceptions.UnauthorizedException; import org.example.shared.models.utils.AppConstants; import org.example.shared.models.utils.AppUtils; import org.example.shared.security.UserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.example.shared.models.utils.AppConstants.*; @Service public class PhotoInteractor implements PhotoRestUseCase { @Autowired private PhotoRepository photoRepository; @Autowired private AlbumRepository albumRepository; @Override public PagedResponse<PhotoResponse> getAllPhotos(int page, int size) { AppUtils.validatePageNumberAndSize(page, size); Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, CREATED_AT); Page<PhotoEntity> photos = photoRepository.findAll(pageable); List<PhotoResponse> photoResponses = new ArrayList<>(photos.getContent().size()); for (PhotoEntity photo : photos.getContent()) { photoResponses.add(new PhotoResponse(photo.getId(), photo.getTitle(), photo.getUrl(), photo.getThumbnailUrl(), photo.getAlbum().getId())); } if (photos.getNumberOfElements() == 0) { return new PagedResponse<>(Collections.emptyList(), photos.getNumber(), photos.getSize(), photos.getTotalElements(), photos.getTotalPages(), photos.isLast()); } return new PagedResponse<>(photoResponses, photos.getNumber(), photos.getSize(), photos.getTotalElements(), photos.getTotalPages(), photos.isLast()); } @Override public PhotoResponse getPhoto(Long id) { PhotoEntity photo = photoRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(PHOTO, ID, id)); return new PhotoResponse(photo.getId(), photo.getTitle(), photo.getUrl(), photo.getThumbnailUrl(), photo.getAlbum().getId()); } @Override public PhotoResponse updatePhoto(Long id, PhotoRequest photoRequest, UserPrincipal currentUser) { AlbumEntity album = albumRepository.findById(photoRequest.getAlbumId()) .orElseThrow(() -> new ResourceNotFoundException(ALBUM, ID, photoRequest.getAlbumId())); PhotoEntity photo = photoRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(PHOTO, ID, id)); if (photo.getAlbum().getUser().getId().equals(currentUser.getId()) || currentUser.getAuthorities().contains(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString()))) { photo.setTitle(photoRequest.getTitle()); photo.setThumbnailUrl(photoRequest.getThumbnailUrl()); photo.setAlbumEntity(album); PhotoEntity updatedPhoto = photoRepository.save(photo); return new PhotoResponse(updatedPhoto.getId(), updatedPhoto.getTitle(), updatedPhoto.getUrl(), updatedPhoto.getThumbnailUrl(), updatedPhoto.getAlbum().getId()); } ApiResponse apiResponse = new ApiResponse(Boolean.FALSE, "You don't have permission to update this photo"); throw new UnauthorizedException(apiResponse); } @Override public PhotoResponse addPhoto(PhotoRequest photoRequest, UserPrincipal currentUser) { AlbumEntity album = albumRepository.findById(photoRequest.getAlbumId()) .orElseThrow(() -> new ResourceNotFoundException(ALBUM, ID, photoRequest.getAlbumId())); if (album.getUser().getId().equals(currentUser.getId())) { PhotoEntity photo = new PhotoEntity(photoRequest.getTitle(), photoRequest.getUrl(), photoRequest.getThumbnailUrl(), album); PhotoEntity newPhoto = photoRepository.save(photo); return new PhotoResponse(newPhoto.getId(), newPhoto.getTitle(), newPhoto.getUrl(), newPhoto.getThumbnailUrl(), newPhoto.getAlbum().getId()); } ApiResponse apiResponse = new ApiResponse(Boolean.FALSE, "You don't have permission to add photo in this album"); throw new UnauthorizedException(apiResponse); } @Override public ApiResponse deletePhoto(Long id, UserPrincipal currentUser) { PhotoEntity photo = photoRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(PHOTO, ID, id)); if (photo.getAlbum().getUser().getId().equals(currentUser.getId()) || currentUser.getAuthorities().contains(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString()))) { photoRepository.deleteById(id); return new ApiResponse(Boolean.TRUE, "Photo deleted successfully"); } ApiResponse apiResponse = new ApiResponse(Boolean.FALSE, "You don't have permission to delete this photo"); throw new UnauthorizedException(apiResponse); } @Override public PagedResponse<PhotoResponse> getAllPhotosByAlbum(Long albumId, int page, int size) { AppUtils.validatePageNumberAndSize(page, size); Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, AppConstants.CREATED_AT); Page<PhotoEntity> photos = photoRepository.findByAlbumId(albumId, pageable); List<PhotoResponse> photoResponses = new ArrayList<>(photos.getContent().size()); for (PhotoEntity photo : photos.getContent()) { photoResponses.add(new PhotoResponse(photo.getId(), photo.getTitle(), photo.getUrl(), photo.getThumbnailUrl(), photo.getAlbum().getId())); } return new PagedResponse<>(photoResponses, photos.getNumber(), photos.getSize(), photos.getTotalElements(), photos.getTotalPages(), photos.isLast()); } }
document.addEventListener("DOMContentLoaded", function () { const taskInput = document.getElementById("taskInput"); const addTaskButton = document.getElementById("addTask"); const favoritesList = document.getElementById("favoritesList"); const inboxList = document.getElementById("inboxList"); function addNewTask() { const taskText = taskInput.value.trim(); if (taskText === "") return; const taskItem = document.createElement("li"); taskItem.classList.add("list-group-item", "task"); taskItem.textContent = taskText; const deleteButton = document.createElement("button"); deleteButton.classList.add("btn", "btn-danger", "btn-sm", "float-right"); deleteButton.textContent = "Delete"; const favoriteButton = document.createElement("button"); favoriteButton.classList.add("btn", "btn-warning", "btn-sm", "float-right", "mr-2"); favoriteButton.textContent = "Favorite"; const inboxButton = document.createElement("button"); inboxButton.classList.add("btn", "btn-info", "btn-sm", "float-right", "mr-2"); inboxButton.textContent = "Inbox"; deleteButton.addEventListener("click", function () { taskItem.remove(); }); favoriteButton.addEventListener("click", function () { favoritesList.appendChild(taskItem); favoriteButton.style.display = "none"; inboxButton.style.display = "inline-block"; }); inboxButton.addEventListener("click", function () { inboxList.appendChild(taskItem); favoriteButton.style.display = "inline-block"; inboxButton.style.display = "none"; }); taskItem.appendChild(deleteButton); taskItem.appendChild(favoriteButton); taskItem.appendChild(inboxButton); inboxList.appendChild(taskItem); taskInput.value = ""; } addTaskButton.addEventListener("click", addNewTask); taskInput.addEventListener("keyup", function (event) { if (event.key === "Enter") { addNewTask(); } }); });
# Basics - Make new repo and commit to it ```bash git init . git add . git commit -m "commit message" # Set up remote repo # Origin is what remote will be called git remote add origin <urlOfRepo> git branch -M main # Tell it where to push to for first push # -u is upstream git push -u origin main ``` # Git Local ## Git Branch - Create Branch and then checkout ```bash git branch <branchName> git checkout <branchName> ``` ## Git Merge ```bash git merge <branchName> ``` ## Git Status - Tells commit - Tells current changes since commit ``` bash git status ``` # Git Remote ## Upload to new repo - Create repo on github ```bash ``` ## Git Fetch - Bring in remote changes but don't move HEAD ## Git Pull - Syncs HEAD with remote # Git Push # Git Discard local changes - Get rid of local changes ```bash git reset --hard ```
import { useCallback, useState } from "react"; import { VStack, Icon, Toast, FlatList } from "native-base"; import { Octicons } from "@expo/vector-icons"; import { useNavigation, useFocusEffect } from "@react-navigation/native"; import { api } from "../services/api"; import { Button } from "../components/Button"; import { Header } from "../components/Header"; import { Loading } from "../components/Loading"; import { PoolCard, PoolCardProps } from "../components/PoolCard"; import { EmptyPoolList } from "../components/EmptyPoolList"; export function MyPools() { const [isLoading, setIsLoading] = useState(true); const [pools, setPools] = useState<PoolCardProps[]>([]); const { navigate } = useNavigation(); useFocusEffect( useCallback(() => { getPools(); }, []) ); async function getPools() { try { setIsLoading(true); const response = await api.get("/pools"); setPools(response.data.pools); } catch (err) { console.log(err); Toast.show({ title: "Não foi possível carregar os bolões.", placement: "top", bgColor: "red.500" }); } finally { setIsLoading(false); } } return ( <VStack flex={1} bgColor="gray.900"> <Header title="Meus bolões" /> <VStack mt={6} mx={5} borderBottomWidth={1} borderBottomColor="gray.600" pb={4} mb={4}> <Button title="BUSCAR BOLÃO POR CÓDIGO" onPress={() => navigate("findPool")} leftIcon={<Icon as={Octicons} name="search" color="black" size="md" />} /> </VStack> {isLoading ? <Loading /> : <FlatList data={pools} keyExtractor={(item) => item.id} renderItem={({ item }) => <PoolCard data={item} onPress={() => navigate("detailsPool", { id: item.id })} />} px={5} showsVerticalScrollIndicator={false} _contentContainerStyle={{ pb: 10 }} ListEmptyComponent={() => <EmptyPoolList />} />} </VStack> ); }
import streamlit as st import json import pandas as pd import numpy import re import gensim import pprint from gensim import corpora from gensim.parsing.preprocessing import remove_stopwords import sklearn from sklearn.metrics.pairwise import cosine_similarity from gensim.models import Word2Vec import gensim.downloader as api def main(): html_temp=""" <div style="background-color:cyan;padding:10px"> <h2 style="color:black;text-align:center;">FAQ</h2> </div> """ #response = requests.get('https://www.google.co.in/') st.markdown(html_temp, unsafe_allow_html=True) df = pd.read_csv(r'FAQ final.csv') df.columns = ['Questions', 'Answers'] index_sim = None max_sim = None def clean_sentence(sentence, stopwords = False): sentence = sentence.lower().strip() sentence = re.sub(r'[^a-z0-9\s]', '', sentence) if stopwords: sentence = remove_stopwords(sentence) return sentence def get_cleaned_sentences(df, stopwords=False): sents = df[['Questions']] cleaned_sentences = [] for index, row in df.iterrows(): cleaned = clean_sentence(row['Questions'], stopwords) cleaned_sentences.append(cleaned) return cleaned_sentences cleaned_sentences = get_cleaned_sentences(df, stopwords = True) s = pd.DataFrame(cleaned_sentences) cleaned_sentences_with_stopwords = get_cleaned_sentences(df, stopwords=False) k = pd.DataFrame(cleaned_sentences_with_stopwords) sentences = cleaned_sentences_with_stopwords sentence_words = [[word for word in document.split()] for document in sentences] dic = corpora.Dictionary(sentence_words) bow_corpus = [dic.doc2bow(text) for text in sentence_words] s = st.text_input('Enter your Query') print(s) max_sim_final = -1 question_orig = s question = clean_sentence(question_orig, stopwords = False) question_embedding = dic.doc2bow(question.split()) def retrieveAndPrintFAQAnswers(question_embedding, sentence_embedding, sentences, max_sim_final ): max_sim = -1 index_sim = -1 topTenList = [] topTenDict = {} topTenDictSorted = {} for index, faq_embedding in enumerate(sentence_embedding): sim = cosine_similarity(faq_embedding, question_embedding)[0][0] print(index, sim, sentences[index]) # topTenDict[str(sim)].append(index) if sim>max_sim: max_sim = sim index_sim = index max_sim_final = sim topTenList.append(index) print(index_sim) # topTenDictSorted = sorted(topTenDict.items(), key = # lambda kv:(kv[1], kv[0])) topTenList.sort(reverse=True) return topTenList[0:10] #v2w_model = gensim.models.KeyedVectors.load('w2vecmodel.mod') v2w = None try: v2w_model = gensim.models.KeyedVectors.load("./w2vecmodel.mod") print('Loaded w2v model') except: v2w_model = api.load('word2vec-google-news-300') v2w_model.save("./w2vecmodel.mod") print('Saved glove model') w2vec_embedding_size = len(v2w_model['computer']) def getWordVec(word, model): samp = model['computer'] vec = [0]*len(samp) try: vec = model[word] except: vec = [0]*len(samp) return(vec) def getPhraseEmbedding(phrase, embeddingmodel): samp = getWordVec('computer', embeddingmodel) vec = numpy.array([0]*len(samp)) den = 0 for word in phrase.split(): den = den+1 vec = vec+numpy.array(getWordVec(word, embeddingmodel)) return vec.reshape(1, -1) sent_embedding = [] for sent in cleaned_sentences: sent_embedding.append(getPhraseEmbedding(sent, v2w_model)) question_embedding = getPhraseEmbedding(question, v2w_model) index_sim = retrieveAndPrintFAQAnswers(question_embedding, sent_embedding, cleaned_sentences, max_sim_final) result ='' if st.button('Search'): print('\n search keyword is '+s) index_sim = retrieveAndPrintFAQAnswers(question_embedding, sent_embedding, cleaned_sentences, max_sim_final) print('\n ', index_sim, "\n",max_sim_final) # print(df) print(index_sim) if s!= "" : #with open(r"FAQ final.CSV", encoding='utf-8') as f: #st.header('your searched queries', anchor= None) st.success('your searched queries') #st.error('No values found') #st.write('**----------------------------------------------------------------------**') for i in (index_sim) : print (i , end =" ") st.write('------------------------------------------------------------------------------------------') st.write(df.iloc[i, 0]) st.write(df.iloc[i, 1]) if s not in df.iloc[index_sim, 0]: st.write("Go to google [link](https://www.google.co.in/search?q="+s.replace(' ','%20')+"&source=null)") with open(r"FAQ final.CSV", encoding='utf-8') as d: data = d st.write('--------------------------------------') st.header("Here we have repeated FAQ's", anchor=None) #st.write('**-----------------------------------------------------------------------------------------**') if __name__=='__main__': main()
/* * Copyright &copy; 2009-2011 Rebecca G. Bettencourt / Kreative Software * <p> * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * <a href="http://www.mozilla.org/MPL/">http://www.mozilla.org/MPL/</a> * <p> * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * <p> * Alternatively, the contents of this file may be used under the terms * of the GNU Lesser General Public License (the "LGPL License"), in which * case the provisions of LGPL License are applicable instead of those * above. If you wish to allow use of your version of this file only * under the terms of the LGPL License and not to allow others to use * your version of this file under the MPL, indicate your decision by * deleting the provisions above and replace them with the notice and * other provisions required by the LGPL License. If you do not delete * the provisions above, a recipient may use your version of this file * under either the MPL or the LGPL License. * @since OpenXION 0.9 * @author Rebecca G. Bettencourt, Kreative Software */ package com.kreative.openxion.math; import java.math.*; import java.util.Comparator; import com.kreative.openxion.xom.inst.XOMNumber; /** * Methods for mathematical operations on and functions of XOMNumbers. * @since OpenXION 0.9 * @author Rebecca G. Bettencourt, Kreative Software */ public class XOMNumberMath { private XOMNumberMath(){} public static final Comparator<XOMNumber> comparator = new Comparator<XOMNumber>() { public int compare(XOMNumber o1, XOMNumber o2) { return XOMNumberMath.compare(o1,o2); } }; public static int compare(XOMNumber a, XOMNumber b) { if (a.isUndefined() || b.isUndefined()) { int am, bm; if (a.isNaN()) am = 3; else if (a.isInfinite()) switch (a.getSign()) { case XOMNumber.SIGN_NaN: am = 3; break; case XOMNumber.SIGN_NEGATIVE: am = -2; break; case XOMNumber.SIGN_POSITIVE: am = 2; break; case XOMNumber.SIGN_ZERO: am = 3; break; default: am = 3; break; } else if (a.isUndefined()) am = 3; else if (a.isZero()) am = 0; else switch (a.getSign()) { case XOMNumber.SIGN_NaN: am = 3; break; case XOMNumber.SIGN_NEGATIVE: am = -1; break; case XOMNumber.SIGN_POSITIVE: am = 1; break; case XOMNumber.SIGN_ZERO: am = 0; break; default: am = 3; break; } if (b.isNaN()) bm = 3; else if (b.isInfinite()) switch (b.getSign()) { case XOMNumber.SIGN_NaN: bm = 3; break; case XOMNumber.SIGN_NEGATIVE: bm = -2; break; case XOMNumber.SIGN_POSITIVE: bm = 2; break; case XOMNumber.SIGN_ZERO: bm = 3; break; default: bm = 3; break; } else if (b.isUndefined()) bm = 3; else if (b.isZero()) bm = 0; else switch (b.getSign()) { case XOMNumber.SIGN_NaN: bm = 3; break; case XOMNumber.SIGN_NEGATIVE: bm = -1; break; case XOMNumber.SIGN_POSITIVE: bm = 1; break; case XOMNumber.SIGN_ZERO: bm = 0; break; default: bm = 3; break; } return am-bm; } else { return a.toBigDecimal().compareTo(b.toBigDecimal()); } } public static XOMNumber add(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { if (a.isNaN() || b.isNaN()) return XOMNumber.NaN; else if (a.isInfinite() && b.isInfinite()) { if (a.getSign() == b.getSign()) return a; else return XOMNumber.NaN; } else if (a.isInfinite()) { return a; } else if (b.isInfinite()) { return b; } else { return new XOMNumber(a.toBigDecimal().add(b.toBigDecimal(), mc)); } } public static XOMNumber subtract(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { if (a.isNaN() || b.isNaN()) return XOMNumber.NaN; else if (a.isInfinite() && b.isInfinite()) { if (a.getSign() == b.getOppositeSign()) return a; else return XOMNumber.NaN; } else if (a.isInfinite()) { return a; } else if (b.isInfinite()) { return b.negate(); } else { return new XOMNumber(a.toBigDecimal().subtract(b.toBigDecimal(), mc)); } } public static XOMNumber multiply(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { if (a.isNaN() || b.isNaN()) return XOMNumber.NaN; else if (a.isInfinite() || b.isInfinite()) { if (a.isZero() || b.isZero()) return XOMNumber.NaN; else if (a.getSign() == b.getSign()) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NEGATIVE_INFINITY; } else { return new XOMNumber(a.toBigDecimal().multiply(b.toBigDecimal(), mc)); } } public static XOMNumber divide(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { if (a.isNaN() || b.isNaN()) return XOMNumber.NaN; else if ((a.isInfinite() && b.isInfinite()) || (a.isZero() && b.isZero())) { return XOMNumber.NaN; } else if (b.isZero()) { switch (a.getSign()) { case XOMNumber.SIGN_POSITIVE: return XOMNumber.POSITIVE_INFINITY; case XOMNumber.SIGN_NEGATIVE: return XOMNumber.NEGATIVE_INFINITY; default: return XOMNumber.NaN; } } else if (a.isInfinite()) { if (b.isZero()) return a; else if (a.getSign() == b.getSign()) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NEGATIVE_INFINITY; } else if (b.isInfinite() || a.isZero()) { return XOMNumber.ZERO; } else { return new XOMNumber(a.toBigDecimal().divide(b.toBigDecimal(), mc)); } } public static XOMNumber pow(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { if (a.isNaN() || b.isNaN()) return XOMNumber.NaN; else if (a.isZero()) { switch (b.getSign()) { case XOMNumber.SIGN_NEGATIVE: return XOMNumber.POSITIVE_INFINITY; case XOMNumber.SIGN_ZERO: return XOMNumber.NaN; case XOMNumber.SIGN_POSITIVE: return XOMNumber.ZERO; default: return XOMNumber.NaN; } } else if (a.isInfinite()) { if (a.getSign() == XOMNumber.SIGN_POSITIVE) { switch (b.getSign()) { case XOMNumber.SIGN_NEGATIVE: return XOMNumber.ZERO; case XOMNumber.SIGN_ZERO: return XOMNumber.NaN; case XOMNumber.SIGN_POSITIVE: return XOMNumber.POSITIVE_INFINITY; default: return XOMNumber.NaN; } } else { if (b.isZero() || b.isInfinite()) return XOMNumber.NaN; else try { BigInteger i = b.toBigDecimal().toBigIntegerExact(); if (i.compareTo(BigInteger.ZERO) < 0) return XOMNumber.ZERO; else if (i.testBit(0)) return XOMNumber.NEGATIVE_INFINITY; else return XOMNumber.POSITIVE_INFINITY; } catch (Exception e) { return XOMNumber.NaN; } } } else if (b.isZero()) { return XOMNumber.ONE; } else if (b.isInfinite()) { BigDecimal av = a.toBigDecimal(); if (b.getSign() == XOMNumber.SIGN_POSITIVE) { if (av.compareTo(BigDecimal.ONE.negate()) <= 0) return XOMNumber.NaN; else if (av.compareTo(BigDecimal.ONE) < 0) return XOMNumber.ZERO; else if (av.compareTo(BigDecimal.ONE) == 0) return XOMNumber.NaN; else return XOMNumber.POSITIVE_INFINITY; } else { if (av.compareTo(BigDecimal.ONE.negate()) <= 0) return XOMNumber.NaN; else if (av.compareTo(BigDecimal.ONE) < 0) return XOMNumber.POSITIVE_INFINITY; else if (av.compareTo(BigDecimal.ONE) == 0) return XOMNumber.NaN; else return XOMNumber.ZERO; } } else { return new XOMNumber(mp.pow(a.toBigDecimal(), b.toBigDecimal(), mc)); } } public static XOMNumber toDeg(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return n; else { BigDecimal d = n.toBigDecimal(); d = d.multiply(BigDecimal.valueOf(180),mc).divide(mp.pi(mc),mc); return new XOMNumber(d); } } public static XOMNumber toRad(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return n; else { BigDecimal d = n.toBigDecimal(); d = d.multiply(mp.pi(mc),mc).divide(BigDecimal.valueOf(180),mc); return new XOMNumber(d); } } public static XOMNumber annuity(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { if (a.isZero() || b.isZero()) return b; else return divide(subtract(XOMNumber.ONE,pow(add(XOMNumber.ONE,a,mc,mp),b.negate(),mc,mp),mc,mp),a,mc,mp); } public static XOMNumber compound(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { if (a.isZero() || b.isZero()) return XOMNumber.ONE; else return pow(add(XOMNumber.ONE,a,mc,mp),b,mc,mp); } public static XOMNumber sqrt(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal d = mp.sqrt(n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber cbrt(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.NEGATIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal d = mp.cbrt(n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber agm(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { XOMNumber t = new XOMNumber(2); while (true) { if (a.isNaN() || b.isNaN()) return XOMNumber.NaN; XOMNumber m = divide(add(a,b,mc,mp),t,mc,mp); XOMNumber g = sqrt(multiply(a,b,mc,mp),mc,mp); if (m.equals(g)) return m; a = m; b = g; } } public static XOMNumber exp(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.ZERO; else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal d = mp.exp(n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber expm1(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.ONE.negate(); else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal d = mp.expm1(n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber exp2(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.ZERO; else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal d = mp.pow(BigDecimal.valueOf(2), n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber exp10(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.ZERO; else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal d = mp.pow(BigDecimal.valueOf(10), n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber log(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal theNumber = n.toBigDecimal(); int cmp = theNumber.compareTo(BigDecimal.ZERO); if (cmp < 0) return XOMNumber.NaN; else if (cmp == 0) return XOMNumber.NEGATIVE_INFINITY; else { BigDecimal d = mp.log(theNumber, mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } } public static XOMNumber log1p(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal theNumber = n.toBigDecimal(); int cmp = theNumber.compareTo(BigDecimal.ONE.negate()); if (cmp < 0) return XOMNumber.NaN; else if (cmp == 0) return XOMNumber.NEGATIVE_INFINITY; else { BigDecimal d = mp.log1p(theNumber, mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } } public static XOMNumber log2(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal theNumber = n.toBigDecimal(); int cmp = theNumber.compareTo(BigDecimal.ZERO); if (cmp < 0) return XOMNumber.NaN; else if (cmp == 0) return XOMNumber.NEGATIVE_INFINITY; else { BigDecimal d = mp.log2(theNumber, mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } } public static XOMNumber log10(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else { BigDecimal theNumber = n.toBigDecimal(); int cmp = theNumber.compareTo(BigDecimal.ZERO); if (cmp < 0) return XOMNumber.NaN; else if (cmp == 0) return XOMNumber.NEGATIVE_INFINITY; else { BigDecimal d = mp.log10(theNumber, mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } } public static XOMNumber sin(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; return new XOMNumber(mp.sin(n.toBigDecimal(), mc)); } public static XOMNumber cos(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; return new XOMNumber(mp.cos(n.toBigDecimal(), mc)); } public static XOMNumber tan(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; else { BigDecimal theNumber = n.toBigDecimal(); BigDecimal s = mp.sin(theNumber, mc); BigDecimal c = mp.cos(theNumber, mc); int sc = s.compareTo(BigDecimal.ZERO); int cc = c.compareTo(BigDecimal.ZERO); if (sc == 0) return XOMNumber.ZERO; else if (cc == 0) return (sc < 0) ? XOMNumber.NEGATIVE_INFINITY : XOMNumber.POSITIVE_INFINITY; else return new XOMNumber(s.divide(c, mc)); } } public static XOMNumber cot(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; else { BigDecimal theNumber = n.toBigDecimal(); BigDecimal c = mp.cos(theNumber, mc); BigDecimal s = mp.sin(theNumber, mc); int cc = c.compareTo(BigDecimal.ZERO); int sc = s.compareTo(BigDecimal.ZERO); if (cc == 0) return XOMNumber.ZERO; else if (sc == 0) return (cc < 0) ? XOMNumber.NEGATIVE_INFINITY : XOMNumber.POSITIVE_INFINITY; else return new XOMNumber(c.divide(s, mc)); } } public static XOMNumber csc(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; BigDecimal d = mp.sin(n.toBigDecimal(), mc); if (d.compareTo(BigDecimal.ZERO) == 0) return XOMNumber.POSITIVE_INFINITY; else return new XOMNumber(BigDecimal.ONE.divide(d, mc)); } public static XOMNumber sec(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; BigDecimal d = mp.cos(n.toBigDecimal(), mc); if (d.compareTo(BigDecimal.ZERO) == 0) return XOMNumber.POSITIVE_INFINITY; else return new XOMNumber(BigDecimal.ONE.divide(d, mc)); } public static XOMNumber sinh(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.NEGATIVE_INFINITY; else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } return new XOMNumber(mp.sinh(n.toBigDecimal(), mc)); } public static XOMNumber cosh(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.isInfinite()) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } return new XOMNumber(mp.cosh(n.toBigDecimal(), mc)); } public static XOMNumber tanh(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.ONE.negate(); else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.ONE; else return XOMNumber.NaN; } return new XOMNumber(mp.tanh(n.toBigDecimal(), mc)); } public static XOMNumber coth(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.ONE.negate(); else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.ONE; else return XOMNumber.NaN; } else { BigDecimal d = mp.tanh(n.toBigDecimal(), mc); if (d.compareTo(BigDecimal.ZERO) == 0) return XOMNumber.POSITIVE_INFINITY; else return new XOMNumber(BigDecimal.ONE.divide(d, mc)); } } public static XOMNumber csch(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.isInfinite()) return XOMNumber.ZERO; else return XOMNumber.NaN; } else { BigDecimal d = mp.sinh(n.toBigDecimal(), mc); if (d.compareTo(BigDecimal.ZERO) == 0) return XOMNumber.POSITIVE_INFINITY; else return new XOMNumber(BigDecimal.ONE.divide(d, mc)); } } public static XOMNumber sech(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.isInfinite()) return XOMNumber.ZERO; else return XOMNumber.NaN; } else { BigDecimal d = mp.cosh(n.toBigDecimal(), mc); if (d.compareTo(BigDecimal.ZERO) == 0) return XOMNumber.POSITIVE_INFINITY; else return new XOMNumber(BigDecimal.ONE.divide(d, mc)); } } public static XOMNumber asin(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; else { BigDecimal theNumber = n.toBigDecimal(); if (theNumber.abs().compareTo(BigDecimal.ONE) > 0) return XOMNumber.NaN; else return new XOMNumber(mp.asin(theNumber, mc)); } } public static XOMNumber acos(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; else { BigDecimal theNumber = n.toBigDecimal(); if (theNumber.abs().compareTo(BigDecimal.ONE) > 0) return XOMNumber.NaN; else return new XOMNumber(mp.acos(theNumber, mc)); } } public static XOMNumber atan(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return new XOMNumber(mp.pi(mc).divide(BigDecimal.valueOf(2.0)).negate()); else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return new XOMNumber(mp.pi(mc).divide(BigDecimal.valueOf(2.0))); else return XOMNumber.NaN; } else { return new XOMNumber(mp.atan(n.toBigDecimal(), mc)); } } public static XOMNumber atan2(XOMNumber y, XOMNumber x, MathContext mc, MathProcessor mp) { if (y.isNaN() || x.isNaN()) return XOMNumber.NaN; else if (y.isInfinite() || x.isInfinite()) { if (y.isZero() && x.isInfinite()) { switch (x.getSign()) { case XOMNumber.SIGN_POSITIVE: return XOMNumber.ZERO; case XOMNumber.SIGN_NEGATIVE: return new XOMNumber(mp.pi(mc)); default: return XOMNumber.NaN; } } else if (y.isInfinite() && x.isZero()) { switch (y.getSign()) { case XOMNumber.SIGN_POSITIVE: return new XOMNumber(mp.pi(mc).divide(BigDecimal.valueOf(2),mc)); case XOMNumber.SIGN_NEGATIVE: return new XOMNumber(mp.pi(mc).divide(BigDecimal.valueOf(2),mc).negate()); default: return XOMNumber.NaN; } } else { return XOMNumber.NaN; } } else { return new XOMNumber(mp.atan2(y.toBigDecimal(), x.toBigDecimal(), mc)); } } public static XOMNumber acot(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return new XOMNumber(mp.pi(mc)); else if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.ZERO; else return XOMNumber.NaN; } else { return new XOMNumber(mp.pi(mc).divide(BigDecimal.valueOf(2),mc).subtract(mp.atan(n.toBigDecimal(),mc),mc)); } } public static XOMNumber acsc(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.isInfinite()) return XOMNumber.ZERO; else return XOMNumber.NaN; } else { BigDecimal theNumber = n.toBigDecimal(); if (theNumber.abs().compareTo(BigDecimal.ONE) < 0) return XOMNumber.NaN; else return new XOMNumber(mp.asin(BigDecimal.ONE.divide(theNumber, mc), mc)); } } public static XOMNumber asec(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.isInfinite()) return new XOMNumber(mp.pi(mc).divide(BigDecimal.valueOf(2),mc)); else return XOMNumber.NaN; } else { BigDecimal theNumber = n.toBigDecimal(); if (theNumber.abs().compareTo(BigDecimal.ONE) < 0) return XOMNumber.NaN; else return new XOMNumber(mp.acos(BigDecimal.ONE.divide(theNumber, mc), mc)); } } public static XOMNumber asinh(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return n; else { BigDecimal x = n.toBigDecimal(); BigDecimal sqrtxsqp1 = mp.sqrt(x.multiply(x,mc).add(BigDecimal.ONE,mc),mc); BigDecimal asinh = mp.log(x.add(sqrtxsqp1,mc),mc); if (asinh == null) return XOMNumber.NaN; else return new XOMNumber(asinh); } } public static XOMNumber acosh(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return n; else return XOMNumber.NaN; } else { int cmp = n.toBigDecimal().compareTo(BigDecimal.ONE); if (cmp < 0) return XOMNumber.NaN; else if (cmp == 0) return XOMNumber.ZERO; BigDecimal x = n.toBigDecimal(); BigDecimal sqrtxm1 = mp.sqrt(x.subtract(BigDecimal.ONE,mc),mc); BigDecimal sqrtxp1 = mp.sqrt(x.add(BigDecimal.ONE,mc),mc); BigDecimal xm1txp1 = sqrtxm1.multiply(sqrtxp1,mc); BigDecimal acosh = mp.log(x.add(xm1txp1,mc),mc); if (acosh == null) return XOMNumber.NaN; else return new XOMNumber(acosh); } } public static XOMNumber atanh(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; else { int cmp = n.toBigDecimal().abs().compareTo(BigDecimal.ONE); if (cmp > 0) return XOMNumber.NaN; else if (cmp == 0) return (n.toBigDecimal().signum() < 0) ? XOMNumber.NEGATIVE_INFINITY : XOMNumber.POSITIVE_INFINITY; BigDecimal x = n.toBigDecimal(); BigDecimal onemx = BigDecimal.ONE.subtract(x,mc); BigDecimal sqrt1mx2 = mp.sqrt(BigDecimal.ONE.subtract(x.multiply(x,mc),mc),mc); BigDecimal atanh = mp.log(sqrt1mx2.divide(onemx,mc),mc); if (atanh == null) return XOMNumber.NaN; else return new XOMNumber(atanh); } } public static XOMNumber acoth(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.isInfinite()) return XOMNumber.ZERO; else return XOMNumber.NaN; } else { int cmp = n.toBigDecimal().abs().compareTo(BigDecimal.ONE); if (cmp < 0) return XOMNumber.NaN; else if (cmp == 0) return (n.toBigDecimal().signum() < 0) ? XOMNumber.NEGATIVE_INFINITY : XOMNumber.POSITIVE_INFINITY; BigDecimal x = n.toBigDecimal(); BigDecimal a = x.add(BigDecimal.ONE,mc).divide(x.subtract(BigDecimal.ONE,mc),mc); BigDecimal acoth = mp.log(a,mc).divide(BigDecimal.valueOf(2)); if (acoth == null) return XOMNumber.NaN; else return new XOMNumber(acoth); } } public static XOMNumber acsch(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.isInfinite()) return XOMNumber.ZERO; else return XOMNumber.NaN; } else { if (n.isZero()) return XOMNumber.NaN; BigDecimal x = n.toBigDecimal(); BigDecimal rx = BigDecimal.ONE.divide(x,mc); BigDecimal rxx = BigDecimal.ONE.divide(x.multiply(x,mc),mc); BigDecimal sqrt1prxx = mp.sqrt(BigDecimal.ONE.add(rxx,mc),mc); BigDecimal acsch = mp.log(sqrt1prxx.add(rx,mc),mc); if (acsch == null) return XOMNumber.NaN; else return new XOMNumber(acsch); } } public static XOMNumber asech(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) return XOMNumber.NaN; else { if (n.getSign() == XOMNumber.SIGN_NEGATIVE) return XOMNumber.NaN; else if (n.isZero()) return XOMNumber.POSITIVE_INFINITY; int cmp = n.toBigDecimal().abs().compareTo(BigDecimal.ONE); if (cmp > 0) return XOMNumber.NaN; else if (cmp == 0) return XOMNumber.ZERO; BigDecimal x = n.toBigDecimal(); BigDecimal rx = BigDecimal.ONE.divide(x,mc); BigDecimal sqrtrxm1 = mp.sqrt(rx.subtract(BigDecimal.ONE,mc),mc); BigDecimal sqrtrxp1 = mp.sqrt(rx.add(BigDecimal.ONE,mc),mc); BigDecimal rxm1trxp1 = sqrtrxm1.multiply(sqrtrxp1,mc); BigDecimal asech = mp.log(rxm1trxp1.add(rx,mc),mc); if (asech == null) return XOMNumber.NaN; else return new XOMNumber(asech); } } public static XOMNumber gamma(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else if (n.isZero()) return XOMNumber.POSITIVE_INFINITY; else { BigDecimal d = mp.gamma(n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber loggamma(XOMNumber n, MathContext mc, MathProcessor mp) { if (n.isUndefined()) { if (n.getSign() == XOMNumber.SIGN_POSITIVE) return XOMNumber.POSITIVE_INFINITY; else return XOMNumber.NaN; } else if (n.isZero()) return XOMNumber.POSITIVE_INFINITY; else { BigDecimal d = mp.loggamma(n.toBigDecimal(), mc); if (d == null) return XOMNumber.NaN; else return new XOMNumber(d); } } public static XOMNumber fact(XOMNumber n, MathContext mc, MathProcessor mp) { return gamma(add(n,XOMNumber.ONE,mc,mp),mc,mp); } public static XOMNumber logfact(XOMNumber n, MathContext mc, MathProcessor mp) { return loggamma(add(n,XOMNumber.ONE,mc,mp),mc,mp); } public static XOMNumber beta(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { return divide(multiply(gamma(a,mc,mp),gamma(b,mc,mp),mc,mp),gamma(add(a,b,mc,mp),mc,mp),mc,mp); } public static XOMNumber logbeta(XOMNumber a, XOMNumber b, MathContext mc, MathProcessor mp) { return subtract(add(loggamma(a,mc,mp),loggamma(b,mc,mp),mc,mp),loggamma(add(a,b,mc,mp),mc,mp),mc,mp); } public static XOMNumber nPr(XOMNumber n, XOMNumber r, MathContext mc, MathProcessor mp) { return divide(gamma(add(n,XOMNumber.ONE,mc,mp),mc,mp),gamma(add(subtract(n,r,mc,mp),XOMNumber.ONE,mc,mp),mc,mp),mc,mp); } public static XOMNumber nCr(XOMNumber n, XOMNumber r, MathContext mc, MathProcessor mp) { return divide(divide(gamma(add(n,XOMNumber.ONE,mc,mp),mc,mp),gamma(add(r,XOMNumber.ONE,mc,mp),mc,mp),mc,mp),gamma(add(subtract(n,r,mc,mp),XOMNumber.ONE,mc,mp),mc,mp),mc,mp); } }
%{ int COMMENT = 0; %} identifier [a-zA-Z][a-zA-Z0-9]* %% #.* { printf("\n%s is a PREPROCESSOR DIRECTIVE", yytext); } int|float|char|double|while|for| do|if|break|continue|void|switch|case|long|struct|const|typedef| return|else|goto { if (!COMMENT) printf("\n\t%s is a KEYWORD", yytext); } "/*" { COMMENT = 1; } "*/" { COMMENT = 0; } {identifier}\( { if (!COMMENT) printf("\n\nFUNCTION\n\t%s", yytext); } \{ { if (!COMMENT) printf("\n BLOCK BEGINS"); } \} { if (!COMMENT) printf("\n BLOCK ENDS"); } {identifier}(\[[0-9]*\])? { if (!COMMENT) printf("\n %s IDENTIFIER", yytext); } \".*\" { if (!COMMENT) printf("\n\t%s is a STRING", yytext); } [0-9]+ { if (!COMMENT) printf("\n\t%s is a NUMBER", yytext); } \)(\;)? { if (!COMMENT) printf("\n\t"); ECHO; printf("\n"); } \( ECHO; = { if (!COMMENT) printf("\n\t%s is an ASSIGNMENT OPERATOR", yytext); } \<= |\>= |\< |== |\> { if (!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR", yytext); } %% int main(int argc, char **argv) { if (argc > 1) { FILE *file = fopen(argv[1], "r"); if (!file) { printf("could not open %s \n", argv[1]); exit(1); } yyin = file; } yylex(); printf("\n\n"); return 0; } int yywrap() { return 1; } Input: $vi var.c #include<stdio.h> main() { int a,b; } Output: $lex lex.l $cc lex.yy.c $./a.out var.c #include<stdio.h> is a PREPROCESSOR DIRECTIVE FUNCTION main ( ) BLOCK BEGINS int is a KEYWORD a IDENTIFIER b IDENTIFIER BLOCK ENDS
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform, } from '@nestjs/common'; import * as Joi from 'joi'; @Injectable() export class AdminGetMeetingsValidation implements PipeTransform { private schema: Joi.ObjectSchema; constructor() { this.schema = Joi.object({ q: Joi.string(), sort: Joi.string(), direction: Joi.string(), usePage: Joi.boolean(), page: Joi.number().integer().min(1), limit: Joi.number().integer().min(1), }); } transform(value: any, metadata: ArgumentMetadata) { const { error, value: validatedValue } = this.schema.validate(value); if (error) throw new BadRequestException(error.message); return validatedValue; } }
import { StyleSheet, View} from 'react-native' import React from 'react' import { Fontisto } from '@expo/vector-icons' import { FontAwesome } from '@expo/vector-icons' import { MaterialIcons,Ionicons } from '@expo/vector-icons' import { createBottomTabNavigator } from '@react-navigation/bottom-tabs' import ShopStack from './ShopStack' import CartStack from './CartStack' import OrderStack from './OrderStack' import MyProfileStack from './MyProfileStack' import { colors } from '../Global/Colors' const Tab = createBottomTabNavigator() const TabNavigator = () => { return ( <Tab.Navigator screenOptions={{ headerShown: false, tabBarShowLabel: false, tabBarStyle: styles.tabBar, }} > <Tab.Screen name='Shop' component={ShopStack} options={{ tabBarIcon: ({focused}) => { return ( <View> <Fontisto name="shopping-store" size={24} color={focused ? "black": "gray"} /> </View> ) } }} /> <Tab.Screen name='Cart' component={CartStack} options={{ tabBarIcon: ({focused}) => { return ( <View> <FontAwesome name="shopping-basket" size={24} color={focused ? "black": "gray"} /> </View> ) } }} /> <Tab.Screen name='Orders' component={OrderStack} options={{ tabBarIcon: ({focused}) => { return ( <View> <MaterialIcons name="playlist-add-check" size={30} color={focused ? "black": "gray"} /> </View> ) } }} /> <Tab.Screen name="MyProfile" component={MyProfileStack} options={{ tabBarIcon: ({ focused }) => { return ( <View style={styles.item}> <Ionicons name="person-circle-outline" size={24} color={ focused ? 'black' : 'gray' } /> </View> ); }, }} /> </Tab.Navigator> ) } export default TabNavigator const styles = StyleSheet.create({ tabBar: { backgroundColor: colors.violet, shadowColor: 'black', elevation: 4, height: 50, } })
Life history traits, in biology and ecology, refer to a set of characteristics and strategies exhibited by organisms that describe how they allocate resources and energy throughout their lifespan. These traits are crucial for understanding an organism's adaptation to its environment and its reproductive strategies. Common life history traits include: 1. **Reproduction**: - **Semelparity**: Organisms reproduce only once in their lifetime, often with a single large reproductive event. - **Iteroparity**: Organisms reproduce multiple times during their lifetime, with smaller reproductive events. 2. **Reproductive Age and Effort**: - **Age at First Reproduction**: The age at which an organism starts reproducing. - **Reproductive Effort**: The amount of energy and resources invested in reproduction. 3. **Offspring Number and Size**: - **High Fecundity**: Producing many offspring, often with low individual investment in each. - **Low Fecundity**: Producing fewer offspring but with a higher individual investment. 4. **Survivorship and Longevity**: - **High Survivorship**: A strategy that favours the survival of a large portion of offspring. - **Low Survivorship**: A strategy that produces many offspring with the expectation that few will survive to adulthood. - **Longevity**: The lifespan of an organism. 5. **Growth and Development**: - **Fast Growth**: Rapid development and growth to maturity. - **Slow Growth**: Slower development and maturation, often associated with longer lifespans. 6. **Parental Care**: - **No Parental Care**: Organisms provide little or no care for their offspring. - **Intensive Parental Care**: Organisms invest a significant amount of time and resources in caring for their offspring. 7. **Reproductive Mode**: - **Sexual Reproduction**: Involves the fusion of gametes from two parents, introducing genetic diversity. - **Asexual Reproduction**: Involves the creation of genetically identical offspring from a single parent. 8. **Dispersal**: - **High Dispersal**: Offspring tend to disperse widely from their place of birth. - **Low Dispersal**: Offspring remain close to their place of birth. 9. **Resource Allocation ([[principle of allocation]])**: - **[[life history trade-offs]]**: Organisms often face trade-offs between the allocation of resources to growth, reproduction, and survival. These life history traits vary across different species and are influenced by factors such as environmental conditions, predation pressures, resource availability, and ecological niches. The specific combination of traits in an organism's life history reflects its evolutionary adaptation to its particular ecological niche and can significantly impact its population dynamics and survival. ![[Pasted image 20231102145028.png]]
import { Injectable, OnApplicationBootstrap } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import TelegramBot, { Message } from 'node-telegram-bot-api'; import { AppConfig } from '../config/types'; import { StepService } from './step.service'; import { UserService } from './user.service'; @Injectable() export class BotService implements OnApplicationBootstrap { private _bot: TelegramBot; constructor( private readonly config: ConfigService<AppConfig, true>, private readonly userService: UserService, private readonly stepService: StepService, ) { this._bot = new TelegramBot(this.config.get('TELEGRAM_BOT_API_KEY'), { polling: false, }); this.stepService.bot = this._bot; } get bot(): TelegramBot { return this._bot; } async onApplicationBootstrap(): Promise<void> { this.bot.setWebHook('https://' + this.config.get('BASE_API_HOST') + '/bot'); this.bot.on('message', async (message: Message) => { const user = await this.userService.createUserIfNotExist(message); await this.stepService.makeFirstStep(user); }); this.bot.on('callback_query', async (query) => { await this.stepService.handleButton(query); }) } }
var MMailApp = this; /** send * ### ⚙️Options * * Semple options: * * `{to: `email`, subject: "hi", htmlbody: "<b>Bold!</b>"}` * | **Parameter** | **Type** | **Notes** | |:----------------|:---------|:----------------------------------------------------------------------| | `to` | String | comma-separated, also may use: `recipient`, `recipients` | | `cc` | String | comma-separated | | `bcc` | String | comma-separated | | `subject` | String | | | `body` | String | | | `htmlbody` | String | | | `name` | String | default: the user's name | | `from` | String | for paid accounts. One of `var aliases = GmailApp.getAliases();` | | `replyto` | String | | | `noreply` | Integer | 1 =`true`, for paid accounts | | `inlineimages` | Object | `{name: blob}`, use in HtmlBody: `inline <img src='cid:name'> image!` | | `attachments` | Array | `[blob, blob]` | * * ### Author * `@max__makhrov` * * ![CoolTables](https://raw.githubusercontent.com/cooltables/pics/main/logos/ct_logo_small.png) * [cooltables.online](https://www.cooltables.online/) * */ function send(options) { /** * * 1. Try MailApp * 2. Try GmailApp * 3. Try Gmail API * * if `from` parameter is set, the script will try GmailApp * */ var settings = { min_quota: 2 } // let use of different naming conventions setOptionsNamings_(options); // get remaining quota var quota = getRemainingMailQuota_(); if (quota <= settings.min_quota) { console.log('Regular sendMail Quota is exceeded. Use Gmail API'); if (typeof Gmail == 'undefined') { throw '🧐you are out of your daily Quota. 👌Fix: Please enable Gmail API Advanced Service.' } var res = sendGmailApi(options); return res; } if (options.from && options.from !== '') { console.log('use GmailApp'); sendGmail_(options); } else { console.log('use MailApp'); sendMail_(options); } /** returns quota in case GmialApp of MailApp was used */ return { ramaining_quota: getRemainingMailQuota_() } } /** * let user use * * `options.htmlbody` OR `options.htmlBody` * * and other naming conventions */ function setOptionsNamings_(options) { options.to = options.to || options.recipient || options.recipients; options.htmlbody = options.htmlbody || options.htmlBody || options.html_body; options.replyto = options.replyto || options.replyTo || options.reply_to; options.replytoname = options.replytoname || options.replyToName || options.reply_to_name; options.noreply = options.noreply || options.noReply || options.no_reply; options.inlineimages = options.inlineimages || options.inlineImages || options.inline_images; } /** * Get and log your daily mail quota */ function getRemainingMailQuota_() { // https://stackoverflow.com/questions/2744520 var quota = MailApp.getRemainingDailyQuota(); // console.log('You can send ~ ' + quota + ' emails this day.'); return quota; } // __ __ _ _ // | \/ | (_) | /\ // | \ / | __ _ _| | / \ _ __ _ __ // | |\/| |/ _` | | | / /\ \ | '_ \| '_ \ // | | | | (_| | | |/ ____ \| |_) | |_) | // |_| |_|\__,_|_|_/_/ \_\ .__/| .__/ // | | | | // |_| |_| // function test_getMailApp() { // var test_blobs = getTestBlobs_(); // var options = { // to: '[email protected]', // required // cc: '[email protected]', // bcc: '[email protected],[email protected]', // name: '🎩Mad Hatter', // from: '[email protected]', // works only if for paid accounts // subject: '🥸Test Test Test', // body: '💪 body!', // htmlBody: test_blobs.htmlBody, // '<b>💪Bold Hello</b><br>How are you?' // noreply: 1, // replyto: '[email protected]', // attachments: test_blobs.array, // inlineimages: test_blobs.object // } // var response = sendMail_(options); // } /** sendMail_ * * As descubed here: * https://developers.google.com/apps-script/reference/mail/mail-app#sendemailrecipient,-subject,-body,-options */ function sendMail_(options) { // Warning // noReply is only for paid accounts // // Note // You cannot use `from` with this method // let use of different naming conventions setOptionsNamings_(options); /** body */ if (!options.body || options.body === '') { options.body = '<this message was sent automatically without email body>'; } /** subject */ if (!options.subject || options.subject === '') { options.subject = '(No Subject)' } /** other options */ var addProperty_ = function(main, donor, mainKey, donorKey) { var val = donor[donorKey]; if (donorKey === 'noreply' ) { if (val) { main[mainKey] = true; return; } } if ( val && val !== '' ) { main[mainKey] = val; } } var mail_options = { }; var keys = { attachments: 'attachments', bcc: 'bcc', cc: 'bcc', htmlbody: 'htmlBody', inlineimages: 'inlineImages', name: 'name', noreply: 'noReply', replyto: 'replyTo' } for (var k in keys) { addProperty_( mail_options, options, keys[k], k ); } // console.log(JSON.stringify(mail_options, null, 4)) MailApp.sendEmail( options.to, options.subject, options.body, mail_options ); return 0; } // _____ _ _ // / ____| (_) | /\ // | | __ _ __ ___ __ _ _| | / \ _ __ _ __ // | | |_ | '_ ` _ \ / _` | | | / /\ \ | '_ \| '_ \ // | |__| | | | | | | (_| | | |/ ____ \| |_) | |_) | // \_____|_| |_| |_|\__,_|_|_/_/ \_\ .__/| .__/ // | | | | // |_| |_| // function test_getGmailApp() { // var test_blobs = getTestBlobs_(); // var options = { // to: '[email protected]', // required // cc: '[email protected]', // bcc: '[email protected],[email protected]', // name: '🎩Mad Hatter', // from: '[email protected]', // works only if for paid accounts // subject: '🥸Test Test Test', // body: '💪 body!', // // htmlBody: test_blobs.htmlBody, // '<b>💪Bold Hello</b><br>How are you?' // noreply: 1, // replyto: '[email protected]', // attachments: test_blobs.array, // inlineimages: test_blobs.object // } // var response = sendGmail_(options); // } /** sendGmail_ * * As descubed here: * https://developers.google.com/apps-script/reference/gmail/gmail-app#sendemailrecipient,-subject,-body,-options */ function sendGmail_(options) { // Warning // noReply is only for paid accounts // // Warning! // Emojis does not work with this method // // Note // Usage of `from` is limited // You need to create an alias first // https://support.google.com/mail/answer/22370?hl=en // you must have a paid account // and create alias. // To test your aliases: // var aliases = GmailApp.getAliases(); // let use of different naming conventions setOptionsNamings_(options); /** body */ if (!options.body || options.body === '') { options.body = '<this message was sent automatically without email body>'; } /** subject */ if (!options.subject || options.subject === '') { options.subject = '(No Subject)' } /** other options */ var addProperty_ = function(main, donor, mainKey, donorKey) { var val = donor[donorKey]; if (donorKey === 'noreply' ) { if (val) { main[mainKey] = true; return; } } if ( val && val !== '' ) { main[mainKey] = val; } } var mail_options = { }; var keys = { attachments: 'attachments', bcc: 'bcc', cc: 'bcc', 'from': 'from', htmlbody: 'htmlBody', inlineimages: 'inlineImages', name: 'name', noreply: 'noReply', replyto: 'replyTo' } for (var k in keys) { addProperty_( mail_options, options, keys[k], k ); } // console.log(JSON.stringify(mail_options, null, 4)) GmailApp.sendEmail( options.to, options.subject, options.body, mail_options); return 0; } // _____ _ _ _____ _____ // / ____| (_) | /\ | __ \_ _| // | | __ _ __ ___ __ _ _| | / \ | |__) || | // | | |_ | '_ ` _ \ / _` | | | / /\ \ | ___/ | | // | |__| | | | | | | (_| | | | / ____ \| | _| |_ // \_____|_| |_| |_|\__,_|_|_| /_/ \_\_| |_____| // function test_getGmailApiSets() { // var test_blobs = getTestBlobs_(); // var options = { // to: '[email protected]', // required // cc: '[email protected]', // bcc: '[email protected],[email protected]', // name: '🎩Mad Hatter', // // from: '[email protected]', // works only if for paid accounts // subject: '🥸Test Test Test', // body: '💪 body!', // htmlBody: test_blobs.htmlBody, // '<b>💪Bold Hello</b><br>How are you?' // noReply: 1, // replyTo: '[email protected]', // replyToName: '🦸Stranger', // attachments: test_blobs.array, // inlineImages: test_blobs.object // } // var response = sendGmailApi_(options) // console.log(JSON.stringify(response)) // } /** sendGmailApi * ### Warning * ⚠️Enable Gmail * [advanced service](https://developers.google.com/apps-script/guides/services/advanced) * first in order to use this code * * ### ⚙️Options * * Semple options: * * `{to: email, subject: "hi", htmlbody: "<b>Bold!</b>"}` * | **Parameter** | **Type** | **Notes** | |:----------------|:---------|:----------------------------------------------------------------------| | `to` | String | comma-separated, also may use: `recipient`, `recipients` | | `cc` | String | comma-separated | | `bcc` | String | comma-separated | | `subject` | String | | | `body` | String | | | `htmlbody` | String | | | `name` | String | default: the user's name | | `from` | String | for paid accounts. One of `var aliases = GmailApp.getAliases();` | | `replyto` | String | | | `noreply` | Integer | 1 = no reply = true | | `inlineimages` | Object | `{name: blob}`, use in HtmlBody: `inline <img src='cid:name'> image!` | | `attachments` | Array | `[blob, blob]` | 🕵There's also a hidden option: `replyToName`. This option is for Gmail API only * * * ### Return Sample ``` {"labelIds":["UNREAD","SENT","INBOX"], "id":"1831c4c0aa922712", "threadId":"1831c4c0aa922712", "url":"https://mail.google.com/mail/u/0/#inbox/1831c4c0aa922712"} ``` * * ### Author * `@max__makhrov` * * ![CoolTables](https://raw.githubusercontent.com/cooltables/pics/main/logos/ct_logo_small.png) * [cooltables.online](https://www.cooltables.online/) * */ function sendGmailApi(options) { // Note // Usage of `from` is limited // You need to create an alias first // https://support.google.com/mail/answer/22370?hl=en // you must have a paid account // and create alias. // To test your aliases: // var aliases = GmailApp.getAliases(); var rfcString = getGmailApiString_(options); // console.log(rfcString); var result = sendGmailApiByRaw_(rfcString); return result; } /** * send Gmail API email * * @param {string} raw - RFC 2822 formatted and base64url encoded email * */ function sendGmailApiByRaw_(raw) { var raw_encoded = Utilities.base64EncodeWebSafe(raw); // console.log(raw_encoded); var response = Gmail.Users.Messages.send({raw: raw_encoded}, "me"); if (response.threadId) { response.url = 'https://mail.google.com/mail/u/0/#inbox/' + response.threadId; } return response; } /** * get raw RFC 2822 formatted and base64url encoded email * * ## Credits * [😺github/muratgozel/MIMEText](https://github.com/muratgozel/MIMEText) — RFC 2822 compliant raw email message generator * * [♨️Emoji in email subject with Apps Script?](https://stackoverflow.com/a/66088350/5372400) - sample script by Tanaike */ function getGmailApiString_(options) { // let use of different naming conventions setOptionsNamings_(options); /** parameters */ var boundary = 'happyholidays'; var boundary2 = 'letthemerrybellskeepringing'; var dd = '--'; var header = ['MIME-Version: 1.0']; var body = []; /** for emojis to go */ var getEncoded_ = function(str) { return Utilities.base64Encode( str, Utilities.Charset.UTF_8); } /** for emojis to go in names */ var getEncodedString_ = function(str) { return '=?UTF-8?B?' + getEncoded_(str) + '?='; } /** add <tags> */ var addTags_ = function(str) { return '<' + str + '>'; } /** for emails */ var getParsedEmails_ = function(str) { var arr = str.split(',').map(addTags_); return arr.join(', '); } /** 1️⃣From */ var fromemail = Session.getEffectiveUser().getEmail(); if (options.from) { fromemail = options.from; } var i_from = addTags_(fromemail); if (options.name && options.name !== '') { i_from = getEncodedString_(options.name) + ' ' + i_from; } header.push('From: ' + i_from); /** 2️⃣Reply To & No Reply */ if (options.replyto && options.replyto !== '') { var replyto = addTags_(options.replyto); if (options.replytoname && options.replytoname !== '') { replyto = getEncodedString_(options.replytoname) + ' ' + replyto; } header.push('Reply-To: ' + replyto); } else if (options.noreply) { header.push('Reply-To: No Reply <[email protected]>'); } /** 3️⃣ To */ if (!options.to || options.to === '') { throw "😮resepient is missing. Please add like this: `{to: '[email protected]'}`" } header.push('To: ' + getParsedEmails_(options.to)); /** 4️⃣ Cc & Bcc */ if (options.cc && options.cc !== '') { header.push('Cc: ' + getParsedEmails_(options.cc)); } if (options.bcc && options.bcc !== '') { header.push('Bcc: ' + getParsedEmails_(options.bcc)); } /** 5️⃣ Subject */ if (!options.subject || options.subject === '') { options.subject = '(No Subject)' } header.push('Subject: ' + getEncodedString_(options.subject)); /** 6️⃣ Other Headers & delimiters */ body.push('Content-Type: multipart/mixed; boundary=' + boundary); body.push(''); body.push(dd + boundary); body.push('Content-Type: multipart/alternative; boundary=' + boundary2); body.push(''); /** 7️⃣ body & htmlBody */ body.push(dd + boundary2); body.push('Content-Type: text/plain; charset=UTF-8'); body.push('Content-Transfer-Encoding: base64'); body.push(''); if (!options.body || options.body === '') { options.body = '<this message was sent automatically without email body>'; } body.push(getEncoded_(options.body)); if (options.htmlbody && options.htmlbody !== '') { body.push(dd +boundary2); body.push('Content-Type: text/html; charset=UTF-8'); body.push('Content-Transfer-Encoding: base64'); body.push(''); body.push(getEncoded_(options.htmlbody)); } /** 8️⃣ Attachments */ if (options.attachments && options.attachments !== '') { body.push(dd + boundary2 + dd); var attach; for (var i = 0; i < options.attachments.length; i++) { attach = options.attachments[i]; body.push(dd + boundary); body.push('Content-Type: ' + attach.getContentType() + '; charset=UTF-8'); body.push('Content-Transfer-Encoding: base64'); body.push('Content-Disposition: attachment;filename="' + attach.getName() + '"'); body.push(''); body.push(Utilities.base64Encode(attach.getBytes())); } } /** 9️⃣ Inline Images */ if (options.inlineimages && options.inlineimages !== '') { body.push(dd + boundary2 + dd); var inline; for (var k in options.inlineimages) { inline = options.inlineimages[k]; body.push(dd + boundary); body.push('Content-Type: ' + inline.getContentType() + '; name=' + inline.getName()); body.push('Content-Transfer-Encoding: base64'); body.push('X-Attachment-Id: ' + k); body.push('Content-ID: <' + k + '>'); body.push(''); body.push(Utilities.base64Encode(inline.getBytes())); } } /** 🔟 Result */ body.push(''); body.push(dd + boundary + dd); var result = header.concat(body).join('\r\n'); return result; } // _______ _ // |__ __| | | // | | ___ ___| |_ ___ // | |/ _ \/ __| __/ __| // | | __/\__ \ |_\__ \ // |_|\___||___/\__|___/ /** * this function demonstrates * how to get blobs by URL * for your email */ function getTestBlobs_() { var source = 'https://raw.githubusercontent.com/'; var options = { urls: { 'coolTablesLogo': source + 'cooltables/pics/main/logos/ct_logo_small.png', 'partyFace': source + 'Max-Makhrov/myFiles/master/partyface.png' }, html: "🔍 inline CoolTables Logo<img src='cid:coolTablesLogo'> image! <br>" + "Hoooorrraaay! <img src='cid:partyFace'>" } var blobsArray = [], blobsObject = {}; var blob; for (var k in options.urls) { blob = UrlFetchApp .fetch(options.urls[k]) .getBlob() .setName(k); blobsArray.push(blob); blobsObject[k] = blob; } return { array: blobsArray, // for attachments object: blobsObject, // for inline images htmlBody: options.html }; }
// // CounterViewModel.swift // ZikrAppSUI // // Created by Yerassyl Zhassuzakhov on 16.01.2023. // import SwiftUI import Factory final class CounterViewModel: ObservableObject, Hapticable { @AppStorage("counterCount") private(set) var count: Int = 0 @Injected(Container.analyticsService) private var analyticsService func zikrDidTap() { hapticLight() count += 1 } func reset() { hapticStrong() count = 0 } func onAppear() { analyticsService.trackOpenCounter(count: count) } func onDisappear() { analyticsService.trackCloseCounter(count: count) } }
#ifndef _QUEUE_H_ #define _QUEUE_H_ #include <exception> #include "Array.h" /** * @class Queue * * Basic queue for abitrary elements. */ template <typename T> class Queue : public Array <T> { private: struct Node { T element_; int priority_; Node* next_; }; Node* head_; Node* tail_; // int max_; again, just not sure how to handle the max situation. this seems like the part where inheritance from Array comes in. // I've tried refactoring this entire assignment twice, aggregation and virtual/poly. I need to stop by office hours and get some //clarification so I can meet the inheritance requirements by second submission. int size_; public: //Type definition of the type. typedef T type; /// Default constructor. Queue(void); /// Destructor. ~Queue(void); /** * Number of elements in the queue. * * @return Size of the stack. */ size_t size(void) const; /** * Test if the queue is empty * * @retval true The queue is empty * @retval false The queue is not empty */ bool is_empty(void) const; /** * Enqueue a new element into the queue. * * @param[in] payload Element to add to the queue * @param[in] priority Position of element */ void Queue<T>::enqueue(T element, int priority); /** * Dequeue tail element from the queue. * * @return Reference to self */ void Queue<T>::dequeue(void); /** * Queue is structured similar to a linked list. Remove all elements with this method to release memory. */ void Queue<T>::clear(void); }; #include "Queue.inl" #endif // !defined _QUEUE_H_
package staffmanager; import io.gatling.core.scenario.Scenario; import io.gatling.javaapi.core.ChainBuilder; import io.gatling.javaapi.core.ScenarioBuilder; import io.gatling.javaapi.core.Simulation; import io.gatling.javaapi.http.HttpProtocolBuilder; import static io.gatling.javaapi.core.CoreDsl.*; import static io.gatling.javaapi.http.HttpDsl.http; public class MissionSimulation extends Simulation { HttpProtocolBuilder httpProtocolBuilder = http.baseUrl("http://localhost:8080"); ChainBuilder getMissions = repeat(1).on( exec(http("get all missions") .get("/api/v1/mission") ).pause(2)); ChainBuilder updateMission = repeat(1).on( exec(http("update mission") .put("/api/v1/mission/5") .body(ElFileBody("bodies/UpdateMission.json")).asJson() ).pause(2)); ScenarioBuilder scn = scenario("Test missions endpoints performances") .exec(getMissions) .exec(updateMission); { setUp(scn.injectOpen(rampUsers(40).during(5))) .protocols(httpProtocolBuilder); } }
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:tictac_game/game_logic.dart'; import 'package:flutter_launcher_icons/android.dart'; class MainHome extends StatefulWidget { @override State<MainHome> createState() => _MainHomeState(); } class _MainHomeState extends State<MainHome> { String activePlayer = 'X'; String result = ''; bool gameOver = false; bool isSwitch = false; int turne = 0; Game game = Game(); _onTapFunctine(int index) async { if ((Player.playerX.isEmpty || !Player.playerX.contains(index)) && (Player.playerO.isEmpty || !Player.playerO.contains(index))) { game.playGmae(index, activePlayer); updatState(); if (!isSwitch && !gameOver) { await game.autoPlay(activePlayer); updatState(); } } } void updatState() { setState(() { activePlayer = (activePlayer == "X" ? "O" : "X"); turne++; }); String winnerPlayer = game.checkWiner(); if (winnerPlayer != '') { gameOver = true; result = '$winnerPlayer is the winner!'; } else if (!gameOver && turne == 9) { result = 'It\'s Draw!'; } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).primaryColor, body: SafeArea( child: MediaQuery.of(context).orientation == Orientation.portrait ? Column( children: [ const SizedBox( height: 20, ), ..._firstBlock(), _expandedWidget(context), ...lastBlock(), ], ) : Row( children: [ Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ..._firstBlock(), const SizedBox( height: 20, ), ...lastBlock(), ], ), ), _expandedWidget(context), ], )), ); } List<Widget> _firstBlock() { return [ SwitchListTile.adaptive( title: const Text( 'Turn on/off two player', style: TextStyle( color: Colors.white, fontSize: 28, ), textAlign: TextAlign.center, ), value: isSwitch, onChanged: (bool newValue) { setState(() { isSwitch = newValue; }); }, ), const SizedBox( height: 10, ), Text( "It\'s $activePlayer turn".toUpperCase(), style: const TextStyle( fontSize: 50, color: Colors.white, ), textAlign: TextAlign.center, ), ]; } Expanded _expandedWidget(BuildContext context) { return Expanded( child: GridView.count( padding: const EdgeInsets.all(16.0), mainAxisSpacing: 8.0, crossAxisSpacing: 8.0, childAspectRatio: 1.0, crossAxisCount: 3, children: List.generate( 9, (index) => InkWell( borderRadius: BorderRadius.circular(16.0), onTap: gameOver == true ? null : () => _onTapFunctine(index), child: Container( decoration: BoxDecoration( color: Theme.of(context).shadowColor, borderRadius: BorderRadius.circular(16.0)), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( Player.playerX.contains(index) ? "X" : Player.playerO.contains(index) ? "O" : "", style: TextStyle( color: Player.playerX.contains(index) ? Colors.blue : Colors.pink, fontSize: 70, ), textAlign: TextAlign.center, ), ], ), )), ), ), ), ); } List<Widget> lastBlock() { return [ Text( result, style: const TextStyle( fontSize: 40, color: Colors.white, ), textAlign: TextAlign.center, ), const SizedBox( height: 10, ), ElevatedButton.icon( onPressed: () { setState(() { Player.playerX = []; Player.playerO = []; activePlayer = 'X'; result = ''; gameOver = false; turne = 0; }); }, icon: const Icon(Icons.replay), label: const Text( "Repeat the game", ), style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Theme.of(context).splashColor), ), ), ]; } }
package com.example.submission2.Reminder; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.widget.Toast; import androidx.core.app.NotificationCompat; import com.example.submission2.MainActivity; import com.example.submission2.Model.MovieDataRes; import com.example.submission2.Model.MovieResponse; import com.example.submission2.Network.RetrofitHelper; import com.example.submission2.R; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class UpComingReminder extends BroadcastReceiver { public final static int NOTIFICATION_ID_ = 502; public static final String EXTRA_MESSAGE_RECIEVE = "messageRelease"; public static final String EXTRA_TYPE_RECIEVE = "typeRelease"; private static final CharSequence CHANNEL_NAME = "dicoding channel"; private static final int MAX_NOTIFICATION = 2; public List<MovieDataRes> listMovie = new ArrayList<>(); private int idNotification = 0; public UpComingReminder() { } @Override public void onReceive(final Context context, Intent intent) { final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String today = sdf.format(date); RetrofitHelper.getService().getReleaseTodayMovie(RetrofitHelper.API_KEY, today, today) .enqueue(new Callback<MovieResponse>() { @Override public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) { if (response.isSuccessful()) { listMovie = response.body().getResults(); List<MovieDataRes> items = response.body().getResults(); int index = new Random().nextInt(items.size()); MovieDataRes item = items.get(index); idNotification++; String title = items.get(index).getTitle(); String message = items.get(index).getOverview(); sendNotification(context, title, message, idNotification); } } @Override public void onFailure(Call<MovieResponse> call, Throwable t) { } }); } private void sendNotification(Context context, String title, String desc, int id) { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_notifications_white_48px); Intent intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(context, NOTIFICATION_ID_, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder; //Melakukan pengecekan jika idNotification lebih kecil dari Max Notif String CHANNEL_ID = "CHANNEL_01"; if (idNotification < MAX_NOTIFICATION) { mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID) .setContentTitle("" + listMovie.get(idNotification).getOriginalTitle()) .setContentText(listMovie.get(idNotification).getOverview()) .setSmallIcon(R.drawable.ic_movie_black) // .setLargeIcon(largeIcon) .setGroup(EXTRA_MESSAGE_RECIEVE) .setContentIntent(pendingIntent) .setAutoCancel(true); } else { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle() .addLine(listMovie.get(idNotification).getOriginalTitle()) .addLine(listMovie.get(idNotification - 1).getOriginalTitle()) .setBigContentTitle(idNotification + " New Movie") .setSummaryText("Movie Catalogue"); mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID) .setContentTitle(idNotification + " New Movie") // .setContentText("[email protected]") .setSmallIcon(R.drawable.ic_movie_black) .setGroup(EXTRA_MESSAGE_RECIEVE) .setGroupSummary(true) .setContentIntent(pendingIntent) .setStyle(inboxStyle) .setAutoCancel(true); } /* Untuk android Oreo ke atas perlu menambahkan notification channel Materi ini akan dibahas lebih lanjut di modul extended */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { /* Create or update. */ NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); mBuilder.setChannelId(CHANNEL_ID); if (mNotificationManager != null) { mNotificationManager.createNotificationChannel(channel); } } Notification notification = mBuilder.build(); if (mNotificationManager != null) { mNotificationManager.notify(idNotification, notification); } } public void setAlarm(Context context, String type, String time, String message) { cancelAlarm(context); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, UpComingReminder.class); intent.putExtra(EXTRA_MESSAGE_RECIEVE, message); intent.putExtra(EXTRA_TYPE_RECIEVE, type); String[] timeArray = time.split(":"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeArray[0])); calendar.set(Calendar.MINUTE, Integer.parseInt(timeArray[1])); calendar.set(Calendar.SECOND, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID_, intent, 0); if (alarmManager != null) { alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); } Toast.makeText(context, R.string.app_name, Toast.LENGTH_SHORT).show(); } public void cancelAlarm(Context context) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, UpComingReminder.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, NOTIFICATION_ID_, intent, 0); if (alarmManager != null) { alarmManager.cancel(pendingIntent); } Toast.makeText(context, R.string.app_name, Toast.LENGTH_SHORT).show(); } }
package com.filmstar.api.actions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import com.filmstar.api.controllers.commands.DoDeleteFavoriteMovieDeleteController; import com.filmstar.api.entities.Movie; import com.filmstar.api.entities.User; import com.filmstar.api.usecases.DeleteFavoriteMovieUseCase; @SpringBootTest public class DeleteFavoriteMovieTests { @Mock private DeleteFavoriteMovieUseCase deleteFavoriteMovieUseCase; @InjectMocks private DoDeleteFavoriteMovieDeleteController controller; @Test public void testExecute_DeleteFavoriteMovie_Accepted() { Long movieId = 1L; User user = new User(); Movie movie = new Movie(); when(deleteFavoriteMovieUseCase.execute(movieId, user)).thenReturn(new ResponseEntity<>(Map.of("message", "Movie with id: 1 deleted from favorites"), HttpStatus.ACCEPTED)); ResponseEntity<Map<String, String>> responseEntity = controller.execute(movieId, user); assertEquals(HttpStatus.ACCEPTED, responseEntity.getStatusCode()); assertEquals("Movie with id: 1 deleted from favorites", responseEntity.getBody().get("message")); verify(deleteFavoriteMovieUseCase, times(1)).execute(movieId, user); } }
package ooc.yoursolution; import java.util.Map; import ooc.enums.Make; import ooc.enums.Month; import java.util.HashMap; //import HashMap /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author TahR */ public class Car implements CarInterface { //variables private int id; private Make make; private double rate; private Map<Month, Boolean[]> map; public Car(int id, Make make, double rate) { this.id = id; this.make = make; this.rate = rate; createAvailability(); } @Override public Map createAvailability() { map = new HashMap<>(); /*decision based on the explanation in this website https://examples.javacodegeeks.com/java-map-example/ */ map.put(Month.JANUARY, new Boolean[31]); map.put(Month.FEBRUARY, new Boolean[28]); map.put(Month.MARCH, new Boolean[31]); map.put(Month.APRIL, new Boolean[30]); map.put(Month.MAY, new Boolean[31]); map.put(Month.JUNE, new Boolean[30]); map.put(Month.JULY, new Boolean[31]); map.put(Month.AUGUST, new Boolean[31]); map.put(Month.SEPTEMBER, new Boolean[30]); map.put(Month.OCTOBER, new Boolean[31]); map.put(Month.NOVEMBER, new Boolean[30]); map.put(Month.DECEMBER, new Boolean[31]); return map; } @Override public Make getMake() { return make; } @Override public void setMake(Make make) { this.make = make; } @Override public double getRate() { return rate; } @Override public void setRate(double rate) { this.rate = rate; } @Override public Map getAvailability() { return map; } @Override public void setAvailability(Map availability) { this.map = map; } @Override public int getId() { return id; } @Override public boolean isAvailable(Month month, int day) { Boolean[] availability = map.get(month);//access a value in the enum if (availability[day-1] == null) { availability[day-1] = true; //if it's available return true } return availability[day-1]; } @Override public boolean book(Month month, int day) { if (map.get(month)[day-1]) { map.get(month)[day-1] = false; //if it's not booked return true return true; } return false; } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Threading.Tasks; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Warehouses; using Nop.Data; using Nop.Services.Catalog; using Nop.Services.Localization; using Nop.Services.Warehouses.Interface; using Org.BouncyCastle.Asn1; namespace Nop.Services.Warehouses { public class WarehouseProductService : IWarehouseProductService { #region Fields private readonly ILocalizationService _localizationService; private readonly IRepository<WarehouseProduct> _warehouseProductRepository; private readonly IStaticCacheManager _staticCacheManager; private readonly IProductService _productService; #endregion #region Ctor public WarehouseProductService( ILocalizationService localizationService, IRepository<WarehouseProduct> warehouseProductRepository, IStaticCacheManager staticCacheManager , IProductService productService) { _localizationService = localizationService; _warehouseProductRepository = warehouseProductRepository; _staticCacheManager = staticCacheManager; _productService = productService; } #endregion #region Methods /// <summary> /// Delete Warehouse Product /// </summary> /// <param name="warehouseProduct">warehouseProduct</param> /// <returns>A task that represents the asynchronous operation</returns> public async Task DeleteWarehouseProductAsync(WarehouseProduct warehouseProduct) { if (warehouseProduct is null) throw new ArgumentNullException(nameof(warehouseProduct)); await _warehouseProductRepository.DeleteAsync(warehouseProduct); } /// <summary> /// Delete a list of Warehouse Products /// </summary> /// <param name="WarehouseProducts">WarehouseProducts</param> /// <returns>A task that represents the asynchronous operation</returns> public async Task DeleteWarehouseProductAsync(IList<WarehouseProduct> warehouseProducts) { if (warehouseProducts is null) throw new ArgumentNullException(nameof(warehouseProducts)); await _warehouseProductRepository.DeleteAsync(warehouseProducts); } /// <summary> /// Gets all Warehouse Products /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the Warehouse Products /// </returns> public async Task<IList<WarehouseProduct>> GetAllWarehouseProductsAsync() { return await _warehouseProductRepository.GetAllAsync(query => query.Where(x => !x.Deleted)); } /// <summary> /// Gets all available Warehouse Products /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the available Warehouse Products /// </returns> public async Task<IList<WarehouseProduct>> GetAllAvailableWarehouseProductsAsync() { return await _warehouseProductRepository.GetAllAsync(query => query.Where(x => x.Available && !x.Deleted)); } /// <summary> /// Gets Warehouse Product by identifier /// </summary> /// <param name="warehouseProductId">Warehouse Product identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the Warehouse Product /// </returns> public async Task<WarehouseProduct> GetWarehouseProductByIdAsync(int warehouseProductId) { return await _warehouseProductRepository.GetByIdAsync(warehouseProductId); } public async Task<IEnumerable<int>> GetProductsIdsByWarehouseProductCategoryMappingIdsAsync(IEnumerable<int> warehouseProductCategoryMappingIds) { var warehouseProducts = await _warehouseProductRepository.GetAllAsync(query => query.Where(x => warehouseProductCategoryMappingIds.Contains(x.WarehouseProductCategoryMappingId) && !x.Deleted)); return warehouseProducts.Select(x => x.ProductId); } /// <summary> /// Gets all warehouse products /// </summary> /// <param name="warehouseId">Warehouse identifier</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// </param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the warehouse products /// </returns> public async Task<IPagedList<WarehouseProduct>> GetAllWarehouseProductsAsync(int warehouseId,string productName, string sku, int pageIndex = 0, int pageSize = int.MaxValue) { try { var warehouseProducts = await _warehouseProductRepository.GetAllAsync(query => { query = query.Where(x => !x.Deleted && x.WarehouseId == warehouseId); if (!string.IsNullOrWhiteSpace(productName)) query = query.Where(x => x.Name.Contains(productName)); if (!string.IsNullOrWhiteSpace(sku)) query = query.Where(x => x.Sku.Contains(sku)); return query.OrderBy(x => x.Id); }); //paging return new PagedList<WarehouseProduct>(warehouseProducts, pageIndex, pageSize); } catch (Exception ex) { throw; } } /// <summary> /// Get warehouse product by identifiers /// </summary> /// <param name="warehouseProductIds">warehouse product identifiers</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the warehouse product that retrieved by identifiers /// </returns> public async Task<IList<WarehouseProduct>> GetWarehouseProductByIdsAsync(int[] warehouseProductIds) { return await _warehouseProductRepository.GetByIdsAsync(warehouseProductIds, includeDeleted: false); } /// <summary> /// Inserts a Warehouse Product /// </summary> /// <param name="warehouseProduct">>warehouseProduct</param> /// <returns>A task that represents the asynchronous operation</returns> public async Task InsertWarehouseProductAsync(WarehouseProduct warehouseProduct) { if (warehouseProduct is null) throw new ArgumentNullException(nameof(warehouseProduct)); await _warehouseProductRepository.InsertAsync(warehouseProduct); } /// <summary> /// Updates the Warehouse Product /// </summary> /// <param name="warehouseProduct">>warehouseProduct</param> /// <returns>A task that represents the asynchronous operation</returns> public async Task UpdateWarehouseProductAsync(WarehouseProduct warehouseProduct) { if (warehouseProduct is null) throw new ArgumentNullException(nameof(warehouseProduct)); await _warehouseProductRepository.UpdateAsync(warehouseProduct); } #endregion } }
import { Typography } from "@material-ui/core"; import React, { useState } from "react"; import "./App.css"; import { TimeRemainingState } from "./Interfaces/Interfaces"; // const HiastSchedule : number [] = [ // 900 , 1015 , 1025, 1140 , 1150, 1305 , 1350 , 1505 , 1515 , 1630 // ] const HiastSchedule: number[] = [ 900, 1005, 1010, 1115, 1120, 1225, 1255, 1400, 1405, 1510, ]; const whatToSay: string[] = [ "Good Morning", "First Period", "10 mins Break", "Second Period", "10 mins Break", "Third Period", "Lunch Break", "Forth Period", "10 mins Break", "Fifth Period", "Classes Are Over For Today", ]; const HScheduleDates: Date[] = HiastSchedule.map(function (x: number): Date { let d = new Date(); d.setHours(Math.floor(x / 100)); d.setMinutes(x % 100); d.setSeconds(0); return d; }); function getTimeRemaining( whatToSayIndex: number, endtime: Date ): TimeRemainingState { let now: Date = new Date(); let total: number = endtime.valueOf() - now.valueOf(); const seconds = Math.floor((total / 1000) % 60); const minutes = Math.floor((total / 1000 / 60) % 60); const hours = Math.floor((total / (1000 * 60 * 60)) % 24); const days = Math.floor(total / (1000 * 60 * 60 * 24)); return { whatToSayIndex, total, days, hours, minutes, seconds, }; } function whereAmI(list: Date[]): TimeRemainingState { let now = new Date(); let index: number = 0; while (now.valueOf() - list[index].valueOf() > 0) { index = index + 1; if (index === list.length) { break; } } if (index === list.length) { let d: Date = list[0]; d.setDate(now.getDay() + 1); return getTimeRemaining(index, d); } else return getTimeRemaining(index, list[index]); } function TimeRemainingStringify(x: TimeRemainingState): string { let output: string = ``; let h: string = x.hours.toString(); let m: string = x.minutes < 10 ? `0` + x.minutes.toString() : x.minutes.toString(); let s: string = x.seconds < 10 ? `0` + x.seconds.toString() : x.seconds.toString(); if (x.hours !== 0 || x.minutes !== 0 || x.seconds !== 0) { output += whatToSay[x.whatToSayIndex] + " "; if (x.whatToSayIndex + 1 < whatToSay.length) { if (x.hours !== 0) { output += h + `:` + m + `:` + s; } else if (x.minutes !== 0) { output += m + `:` + s; } else if (x.seconds !== 0) { output += x.seconds + (x.seconds !== 1 ? ` Seconds` : ` Second`); } output += " Until " + whatToSay[x.whatToSayIndex + 1]; } } else { output += whatToSay[x.whatToSayIndex + 1]; } return output; } export function TimeRemaining(): JSX.Element { const [state, setState] = useState<TimeRemainingState>( whereAmI(HScheduleDates) ); React.useEffect( () => { let ID: any = setInterval(() => { setState(whereAmI(HScheduleDates)); }, 1000); return function cleanup() { clearInterval(ID); }; }, // eslint-disable-next-line react-hooks/exhaustive-deps [] ); return ( <div className="App-header"> <Typography variant="h2" id="TimeRemaining" align="center"> {TimeRemainingStringify(state)} </Typography> </div> ); }
// "for of" loop // ["", "", ""] //[{}, {}, {}] const arr = [1, 2, 3, 4, 5]; // takes each element of "arr" in "num" // for (const num of arr){ // console.log(num); // } // const greet = "Hello world!"; // for(const letter of greet){ // console.log(letter); // } // Maps /* 1. Objects containing key-value pairs which are unique. 2. It remembers the order. */ const map = new Map(); map.set("IN", "India"); map.set("USA", "United States of India"); map.set("Fr", "France"); map.set("IN", "India"); // console.log(typeof map); // o/p: object // console.log(map); // for(const elem of map){ // console.log(elem); // logs each key-value pair as an array // } for (const [key, value] of map) { // we hold key and value after destructuring for each key-value array given as output console.log(key, ":-", value); } // IMP NOTE : "Maps" are iterable but "normal objects" are not, using 'for of' loop
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ChargingStation } from '../../../interfaces/ChargingStations'; import { ChargingstationService } from '../../../services/chargingstation.service'; import { Observer } from 'firebase'; import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; import { Auth2Service } from '../../../auth/auth2.service'; import { StationDetailDialogComponent } from './dialogs/station-detail-dialog/station-detail-dialog.component'; import { UserService } from 'src/app/services/user.service'; @Component({ selector: 'app-maps', templateUrl: './maps.component.html', styleUrls: ['./maps.component.scss'] }) export class MapsComponent implements OnInit, OnDestroy { constructor( private csService: ChargingstationService, private userService: UserService, private dialog: MatDialog, private Auth: Auth2Service ) { // Laoding moet worden disabled als we op de pagina komen this.Auth.loading = false; // Toont huidige locatie if (navigator) { navigator.geolocation.getCurrentPosition(pos => { this.lng = +pos.coords.longitude; this.lat = +pos.coords.latitude; }); } } // pinSparky: string = "../../../../assets/images/MapsMarker.png"; lat: any; lng: any; stations: ChargingStation[]; csObserver: any; // Map styling -> verstopt points-of-interest public mapStyles = [ { featureType: 'poi', elementType: 'labels', stylers: [ { visibility: 'off' } ] } ]; // pin styling -> gebruikt custom pin en resized public pinSparky = { url: '../../../../assets/images/MapsMarker.png', scaledSize: { width: 50, height: 50 } }; // Map styling -> verstopt points-of-interest isReturn: boolean; getStations() { this.csObserver = this.csService.ChargingStations.subscribe(stations => { if (stations) { this.stations = stations; this.stations.forEach(s => { s.mlat = s.lat; s.mlon = s.lon; }); } }); } ngOnInit() { this.getStations(); this.userService.updateLoanHistory(); this.userService.currentLoanHistory.subscribe(history => { if (history.find(d => d.isOngoing === true)) { this.isReturn = true; } else { this.isReturn = false; } }); this.csService.updateCharginStations(); } ngOnDestroy() { this.csObserver.unsubscribe(); } // On Marker CLick open dialog openDialog(station: ChargingStation) { const dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = false; dialogConfig.autoFocus = false; dialogConfig.data = station; const dialogRef = this.dialog.open(StationDetailDialogComponent, dialogConfig); dialogRef.afterClosed().subscribe(x => { this.csService.updateCharginStations(); }); } }
import { useState, useEffect, useContext } from "react"; import { app } from "firebaseApp"; import { getAuth, onAuthStateChanged } from "firebase/auth"; import { ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import ThemeContext from "context/ThemeContext"; import Router from "components/Router"; import Loader from "components/Loader"; function App() { const context = useContext(ThemeContext); const auth = getAuth(app); // auth 체크전 loader 띄어주기 const [init, setInit] = useState<boolean>(false); // auth currentUser가 있으면 authenticated const [isAuthenticated, setIsAuthenticated] = useState<boolean>( !!auth?.currentUser, ); useEffect(() => { onAuthStateChanged(auth, (user) => { if (user) { setIsAuthenticated(true); } else { setIsAuthenticated(false); } setInit(true); }); }, [auth]); return ( <div className={context.theme === "light" ? "white" : "dark"}> <ToastContainer /> {init ? <Router isAuthenticated={isAuthenticated} /> : <Loader />} </div> ); } export default App;
//evolution function getAllEvolutions(evol, selectedPokemon) { const evolutions = []; function recursiveEvolutions(currentChain) { const species = currentChain.species.name; if (selectedPokemon !== species) { evolutions.push(species); } currentChain.evolves_to.forEach(nextEvolution => { recursiveEvolutions(nextEvolution); }); } recursiveEvolutions(evol); return displayEvolutions(evolutions); } //render pokemon function getEvolutions(species, selectedPokemon) { fetch(species.url) .then(response => response.json()) .then(data => { fetch(data.evolution_chain.url) .then(response => response.json()) .then(evol => { getAllEvolutions(evol.chain, selectedPokemon); }) .catch(error => { console.error('Error fetching evolution chain data:', error); }); }) .catch(error => { console.error('Error fetching species data:', error); }); } //show pokemon function displayEvolutions(evolutions) { const pokeIconContainer = document.getElementById('pokeIcon'); let iconsHTML = ''; function renderNextImage(index) { if (index >= evolutions.length) { return; // Se han renderizado todas las imágenes } const pokemonName = evolutions[index]; fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`) .then(response => response.json()) .then(data => { const pokemonImage = data.sprites.front_default; iconsHTML += ` <div class="section__container--icon" data-hover="${data.id}"> <img class="section__icon" src="${pokemonImage}" alt="${data.name}" onclick="fetchPokemonInfo(${data.id})" /> </div> `; pokeIconContainer.innerHTML = iconsHTML; setTimeout(() => { renderNextImage(index + 1); }, 100); }) .catch(error => { console.error(`Error fetching Pokémon data for ${pokemonName}:`, error); }); } renderNextImage(0); } function submitPokemon(id) { let form = document.getElementById('form'); let input = form.getElementById('#pokemonInput').value(id); form.submit(input); } // render main pokemon card function fetchPokemonInfo(valueInput) { if (valueInput != '') { $.ajax({ url: 'https://pokeapi.co/api/v2/pokemon/' + valueInput, success: function (data) { $('#pokemonInput').val(''); let number = data.id; let name = data.name; let image = data.sprites.other["official-artwork"].front_default; let types = data.types; let species = { name: data.species.name, url: data.species.url }; function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } let typeInfoArray = types.map(function (type) { return { name: type.type.name, url: type.type.url }; }); statsArray = data.stats.map(function (s) { return { label: s.stat.name, stat: s.base_stat, }; }); $('#pokeInfo').html(` <div class="section__pokemon--information"> <div class="section__card"> <img class="section__main--image" src="${image}" alt="${name}" /> <div class="section__display--icon" id="pokeIcon"></div> </div> <div> <h4>#${number}</h4> <h5>${capitalizeFirstLetter(name)}</h5> </div> <div class="section__type"> ${typeInfoArray.map(typeInfo => `<div class="section__chip ${typeInfo.name}">${typeInfo.name}</div>`).join('')} </div> <button id="toggleChartBtn" class="section__btn" onClick="showChart(statsArray)">Show Stats</button> <div id="evolutionContainer" class="section__evolutions"> </div> </div> <div id="chart" class="d-none section__card"> <canvas class="section__canvas" id="pokeStats"></canvas> </div> `); $('#pokeInfo').focus(); //evolution getEvolutions(species, name); }, error: function () { Swal.fire({ icon: 'error', title: 'Pokemon Not Found', text: 'The entered value does not correspond to a valid Pokemon.', }); } }); } else { Swal.fire({ icon: 'warning', title: 'Enter a value', text: 'Please enter a name or number.', }); } } $(document).ready(function () { document.getElementById('form').addEventListener('submit', function (event) { event.preventDefault(); let valueInput = document.getElementById('pokemonInput').value; fetchPokemonInfo(valueInput); }); //change main image $('#pokeIcon').on('click', '.section__icon', function () { const clickedImageSrc = $(this).attr('src'); $('.section__main--image').attr('src', clickedImageSrc); }); }); //toggle function attachToggleChartListener() { let toggleChartBtn = document.getElementById('toggleChartBtn'); if (toggleChartBtn) { toggleChartBtn.addEventListener('click', function () { showChart(statsArray); }); } } document.addEventListener('DOMContentLoaded', function () { attachToggleChartListener(); }); //chart let myChart = null; function showChart(statsArray) { let chart = document.getElementById('chart'); chart.classList.toggle('d-none'); let canvas = document.getElementById('pokeStats').getContext('2d'); if (myChart) { myChart.destroy(); } const orderedData = ['hp', 'attack', 'defense', 'special-defense', 'special-attack', 'speed'] .map(label => statsArray.find(stat => stat.label === label).stat); const config = { type: 'radar', data: { datasets: [{ data: orderedData, fill: true, backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgb(255, 99, 132)', pointBackgroundColor: 'rgb(255, 99, 132)', pointBorderColor: '#fff', pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgb(255, 99, 132)' }], labels: ['HP', 'Attack', 'Defense', 'Sp.Def', 'Sp.Atk', 'Speed'] }, options: { maintainAspectRatio: false, responsive: true, scales: { r: { beginAtZero: true, pointLabels: { font: { weight: 'bold', color: '#313131', size: 14, }, callback: function (value, index, values) { return [value, statsArray[index].stat]; // Retorna un arreglo para separar etiqueta y valor }, }, ticks: { display: false, }, grid: { display: true, }, }, }, plugins: { legend: { display: false, }, }, }, }; myChart = new Chart(canvas, config); } //autocomplete document.addEventListener('DOMContentLoaded', function () { let input = document.getElementById('pokemonInput'); let awesomplete = new Awesomplete(input, { minChars: 2, maxItems: 10, list: [], }); let searchTimeout; input.addEventListener('input', function () { let inputValue = input.value.trim(); clearTimeout(searchTimeout); searchTimeout = setTimeout(function () { if (inputValue.length >= awesomplete.minChars) { fetch(`https://pokeapi.co/api/v2/pokemon/?limit=1000`) .then((response) => response.json()) .then((data) => { var pokemonNames = data.results .map((pokemon) => pokemon.name) .filter((name) => name.includes(inputValue.toLowerCase())); awesomplete.list = pokemonNames; }) .catch((error) => { console.error('Error fetching Pokémon data:', error); }); } else { awesomplete.list = []; } }, 300); }); });
const express = require('express'); const { getAllUsers, getUser, createUser, updateUser, deleteUser, updateMe, deleteMe, getMe, uploadUserPhoto, resizeUserPhoto, } = require('../controllers/userController'); const authController = require('./../controllers/authController'); const { update } = require('../models/userModel'); const router = express.Router(); router.post('/signup', authController.signup); router.post('/login', authController.login); router.post('/forgotPassword', authController.forgotPassword); router.patch('/resetPassword/:token', authController.resetPassword); // Proctect All routes after this middleware router.use(authController.protect); router.patch( '/updateMyPassword', authController.updatePassword ); router.get('/me', getMe, getUser); router.patch('/updateMe', uploadUserPhoto, resizeUserPhoto, updateMe); router.delete('/deleteMe', deleteMe); router.use(authController.restrictTo('admin')); router.route('/').get(getAllUsers).post(createUser); router.route('/:id').get(getUser).patch(updateUser).delete(deleteUser); module.exports = router;
import { useCallback } from "react"; import { useTranslation } from "react-i18next"; import { useMutation, useQuery } from "urql"; import { graphql } from "@/apis/graphql/generated"; import { TaskList } from "@/modules/tasks/components/TaskList"; import { TaskStatus } from "@/modules/tasks/constants"; export interface TasksScreenProps { className?: string; children?: React.ReactNode; } const ORDERED_TASK_STATUS_LIST = [ null, TaskStatus.Backlog, TaskStatus.Todo, TaskStatus.InProgress, TaskStatus.Done, TaskStatus.Cancelled, ]; const COLLAPSED_TASK_STATUS_LIST = [null, TaskStatus.Backlog, TaskStatus.Done, TaskStatus.Cancelled]; export const TasksScreenQuery = graphql(` query TasksScreen { tasks { ...TaskList_TaskFragment } } `); export const UpdateTaskMutation = graphql(` mutation UpdateTask($input: UpdateTaskInput!) { updateTask(input: $input) { ...TaskList_TaskFragment } } `); export const TasksScreen: React.FC<TasksScreenProps> = () => { const { t } = useTranslation(); const [tasksScreen] = useQuery({ query: TasksScreenQuery, requestPolicy: "cache-and-network", }); const [_, updateTaskMutation] = useMutation(UpdateTaskMutation); const handleTasksDrop = useCallback( (taskIds: string[], status: Maybe<TaskStatus>) => { // FIXME: Only handle single drag for now const task = tasksScreen.data?.tasks.find((task) => task.id === taskIds[0]); if (!task) { return; } updateTaskMutation({ input: { id: task.id.toString(), status, dirtyFields: ["status"] }, }); }, [tasksScreen.data?.tasks, updateTaskMutation], ); return ( <div className="flex w-full h-full"> <div un-p="t-6" un-h="full" className="flex flex-col min-w-0"> <h1 un-m="b-4" un-text="3xl" un-font="semibold" className="px-6 text-gray-700"> {t("modules.tasks.title")} </h1> <div className="flex px-6 flex-1 mt-2 gap-2 overflow-x-auto"> {ORDERED_TASK_STATUS_LIST.map((status) => { const tasks = tasksScreen.data?.tasks.filter((task) => task.status === status); const collapsed = COLLAPSED_TASK_STATUS_LIST.includes(status); return ( <TaskList key={status} status={status} collapsed={collapsed} tasks={tasks} onDrop={handleTasksDrop} /> ); })} </div> </div> </div> ); };
<script setup> import store from "../../store"; import {computed, onMounted, ref} from "vue"; import UserModal from "./UserModal.vue"; import UsersTable from "./UsersTable.vue"; import { BaseCreateButton } from "@/components/base"; const DEFAULT_USER = { id: '', title: '', description: '', image: '', price: '' }; const users = computed(() => store.state.users); const userModel = ref({...DEFAULT_USER}); const showUserModal = ref(false); function showAddNewModal() { showUserModal.value = true } function editUser(u) { userModel.value = u; showAddNewModal(); } function onModalClose() { userModel.value = {...DEFAULT_USER} } </script> <template> <div class="flex items-center justify-between mb-3"> <h1 class="text-3xl font-semibold px-2">Users</h1> <BaseCreateButton user @click="showAddNewModal()" /> </div> <UsersTable @clickEdit="editUser"/> <UserModal v-model="showUserModal" :user="userModel" @close="onModalClose"/> </template>
using ViaEventAssociantion.Core.domain.Enums; using ViaEventAssociantion.Core.domain.EventProperties; using ViaEventAssociation.Core.Tools.OperationResult; namespace UnitTests.Features.Event.Ready; public class Ready { private ViaEventAssociantion.Core.domain.Event createdEvent; private ViaEventAssociantion.Core.domain.Event validCreatedEvent; [SetUp] public void Setup() { EventId eventId = new EventId(1); var result = ViaEventAssociantion.Core.domain.Event.Create(eventId); createdEvent = ((Result<ViaEventAssociantion.Core.domain.Event>)result).Values; EventId eventId2 = new EventId(1); var result2 = ViaEventAssociantion.Core.domain.Event.Create(eventId2); validCreatedEvent = ((Result<ViaEventAssociantion.Core.domain.Event>)result2).Values; validCreatedEvent.SetEventStatus(EventStatus.Draft); validCreatedEvent.MakeEventPrivate(); validCreatedEvent.UpdateTitle("Great event"); validCreatedEvent.UpdateDescription("Amazingly great event!"); DateTime currentTime = DateTime.Now; DateTime startTime = currentTime.AddHours(-1); DateTime endTime = currentTime.AddHours(2); validCreatedEvent.StartTime = startTime; validCreatedEvent.EndTime = endTime; validCreatedEvent.SetMaxNrOfGuests(19); } [Test] public void UpdateDescription_S1() { //Act ResultBase resultBase = validCreatedEvent.MakeEventReady(); //Assert Assert.IsTrue(resultBase.IsSuccess); Assert.That(validCreatedEvent.Status, Is.EqualTo(EventStatus.Ready)); Assert.That(resultBase.ErrorMessages.Count, Is.EqualTo(0)); } [Test] public void UpdateDescription_F1() { //Arrange validCreatedEvent.SetEventStatus(EventStatus.Draft); //Act ResultBase resultBase = createdEvent.MakeEventReady(); //Assert Assert.IsTrue(!resultBase.IsSuccess); Assert.That( string.Join(", ", resultBase.ErrorMessages), Is.EqualTo( "Title must be set., Description must be set., Start date time must be set., End date time must be set." ) ); } [Test] public void UpdateDescription_F2() { //Arrange createdEvent.SetEventStatus(EventStatus.Cancelled); //Act ResultBase resultBase = createdEvent.MakeEventReady(); //Assert Assert.IsTrue(!resultBase.IsSuccess); Assert.That(resultBase.ErrorMessages.Count, Is.EqualTo(1)); Assert.That( resultBase.ErrorMessages[0], Is.EqualTo("A cancelled event cannot be readied.") ); } [Test] public void UpdateDescription_F3() { //Arrange DateTime currentTime = DateTime.Now; DateTime startTime = currentTime.AddHours(1); DateTime endTime = currentTime.AddHours(3); validCreatedEvent.UpdateTimeRange(startTime, endTime); //Act ResultBase resultBase = validCreatedEvent.MakeEventReady(); //Assert Assert.IsTrue(!resultBase.IsSuccess); Assert.That(resultBase.ErrorMessages.Count, Is.EqualTo(1)); Assert.That( resultBase.ErrorMessages[0], Is.EqualTo("An event in the past cannot be made ready.") ); } [Test] public void UpdateDescription_F4() { //Arrange validCreatedEvent.SetEventStatus(EventStatus.Cancelled); validCreatedEvent.UpdateTitle(""); //Act ResultBase resultBase = createdEvent.MakeEventReady(); //Assert Assert.IsTrue(!resultBase.IsSuccess); Assert.That(resultBase.ErrorMessages[0], Is.EqualTo("Title must be set.")); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" type="text/css" href="./css/main.css" /> <link rel="stylesheet" type="text/css" href="./css/class.css" /> <link rel="stylesheet" type="text/css" href="./css/responsive.css" /> </head> <body> <header> <div> <img src="./img/Logo.svg"> </div> <div> <a href="">Technology</a> <a href="">Ideas</a> <a href="">Leadership</a> <a href="">Video</a> <a href="">News</a> <a href="">Finance</a> <a href="">Entertainment</a> </div> <div> <img src="./img/Menu icon.svg"> </div> </header> <contents> <div class="grid-container"> <div class="grid-item dark main" style="background-image: url(./img/green-chameleon-176136.png);"> <div class="arrow"><img src="./img/Arrow-left.svg"></div> <div class="item-content"> <div class="ribbon">Finance</div> <div> <h1>This tie brand is bucking the retail apocalypse with a massive store expansion</h1> <p>There is a lot of exciting stuff going on in the stars above us that make astronomy so much fun. The truth is the universe is a constantly changing, moving.</p> </div> <div class="response-buttons"> <img src="./img/share.svg"><span>275</span> <img src="./img/view.svg"><span>275</span> <img src="./img/comment.svg"><span>12</span> </div> </div> <div class="arrow"><img src="./img/Arrow-right.svg"></div> </div> <div class="grid-item dark" style="background-image: url(./img/oliur-rahman-123819.png);"> <div class="ribbon">Finance</div> <div class="item-content"> <h2>Unmatched Toner Cartridge Quality: 20% Less Than OEM Price</h2> <div class="response-buttons"> <img src="./img/share.svg"><span>275</span> <img src="./img/view.svg"><span>275</span> <img src="./img/comment.svg"><span>12</span> </div> </div> </div> <div class="grid-item dark" style="grid-row-start: span 2; background-color: #FF565C;"> <div class="item-content"> <h1>This tie brand is bucking the retail apocalypse with a massive store expansion</h1> <p>The universe is constantly changing, moving. Some would say it’s a “living” thing because you never know what you are going to see on any given night.</p> <button class="btn-outline">Read more</button> </div> </div> <div class="grid-item light" style="grid-row-start: span 2; padding-top: 2rem;"> <div class="ribbon">Featured Stories</div> <div class="stories"> <div class="story"><span>Compare Prices: Find The Best Computer Accessory</span></div> <div class="story"><span>Why You Should Use External IT Support</span></div> <div class="story"><span>Why You Should Use In-House IT Support</span></div> <div class="story"><span>Choosing The Best Audio Player Software</span></div> <div class="story"><span>Addiction When Gambling Becomes A Problem</span></div> </div> </div> <div class="grid-item dark" style="grid-column-start: span 2; background-image: url(./img/oliur-rahman-272875.png);"> <div class="ribbon">Entertainment</div> <div class="item-content"> <h2>Here’s The Difference Between Used, Refurbished, Remarketed, And Rebuilt Electronic Equipment </h2> <div class="response-buttons"> <img src="./img/share.svg"><span>275</span> <img src="./img/view.svg"><span>275</span> <img src="./img/comment.svg"><span>12</span> </div> </div> </div> <div class="grid-item dark" style="background-image: url(./img/igor-son-285029.png);"> <div class="ribbon">Finance</div> <div class="item-content"> <h2>Optimize Your PC’s Performance With These 3 Programs</h2> <div class="response-buttons"> <img src="./img/share.svg"><span>275</span> <img src="./img/view.svg"><span>275</span> <img src="./img/comment.svg"><span>12</span> </div> </div> </div> <div class="grid-item dark" style="background-image: url(./img/crew-22235.png);"> <div class="ribbon">Gaming</div> <div class="item-content"> <h2>Search Engine Optimization And Advertising</h2> <div class="response-buttons"> <img src="./img/share.svg"><span>275</span> <img src="./img/view.svg"><span>275</span> <img src="./img/comment.svg"><span>12</span> </div> </div> </div> <div class="grid-item dark" style="background-image: url(./img/dose-media-344938.png);"> <div class="ribbon">Technology</div> <div class="item-content"> <h2>Where To Find Unique Myspace Layouts</h2> <div class="response-buttons"> <img src="./img/share.svg"><span>275</span> <img src="./img/view.svg"><span>275</span> <img src="./img/comment.svg"><span>12</span> </div> </div> </div> </div> </contents> <footer> <div> <img src="./img/Logo-white.svg"> <span>© 2018 Deck <br>Component based UI Kit</span> </div> <div> <a href="">Technology</a> <a href="">Leadership</a> <a href="">News</a> <a href="">Entertainment</a> <a href="">Ideas</a> <a href="">Video</a> <a href="">Finance</a> </div> <div> <div><span>Follow us:</span><img src="./img/instagram.svg"><img src="./img/pinterest.svg"><img src="./img/twitter.svg"><img src="./img/facebook.svg"></div> <div><input type="text" placeholder="Your E-mail"><button class="btn-red">Subscribe</button></div> </div> </footer> </body> <script> Array.from(document.querySelectorAll('.story')).forEach((e, i) => { let label = document.createElement('label'); label.appendChild(document.createTextNode((i + 1))); e.insertBefore(label, e.firstChild); }); </script> </html>
<template> <popup-view class="festival-business-popup" :show="show" :overlay="true" @clickmask="$emit('on-mask-click')"> <view class="festival-business-card"> <view class="festival-business-card__header"> 共{{business && business.length || 0}}家店铺可用 </view> <view class="festival-business-card__content"> <!-- 礼包商品列表 --> <view class="festival-business-list"> <view v-for="item in business" :key="item._id" class="festival-business-item"> <view class="festival-business-row"> <view class="festival-business-row__center"> <view class="festival-business-row__title"> {{item.name}} </view> <view class="festival-business-row__addr"> {{item.addr}} </view> </view> <view class="festival-business-row__left"> <view class="festival-business-row__btn-op is-nav" @click="handleBtnLocationClick(item)"> <view class="iconfont icon-daohang1"></view> </view> <view class="festival-business-row__btn-op is-phone" @click="handleBtnPhoneClick(item)"> <view class="iconfont icon-dianhua1"></view> </view> </view> </view> </view> </view> <!-- 礼包商品列表 end --> </view> </view> </popup-view> </template> <script> import App from '@/common/js/app.js' import PopupView from '@/components/template/PopManager.vue' export default { components: { PopupView }, props: { // 是否显示 show: { type: Boolean, default: false }, // 列表数据 business: { type: Array, default() { return [ // { // _id: '01', // name: '玉林串串香玉林串串香玉林串串香玉林串串香玉林串串香玉林串串香玉林串串香', // addr: '体育路与联盟路交叉路口凤凰奥斯卡2楼体育路与联盟路交叉路口凤凰奥斯卡2楼体育路与联盟路交叉路口凤凰奥斯卡2楼', // lat: 0, // long: 0, // phone: '' // } ] } } }, methods: { // 导航按钮点击事件 handleBtnLocationClick(item) { App.openLocation({ address: item.address, latitude: +item.lat, longitude: +item.long, success() { console.log('success') } }) }, // 电话按钮点击事件 handleBtnPhoneClick(item) { uni.makePhoneCall({ phoneNumber: item.phone }) } } } </script> <style lang="scss" scoped> .festival-business-card__header { display: flex; align-items: center; justify-content: center; height: 108rpx; font-weight: bold; color: #333; font-size: 32rpx; } .festival-business-card { position: relative; box-sizing: border-box; width: 690rpx; background-color: #fff; border-radius: 10rpx; } .festival-business-card__content { box-sizing: border-box; height: 500rpx; margin: 0 auto; padding: 0 30rpx; overflow-y: auto; } .festival-business-item { padding: 40rpx 0; border-bottom: 1px solid #EEEEEE; &:first-child { padding-top: 0; } &:last-child { border-bottom: none; } } .festival-business-row { display: flex; align-items: center; } .festival-business-row__center { min-width: 0; flex: 1; } .festival-business-row__title { font-weight: bold; font-size: 30rpx; color: #333; } .festival-business-row__addr { margin-top: 8rpx; font-size: 24rpx; color: #999; } .festival-business-row__left { display: flex; justify-content: space-between; margin-left: 60rpx; } .festival-business-row__btn-op { display: flex; align-items: center; justify-content: center; width: 54rpx; height: 54rpx; border-radius: 100%; background-color: #FCCA1E; .iconfont { line-height: 1; color: #333333; font-size: 28rpx; } &+& { margin-left: 40rpx; } } </style>
# Markdown Editor ## Description The Markdown Editor project is a web application designed to provide a user-friendly interface for writing and previewing Markdown-formatted text. Markdown is a lightweight markup language with plain-text formatting syntax, which can be converted to HTML or other rich text formats. The Markdown Editor allows users to compose Markdown text in a convenient editor pane and instantly preview the rendered HTML output in a separate pane, making it easy to create well-formatted documents, blog posts, README files, and more. ## Features - **Markdown Editor**: Provides a text editor interface where users can compose Markdown-formatted text using familiar syntax such as headers, lists, links, images, code blocks, and more. - **Live Preview**: Renders a real-time preview of the Markdown text as HTML, allowing users to see how the formatted content will appear in the final document. - **Syntax Highlighting**: Highlights Markdown syntax elements in the editor pane to improve readability and help users identify different parts of their document. - **Side-by-Side View**: Displays the Markdown editor and the live preview side by side or in separate tabs, giving users flexibility in their editing and previewing workflow. - **Fullscreen Mode**: Allows users to switch to fullscreen mode for distraction-free writing and editing, maximizing the available screen space for the editor and preview panes. - **Export to HTML**: Enables users to export the Markdown content as HTML code or download the rendered HTML file for use in other applications or publishing platforms. - **Import Markdown Files**: Supports importing existing Markdown files from local storage or external sources, allowing users to continue editing or previewing previously created documents. - **Customization Options**: Provides options for customizing the editor theme, font size, line height, and other preferences to suit individual user preferences and workflow. - **Keyboard Shortcuts**: Includes keyboard shortcuts for common Markdown formatting actions, navigation, and editor commands to improve productivity and streamline the editing experience. - **Syntax Guide**: Offers a built-in syntax guide or cheat sheet to help users learn Markdown syntax and discover available formatting options and conventions. - **Responsive Design**: The application is responsive and accessible on various devices, including desktops, tablets, and smartphones, ensuring a consistent user experience across different screen sizes. ## Technologies Used - **JavaScript**: For implementing dynamic functionality, handling user interactions, and updating the Markdown editor and preview panes. - **HTML**: For structuring the web page layout and embedding elements such as the editor textarea, preview pane, buttons, and menus within the document. - **CSS**: For styling the web page layout, including typography, colors, spacing, alignment, and visual aesthetics, to create an appealing and user-friendly interface. - **Markdown Parser**: Utilizes a Markdown parsing library or custom parser to convert Markdown text to HTML for live preview and exporting purposes. ## Setup To set up and run the Markdown Editor project: 1. **Clone the Repository**: Clone the project repository to your local machine using the following command: ```bash git clone <repository_url> ``` 2. **Navigate to the Project Directory**: Open your terminal or command prompt and navigate to the directory where you cloned the project. 3. **Open Index.html File**: Open the `index.html` file in your web browser or serve it using a local server (e.g., using VS Code's Live Server extension or Python's SimpleHTTPServer module). 4. **Start Writing Markdown**: Once the application is loaded, users can start writing Markdown text in the editor pane and see the live preview of the rendered HTML content in real-time. 5. **Explore and Enjoy**: Explore the Markdown syntax, experiment with different formatting options, preview the output, and create beautifully formatted documents with ease using the Markdown Editor. 6. **Provide Feedback**: Share your feedback, suggestions, or bug reports with the project maintainers to help improve the Markdown Editor application and make it more user-friendly and feature-rich. ---
import { closeObs, useDispatch, useSelector } from "@/lib/redux" import ObservationItem from "./obs-item" import Loading from "@/app/loading" export const ObservationsView = () => { const { observations, isLoadingObservations } = useSelector( (state) => state.places ) const { isObservationsHide } = useSelector((state) => state.ui) const dispatch = useDispatch() // if (isLoadingObservations) // return <Loading message="loading recent notable observations" /> let id = 0 return ( <div className={ "absolute top-2 md:top-4 right-4 max-h-[50vh] md:max-h-[70vh] w-80 md:w-[50vw] z-50 transition-opacity bg-white shadow-2xl overflow-y-scroll " + `${isObservationsHide ? "invisible" : ""}` } > {isLoadingObservations ? ( <Loading message="loading recent notable observations" /> ) : ( <> <div className="flex flex-row justify-between sticky top-0 bg-birdo-50 p-2"> <h1 className="text-birdo-700 text-xl font-extrabold sm:text-2xl text-lef "> Observations </h1> <button type="button" data-drawer-hide="drawer-example" aria-controls="drawer-example" className="text-birdo-800 bg-transparent hover:bg-birdo-accent-100 hover:text-birdo-accent-700 rounded-lg text-sm w-8 h-8 inline-flex items-center justify-center" onClick={() => dispatch(closeObs())} > <svg className="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14" > <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" /> </svg> <span className="sr-only">Close menu</span> </button> </div> {!(observations.length === 0) && ( <ul className="p-2 "> {observations.map((obs) => { id++ return ( <ObservationItem observation={obs} key={`${obs.subId}_${obs.obsDt}-${id}`} /> ) })} </ul> )} </> )} </div> ) }
import { ajax } from "rxjs/internal/ajax/ajax"; import { catchError, delay, map, mergeMap, Observable, of, timer } from "rxjs"; import { redirect } from "react-router-dom"; import { GetAjaxObservable, TokenType } from "./loginRequests"; import { getCookie } from "../Helpers/CookieHelper"; import { User, UserInput } from "../Types/User"; import { Post, PostInput } from "../Types/Post"; const url = "https://localhost:7295/graphql"; interface GraphqlPosts { posts: { posts: Post[] } } export function requestPosts(offset: Number, next: Number, order: String, user_timestamp: Date, categories?: number[]) { return GetAjaxObservable<GraphqlPosts>( `query($Input: GetPostsInput!){ posts{ posts(input: $Input){ id title text date_Created date_Edited user_Id user_Username likes comments liked } } }`, { "Input": { "offset": offset, "next": next, "order": order, "user_Timestamp": user_timestamp.toISOString(), "categories": categories } }, false ).pipe( map((value) => { return value.response.data.posts.posts; }), catchError((error) => { throw error }) ); } export function requestSearchedPosts(offset: Number, next: Number, user_timestamp: Date, search: string) { return GetAjaxObservable<GraphqlPosts>( `query($Input: GetSearchedPostsInput!){ posts{ posts:searchedPosts(input: $Input){ id title text date_Created date_Edited user_Id user_Username likes comments liked } } }`, { "Input": { "offset": offset, "next": next, "user_Timestamp": user_timestamp.toISOString(), "search": search } }, false ).pipe( map((value) => { return value.response.data.posts.posts; }), catchError((error) => { throw error }) ); } export function requestUserPosts(author_username: String, offset: Number, next: Number, order: String, user_timestamp: Date) { return GetAjaxObservable<GraphqlPosts>( `query($Input: GetUserPostsInput!){ posts{ posts:userPosts(input: $Input){ id title text date_Created date_Edited user_Id user_Username likes comments liked } } }`, { "Input": { "author_Username": author_username, "offset": offset, "next": next, "order": order, "user_Timestamp": user_timestamp.toISOString() } }, false ).pipe( map((value) => { return value.response.data.posts.posts; }), catchError((error) => { throw error }) ); } interface GraphqlPost { posts: { post: Post } } export function requestPostById(id: Number) { return GetAjaxObservable<GraphqlPost>( `query($Input: GetPostByIdInput!){ posts{ post(input: $Input){ id title text date_Created date_Edited user_Id categories{ id, title } user_Username likes comments liked } } }` , { "Input": { "id": id } }, false ).pipe( map((value) => { return value.response.data.posts.post; }), catchError((error) => { throw error }) ); } interface GraphqlCreatePost { post: { createPost: string } } export function createPostRequest(PostInput: PostInput) { return GetAjaxObservable<GraphqlCreatePost>(` mutation($Input: CreatePostInput!){ post{ createPost(input: $Input) } }`, { "Input": { "title": PostInput.title, "text": PostInput.text } } ).pipe( map((value) => { if (value.response.errors) { throw new Error(value.response.errors[0].message); } return value.response.data.post.createPost; }), catchError((error) => { throw error }) ); } interface GraphqlUpdatePost { post: { updatePost: string } } export function updatePostRequest(text: String, id: Number) { return GetAjaxObservable<GraphqlUpdatePost>(` mutation($Input: UpdatePostInput!){ post{ updatePost(input: $Input) } }`, { "Input": { "text": text, "id": id } } ).pipe( map((value) => { if (value.response.errors) { throw new Error(value.response.errors[0].message); } return value.response.data.post.updatePost; }), catchError((error) => { throw error }) ); } interface GraphqlAddPostCategory { post: { addPostCategory: string } } export function addPostCategoryRequest(post_id: number, category_id: number) { return GetAjaxObservable<GraphqlAddPostCategory>(` mutation($Input: AddPostCategoryInput!){ post{ addPostCategory(input: $Input) } }`, { "Input": { "post_Id": post_id, "category_Id": category_id } } ).pipe( map((value) => { if (value.response.errors) { throw new Error(value.response.errors[0].message); } return value.response.data.post.addPostCategory; }), catchError((error) => { throw error }) ); } interface GraphqlRemovePostCategory { post: { removePostCategory: string } } export function removePostCategoryRequest(post_id: number, category_id: number) { return GetAjaxObservable<GraphqlRemovePostCategory>(` mutation($Input: RemovePostCategoryInput!){ post{ removePostCategory(input: $Input) } }`, { "Input": { "post_Id": post_id, "category_Id": category_id } } ).pipe( map((value) => { if (value.response.errors) { throw new Error(value.response.errors[0].message); } return value.response.data.post.removePostCategory; }), catchError((error) => { throw error }) ); } interface GraphqlDeletePost { post: { deletePost: string } } export function deletePostRequest(id: Number) { return GetAjaxObservable<GraphqlDeletePost>(` mutation($Input: DeletePostInput!){ post{ deletePost(input: $Input) } }`, { "Input": { "id": id } } ).pipe( map((value) => { if (value.response.errors) { throw new Error(value.response.errors[0].message); } return value.response.data.post.deletePost; }), catchError((error) => { throw error }) ); } interface GraphqlLikePost { post: { likePost: string } } export function likePostRequest(id: Number) { return GetAjaxObservable<GraphqlLikePost>(` mutation($Input: LikePostInput!){ post{ likePost(input: $Input) } }`, { "Input": { "post_Id": id } } ).pipe( map((value) => { if (value.response.errors) { throw new Error(value.response.errors[0].message); } return value.response.data.post.likePost; }), catchError((error) => { throw error }) ); }
<template> <div class="container" style="background-color: #eef0f5"> <div class="main-container"> <div class="container-a"> <div class="title">快速入口</div> <div class="content"> <el-button type="primary">创建节点组</el-button> <el-button type="primary">购买节点</el-button> <el-button type="primary">管理节点组</el-button> <el-button type="primary">管理会话</el-button> </div> </div> <div class="container-b"> <div class="title">数据监控</div> <div class="content"> <div class="sub-container"> <div class="sub-title">节点组</div> <div class="sub-content">0</div> </div> <div class="sub-container"> <div class="sub-title">我购买的节点</div> <div class="sub-content">0</div> </div> <div class="sub-container"> <div class="sub-title">会话</div> <div class="sub-content">0</div> </div> </div> </div> <div class="container-c"> <div class="title">数据监控</div> <el-table :data="tableData" :columns="columnData"></el-table> </div> </div> </div> </template> <script> export default { data() { return { columnData: [ { title: "节点名称", field: "nodeName" }, { title: "实例名称", field: "instanceName" }, { title: "使用占比", field: "usagePercentage" }, ], tableData: [ { nodeName: "节点1", instanceName: "实例1", usagePercentage: "50%" }, { nodeName: "节点2", instanceName: "实例2", usagePercentage: "30%" }, { nodeName: "节点3", instanceName: "实例3", usagePercentage: "20%" }, ], }; }, }; </script> <style scoped> .container { display: flex; justify-content: center; background-color: #eef0f5; padding: 24px; } .main-container { display: flex; flex-direction: column; width: 50vw; } .container div { padding: 16px; background-color: #ffffff; } .container .title { font-weight: bold; font-size: 20px; } .container .content { display: flex; justify-content: space-between; margin-top: 48px; } .container .content el-button { margin-right: 24px; } .container .sub-container { display: flex; justify-content: space-between; margin-top: 16px; background-color: #e9edfa; width: 200px; height: 60px; padding: 16px; } .container .sub-container .sub-title { font-weight: bold; } .container-c .title { font-weight: bold; font-size: 20px; margin-bottom: 16px; } .el-table { width: 100%; } </style>
import { faCircleXmark } from "@fortawesome/free-solid-svg-icons" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import "../reserve/reserve.css" import useFetch from "../hook/useFetch" import { useContext, useState } from "react" import { SearchContext } from "../../context/searchContext" import axios from "axios" import { useNavigate } from "react-router-dom" const Reserve = ({ setOpen, hotelId }: any) => { const { data, loading, error } = useFetch(`/hotels/room/${hotelId}`); const [selectRooms, setSelectRooms] = useState<any>([]) const { dates } = useContext<any>(SearchContext) const navigate = useNavigate() const getDatesInRange = (startDate: any, endDate: any) => { const start = new Date(startDate); const end = new Date(endDate); const date = new Date(start.getTime()); const dates = []; while (date <= end) { dates.push(new Date(date).getTime()); date.setDate(date.getDate() + 1); } return dates; }; const alldates = getDatesInRange(dates[0].startDate, dates[0].endDate) const isAvailable = (roomNumber: any) => { const isFound = roomNumber.unavailableDates.some((date: any) => alldates.includes(new Date(date).getTime()) ); return !isFound } const handleSelect = (e: any) => { const checked = e.target.checked const value = e.target.value setSelectRooms(checked ? [...selectRooms, value] : selectRooms.filter((item: any) => item !== value)) } const handleClick = async () => { try { await Promise.all(selectRooms.map((roomId: any) => { const res: any = axios.put(`/rooms/availability/${roomId}`, { dates: alldates }) return res.data })) setOpen(false) navigate("/") } catch (err) { } } return ( <div className="reserve"> <div className="rContainer"> <FontAwesomeIcon icon={faCircleXmark} className="rClose" onClick={() => setOpen(false)} /> <span>Select your rooms:</span> {data.map((item: any) => ( <div className="rItem" key={item._id}> <div className="rItemInfo"> <div className="rTitle">{item.title}</div> <div className="rDesc">{item.desc}</div> <div className="rMax"> Max people: <b>{item.maxPeople}</b> </div> <div className="rPrice">{item.price}</div> </div> <div className="rSelectRooms"> {item.roomNumbers.map((roomNumber: any, index: any) => ( <div className="room" key={index}> <label>{roomNumber.number}</label> <input type="checkbox" value={roomNumber._id} onChange={handleSelect} disabled={!isAvailable(roomNumber)} /> </div> ))} </div> </div> ))} <button onClick={handleClick} className="rButton">Reserve Now!</button> </div> </div> ) } export default Reserve
// // NetworkManager.swift // gallery // // Created by Павел Кривцов on 19.09.2021. // import UIKit enum NetworkResult<Error> { case success case failure(Error) } enum NetworkResponse: String, Error { case authenticationError = "Authentication error" case badRequest = "Bad request" case outdated = "Outdated" case failed = "Failed" case noData = "No data" case unableToDecode = "Unable to decode" } protocol NetworkManagerOutput: AnyObject { func cancelDownloadTask() func getPhotos(from page: Int, onCompletion: @escaping (Result<[Photo], NetworkResponse>) -> Void) func getFoundPhotos(from page: Int, from searchText: String, onCompletion: @escaping (Result<[Photo], NetworkResponse>) -> Void) func getTotalPhotosNumber(from searchText: String, onCompletion: @escaping(Int) -> Void) func getSelectedPhoto(by id: String, onCompletion: @escaping (Result<Photo, NetworkResponse>) -> Void) func downloadPhoto(photo: Photo) func downloadImage(url: URL, onCompletion: @escaping(Result<UIImage, NetworkResponse>) -> Void) } class NetworkManager: NSObject { weak var presenter: NetworkServiceInput? private var task : URLSessionTask? private var imageCache = NSCache<NSString, UIImage>() private func taskResume<T: Decodable>(from request: URLRequest, type: T.Type, onCompletion: @escaping(Result<T, NetworkResponse>) -> Void) { task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in DispatchQueue.main.async { guard let `self` = self else { return } if error != nil { onCompletion(.failure(NetworkResponse.failed)) } if let response = response as? HTTPURLResponse { let result = self.handleNetworkResponse(response) switch result { case .success: guard let responseData = data else { onCompletion(.failure(NetworkResponse.noData)) return } do { let apiResponse = try JSONDecoder().decode(type, from: responseData) onCompletion(.success(apiResponse)) } catch { onCompletion(.failure(NetworkResponse.unableToDecode)) } case .failure(let failureError): onCompletion(.failure(failureError)) } } } } task?.resume() } private func createRequest(from url: URL) -> URLRequest? { guard let clientId = getEnvironmentVar("API_KEY") else { return nil } var request = URLRequest(url: url) request.addValue(clientId, forHTTPHeaderField: "Authorization") request.httpMethod = "GET" return request } private func handleNetworkResponse(_ response: HTTPURLResponse) -> NetworkResult<NetworkResponse> { switch response.statusCode { case 200...299 : return .success case 401...500 : return .failure(NetworkResponse.authenticationError) case 501...599 : return .failure(NetworkResponse.badRequest) case 600 : return .failure(NetworkResponse.outdated) default: return .failure(NetworkResponse.failed) } } private func getEnvironmentVar(_ name: String) -> String? { guard let rawValue = getenv(name) else { return nil } return String(utf8String: rawValue) } } extension NetworkManager: NetworkManagerOutput { func getPhotos(from page: Int, onCompletion: @escaping (Result<[Photo], NetworkResponse>) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "api.unsplash.com" urlComponents.path = "/photos" urlComponents.queryItems = [URLQueryItem(name: "page", value: "\(page)"), URLQueryItem(name: "per_page", value: "30"), URLQueryItem(name: "order_by", value: "popular")] guard let url = urlComponents.url, let request = self.createRequest(from: url) else { onCompletion(.failure(NetworkResponse.failed)) return } taskResume(from: request, type: [Photo].self) { result in switch result { case .success(let photos): onCompletion(.success(photos)) case .failure(let failureError): onCompletion(.failure(failureError)) } } } func getFoundPhotos(from page: Int, from searchText: String, onCompletion: @escaping (Result<[Photo], NetworkResponse>) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "api.unsplash.com" urlComponents.path = "/search/photos" urlComponents.queryItems = [URLQueryItem(name: "page", value: "\(page)"), URLQueryItem(name: "query", value: "\(searchText)"), URLQueryItem(name: "per_page", value: "30")] guard let url = urlComponents.url, let request = self.createRequest(from: url) else { onCompletion(.failure(NetworkResponse.failed)) return } taskResume(from: request, type: SearchResults.self) { result in switch result { case .success(let searchResults): onCompletion(.success(searchResults.results)) case .failure(let failureError): onCompletion(.failure(failureError)) } } } func getTotalPhotosNumber(from searchText: String, onCompletion: @escaping(Int) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "api.unsplash.com" urlComponents.path = "/search/photos" urlComponents.queryItems = [URLQueryItem(name: "query", value: "\(searchText)")] guard let url = urlComponents.url, let request = self.createRequest(from: url) else { return } taskResume(from: request, type: SearchResults.self) { result in switch result { case .success(let searchResults): onCompletion(searchResults.total) case .failure(_): break } } } func getSelectedPhoto(by id: String, onCompletion: @escaping (Result<Photo, NetworkResponse>) -> Void) { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "api.unsplash.com" urlComponents.path = "/photos/\(id)" guard let url = urlComponents.url, let request = self.createRequest(from: url) else { onCompletion(.failure(NetworkResponse.failed)) return } taskResume(from: request, type: Photo.self) { result in switch result { case .success(let photo): onCompletion(.success(photo)) case .failure(let failureError): onCompletion(.failure(failureError)) } } } func downloadImage(url: URL, onCompletion: @escaping(Result<UIImage, NetworkResponse>) -> Void ) { if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) { onCompletion(.success(cachedImage)) } else { let request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad) let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in guard let `self` = self else { return } DispatchQueue.main.async { if error != nil { onCompletion(.failure(NetworkResponse.failed)) } if let response = response as? HTTPURLResponse { let result = self.handleNetworkResponse(response) switch result { case .success: guard let responseData = data, let image = UIImage(data: responseData) else { onCompletion(.failure(NetworkResponse.noData)) return } onCompletion(.success(image)) case .failure(let failureError): onCompletion(.failure(failureError)) } } } } task.resume() } } func downloadPhoto(photo: Photo) { let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) guard let clientId = getEnvironmentVar("API_KEY"), let url = URL(string: photo.urls.raw) else { return } var request = URLRequest(url: url) request.addValue(clientId, forHTTPHeaderField: "Authorization") request.httpMethod = "GET" task = session.downloadTask(with: request) task?.resume() } func cancelDownloadTask() { task?.cancel() } } // MARK: - URLSessionDownloadDelegate extension NetworkManager: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let data = try? Data(contentsOf: location) else { DispatchQueue.main.async { self.presenter?.failedDownloadPhoto() } return } DispatchQueue.main.async { self.presenter?.savePhoto(from: data) } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) DispatchQueue.main.async { self.presenter?.trackDownloadProgress(progress: progress) } } }
package br.edu.ufcg.virtus.tracker.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.logging.log4j.util.Strings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import br.edu.ufcg.virtus.common.exception.BusinessException; import br.edu.ufcg.virtus.common.service.CrudService; import br.edu.ufcg.virtus.tracker.enums.AttributeType; import br.edu.ufcg.virtus.tracker.model.Attribute; import br.edu.ufcg.virtus.tracker.model.TrackerModel; import br.edu.ufcg.virtus.tracker.repository.AttributeRepository; @Service public class AttributeService extends CrudService<Attribute, Integer> { @Autowired private AttributeRepository repository; @Autowired private AttributeValueService attributeValueService; private final int STRING_MIN_LENGTH = 1; private final int STRING_MAX_LENGTH = 255; @Override protected AttributeRepository getRepository() { return this.repository; } public void insertMultipleAttributesFromTrackerModel(TrackerModel model) throws BusinessException { if (model.getAttributes() != null && !model.getAttributes().isEmpty()) { this.collectRelatedAttributeEntities(model); final List<Attribute> attributesWithoutRelationship = model.getAttributes().stream() .filter(attribute -> attribute.getRelatedAttribute() == null).collect(Collectors.toList()); final List<Attribute> persistedAttributes = new ArrayList<>(); for (final Attribute attribute : attributesWithoutRelationship) { this.saveAttribute(model, attribute, this.getAttributeRelationships(model.getAttributes()), persistedAttributes, model.getAttributes()); } } } private void collectRelatedAttributeEntities(TrackerModel model) { model.getAttributes().stream().forEach(attribute -> { if (attribute.getRelatedAttribute() != null) { final Attribute attributeEntity = model.getAttributes().stream().filter(attributeSearch -> attributeSearch.getTitle().equals(attribute.getRelatedAttribute().getTitle())).findFirst().orElse(null); attribute.setRelatedAttribute(attributeEntity); } }); } private void saveAttribute(TrackerModel model, Attribute attribute, Map<Attribute, List<Attribute>> attributeRelationships, List<Attribute> persistedAttributes, List<Attribute> allAttributes) throws BusinessException { if (!persistedAttributes.contains(attribute)) { if (!attribute.isDeleted()) { this.validateRequiredFields(attribute, model.getId(), allAttributes); this.validateAttributeType(attribute); } attribute.setTrackerModel(model); this.repository.save(attribute); persistedAttributes.add(attribute); for (final Attribute attributeRelationship : attributeRelationships.get(attribute)) { this.saveAttribute(model, attributeRelationship, attributeRelationships, persistedAttributes, allAttributes); } } } private Map<Attribute, List<Attribute>> getAttributeRelationships(List<Attribute> attributes) { final Map<Attribute, List<Attribute>> attributeRelationships = new HashMap<>(); attributes.forEach(attribute -> { final List<Attribute> childAttributes = attributes.stream() .filter(childAttribute -> childAttribute.getRelatedAttribute() != null ? childAttribute.getRelatedAttribute().getTitle().equals(attribute.getTitle()) : false) .collect(Collectors.toList()); attributeRelationships.put(attribute, childAttributes); }); return attributeRelationships; } @Override public void delete(Integer id) throws BusinessException { if (!this.repository.existsById(id)) { throw new BusinessException("tracker-model.attribute.not.found", HttpStatus.BAD_REQUEST); } this.attributeValueService.deleteByAttributeId(id); this.repository.deleteById(id); } public String getCurrencyByAttributeNameAndTrackerModel(Integer trackerModelId, String attributeName) { return this.repository.getCurrencyByAttributeNameAndTrackerModel(trackerModelId, attributeName); } private void validateRequiredFields(Attribute attribute, Integer trackerModelId, List<Attribute> allAttributes) throws BusinessException { if (attribute.getType() == null) { throw new BusinessException("tracker-model.attribute.type.empty", HttpStatus.BAD_REQUEST); } if (Strings.isBlank(attribute.getTitle())) { throw new BusinessException("tracker-model.attribute.name.empty", HttpStatus.BAD_REQUEST); } boolean exists = false; Attribute attributeWithName = this.repository.getByTitleAndTrackerModelIdAndDeletedFalse(attribute.getTitle(), trackerModelId); if (attributeWithName != null) { exists = allAttributes.stream().anyMatch(att -> att.getId() != attribute.getId() && att.getId() == attributeWithName.getId() && att.getTitle() == attribute.getTitle()); } if (exists) { throw new BusinessException("tracker-model.attribute.name.exists", HttpStatus.BAD_REQUEST); } } private void validateAttributeType(Attribute attribute) throws BusinessException { switch (attribute.getType()) { case INTEGER: case DECIMAL: this.validateNumberType(attribute); break; case STRING: this.validateStringType(attribute); break; case LIST: this.validateListType(attribute); break; case DATE: this.validateDateType(attribute); break; default: break; } } private void validateNumberType(Attribute attribute) throws BusinessException { if (attribute.getMinValue() != null && attribute.getMaxValue() != null && attribute.getMinValue() > attribute.getMaxValue()) { if (AttributeType.INTEGER.equals(attribute.getType())) { throw new BusinessException("tracker-model.attribute.type.integer.min-greater-than-max", HttpStatus.BAD_REQUEST); } else { throw new BusinessException("tracker-model.attribute.type.decimal.min-greater-than-max", HttpStatus.BAD_REQUEST); } } } private void validateStringType(Attribute attribute) throws BusinessException { if (attribute.getMaxLength() < this.STRING_MIN_LENGTH) { throw new BusinessException("tracker-model.attribute.type.string.min-length", HttpStatus.BAD_REQUEST); } if (attribute.getMaxLength() > this.STRING_MAX_LENGTH) { throw new BusinessException("tracker-model.attribute.type.string.max-length", HttpStatus.BAD_REQUEST); } } private void validateListType(Attribute attribute) throws BusinessException { if (Strings.isBlank(attribute.getListValues())) { throw new BusinessException("tracker-model.attribute.type.list.options-empty", HttpStatus.BAD_REQUEST); } } private void validateDateType(Attribute attribute) throws BusinessException { if (attribute.getMinDate() != null && attribute.getMaxDate() != null && attribute.getMinDate().getTimeInMillis() > attribute.getMaxDate().getTimeInMillis()) { throw new BusinessException("tracker-model.attribute.type.date.min-greater-than-max", HttpStatus.BAD_REQUEST); } } }
package com.alkemy.ong.data.entities; import lombok.*; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.UpdateTimestamp; import org.hibernate.annotations.Where; import javax.persistence.*; import java.time.LocalDateTime; @Entity @Table(name = "users") @SQLDelete(sql = "UPDATE users SET deleted=true WHERE id=?") @Where(clause = "deleted = false") @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Builder public class UserEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id private Long id; @Column(name = "first_name", nullable = false) private String firstName; @Column(name = "last_name",nullable = false) private String lastName; @Column(unique = true) private String email; @Column(nullable = false) private String password; private String photo; @OneToOne @JoinColumn(name = "role_id") private RoleEntity roleId; @Column(name = "updated_at") @UpdateTimestamp private LocalDateTime updatedAt; @Column(name = "created_at") @CreationTimestamp private LocalDateTime createdAt; private boolean deleted = false; }
from typing import List from math import inf from SBSim import ( VacuumCleaner, STAY, MOVE, CLEN, CHAR, ) from SBSim.base import UserMap ''' WARNING Do not change def name, arguments and return. --- ''' class UserRobot(VacuumCleaner): def __init__( self, fuel: int = 100, energy_consumption: int = 10, move_consumption: int = 10, postion: List[int] = ..., vision_sight: int = 2 ) -> None: super().__init__( fuel=fuel, energy_consumption=energy_consumption, move_consumption=move_consumption, postion=postion, vision_sight=vision_sight ) ''' If you want to store some values, define your variables here. Using `self`-based variables, you can re-call the value of previous state easily. ''' self.dir_x = 0 self.dir_y = 0 def algorithms( self, grid_map: UserMap ): ''' You can code your algorithm using robot.position and map.information. The following introduces accessible data; 1) the position of robot, 2) the information of simulation map. Here, you should build an algorithm that determines the next action of the robot. Robot:: - position (list-type) : (x, y) - mode (int-type) :: You can determine robot state using 'self.mode', and we provide 4-state. (STAY, MOVE, CLEN, CHAR) Example:: 1) You want to move the robot to target position. >>> self.mode = MOVE 2) Clean-up tail. >>> self.mode = CLEN map:: - grid_map : grid_map.height : the value of height of map. Example:: >>> print( grid_map.height ) grid_map.width : the value of width of map. Example:: >>> print( grid_map.width ) grid_map[ <height/y> ][ <width/x> ] : the data of map, it consists of 2-array. - grid_map[<h>][<w>].req_energy : the minimum energy to complete cleaning. It is assigned randomly, and it is int-type data. - grid_map[<h>][<w>].charger : is there a charger in this tile? boolean-type data. Example:: >>> x = self.position.x >>> y = self.position.y >>> print( grid_map[y][x].req_energy ) >>> if grid_map[y][x].req_energy > 0: >>> self.mode = CLEN Tip:: - Try to avoid loop-based codes such as `while` as possible. It will make the problem harder to solve. ''' robot_x = self.position.x robot_y = self.position.y self.max_h = grid_map.height - 1 self.max_w = grid_map.width - 1 if self.mode == STAY: self.mode = MOVE self.dir_x = 1 self.dir_y = 0 if position == (8, 8) self.mode = CHAR if robot_x == self.max_w - 1: self.dir_x = 1 self.dir_y = 0 if grid_map.map[robot_y][robot_x].req_energy == 10: self.mode = MOVE else: self.mode = CLEN if robot_x == self.max_w - 1: self.dir_x = -1 self.dir_y = 0 if grid_map.map[robot_y][robot_x].req_energy == 10: self.mode = MOVE else: self.mode = CLEN if robot_y == self.max_h - 1: self.dir_x = 0 self.dir_y = 1 if grid_map.map[robot_y][robot_x].req_energy == 10: self.mode = MOVE else: self.mode = CLEN if robot_y == self.max_h - 1: self.dir_x = 0 self.dir_y = -1 if grid_map.map[robot_y][robot_x].req_energy == 10: self.mode = MOVE else: self.mode = CLEN if robot_x == 1 and robot_y == self.max_h - 1: self.dir_x = 0 self.dir_y = -1 if grid_map.map[robot_y][robot_x].req_energy == 10: self.mode = MOVE else: self.mode = CLEN if robot_x == self.max_w - 1 and robot_y == self.max_h - 1: self.dir_x = -1 self.dir_y = 0 if grid_map.map[robot_y][robot_x].req_energy == 10: self.mode = MOVE else: self.mode = CLEN if robot_x == 1 and robot_y == 1: self.dir_x = 1 self.dir_y = 0
import { Grid, IconButton, Paper, Typography, Container } from "@material-ui/core"; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import { useHistory } from "react-router-dom"; import { makeStyles } from "@material-ui/core/styles"; import "firebase/auth"; import { useEffect } from "react"; import { useState } from "react"; import firebase from "firebase/app"; import firestore from "./firestore.js"; import { Button, Switch } from "@mui/material"; import Backdrop from '@material-ui/core/Backdrop'; import CircularProgress from '@material-ui/core/CircularProgress'; const useStyles = makeStyles((theme) => ({ paper: { display: 'flex', textAlign: "left", flexDirection: 'column', padding: theme.spacing(2), marginTop: theme.spacing(2), }, backdrop: { zIndex: theme.zIndex.drawer + 1, color: '#fff', display: "flex", flexDirection: "column", } })); function Settings() { const classes = useStyles() const history = useHistory(); const [use12HourClock, setUse12HourClock] = useState(localStorage.getItem("use12HourClock") === "true"); const [returning, setReturning] = useState(false); const [autoCalculateLunch, setAutoCalculateLunch] = useState(localStorage.getItem("autoCalculateLunch") === "true"); const [backgroundColor, setBackgroundColor] = useState(localStorage.getItem("backgroundColor") === null || localStorage.getItem("backgroundColor") === "" ? "#ffffff" : localStorage.getItem("backgroundColor")); const handle12HourClockChange = (event) => { setUse12HourClock(event.target.checked); } function handleAutoCalculateLunchChange(event) { setAutoCalculateLunch(event.target.checked); } function goBack() { setReturning(true); firestore.db.collection("users").doc(localStorage.getItem('uid')).set({use12HourClock: use12HourClock, backgroundColor: backgroundColor, autoCalculateLunch: autoCalculateLunch}, {merge: true}).then(() => { history.push("/") window.location.reload(); }) } useEffect(() => { firebase.auth().onAuthStateChanged((user) => { if (!user) { localStorage.clear() window.location.href = "/signin"; } }) }, []) return ( <div className="App" style={{backgroundColor: backgroundColor}}> <Backdrop className={classes.backdrop} open={returning}> <CircularProgress color="inherit" /> <h1>Saving</h1> </Backdrop> <header className="App-header"> <Grid container direction="row" alignItems="center" justify="center"> <Grid item align="center"><IconButton onClick={goBack} style={{ color: "white" }} title="Save and go back"><ArrowBackIcon /></IconButton></Grid> <Grid item style={{ marginLeft: 10, marginRight: 10 }} align="center"> <h3>Settings</h3> </Grid> </Grid> </header> <Container maxWidth='sm'> <Paper className={classes.paper} elevation={3} variant="outlined" style={{backgroundColor: "#f0f9ff"}}> <Grid container direction="row" alignItems="center"> <Grid item align="left" xs={10}>Use 12-hour time format</Grid> <Grid item align="right" xs={2}><Switch checked={use12HourClock} onChange={handle12HourClockChange}></Switch></Grid> </Grid> <Grid container direction="row" alignItems="center"> <Grid item align="left" xs={10}>Auto Calculate Lunch</Grid> <Grid item align="right" xs={2}><Switch checked={autoCalculateLunch} onChange={handleAutoCalculateLunchChange}></Switch></Grid> </Grid> <Grid container direction="row" alignItems="center"> <Grid item align="left" xs={10}>App Background Color</Grid> <Grid item align="right" xs={2}><input type="color" value={backgroundColor} onChange={e => {setBackgroundColor(e.target.value)}}/></Grid> </Grid> </Paper> </Container> </div> ); } export default Settings;
import '@tarojs/async-await' import Taro, { Component } from '@tarojs/taro' import { Provider } from '@tarojs/redux' import Index from './pages/index' import configStore from './store' import './app.scss' // 如果需要在 h5 环境中开启 React Devtools // 取消以下注释: // if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5') { // require('nerv-devtools') // } const store = configStore() class App extends Component { config = { pages: [ 'pages/index/index', 'pages/pwd-create/index', 'pages/pwd-preview/index', 'pages/pwd-store/index', ], window: { backgroundTextStyle: 'light', navigationBarBackgroundColor: '#fff', navigationBarTitleText: '六娃', navigationBarTextStyle: 'black' }, tabBar: { color: "#666", selectedColor: "#b4282d", backgroundColor: "#fafafa", borderStyle: 'black', list: [{ pagePath: "pages/index/index", // iconPath: "./assets/tab-bar/home.png", // selectedIconPath: "./assets/tab-bar/home-active.png", text: "首页" }, { pagePath: "pages/pwd-store/index", // iconPath: "./assets/tab-bar/cate.png", // selectedIconPath: "./assets/tab-bar/cate-active.png", text: "密码仓库" }, { pagePath: "pages/pwd-preview/index", // iconPath: "./assets/tab-bar/cart.png", // selectedIconPath: "./assets/tab-bar/cart-active.png", text: "解锁密码箱" }, { pagePath: "pages/pwd-create/index", // iconPath: "./assets/tab-bar/user.png", // selectedIconPath: "./assets/tab-bar/user-active.png", text: "锻造密码箱" }] } } componentDidMount () {} componentDidShow () {} componentDidHide () {} componentCatchError () {} componentDidCatchError () {} // 在 App 类中的 render() 函数没有实际作用 // 请勿修改此函数 render () { return ( <Provider store={store}> <Index /> </Provider> ) } } Taro.render(<App />, document.getElementById('app'))
/* * Copyright (c) 2007-2011 by Stefan Laubenberger. * * Bogatyr is free software: you can redistribute it and/or modify * it under the terms of the General Public License v2.0. * * Bogatyr is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details: * <http://www.gnu.org/licenses> * * This distribution is available at: * <http://code.google.com/p/bogatyr/> * <http://dev.laubenberger.net/bogatyr/> * * Contact information: * Stefan Laubenberger * Bullingerstrasse 53 * CH-8004 Zuerich * * <http://www.laubenberger.net> * * <[email protected]> */ package net.laubenberger.bogatyr.misc.xml.adapter; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.xml.bind.annotation.adapters.XmlAdapter; import net.laubenberger.bogatyr.misc.xml.XmlEntry; import net.laubenberger.bogatyr.misc.xml.XmlMap; /** * Map adapter for the key {@link String} and value {@link Map} (multi map). * * @author Stefan Laubenberger * @version 0.9.4 (20101227) * @since 0.9.2 */ public class MapAdapterMap extends XmlAdapter<XmlMap, Map<String, Map<String, String>>> { /* * Overridden methods */ @Override public XmlMap marshal(final Map<String, Map<String, String>> map) throws Exception { if (null != map) { final XmlMap xmlMap = new XmlMap(); for (final Entry<String, Map<String, String>> entry : map.entrySet()) { for (final Entry<String, String> item : entry.getValue().entrySet()) { xmlMap.getEntries().add(new XmlEntry(entry.getKey(), item.getKey(), item.getValue())); } } return xmlMap; } return null; } @Override public Map<String, Map<String, String>> unmarshal(final XmlMap xmlMap) throws Exception { if (null != xmlMap) { final Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); for (final XmlEntry entry : xmlMap.getEntries()) { Map<String, String> items = map.get(entry.getId()); if (null == items) { items = new HashMap<String, String>(); } items.put(entry.getKey(), entry.getValue()); map.put(entry.getId(), items); } return map; } return null; } }
import { LocalStorage } from 'quasar' import {mapActions, mapGetters} from 'vuex' export const defaultMixin = { data() { return { roles: null, user_id: null, accessToken: null, baseURL: 'http://localhost:4000/api' } }, methods: { ...mapActions('auth', ['restoreState']), axiosAuth () { this.roles = LocalStorage.getItem(`${process.env.APP_MACHINE_NAME}-auth`)?.roles; this.user_id = LocalStorage.getItem(`${process.env.APP_MACHINE_NAME}-auth`)?.user_id; this.accessToken = LocalStorage.getItem(`${process.env.APP_MACHINE_NAME}-auth`)?.token; if (this.accessToken) { let token = LocalStorage.getItem(`${process.env.APP_MACHINE_NAME}-auth`).token this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token } } }, computed: { ...mapGetters('auth', ['fName']), appName () { return process.env.APP_NAME }, isUser() { return this.roles && this.roles.includes('user') }, isAdmin() { return this.roles && this.roles.includes('admin') }, }, created () { this.axiosAuth() // if the browser has been reloaded, restore application state from localstorage this.restoreState() }, } export const myLoading = { methods: { loadingShow (component) { this[component].loading = true }, loadingHide (component) { this[component].loading = false } } }
package automation.example.demo.features.youtube.ui.pages; import org.openqa.selenium.By; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import automation.example.demo.drivermanager.DriverManager; import automation.example.demo.pageobject.MobileObject; import io.appium.java_client.AppiumBy; import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.iOSXCUITFindBy; import io.qameta.allure.Step; public class YoutubeHomePage extends MobileObject { @AndroidFindBy(xpath = "//android.widget.ImageView[@content-desc=\"Search\"]") @iOSXCUITFindBy(accessibility = "id.ui.navigation.search.button") WebElement searchIcon; @AndroidFindBy(id = "com.google.android.youtube:id/search_edit_text") @iOSXCUITFindBy(id = "id.navigation.search.text_field") WebElement searchBar; public By suggestionList(int index) { Platform platform = DriverManager.getMobilePlatform(driver); if (platform.equals(Platform.ANDROID)) { return AppiumBy.xpath(String.format("(//android.widget.TextView)[%s]", index)); } else { return AppiumBy.xpath(String.format("ios[%s]", index)); } } public By suggestionList(String itemName) { Platform platform = DriverManager.getMobilePlatform(driver); if (platform.equals(Platform.ANDROID)) { return AppiumBy.xpath(String.format("(//android.widget.TextView)[@text='%s']", itemName)); } else { return AppiumBy.xpath(String.format("//XCUIElementTypeStaticText[@name='%s, Search suggestion']", itemName)); } } public YoutubeHomePage(WebDriver driver) { super(driver); } @Step("Search for keyword") public void searchFor(String keyword) { clickOn(searchIcon); enter(searchBar, keyword); } @Step("Choose an item from suggestion list") public void chooseAnItemFromSuggestionList(int index) { waitUntilElementVisible(suggestionList(index), 30); clickOn(suggestionList(index)); } public void chooseAnItemFromSuggestionList(String itemName) { waitUntilElementVisible(suggestionList(itemName), 30); clickOn(suggestionList(itemName)); } }
package uk.gov.hmcts.juror.api.moj.controller.response.expense; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; class CombinedSimplifiedExpenseDetailDtoTest { @Test void positiveCombinedSimplifiedExpenseDetailConstructor() { CombinedSimplifiedExpenseDetailDto combinedSimplifiedExpenseDetailDto = new CombinedSimplifiedExpenseDetailDto(); assertThat(combinedSimplifiedExpenseDetailDto.getExpenseDetails()).isNotNull(); assertThat(combinedSimplifiedExpenseDetailDto.getTotal()).isNotNull(); } @Test void positiveAddExpenseDetail() { CombinedSimplifiedExpenseDetailDto combinedSimplifiedExpenseDetailDto = new CombinedSimplifiedExpenseDetailDto(); CombinedSimplifiedExpenseDetailDto.Total total = mock(CombinedSimplifiedExpenseDetailDto.Total.class); combinedSimplifiedExpenseDetailDto.setTotal(total); SimplifiedExpenseDetailDto simplifiedExpenseDetailDto = mock(SimplifiedExpenseDetailDto.class); combinedSimplifiedExpenseDetailDto.addSimplifiedExpenseDetailDto(simplifiedExpenseDetailDto); verify(total, times(1)).add(simplifiedExpenseDetailDto); assertThat(combinedSimplifiedExpenseDetailDto.getExpenseDetails()).hasSize(1) .contains(simplifiedExpenseDetailDto); } @Nested class TotalTest { @Test void positiveTotalConstructor() { CombinedSimplifiedExpenseDetailDto.Total total = new CombinedSimplifiedExpenseDetailDto.Total(); assertThat(total.getTotalAttendances()).isZero(); assertThat(total.getFinancialLoss()).isZero(); assertThat(total.getTravel()).isZero(); assertThat(total.getFoodAndDrink()).isZero(); assertThat(total.getSmartcard()).isZero(); assertThat(total.getTotalDue()).isZero(); assertThat(total.getTotalPaid()).isZero(); assertThat(total.getBalanceToPay()).isZero(); } @Test void positiveAdd() { final CombinedSimplifiedExpenseDetailDto.Total total = new CombinedSimplifiedExpenseDetailDto.Total(); SimplifiedExpenseDetailDto simplifiedExpenseDetailDto = new SimplifiedExpenseDetailDto(); simplifiedExpenseDetailDto.setFinancialLoss(new BigDecimal("20.01")); simplifiedExpenseDetailDto.setTravel(new BigDecimal("20.02")); simplifiedExpenseDetailDto.setSmartcard(new BigDecimal("20.03")); simplifiedExpenseDetailDto.setFoodAndDrink(new BigDecimal("20.04")); simplifiedExpenseDetailDto.setTotalDue(new BigDecimal("20.05")); simplifiedExpenseDetailDto.setTotalPaid(new BigDecimal("20.06")); simplifiedExpenseDetailDto.setBalanceToPay(new BigDecimal("20.07")); total.add(simplifiedExpenseDetailDto); assertThat(total.getTotalAttendances()).isEqualTo(1); assertThat(total.getFinancialLoss()).isEqualTo(new BigDecimal("20.01")); assertThat(total.getTravel()).isEqualTo(new BigDecimal("20.02")); assertThat(total.getSmartcard()).isEqualTo(new BigDecimal("20.03")); assertThat(total.getFoodAndDrink()).isEqualTo(new BigDecimal("20.04")); assertThat(total.getTotalDue()).isEqualTo(new BigDecimal("20.05")); assertThat(total.getTotalPaid()).isEqualTo(new BigDecimal("20.06")); assertThat(total.getBalanceToPay()).isEqualTo(new BigDecimal("20.07")); total.add(simplifiedExpenseDetailDto); assertThat(total.getTotalAttendances()).isEqualTo(2); assertThat(total.getFinancialLoss()).isEqualTo(new BigDecimal("40.02")); assertThat(total.getTravel()).isEqualTo(new BigDecimal("40.04")); assertThat(total.getSmartcard()).isEqualTo(new BigDecimal("40.06")); assertThat(total.getFoodAndDrink()).isEqualTo(new BigDecimal("40.08")); assertThat(total.getTotalDue()).isEqualTo(new BigDecimal("40.10")); assertThat(total.getTotalPaid()).isEqualTo(new BigDecimal("40.12")); assertThat(total.getBalanceToPay()).isEqualTo(new BigDecimal("40.14")); } } }
import React, { useEffect, useState } from 'react'; import ShowSingleCard from './ShowSingleCard'; import '../../../Utilities/Custom.css'; import Loading from '../../../Components/Loading'; const ShowSection = () => { const [shows, setShows] = useState([]); useEffect(() => { fetch('https://api.tvmaze.com/search/shows?q=all') .then(res => res.json()) .then(data => setShows(data)); }, []); if (!shows.length) { return <Loading />; } return ( <div className='container'> <div className='cards'> <div className='cards-text'> <h2>Chose Your Favourite Show</h2> <p>Most watched movies by days</p> </div> { shows.map(show => <ShowSingleCard show={show} key={show.show.id} />) } </div> </div> ); }; export default ShowSection;
import React, { Component } from 'react'; // Externals import PropTypes from 'prop-types'; import axios from 'axios'; // Material helpers import { withStyles } from '@material-ui/core'; // Material components import { CircularProgress, Typography } from '@material-ui/core'; // Shared layouts import { Dashboard as DashboardLayout } from 'layouts'; // Shared services import { getUsers } from 'services/user'; // Custom components import { UsersToolbar, MateriasTable } from './components'; // Component styles import styles from './styles'; import { async } from 'q'; import { Link } from 'react-router-dom'; // Material components import { Avatar, Checkbox, Table, TableBody, TableCell, TableHead, TableRow, TablePagination } from '@material-ui/core'; class CargarMateria extends Component { signal = true; state = { isLoading: false, limit: 10, carga: [], selectedUsers: [], error: null }; async getMaterias(){ try{ this.setState({ isLoading: true }); const { limit } = this.state; const { users } = await getUsers(limit); let materias = await axios({ method: 'Get', url: 'http://localhost:3000/user/materias/' + localStorage.getItem('u_id'), headers: {auth: localStorage.getItem('token')} }); let carga = materias.data; if (this.signal) { this.setState({ isLoading: false, carga }); } }catch(error){ if (this.signal) { this.setState({ isLoading: false, error }); } } } componentDidMount() { this.signal = true; this.getMaterias(); } componentWillUnmount() { this.signal = false; } handleSelect = selectedUsers => { this.setState({ selectedUsers }); }; renderMaterias(){ const { classes } = this.props; const { isLoading, users, error, carga } = this.state; if (isLoading) { return ( <div className={classes.progressWrapper}> <CircularProgress /> </div> ); } if (error) { return <Typography variant="h6">{error}</Typography>; } if (carga.length === 0) { return <Typography variant="h6">There are no users</Typography>; } return ( <MateriasTable // onSelect={this.handleSelect} carga={carga} /> ); } render(){ const { classes } = this.props; const { selectedUsers } = this.state; return( <DashboardLayout title="Materias"> <div className={classes.root}> <h1>Cargas actuales</h1> <div className={classes.content} > {this.renderMaterias()} </div> </div> </DashboardLayout> ); } } CargarMateria.propTypes = { className: PropTypes.string, classes: PropTypes.object.isRequired }; export default withStyles(styles)(CargarMateria);
package com.bestbuy.crudtest; import com.bestbuy.model.ProductPojo; import com.bestbuy.testbase.TestBase; import com.bestbuy.utils.TestUtils; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.Test; import static io.restassured.RestAssured.given; public class ProductsCRUDTest extends TestBase { static String name = "Duracell - AAA Batteries (4-Pack)" + TestUtils.getRandomValue(); static String type = "HardGood" + TestUtils.getRandomValue(); static Double price= 5.49; static String upc="041333424019"; static double shipping = 0; static String description = "Compatible with select electronic devices"; static String manufacturer = "Duracell"; static String model = "MN2400B4Z"; static String url = "http://www.bestbuy.com/site/duracell-aaa-batteries-4-pack/43900.p?id=1051384074145&skuId=43900&cmp=RMXCC"; static String image= "http://img.bbystatic.com/BestBuy_US/images/products/4390/43900_sa.jpg"; static Object productId; @Test public void getProductData() { Response response = given() .when() .get("/products"); response.then().statusCode(200); response.prettyPrint(); } @Test public void createStore(){ ProductPojo productPojo = new ProductPojo(); productPojo.setName(name); productPojo.setType(type); productPojo.setPrice(price); productPojo.setUpc(upc); productPojo.setShipping(shipping); productPojo.setDescription(description); productPojo.setManufacturer(manufacturer); productPojo.setModel(model); productPojo.setUrl(url); productPojo.setImage(image); Response response = given() .contentType(ContentType.JSON) .body(productPojo) .when() .post("/products"); response.then().log().all().statusCode(201); } @Test public void getProductId() { Response response = given() .when() .get("/products/9999683"); response.then().statusCode(200); response.prettyPrint(); } @Test public void updateProduct(){ ProductPojo productPojo= new ProductPojo(); productPojo.setName(name + "Updated"); productPojo.setType(type); productPojo.setPrice(price); productPojo.setUpc(upc); productPojo.setShipping(shipping); productPojo.setDescription("Apple ID"); productPojo.setManufacturer(manufacturer); productPojo.setModel(model); productPojo.setUrl(url); productPojo.setImage(image); Response response = given() .contentType(ContentType.JSON) .when() .body(productPojo) .patch("/products/9999683"); response.prettyPrint(); response.then().log().all().statusCode(200); } @Test public void deleteStore() { Response response = given() .when() .delete("/products/9999683"); response.prettyPrint(); response.then().log().all().statusCode(200); } }
# Functions to handle missing values on a dataset # # M. Vallar - 09/2023 import pandas as pd def fill_missing_KNN_imputer(df: pd.core.frame.DataFrame, cols: list) -> pd.core.frame.DataFrame: """ Fill the missing data using the KNN imputer Args: df (obj): pd.dataframe containing the total data cols (list): list with name of the columns to fill Returns: df_imputed (obj): pd.dataframe containing the imputed data """ from sklearn.impute import KNNImputer imputer = KNNImputer(missing_values=pd.NA, n_neighbors=10) return pd.DataFrame(imputer.fit_transform(df), columns=cols)
<script setup lang="ts"> import { computed } from "@vue/runtime-core" import { useRoute } from 'vue-router' const props = defineProps({ text: { type: String, default: 'Home' }, icon: { type: String, default: 'mdi-home' }, to: { type: String, default: '/' }, color: { type: String, default: 'primary' } }) const route = useRoute() const active = computed(() => route.path === props.to) </script> <template> <v-btn :color="color" variant="text" size="large" @click="$router.push(props.to)" class="rounded-0"> <span :class="`pb-1 ${active ? 'active' : 'inactive'}`"> <v-icon class="mr-2" size="x-large">{{ props.icon }}</v-icon> {{ props.text }} </span> </v-btn> </template> <style scoped> /* They all need border so they don't shift on click */ .inactive { border-bottom: 2px solid transparent; } .active { border-bottom: 2px solid rgb(var(--v-theme-primary)); } </style>
<template> <div class="slider-dynamic"> <div v-swiper:mySwiper="swiperOption"> <div class="swiper-wrapper slider-dynamic__wrapper"> <div v-for="slide in data" :key="slide.id" class="swiper-slide slider-dynamic__slide" > <DynamicSlide :slide="slide" /> </div> <div class="swiper-slide slider-dynamic__slide" /> </div> </div> <div class="pagination-wrapper"> <div class="custom-pagination"> <div v-for="(b,i) in data" :key="i" class="custom-pagination-bullet" :class="{ 'custom-pagination-bullet-active' : i === activeIndex }" /> </div> </div> <button class="slider__arrow-left" :style="{ transform: 'translate(-50%, -50%)', display: showLeft && showArrows ? '' : 'none' }" @click="mySwiper.slidePrev()" > <img src="~/static/pics/global/svg/slider_arrow_left.svg" alt="Налево"> </button> <button class="slider__arrow-right" :style="{ transform: 'translate(50%, -50%)', display: showRight && showArrows ? '' : 'none' }" @click="mySwiper.slideNext();" > <img src="~/static/pics/global/svg/slider_arrow_right.svg" alt="Направо"> </button> </div> </template> <script> import DynamicSlide from '~/components/pages/main/DynamicSlide'; export default { components: { DynamicSlide, }, props: { data: { type: Array, required: true, }, }, data() { return { swiperOption: { spaceBetween: 24, slidesPerView: 4, init: false, breakpoints: { 1000: { slidesPerView: 3, spaceBetween: 20, }, 600: { slidesPerView: 2, spaceBetween: 10, }, }, }, showLeft: false, showRight: false, showArrows: true, activeIndex: 0, }; }, beforeDestroy() { this.$bus.$off('mainPageReady'); }, mounted() { this.mySwiper.on('imagesReady', () => { window.addEventListener('resize', this.onResize, false); this.onResize(); this.$bus.$on('mainPageReady', () => { this.updateActiveSlide(); }); }); this.mySwiper.on('slideChange', () => { this.updateArrows(); this.updateActiveSlide(); this.activeIndex = this.mySwiper.activeIndex; }); this.mySwiper.init(this.swiperOption); this.updateArrows(); }, methods: { onResize() { if (!document.querySelector('.slider-dynamic')) window.removeEventListener('resize', this.onResize, false); this.updateActiveSlide(); if (window.innerWidth <= 1000) { this.showArrows = false; } else { this.showArrows = true; } }, updateArrows() { this.showLeft = !this.mySwiper.isBeginning; this.showRight = !this.mySwiper.isEnd; }, updateActiveSlide() { if (window.innerWidth > 1000) { setTimeout(() => { const slides = this.$el.querySelectorAll('.swiper-slide'); const slideWidth = (this.$el.querySelector('.swiper-wrapper').offsetWidth - this.swiperOption.spaceBetween * (this.swiperOption.slidesPerView - 1)) / 4; for (let i = 0; i < slides.length; i++) { slides[i].style.width = `${slideWidth}px`; } if (this.$el.querySelector('.swiper-slide-next')) this.$el.querySelector('.swiper-slide-next').style.width = `${Math.floor(this.$el.querySelector('.swiper-wrapper').offsetWidth - slideWidth * 2 - this.swiperOption.spaceBetween * 2)}px`; }); } }, }, }; </script>
from typing import Dict, List, Tuple, Optional, Set from collections import defaultdict def argmax_dict(d: dict) -> str: return sorted(d, key=lambda x: -d[x])[0] class DictWithAddition: def __init__(self, d: dict): self.d = d def __add__(self, other): out_d = self.d.copy() for key, value in other.d.items(): out_d[key] = self.d.get(key, 0) + value return DictWithAddition(out_d) def __radd__(self, other): if other == 0: return self else: return self.__add__(other) class ProvinceResults: def __init__(self, name: str, nseats: int, votes_per_pparty: Dict[str, int]): self.name = name self.nseats = nseats self.votes_per_pparty = votes_per_pparty self.seats_per_pparty = self.assign_seats_to_pparty() def assign_seats_to_pparty(self) -> Dict[str, int]: nseats_remaining = self.nseats seats = {party: 0 for party in self.votes_per_pparty} transformed_results = self.votes_per_pparty.copy() while nseats_remaining: most_voted_party = argmax_dict(transformed_results) seats[most_voted_party] += 1 nseats_remaining -= 1 ratio_seats = seats[most_voted_party]/(1 + seats[most_voted_party]) transformed_results[most_voted_party] *= ratio_seats return seats def transfer_votes(self, transfer_rates: List[Tuple[str, str, float]]): ''' Arguments: - transfer_rates: list of tuples with the following structure, (source, dest, proportion of votes from source to dest) The transfers are applied from the original votes, so the order within list_transfer_votes does not affect the result ''' original_votes = self.votes_per_pparty.copy() for source, dest, prop in transfer_rates: votes_transferred = round(prop*original_votes[source]) self.votes_per_pparty[source] -= votes_transferred self.votes_per_pparty[dest] += votes_transferred self.seats_per_pparty = self.assign_seats_to_pparty() class GeneralResults: def __init__(self, province_results: List[ProvinceResults]): self.province_results = province_results def get_seats_by_pparty(self) -> Dict[str, int]: return sum([ DictWithAddition(province_result.seats_per_pparty) for province_result in self.province_results ]).d def get_votes_by_pparty(self) -> Dict[str, int]: return sum([ DictWithAddition(province_result.votes_per_pparty) for province_result in self.province_results ]).d def retrieve_results_by_province(self, name: str) -> Optional[ProvinceResults]: for province in self.province_results: if province.name == name: return province def get_results(self) -> List[Tuple[str, int, int]]: seats_by_pparty = self.get_seats_by_pparty() votes_by_pparty = self.get_votes_by_pparty() return [ (pparty, votes_by_pparty[pparty], seats_by_pparty[pparty]) for pparty in votes_by_pparty ] def transfer_votes(self, transfer_rates: List[Tuple[str, str, float]]): for province_result in self.province_results: province_result.transfer_votes(transfer_rates) def get_pparties(self, with_seats: bool = True) -> Set[str]: return set( pparty for province_result in self.province_results for pparty, seats in province_result.seats_per_pparty.items() if not with_seats or seats > 0 )
use chrono::{DateTime, Utc}; use futures::{StreamExt, TryStreamExt}; use mongodb::{bson::doc, Client, Collection}; use rocket::async_trait; use serde::Serialize; use crate::types::recipe::Recipe; use crate::utils::parse_and_describe; #[async_trait] pub trait RecipeDao { async fn insert_recipe(&self, recipe: Recipe) -> Result<String, anyhow::Error>; async fn get_recipe(&self, id: Option<String>) -> Vec<ReadableRecipe>; async fn delete_recipe(&self, id: String) -> Result<(), anyhow::Error>; } pub struct MongoRecipeDao { pub uri: String, } async fn get_collection(uri: &String, collection_name: &String) -> Collection<Recipe> { let client = Client::with_uri_str(uri).await.unwrap(); client .database("recipe_project") .collection(collection_name) } #[derive(Debug, Serialize)] pub struct ReadableRecipe { pub id: Option<String>, pub url: String, pub preview_image: Option<String>, pub title: Option<String>, pub added: DateTime<Utc>, pub humanioid_added: String, } impl ReadableRecipe { fn new(r: Recipe) -> ReadableRecipe { return ReadableRecipe { id: r.id, url: r.url, preview_image: r.preview_image, title: r.title, added: r.added.clone(), humanioid_added: parse_and_describe(r.added, chrono_tz::Tz::Europe__Berlin).unwrap(), }; } } #[async_trait] impl RecipeDao for MongoRecipeDao { async fn insert_recipe(&self, recipe: Recipe) -> Result<String, anyhow::Error> { let collection = get_collection(&self.uri, &String::from("recipe")).await; let res = collection.insert_one(recipe, None).await?; Ok(res.inserted_id.to_string()) } async fn get_recipe(&self, id: Option<String>) -> Vec<ReadableRecipe> { let collection = get_collection(&self.uri, &String::from("recipe")).await; if id.is_none() { let mut cursor = collection.find(doc! {}, None).await.unwrap(); let mut recipes: Vec<ReadableRecipe> = vec![]; while let Some(data) = cursor.try_next().await.unwrap() { recipes.push(ReadableRecipe::new(data)) } recipes.reverse(); return recipes; } return vec![]; } async fn delete_recipe(&self, id: String) -> Result<(), anyhow::Error> { let collection = get_collection(&self.uri, &String::from("recipe")).await; let res = collection.delete_one(doc! {"_id": &id}, None).await; if res?.deleted_count != 1 { return Err(anyhow::Error::msg(format!( "Could not find recipe to delete for: {}", id ))); } return Ok(()); } }
import { Component } from '@angular/core'; import { signInWithEmailAndPassword } from "firebase/auth"; import {FormControl, FormGroup, Validators} from "@angular/forms"; import {ActivatedRoute, Router} from "@angular/router"; import {FirebaseService} from "../firebase.service"; @Component({ selector: 'app-authentication-login-user', templateUrl: './authentication-login-user.component.html', styleUrls: ['./authentication-login-user.component.css'] }) export class AuthenticationLoginUserComponent { loginForm: FormGroup; returnUrl: string = '/'; constructor(private route: ActivatedRoute, private router: Router, private firebaseService: FirebaseService) { this.loginForm = new FormGroup({ 'email': new FormControl(null, [Validators.required, Validators.email, Validators.pattern(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)]), 'password': new FormControl(null, [Validators.required]) }); } loginUser() { if (this.firebaseService.auth.currentUser) return; const email = this.loginForm.get('email')?.value; const password = this.loginForm.get('password')?.value; if (email && password && !this.validateEmail() && !this.validatePassword()) { signInWithEmailAndPassword(this.firebaseService.auth, email, password) .then(async () => { this.route.queryParams.subscribe(retUrl => this.returnUrl = retUrl['returnUrl']); await this.router.navigateByUrl(this.returnUrl); }) .catch((error) => { switch (error.code) { case "auth/invalid-email": case "auth/wrong-password": case "auth/user-not-found": this.loginForm.setErrors({firebaseError: "Invalid email or password"}); break; default: this.loginForm.setErrors({firebaseError: "Something went wrong. Please try again later"}); } }); } } validateEmail() { const emailFormItem = this.loginForm.get('email'); if (!emailFormItem) return; if (!emailFormItem.value) return "Please enter email"; if (emailFormItem.errors?.['email'] || emailFormItem.errors?.['pattern']) return "Please enter a valid email"; return; } validatePassword() { const passwordFormItem = this.loginForm.get('password'); if (!passwordFormItem) return; if (!passwordFormItem.value) return "Please enter password"; return; } }
import { GetStaticPaths, GetStaticProps } from 'next'; import { useRouter } from 'next/router'; import { FaGithub } from 'react-icons/fa'; import { getFileBySlugAndType, getFiles } from '@/lib/mdx/helpers'; import CloudinaryImg from '@/components/atomic/images/CloudinaryImg'; import CustomLink from '@/components/atomic/links/CustomLink'; import { Layout } from '@/components/layout/Layout'; import { useMdxComponent } from '@/components/mdx/MDXComponents'; import Seo from '@/components/Seo'; import NotFoundPage from '../404'; import { ProjectFrontMatter } from '@/types/frontmatter'; type SingleProjectPageProps = { frontmatter: ProjectFrontMatter; code: string; }; export default function SingleProjectPage({ frontmatter, code, }: SingleProjectPageProps) { const router = useRouter(); const Component = useMdxComponent(code); if (!router.isFallback && !frontmatter && !code) { return <NotFoundPage />; } return ( <Layout> <Seo templateTitle={frontmatter.name} description={frontmatter.description} date={new Date(frontmatter.publishedAt).toISOString()} /> <main> <section className='bg-bg py-20'> <div className='layout'> <CloudinaryImg className='w-full' publicId={frontmatter.displayImage} alt={frontmatter.name} width={1440} height={792} /> <h1 className='mt-8 text-white'>{frontmatter.name}</h1> <p className='my-4 text-sm text-white'>{frontmatter.description}</p> <div className='mt-2 flex flex-wrap items-center justify-start gap-3 border-b border-white pb-8 text-sm font-medium'> {frontmatter.github && ( <div className='inline-flex items-center gap-2'> <FaGithub className='text-lg text-white' /> <CustomLink href={frontmatter.github} className='mt-1 text-white' > Repository </CustomLink> </div> )} </div> <section className='mt-8 text-white'> <article className='mdx projects prose w-full transition-colors'> <Component opts={{ height: 640, width: 960, }} ></Component> </article> {/* <aside className='py-4'> <div className='sticky top-36'> <TableOfContents toc={toc} minLevel={minLevel} activeSection={activeSection} /> </div> </aside> */} </section> <div className='mt-10 mb-10 flex flex-col items-start gap-4 border-t border-white pt-8'> <CustomLink className='text-white' href='/projects'> ← Back to projects </CustomLink> </div> </div> </section> </main> </Layout> ); } export const getStaticPaths: GetStaticPaths = async () => { const posts = await getFiles('projects'); return { paths: posts.map((p) => ({ params: { slug: p.replace(/\.mdx/, ''), }, })), fallback: false, }; }; export const getStaticProps: GetStaticProps = async ({ params }) => { const slug = params?.['slug'] as string; //TODO 404 const { code, frontmatter } = await getFileBySlugAndType(slug, 'projects'); return { props: { frontmatter: frontmatter as ProjectFrontMatter, code }, }; };
const Job = require("../models/Job") const {StatusCodes}= require("http-status-codes") const {BadRequestError, NotFoundError} = require("../errors") const getAllJobs = async(req, res) =>{ const jobs = await Job.find({createdBy: req.user.userId}).sort("createdAt") res.status(StatusCodes.OK).json({jobs, count: jobs.length}) } const getJob = async(req, res) =>{ const { user: {userId}, params:{id: jobId} } = req const job = await Job.findOne({ _id: jobId, createdBy: userId }) if (!job ) { throw new NotFoundError(`No job with id ${jobId}`) } res.status(StatusCodes.OK).json({job}) } const createJob = async(req, res) =>{ req.body.createdBy = req.user.userId const job = await Job.create(req.body) res.status(StatusCodes.CREATED).json({job}) } const updateJob = async(req, res) =>{ const { body : {company, position}, user: {userId}, params: {id: jobId} } = req if (company === "" || position === "") { throw new BadRequestError("Company or Position fields cannot be empty") } const job = await Job.findByIdAndUpdate( { _id: jobId, createdBy: userId}, req.body, {new: true, runValidators:true}) if (!job) { throw new NotFoundError(`No Job with id ${jobId}`) } res.status(StatusCodes.OK).json({job}) } const deleteJob = async(req, res) =>{ const { user: {userId}, params: {id: jobId} } = req const job = await Job.findByIdAndRemove({ _id: jobId, createdBy: userId }) if (!job) { throw new NotFoundError(`No job with id ${jobId}`) } res.status(StatusCodes.OK).send() } module.exports = { getAllJobs, getJob, createJob, updateJob, deleteJob, }
#[macro_use] extern crate log; extern crate pretty_env_logger; mod args; mod post; mod post_crawler; use clap::Parser; use futures::stream::StreamExt; use rss::ItemBuilder; use std::sync::{Arc, RwLock}; use warp::Filter; const TITLE: &str = "NHK Web Easy RSS Feed"; const LINK: &str = "https://www3.nhk.or.jp/news/easy/"; const DESCRIPTION: &str = "A 3rd-party NHK Web Easy RSS Feed"; #[tokio::main] async fn main() { pretty_env_logger::init(); let args::Args { ip, port, crawl_delay, request_delay, } = args::Args::parse(); let channel_handle = Arc::new(RwLock::new( rss::ChannelBuilder::default() .title(TITLE.to_string()) .link(LINK.to_string()) .description(DESCRIPTION.to_string()) .build(), )); let rss_server = warp::path("rss").and(warp::get()).map({ let channel_handle = channel_handle.clone(); move || { info!("Receive an RSS request"); let reply = channel_handle.read().unwrap().to_string(); info!("{:?}", channel_handle.read().unwrap().items()); info!("Reply: {}", reply); reply } }); tokio::spawn(async move { warp::serve(rss_server).run((ip, port)).await }); loop { let mut news_crawler = post_crawler::NhkWebEasyCrawler::new(voyager::RequestDelay::Fixed( std::time::Duration::from_millis(request_delay), )); let mut posts: Vec<rss::Item> = vec![]; while let Some(post) = news_crawler.next().await { match post { Err(e) => { info!("{e}"); continue; } Ok(post) => { let p = ItemBuilder::default() .title(Some(post.title)) .link(Some(post.url)) .content(Some(post.content)) .pub_date(Some(post.pub_date)) .build(); posts.push(p); } } } let channel = rss::ChannelBuilder::default() .title(TITLE.to_string()) .link(LINK.to_string()) .description(DESCRIPTION.to_string()) .items(posts) .build(); *(channel_handle.write().unwrap()) = channel; info!("Crawled NHK site"); tokio::time::sleep(tokio::time::Duration::from_millis(crawl_delay)).await; } }
# -*- coding: utf-8 -*- from PyQt5.QtCore import QThread, pyqtSignal import numpy as np from scipy.optimize import curve_fit import cv2 import time class Thread_FocusPlane(QThread): signal_end = pyqtSignal() signal_killed = pyqtSignal() def __init__(self, variables, wafer_number, sleep_time = 0.4, percent_remove = 0.35): super(Thread_FocusPlane, self).__init__() self.stop = False self.sleep_time = sleep_time self.variables = variables self.my_scope = self.variables.my_scope self.wafer_number = wafer_number self.percent_remove = percent_remove def run(self): focus_points = self.get_focus_points() xyz, sharpness_score = self.focus_routine_loop(focus_points) if not self.stop: xyz = self.remove_bad_points(xyz, sharpness_score) plane_parameters = self.fit_plane(xyz) if not self.stop: self.save_plane_parameters(plane_parameters) self.signal_end.emit() if self.stop: self.signal_killed.emit() def focus_routine_loop(self, focus_points): xyz = [] sharpness_score_array = [] for point in focus_points: if self.stop: break x, y = point z, sharpness_score = self.focus_routine(x, y) xyz.append((x,y,z)) sharpness_score_array.append(sharpness_score) return xyz, sharpness_score_array def save_plane_parameters(self, parameters): self.variables.set_plane_parameters(parameters, self.wafer_number) def plane(self,coord,a,b,c): return a*coord[0]+b*coord[1]+c def fit_plane(self, xyz): x,y = xyz[:,0], xyz[:,1] X,Y = np.meshgrid(x,y) xy = np.vstack((X.ravel(), Y.ravel())) z = xyz[:,2] guess_c = np.mean(z) popt, pcov = curve_fit(self.plane, xy, z, [0,0,guess_c], maxfev=10000) return popt def remove_bad_points(self, xyz, sharpness_score): xyz = np.asarray(xyz) sharpness_score = np.asarray(sharpness_score) xyz = xyz[np.argsort(sharpness_score)] points_to_remove = int(self.percent_remove*len(xyz)/100) return xyz[points_to_remove::] def get_focus_points(self): all_focus_points = self.variables.get_xy_focus_positions() return all_focus_points[self.wafer_number] def focus_routine(self, x, y): self.my_scope.stage.set_stage_position_xy(x, y) self.my_scope.stage.wait_stage_xy() micron_range = 1000 number_of_steps = 20 self.my_scope.camera.auto_focus(micron_range, number_of_steps) micron_range = 100 number_of_steps = 20 self.my_scope.camera.fine_focus(micron_range, number_of_steps) micron_range = 10 number_of_steps = 20 z, sharpness_score = self.my_scope.camera.fine_focus(micron_range, number_of_steps) return z, sharpness_score def kill(self): self.stop = True class Thread_SlowScan(QThread): signal_end = pyqtSignal() signal_enough_pictures = pyqtSignal() def __init__(self, variables, wafer_number, sleep_time = 0.4): super(Thread_SlowScan, self).__init__() self.stop = False self.sleep_time = sleep_time self.variables = variables self.my_scope = self.variables.my_scope self.wafer_number = wafer_number self.pictures_taken = 0 self.color_correct_trigger = 50 def run(self): self.my_scope.camera.full_resolution() x,y,z = self.get_scan_coordinates() self.scan_routine_loop(x,y,z) def scan_routine_loop(self,x_array, y_array, z_array): self.total_number_pic = len(x_array) self.n_zeros = len(str(self.total_number_pic)) for x, y, z in zip(x_array, y_array, z_array): self.check_color_correct() self.scan_routine(x, y, z) def check_color_correct(self): condition1 = ( self.pictures_taken == self.color_correct_trigger ) condition2 = ( self.pictures_taken == self.total_number_pic ) if condition1 or condition2 : self.signal_enough_pictures.emit() self.pictures_taken+=1 def scan_routine(self, x, y, z, averaging = 1): self.my_scope.stage.set_stage_position_xy(x, y) self.my_scope.stage.set_stage_position_z(z) self.wait_stage_xy() self.wait_stage() time.sleep(self.sleep_time) image = self.take_picture(averaging) self.save_picture(image) def save_picture(self, image): folder_path = self.variables.get_working_folder() pic_number = str(self.pictures_taken).zfill(self.n_zeros) wafer_number = str(self.wafer_number).zfill(2) path = (f"{folder_path}/" f"wafer_{wafer_number}/" f"pictures/" f"pic_{pic_number}.png") compression = [cv2.IMWRITE_PNG_COMPRESSION, 0] cv2.imwrite(path, image, compression) def take_picture(self, averaging): snap = self.my_scope.camera.snap_image() if averaging == 1: return snap image = snap.astype(np.float) for i in range(averaging): snap = self.my_scope.camera.snap_image() image += snap.astype(np.float) time.sleep(self.sleep_time) image = np.round(image/averaging, decimals = 0) return image.astype(np.uint8) def get_scan_coordinates(self): all_coordinates = self.variables.get_xy_scan_positions() xy = all_coordinates[self.wafer_number] x = xy[:,0] y = xy[:,1] #a, b, c are the plane parameters a, b, c = self.variables.get_plane_parameters(self.wafer_number) z = a*x + b*y + c return x, y, z def kill(self): self.stop = True
import React, { Component } from 'react'; import DayPicker from 'react-day-picker'; import 'react-day-picker/lib/style.css'; import { Button, Icon, Grid, Image } from 'semantic-ui-react'; class DaySelect extends Component { constructor(props) { super(props); this.state = { pickerVisible: false }; } componentDidUpdate() { if (this.state.pickerVisible) { document.body.addEventListener('click', this.handleClick.bind(this), true); } } handleDayChange(day) { this.setState({ pickerVisible: false }); this.props.changeSelectedDay(day); } changeToDayBefore() { let newDay = this.props.selectedDay; newDay.setDate(newDay.getDate() - 1); this.handleDayChange(newDay); } changeToDayAfter() { let newDay = this.props.selectedDay; newDay.setDate(newDay.getDate() + 1); this.handleDayChange(newDay); } formatDayText() { if (this.selectedDayIsToday()) { return 'Today'; } let date = this.props.selectedDay; const delimiter = '/'; return [date.getMonth() + 1, date.getDate(), date.getFullYear()].join(delimiter); } selectedDayIsToday() { let date = this.props.selectedDay; let today = new Date(Date.now() - 60000 * new Date().getTimezoneOffset()); return date.toISOString().split('T')[0] === today.toISOString().split('T')[0]; } /** * Hide DayPicker popup if clicked outside */ handleClick(e) { if (document.querySelector('.DayPicker')) { if (!document.querySelector('.DayPicker').contains(e.target)) { document.body.removeEventListener('click', this.handleClick.bind(this), true); this.setState({ pickerVisible: false }); } } } goToToday() { // update hash w/ query param of today's date, then refresh page so query string is re-read window.location.hash = '#/?day=' + new Date(Date.now() - 60000 * new Date().getTimezoneOffset()).toISOString().split('T')[0]; window.location.reload(false); } render() { let dayText = this.formatDayText(); return ( <div className="DaySelect"> {!this.selectedDayIsToday() && ( <Button onClick={this.goToToday} className="DaySelect--today-button small-button"> Back To Today </Button> )} <Button color="red" size="small" animated onClick={this.changeToDayBefore.bind(this)}> <Button.Content> <Icon name="arrow left" /> </Button.Content> </Button> <span className="DaySelect__choose" onClick={() => this.setState({ pickerVisible: true })}> <Button color="red" size="small" animated className="DaySelect__daytext"> {dayText} </Button> </span> {!this.selectedDayIsToday() && ( <Button color="red" size="small" animated onClick={this.changeToDayAfter.bind(this)}> <Button.Content> <Icon name="arrow right" /> </Button.Content> </Button> )} {this.state.pickerVisible && ( <DayPicker onDayClick={this.handleDayChange.bind(this)} selectedDays={this.props.selectedDay} month={ new Date(this.props.selectedDay.getFullYear(), this.props.selectedDay.getMonth()) } /> )} <div className="clearfix" /> </div> ); } } export default DaySelect;
--- import Layout from "../layouts/Layout.astro"; const allBlogs = await Astro.glob("./blogs/*.{md,mdx}"); --- <Layout title="Blogs | Joshue Abance"> <div class="text-center text-white"> <div class="text-left mb-4"> <small> <a href="/" class="hover:underline"> Return Home</a> </small> </div> <h3 class="text-3xl font-black">My Blogs</h3> <p> I want to try writing blogs, usually dev tutorials and such stuff, hope it picks your interest... </p> <div class="mt-12"> <ul class="w-full text-left"> { allBlogs .sort( (a, b) => new Date(b.frontmatter.pubDate).getTime() - new Date(a.frontmatter.pubDate).getTime() ) .map((post) => ( <> <li> <a href={post.url} class="px-4 py-2 flex flex-col hover:bg-black/20 duration-300 rounded-lg" > <h4 class="text-xl font-extrabold tracking-wide leading-loose"> {post.frontmatter.title} </h4> <p class="line-clamp-1">{post.frontmatter.description}</p> <small class="text-gray-300"> {new Date(post.frontmatter.pubDate).toDateString()} </small> </a> </li> <hr class="my-6 border-black/20" /> </> )) } </ul> </div> </div> </Layout>
package dto import ( "github.com/go-playground/validator/v10" ) type Domain struct { ProfileName string `json:"profileName" binding:"required,alphanum" example:"My Profile"` DomainSuffix string `json:"domainSuffix" binding:"required" example:"example.com"` ProvisioningCert string `json:"provisioningCert,omitempty" binding:"required" example:"-----BEGIN CERTIFICATE-----\n..."` ProvisioningCertStorageFormat string `json:"provisioningCertStorageFormat" binding:"required" example:"string"` ProvisioningCertPassword string `json:"provisioningCertPassword,omitempty" binding:"required,lte=64" example:"my_password"` TenantID string `json:"tenantId" example:"abc123"` Version string `json:"version,omitempty" example:"1.0.0"` } var StorageFormatValidation validator.Func = func(fl validator.FieldLevel) bool { provisioningCertStorageFormat, ok := fl.Field().Interface().(string) if ok { if provisioningCertStorageFormat != "raw" && provisioningCertStorageFormat != "string" { return false } } return true }
import operator import logging from typing import Any from config import config from aiogram.types import CallbackQuery, Message, BufferedInputFile, ContentType, InputMediaPhoto from aiogram import html, Bot, F from aiogram_dialog import Window, DialogManager from aiogram_dialog.widgets.kbd import Select, Group, ScrollingGroup, Button, Row, Cancel, Back from aiogram_dialog.widgets.text import Format, Const from aiogram_dialog.widgets.input import MessageInput from aiogram_dialog.api.entities import MediaAttachment, MediaId from aiogram_dialog.widgets.media import DynamicMedia from src.lexicon import LEXICON from src.services import ProductService, PhotoService, S3Service from src.states.states import Product product_service = ProductService() photo_service = PhotoService() s3_service = S3Service() logger = logging.getLogger() token = config.load_config().tg_bot.token bot = Bot(token) async def get_product_photos(dialog_manager: DialogManager, **kwargs): dialog_manager.dialog_data["is_photo"] = None product_id = dialog_manager.dialog_data["product_id"] photo_objects = await photo_service.photos(product_id=product_id) photos = [] for photo_object in photo_objects: photo_bytes = await s3_service.download_file(file_name=photo_object.name) photo_file = BufferedInputFile(photo_bytes, filename=photo_object.name) photo = InputMediaPhoto(media=photo_file) photos.append(photo) dialog_manager.dialog_data["is_photo"] = True if len(photos) > 0: await bot.send_media_group(chat_id=dialog_manager.event.from_user.id, media=photos) photos_data = [ (photo_object.name, str(photo_object.photo_id)) for photo_object in photo_objects ] return { "photos": photos_data } async def product_getter(dialog_manager: DialogManager, **kwargs): product_id = int(dialog_manager.start_data['product_id']) product_data = await product_service.get_product(product_id=product_id) photos = await get_product_photos(dialog_manager) return { "product_title": product_data.title, "product_description": product_data.description, "product_discount": product_data.discount, "product_cost": product_data.cost, "product_delivery_days": product_data.delivery_time.split('.')[0] if len(product_data.delivery_time.split('.')) else 0, "product_delivery_hours": product_data.delivery_time.split('.')[1].split(':')[0] if len(product_data.delivery_time.split('.')) > 1 else 0, "product_delivery_minutes": product_data.delivery_time.split('.')[1].split(':')[1], "product_delivery_seconds": product_data.delivery_time.split('.')[1].split(':')[2], } async def get_product_button(callback: CallbackQuery, widget: Any, dialog_manager: DialogManager, item_id: str): await callback.answer(text=LEXICON["loading"]) dialog_manager.start_data["product_id"] = item_id dialog_manager.dialog_data["product_id"] = item_id await dialog_manager.switch_to(Product.product) async def to_product_update_button(callback: CallbackQuery, button: Button, dialog_manager: DialogManager, **kwargs): await dialog_manager.switch_to(Product.product_update) to_product_update_button = Button( text=Const(LEXICON["update"]), id="to_product_update", on_click=to_product_update_button ) async def add_product_photo_button(callback: CallbackQuery, button: Button, dialog_manager: DialogManager, **kwargs): await dialog_manager.switch_to(Product.product_wait_photo) add_product_photo_button = Button( text=Const(LEXICON["add_photo"]), id="add_product_photo", on_click=add_product_photo_button ) async def add_product_photo(message: Message, message_input: MessageInput, dialog_manager: DialogManager): file_id = message.photo[-1].file_id file_info = await bot.get_file(file_id) file = await bot.download_file(file_info.file_path) photo_data = await s3_service.upload_file(file_path=file_info.file_path, file=file) res = await photo_service.create_photo(name=photo_data.fileName, product_id=dialog_manager.dialog_data['product_id']) await dialog_manager.switch_to(Product.product) product_wait_photo_window = Window( Const(LEXICON["send_photo"]), MessageInput(add_product_photo), state=Product.product_wait_photo ) async def back_to_list_button(callback: CallbackQuery, button: Button, dialog_manager: DialogManager, **kwargs): if 'title' in dialog_manager.dialog_data.keys(): dialog_manager.dialog_data.pop('title') if 'description' in dialog_manager.dialog_data.keys(): dialog_manager.dialog_data.pop('description') if 'discount' in dialog_manager.dialog_data.keys(): dialog_manager.dialog_data.pop('discount') if 'cost' in dialog_manager.dialog_data.keys(): dialog_manager.dialog_data.pop('cost') if 'delivery_time' in dialog_manager.dialog_data.keys(): dialog_manager.dialog_data.pop('delivery_time') await dialog_manager.switch_to(Product.products) back_to_list_button = Button( text=Const(LEXICON["back"]), id="back_to_products_list", on_click=back_to_list_button ) async def product_photos_delete_button(callback: CallbackQuery, button: Button, dialog_manager: DialogManager, **kwargs): await dialog_manager.switch_to(Product.product_delete_photo) product_photos_delete_button = Button( text=Const(LEXICON["delete_photo"]), id="product_photos_delete", on_click=product_photos_delete_button ) async def delete_product_photo_button(callback: CallbackQuery, widget: Any, dialog_manager: DialogManager, item_id: str): photo_object = await photo_service.get_photo(photo_id=int(item_id)) await s3_service.delete_file(file_name=photo_object.name) await photo_service.delete_photo(photo_id=photo_object.photo_id) await dialog_manager.switch_to(Product.product) product_delete_photos_window = Window( Const(LEXICON["delete_photo"]), ScrollingGroup( Select( text=Format("{item[0]}"), item_id_getter=operator.itemgetter(1), items="photos", id="photo_i", when=F["dialog_data"]["is_photo"].is_not(None), on_click=delete_product_photo_button ), id="product_delete_photos_group", width=1, height=10, ), back_to_list_button, state=Product.product_delete_photo, getter=get_product_photos ) product_window = Window( Const(LEXICON["product"]), Format(html.bold(html.quote("{product_title}"))), Format(html.quote("{product_description}")), Format(html.quote("Скидка: {product_discount}")), Format(html.quote("Цена: {product_cost} руб")), Format(html.quote("Время доставки: {product_delivery_days} дней {product_delivery_hours} " "часов {product_delivery_minutes} минут {product_delivery_seconds} секунд")), add_product_photo_button, product_photos_delete_button, to_product_update_button, back_to_list_button, Cancel(Const(LEXICON["complete"])), state=Product.product, getter=product_getter )
# Simple-web-app-with-Database This is a simple PHP script that connects to a MySQL database and retrieves data from a "todo_list" table. It then displays the tasks as an ordered list on a webpage. It serves as a basic example of how to retrieve and display data from a database using PHP. Prerequisites Before you can use this script, you need the following: A web server (e.g., Apache) with PHP support. A MySQL database with a "todo_list" table containing your task data. Knowledge of your database's connection details, including the database host, username, password, and database name. Usage Clone or download this repository to your web server's document root. Open the index.php file in a text editor and update the following lines with your database connection details: $user = "your_username"; $password = "your_password"; $database = "your_database_name"; $table = "todo_list"; Ensure that the "todo_list" table in your MySQL database contains the task data. Access the script through your web browser, e.g., http://localhost/path-to-script/index.php. Script Explanation The index.php script performs the following tasks: It establishes a connection to the MySQL database using the provided credentials. It fetches task data from the "todo_list" table. It displays the retrieved tasks as an ordered list on a webpage. Customization If you want to expand this script or modify its appearance, you can do the following: Add additional functionality, such as the ability to add, update, or delete tasks. Customize the HTML and CSS to improve the look and feel of the displayed tasks. License This project is provided under the MIT License. For more details, see the LICENSE file. Acknowledgments This script is a basic example of how to connect to a MySQL database using PHP and retrieve data. It serves as a starting point for building more advanced applications that involve database interactions. If you have any questions or encounter issues with this script, feel free to reach out for assistance or make improvements as needed. Enjoy using this simple PHP-MySQL Todo List script!
<?php namespace App\Http\Controllers\Home; use App\Http\Controllers\Controller; use Carbon\Carbon; use Illuminate\Http\Request; use App\Models\Portfolio; use Intervention\Image\Facades\Image; class PortfolioController extends Controller { public function allPortfolio() { $portfolio = Portfolio::latest()->get(); return view('admin.portfolio.portfolio_all', compact('portfolio')); } public function addPortfolio() { return view('admin.portfolio.portfolio_add'); } public function storePortfolio(Request $request) { $request->validate([ 'portfolio_name' => 'required', 'portfolio_title' => 'required', 'portfolio_image' => 'required', ], [ 'portfolio_name.required' => 'Portfolio Name is Required', 'portfolio_title.required' => 'Portfolio Title is Required', ]); $image = $request->file('portfolio_image'); $name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension(); Image::make($image)->resize(1020,519)->save('upload/portfolio/'.$name_gen); $save_url = 'upload/portfolio/'.$name_gen; Portfolio::insert([ 'portfolio_name' => $request->portfolio_name, 'portfolio_title' => $request->portfolio_title, 'portfolio_description' => $request->portfolio_description, 'portfolio_image' => $save_url, 'created_at' => Carbon::now(), ]); $notification = [ 'message' => 'Portfolio Inserted Successfully', 'alert-type' => 'success' ]; return redirect()->route('all.portfolio')->with($notification); } public function editPortfolio($id) { $portfolio = Portfolio::findOrFail($id); return view('admin.portfolio.portfolio_edit', compact('portfolio')); } public function updatePortfolio(Request $request) { $portfolio_id = $request->id; if ($request->file('portfolio_image')) { $image = $request->file('portfolio_image'); $name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension(); Image::make($image)->resize(1020,519)->save('upload/portfolio/'.$name_gen); $save_url = 'upload/portfolio/'.$name_gen; Portfolio::findOrFail($portfolio_id)->update([ 'portfolio_name' => $request->portfolio_name, 'portfolio_title' => $request->portfolio_title, 'portfolio_description' => $request->portfolio_description, 'portfolio_image' => $save_url, ]); $notification = [ 'message' => 'Portfolio Updated with Image Successfully', 'alert-type' => 'success' ]; return redirect()->route('all.portfolio')->with($notification); } else { Portfolio::findOrFail($portfolio_id)->update([ 'portfolio_name' => $request->portfolio_name, 'portfolio_title' => $request->portfolio_title, 'portfolio_description' => $request->portfolio_description, ]); $notification = [ 'message' => 'Portfolio Updated without Image Successfully', 'alert-type' => 'success' ]; return redirect()->route('all.portfolio')->with($notification); } } public function deletePortfolio($id) { $portfolio_id = Portfolio::findOrFail($id); $img = $portfolio_id->portfolio_image; unlink($img); Portfolio::findOrFail($id)->delete(); $notification = [ 'message' => 'Portfolio Deleted Successfully', 'alert-type' => 'success' ]; return redirect()->back()->with($notification); } public function portfolioDetails($id) { $portfolio = Portfolio::findOrFail($id); return view('site.portfolio_details', compact('portfolio')); } public function homePortfolio() { $portfolio = Portfolio::latest()->get(); return view('site.portfolio', compact('portfolio')); } }
import torch import matplotlib.pyplot as plt import matplotlib.patches as patches import torchvision.transforms.functional as F from torchvision.datasets import CocoDetection import itertools def convert_coco_format_to_pascal_voc(coco_boxes): """ Convert COCO bounding box format (top_left_x, top_left_y, width, height) to Pascal VOC format (x_min, y_min, x_max, y_max). Args: coco_boxes (Tensor): the bounding boxes in COCO format. Returns: Tensor: the bounding boxes in Pascal VOC format. """ #coco_boxes = coco_boxes.unsqueeze(0) # The input coco_boxes is expected to be a tensor of shape [N, 4] where N is the number of boxes if coco_boxes.size(0) != 0: x_min = coco_boxes[:, 0] y_min = coco_boxes[:, 1] x_max = x_min + coco_boxes[:, 2] y_max = y_min + coco_boxes[:, 3] pascal_boxes = torch.stack((x_min, y_min, x_max, y_max), dim=1) else: pascal_boxes = torch.zeros((0, 4), dtype=torch.float32) return pascal_boxes def custom_collate_fn(batch): """ Custom collate function to handle batching. Parameters: batch: List of tuples (image, target) from the dataset. Returns: tuple: Batch of images and targets. """ images, targets = zip(*batch) # Convert images to tensors if they aren't already images = [F.to_tensor(img) if not isinstance(img, torch.Tensor) else img for img in images] # Convert targets from tuple to list targets = list(targets) return torch.stack(images), targets def denormalize(tensor): """ Denormalize a tensor image with mean and standard deviation. Args: tensor (torch.Tensor): The image tensor to be denormalized. mean (list): The mean used for normalization. std (list): The standard deviation used for normalization. Returns: torch.Tensor: Denormalized image tensor. """ mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] if tensor.ndim == 3: # Single image mean = torch.tensor(mean).view(3, 1, 1) std = torch.tensor(std).view(3, 1, 1) tensor = tensor * std + mean elif tensor.ndim == 4: # Batch of images mean = torch.tensor(mean).view(1, 3, 1, 1) std = torch.tensor(std).view(1, 3, 1, 1) tensor = tensor * std + mean return tensor def pixel_stats(loader): """ Calculate the mean and standard deviation of images in a dataset. This function iterates over a DataLoader and calculates the mean and standard deviation of all images in the dataset. This is useful for normalizing the dataset in future data preprocessing steps. Parameters: - loader (DataLoader): A PyTorch DataLoader object that loads the dataset for which the statistics are to be calculated. The DataLoader should return batches of images and their corresponding labels or targets. Returns: - mean (Tensor): A tensor containing the mean value of each channel in the dataset. - std (Tensor): A tensor containing the standard deviation of each channel in the dataset. """ mean = 0. std = 0. nb_samples = 0. for data, label in loader: images = torch.stack(data) batch_samples = images.size(0) images = images.view(batch_samples, images.size(1), -1) mean += images.mean(2).sum(0) std += images.std(2).sum(0) nb_samples += batch_samples mean /= nb_samples std /= nb_samples # print(f"Calculated mean: {mean}") # print(f"Calculated std: {std}") return mean, std def visualize_sample(dataloader): """ Visualize a single sample from a PyTorch DataLoader containing images and their bounding boxes. Args: dataloader (DataLoader): PyTorch DataLoader with a dataset that returns a tuple of images and targets. """ try: while True: print("\n Entering data check... type 'done' to stop.") idx = input('Provide the sample id: ') if idx.lower() == 'done': print('Exiting data check.') return num_samples = len(dataloader.dataset) # Get a single batch from the dataloader if not idx: images, targets = next(iter(dataloader)) else: idx = int(idx) if idx < num_samples: # Use modulo to wrap around if idx exceeds the dataset length images, targets = next(itertools.islice(dataloader, idx % num_samples, None)) else: print(f"Index out of range. Dataset contains {num_samples} samples.") continue # Assuming that the dataset returns a PIL Image or a tensor that can be converted, and # the targets include 'boxes' and 'labels' image = images[0] # Get the first image from the batch target = targets[0] # Get the first target from the batch im_id = target['image_id'] print(f'Image ID" {im_id}') print(f"{type(image) = }\n{type(target) = }\n{target.keys() = }") print(f"{type(target['boxes']) = }\n{type(target['labels']) = }") # Convert tensor to PIL Image if necessary if isinstance(image, torch.Tensor): image = F.to_pil_image(image) # Create figure and axes fig, ax = plt.subplots(1) # Display the image ax.imshow(image) # Get the bounding boxes and labels from the target boxes = target['boxes'].cpu().numpy() labels = target['labels'].cpu().numpy() # Create a Rectangle patch for each bounding box and add it to the plot for i, box in enumerate(boxes): # Create a Rectangle patch rect = patches.Rectangle((box[0], box[1]), box[2] - box[0], box[3] - box[1], linewidth=1, edgecolor='r', facecolor='none', label=labels[i]) # Add the patch to the Axes ax.add_patch(rect) # Add labels for the first box only to avoid duplicate labels in the legend handles, labels = ax.get_legend_handles_labels() by_label = dict(zip(labels, handles)) plt.legend(by_label.values(), by_label.keys()) plt.show() except KeyboardInterrupt: print('Loop stopped!') except StopIteration: print("Reached the end of the dataset.") def analyze_dataset(dataset_path, annotation_file): """ Analyze the dataset to determine appropriate anchor sizes and aspect ratios. Parameters: dataset_path (str): Path to the dataset directory. annotation_file (str): Path to the annotation file. Returns: A plot of the distribution of bounding box sizes and aspect ratios. """ dataset = CocoDetection(root=dataset_path, annFile=annotation_file) widths = [] heights = [] aspect_ratios = [] areas = [] for _, targets in dataset: for target in targets: bbox = target['bbox'] # COCO format: [xmin, ymin, width, height] width = bbox[2] height = bbox[3] area = width * height widths.append(width) heights.append(height) areas.append(area) aspect_ratios.append(width / height if height > 0 else 0) # Computing max and min areas max_area, min_area = max(areas), min(areas) print('max_area: ', max_area, 'min_area: ', min_area) # Plotting plt.figure(figsize=(12, 6)) plt.subplot(1, 3, 1) plt.hist(widths, bins=50, color='blue', alpha=0.7) plt.title('Distribution of Widths') plt.subplot(1, 3, 2) plt.hist(heights, bins=50, color='green', alpha=0.7) plt.title('Distribution of Heights') plt.subplot(1, 3, 3) plt.hist(aspect_ratios, bins=50, color='red', alpha=0.7) plt.title('Distribution of Aspect Ratios') plt.tight_layout() plt.show()
package com.repair.ms.repairms.services; import com.repair.ms.repairms.entities.RepairDetailEntity; import com.repair.ms.repairms.models.RepairlistModel; import com.repair.ms.repairms.models.VehicleModel; import com.repair.ms.repairms.repositories.RepairDetailRepository; import org.springframework.http.HttpMethod; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.List; import java.util.Optional; @Service public class RepairDetailService { @Autowired RepairDetailRepository repairDetailRepository; @Autowired RepairService repairService; @Autowired RestTemplate restTemplate; /* Aux methods */ /*-------------------------------------------------------------------------------------------------------- * getRepairlistByRepairType: method to retrieve a repair list by its repair type. * * @param repairType - The type of repair list to retrieve. * @return - The repair list with the specified type. --------------------------------------------------------------------------------------------------------*/ public RepairlistModel getRepairlistByRepairType(String repairType) { ResponseEntity<RepairlistModel> responseEntity = restTemplate.exchange( "http://ms-repairlist/ms/listrepair/wt/" + repairType, HttpMethod.GET, null, RepairlistModel.class ); return responseEntity.getBody(); } /* POST OPERATIONS */ /*-------------------------------------------------------------------------------------------------------- * createRepairDetail: Method to create a new repair detail entity in the database; * * @param repairDetailEntity - the repair detail entity to be created; * @return - the created repair detail entity; --------------------------------------------------------------------------------------------------------*/ public RepairDetailEntity createRepairDetail(RepairDetailEntity repairDetailEntity) { /*we get the repairType for the corresponding repairDetail*/ String repairType = repairDetailEntity.getRepairType(); RepairlistModel repairPrice = getRepairlistByRepairType(repairType); /* we get the vehicle and its engineType */ String plate = repairDetailEntity.getVehiclePlate(); VehicleModel vehicle = repairService.getVehicle(plate); String engineType = vehicle.getEngineType(); /* we assign a price depending on the engineType */ double price = 0.0; switch (engineType) { case "gasoline": price = repairPrice.getGasolinePrice(); break; case "diesel": price = repairPrice.getDieselPrice(); break; case "hybrid": price = repairPrice.getHybridPrice(); break; case "electric": price = repairPrice.getElectricPrice(); break; default: price = 0.0; break; } repairDetailEntity.setRepairCost(price); System.out.println(repairDetailEntity.getRepairCost()); return repairDetailRepository.save(repairDetailEntity); } /* GET OPERATIONS */ /*-------------------------------------------------------------------------------------------------------- * getAllRepairDetails: Method to retrieve all repair detail entities from the database. * * @return - List of all repair detail entities. --------------------------------------------------------------------------------------------------------*/ public List<RepairDetailEntity> getAllRepairDetails() { return repairDetailRepository.findAll(); } /* UPDATE OPERATIONS */ /*-------------------------------------------------------------------------------------------------------- * updateRepairDetail: method to update an existing repair detail entity in the database; * * @param id - the ID of the repair detail entity to update; * @param updatedRepairDetail - the updated repair detail entity; * @return - the updated repair detail entity, or empty if not found; --------------------------------------------------------------------------------------------------------*/ public Optional<RepairDetailEntity> updateRepairDetail(Long id, RepairDetailEntity updatedRepairDetail) { return repairDetailRepository.findById(id).map(repairDetail -> { repairDetail.setVehiclePlate(updatedRepairDetail.getVehiclePlate()); repairDetail.setRepairType(updatedRepairDetail.getRepairType()); repairDetail.setRepairDate(updatedRepairDetail.getRepairDate()); repairDetail.setRepairTime(updatedRepairDetail.getRepairTime()); repairDetail.setRepairCost(updatedRepairDetail.getRepairCost()); return repairDetailRepository.save(repairDetail); }); } /* DELETE OPERATIONS */ /*-------------------------------------------------------------------------------------------------------- * deleteRepairDetail: method to delete a repair detail entity from the database; * * @param id - the ID of the repair detail entity to delete; --------------------------------------------------------------------------------------------------------*/ public void deleteRepairDetail(Long id) { repairDetailRepository.deleteById(id); } }
# Bioinformatics Master 1 project - UE HAU805I Stage M1 - Align program ## Introduction Project done for the 1st year of Master degree in Bioinformatics' intership - Program in C++ able to calculate evolutionary distances between amino acids sequences from an aligned FASTA file and create a distance matrice using 5 methods: - Distance estimation [Default]. - Jukes-Cantor model for amino acids [1]. - Poisson model for amino acids [2]. - Kimura estimation for PAM model [3]. - Estimation models for evolutionary distances between amino acids sequences: Poisson Correction and Equal-Input from Thomas Bigot and al., article [4]. ## Installation Clone the repository then compile the Align program with g++ or another C++ compiler. ``` git clone https://github.com/noeliepalermo/Align g++ main.cpp -o align ``` ## Usage ``` ./align [evolutionary distances method option] aligned FASTA file [output file option] ``` The FASTA file must contain aligned proteins sequences. You can use only one option for the evolutionary distances method and the output file. ### Evolutionary distances methods options: ```-d```,```--divergence```: Distance estimation [Default]. ```-h```,```--help```: Display informations about the program. ```-jc```,```--jukescantor```: Jukes-Cantor model for amino acids. ```-k```, ```--kimura```: Kimura estimation for PAM model. ```-p```,```--poisson```: Poisson model for amino acids. ```-pc```,```--poissoncorrection```: Poisson Correction method from Thomas Bigot and al., article. ```-ei```,```--equalinput```: Equal-Input method from Thomas Bigot and al., article. The two methods (Poisson Correction and Equal-Input) from Thomas Bigot and al., article, estimate evolutionary distances for 27 amino acids substitution models: ```AB```, ```BLOSUM62```, ```cpREV64```, ```cpREV```, ```Dayhoff``` [Default], ```DCMut-Dayhoff```, ```DCMut-JTT```, ```DEN```, ```FLU```, ```gcpREV```, ```HIVb```, ```HIVw```, ```JTT```, ```LG```, ```mtART```, ```mtInv```, ```mtMAM```, ```mtMet```, ```mtREV```, ```mtVer```, ```mtZOA```, ```PMB```, ```rtREV```, ```stmtREV```, ```VT```, ```WAG``` and ```WAG*```. ### Output file options: ```-m, --matrice```: Output file ```mat.dist```, with a triangular distance matrice in PHYLIP format. ```-o, --output```: Output file ```seqs.dist```, with a distance matrice and other informations: number of sequences, evolutionary distances and header sequences. ## Quick Demo For testing the program Align, you can use the ```test_align.fasta``` file, which contains 26 proteins sequences from the PhylomeDB. Ignore gaps between all columns of the alignment for generate the expected results. Command to execute the test file: ``` ./align -d test_align.fasta -m ``` The expected results are in the ```test_result_align.dist```. ## References [1] Swofford D.L., Olsen G.J., W. P. and D.M., H. (1996). Phylogenetic inference. in : Hillis, d.m., moritz, c. and mable, b.k., eds. Molecular Systematics, 2nd Edition, Sinauer Associates, Sunderland (MA), (2) :407–514. [2] Zuckerkandl, E., & Pauling, L. (1965). Evolutionary divergence and convergence in proteins. In Evolving genes and proteins (pp. 97-166). Academic Press. [3] Kimura, M. (1991). The neutral theory of molecular evolution: a review of recent evidence. The Japanese Journal of Genetics, 66(4), 367-386. [4] Bigot, T., Guglielmini, J., & Criscuolo, A. (2019). Simulation data for the estimation of numerical constants for approximating pairwise evolutionary distances between amino acid sequences. Data in brief, 25, 104212.
interface calculateOneRepMaxProps { weight: string; reps: string; } const calculateOneRepMax = (arr: Array<calculateOneRepMaxProps>): number[] => { return arr.map((set) => { if (!set) return 0 const weight = parseInt(set.weight) const reps = parseInt(set.reps) const oneRepMax = weight * (36 / (37 - reps)) return Math.round(oneRepMax) }) } export default calculateOneRepMax // NOTE: // HOW TO CALCULATE 1 REP MAX // Brzycki formula: Weight × (36 / (37 – number of reps)) // Epley formula: Weight × (1 + (0.0333 × number of reps)) // Lombardi formula: Weight × (number of reps ^ 0.1) // O'Conner formula: Weight × (1 + (0.025 × number of reps))