text
stringlengths
184
4.48M
import marlo import time import sys import numpy as np np.set_printoptions(threshold=sys.maxsize) # Debug log = True # Agent starting and current coordinates start_coords = (40, 40) curr_coords = start_coords # Stores nodes that are unexplored and explored, respectively frontier = [start_coords] explored = [] # Stores the moves the agent took to get to its last location prev_node = { start_coords: None } # Initialize map of environment with 80 x 80 array # Agent starts in the middle (40, 40) map = np.array([[-1] * 80] * 80) # Initialize Environment client_pool = [('127.0.0.1', 10000)] join_tokens = marlo.make('C:\\Users\\Ryan.Kinnucan\\MinecraftRLAgent\\MarLO\\Missions\\lava_maze.xml', params={ "client_pool": client_pool, "max_retries": 100, "agent_names": ["MarLo-Agent-0"], "allowContinuousMovement": True, "allowDiscreteMovement": True, }) assert len(join_tokens) == 1 join_token = join_tokens[0] env = marlo.init(join_token) env.reset() obs, reward, done, info = env.step(0) map[start_coords[0], start_coords[1]] = reward explored.append(start_coords) # Commands (W/ Indicators of Reliability): # Numerical, use env.step() # 0 = Do Nothing (Reliable) # 1 = Move Forward 1 Block (Reliable) # 2 = Move Backward 1 Block (Reliable) # 3 = Turn Right 90 Degrees (Not Reliable) # 4 = Turn Left 90 Degrees (Not Reliable) # 5 = Look Down (Not Reliable) # 6 = Look Up (Not Reliable) # Human readable, use env.send_command() # move 1/-1 = Move Forward/Backward 1 Block (Reliable) # movewest 1 = Move Right 1 Block (Reliable) # moveeast 1 = Move Left 1 Block (Reliable) # pitch -1/1 = Look Up/Down (Reliable) # Given the agent's current location and a destination, # send the agent to that destination def walk_to_node(start, dest, reverse=True): if (start == dest): return path = reconstruct_path(start, dest, reverse) if log: print("--------------------") print("Path:", path) print("--------------------") for i in range(0, len(path) - 1): curr = path[i] next = path[i + 1] if (next[0] < curr[0] and next[1] == curr[1]): command = "move 1" if (next[0] == curr[0] and next[1] < curr[1]): command = "moveeast 1" if (next[0] > curr[0] and next[1] == curr[1]): command = "move -1" if (next[0] == curr[0] and next[1] > curr[1]): command = "movewest 1" env.send_command(command) time.sleep(0.5) # Reconstruct the agent's path from the start location to the destination. # Start from the destination and work backwards, then reverse if necessary def reconstruct_path(start, dest, reverse): if (reverse): curr_node = dest else: curr_node = start path = [curr_node] prev = prev_node[curr_node] if log: print("--------------------") print("Reconstructing Path") print("Start Node:", start) print("Destination Node:", dest) if (reverse): while (prev != start and prev != None): # if log: # print("--------------------") # print("Curr Node:", curr_node) # print("Prev:", prev) path.append(prev) curr_node = prev prev = prev_node[curr_node] else: while (prev != dest): # if log: # print("--------------------") # print("Curr Node:", curr_node) # print("Prev:", prev) path.append(prev) curr_node = prev prev = prev_node[curr_node] if (reverse): path.append(start) path.reverse() else: path.append(dest) return path # Given a list of neighboring nodes and the # agent's current location, explore all neighbors def explore_neighbors(neighbors, curr_coords): for n in neighbors: if (n not in explored): prev_node[n] = curr_coords if log: print("--------------------") print("Current Neighbor:", n) print("Neighbor's Prev:", prev_node[n]) walk_to_node(curr_coords, n) # Get observation time.sleep(1) obs, reward, done, info = env.step(0) if log: print("--------------------") print("reward:", reward) print("done:", done) print("info", info) # If agent falls into lava, the environment must # be reset so that the agent will respawn, after # which the agent needs to be returned to the # last location it was exploring from if (reward == -100): map[n[0], n[1]] = -100 if log: print("map:") print(map[27:43, 38:46]) print("--------------------") print("Reseting Env") print("--------------------") env.reset() explored.append(n) # Remove lava nodes from frontier because # their neighbors will be inaccessible frontier.remove(n) # Walk the agent back to its previous location # if there are still neighbors to explore if (bool(neighbors)): walk_to_node(start_coords, curr_coords) # If agent does not fall into lava, set the node # at that location equal to the reward, then walk # the agent back to curr_coords if (reward != -100): map[n[0], n[1]] = reward # If the goal node is found, the agent doesn't need # to explore any of the blocks around it unless there # is a path which leads to said blocks that doesn't # go through the goal node if (reward == 100): frontier.remove(n) if log: print("map:") print(map[27:43, 38:46]) explored.append(n) walk_to_node(n, curr_coords, False) # While frontier is not empty while bool(frontier): # Walk agent to the first node in the frontier dest = frontier.pop(0) if log: print("--------------------") print("Node to Explore:", dest) print("Current Node:", curr_coords) walk_to_node(curr_coords, dest) curr_coords = dest # Get agent's current row and column # and all of its neighbors agent_row = curr_coords[0] agent_col = curr_coords[1] neighbors = [ (agent_row - 1, agent_col), (agent_row, agent_col - 1), (agent_row + 1, agent_col), (agent_row, agent_col + 1) ] # If a neighboring node has not already been explored, and # is not already in the frontier, then add it to the frontier for n in neighbors: if ((n not in explored) and (n not in frontier)): frontier.append(n) if log: print("Frontier:", frontier) print("Neighbors:", neighbors) # Explore all neighbors of the current node, then # walk the agent back to its starting location explore_neighbors(neighbors, curr_coords) walk_to_node(curr_coords, start_coords, False) # Once a node has been fully explored, remove it from the frontier if (curr_coords in frontier): frontier.remove(curr_coords) curr_coords = start_coords env.close() print(map[27:43, 38:46])
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="description" content="COS100011 assignment 2"> <meta name="keywords" content="COS100011, assignment 2, creating web applications"> <meta name="author" content="Hy Gia Nguyen"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="styles/style.css"> <script src="scripts/payment.js"></script> <title>Payment</title> </head> <body> <header> <!-- Header section --> <nav> <!-- Logo image with anchor tag link to home page --> <a href="index.html" id="logo"> <img src="images/logo.jpg" title="Home" alt="Company Logo" height="75" width="200"> </a> <!-- Navigation links --> <ul> <li><a href="index.html">Home</a></li> <li><a href="about.html">About</a></li> <li><a href="product.html">Products</a></li> <li><a href="enquire.html">Enquiry</a></li> <li><a href="enhancements2.html">Enhancements</a></li> <li><a class="active" href="payment.html">Payment</a></li> </ul> </nav> </header> <main> <!-- main content starts here --> <h1 class="align-center">Please confirm the information below</h1> <form id="paymentForm" method="post" action="https://mercury.swin.edu.au/it000000/formtest.php"> <!-- form to submit to server --> <fieldset> <!-- Customer's personal details --> <legend>Personal details</legend> <p>Full Name: <span id="fullName"></span></p> <!-- name --> <p>Email: <span id="email"></span></p> <!-- email --> <p>Address: <span id="address"></span></p> <!-- address --> <p>Suburb/Town: <span id="suburb"></span></p> <!-- suburb --> <p>State: <span id="state"></span></p> <!-- state --> <p>Post Code: <span id="postCode"></span></p> <!-- post code--> <p>Phone number: <span id="phone"></span></p> <!-- phone --> <p>Contact method: <span id="contact"></span></p> <!-- contact method --> </fieldset> <fieldset> <!-- Customer's enquiry details --> <legend>Your enquiries</legend> <p>Enquire about: <span id="enquire"></span></p> <p>Chosen product features: <span id="feature"></span></p> <!-- displays all the chosen products information from enquire.html --> <p>Your comment: <span id="comment"></span></p> <!-- customer's comment --> </fieldset> <fieldset> <!-- Purchase information --> <legend>Your Selected Products</legend> <div id="purchases"></div> <p class="align-center">Total bill: <span id="cost"></span></p> <!-- display total cost --> </fieldset> <fieldset> <!-- Payment and card details --> <legend>Payment details</legend> <p> <!-- Card types --> <label for="cardType">Card Type:</label> <select name="cardType" id="cardType"> <option value="visa">Visa</option> <option value="master">MasterCard</option> <option value="amex">American Express</option> </select> </p> <p> <!-- Name on card --> <label for="cardName">Name on Card:</label> <input type="text" name= "cardName" id="cardName" > </p> <p> <!-- Card number --> <label for="cardNumber">Card Number:</label> <input type="text" name= "cardNumber" id="cardNumber" > </p> <p> <!-- Expiry date --> <label for="cardExpiry">Card Expiry date:</label> <input type="text" name= "cardExpiry" id="cardExpiry" placeholder="mm-yy" > </p> <p> <label for="cardCVV">Card verification value:</label> <!-- Card CVV --> <input type="text" name= "cardCVV" id="cardCVV" > </p> </fieldset> <!-- All the hidden inputs are declared here --> <input type="hidden" name="firstName" id="firstNameSend"> <input type="hidden" name="lastName" id="lastNameSend"> <input type="hidden" name="email" id="emailSend"> <input type="hidden" name="address" id="addressSend"> <input type="hidden" name="suburb" id="suburbSend"> <input type="hidden" name="state" id="stateSend"> <input type="hidden" name="postCode" id="postCodeSend"> <input type="hidden" name="phone" id="phoneSend"> <input type="hidden" name="contact" id="contactSend"> <input type="hidden" name="enquire" id="enquireSend"> <input type="hidden" name="features" id="featuresSend"> <input type="hidden" name="comment" id="commentSend"> <input type="hidden" name="purchases" id="purchasesSend"> <input type="hidden" name="cost" id="costSend"> <p> <input type="submit" value="Check Out" class="button"> <!-- submit form to server --> <input type="reset" value="Cancel Order" id="cancelOrder" class="button"> <!-- destroy the memory and redirect to index.html --> </p> </form> </main> <footer> <!-- Footer section --> <p> <a href="https://www.swinburne.edu.au">&copy; Swinburne University of Technology</a> <span>Mark up by: </span> <a href="mailto:101922778@student.swin.edu.au">Hy Gia Nguyen</a> </p> </footer> </body> </html>
import 'package:em_chat_uikit/chat_uikit.dart'; import 'package:flutter/material.dart'; class ListItem extends StatelessWidget { const ListItem({ required this.title, this.subtitle, this.imageWidget, this.trailingString, this.trailingStyle, this.trailingWidget, this.enableArrow = false, this.onTap, super.key, }); final Widget? imageWidget; final String title; final String? subtitle; final String? trailingString; final TextStyle? trailingStyle; final Widget? trailingWidget; final bool enableArrow; final VoidCallback? onTap; @override Widget build(BuildContext context) { final theme = ChatUIKitTheme.of(context); Widget content = SizedBox( height: 54, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (imageWidget != null) SizedBox( width: 28, height: 28, child: imageWidget, ), if (imageWidget != null) const SizedBox(width: 8), Expanded( flex: 2, child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( title, textScaler: TextScaler.noScaling, overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: theme.font.titleMedium.fontSize, fontWeight: theme.font.titleMedium.fontWeight, color: theme.color.isDark ? theme.color.neutralColor100 : theme.color.neutralColor1, ), ), if (subtitle?.isNotEmpty == true) Text( subtitle!, textScaler: TextScaler.noScaling, style: TextStyle( fontSize: theme.font.labelMedium.fontSize, fontWeight: theme.font.labelMedium.fontWeight, color: theme.color.isDark ? theme.color.neutralColor7 : theme.color.neutralColor5, ), ), ], ), ), if (trailingWidget != null) Flexible( fit: FlexFit.loose, child: Align( alignment: Alignment.centerRight, child: trailingWidget, )), if (trailingWidget == null && trailingString != null) Flexible( fit: FlexFit.tight, child: Text( trailingString ?? '', textAlign: TextAlign.right, textScaler: TextScaler.noScaling, overflow: TextOverflow.ellipsis, style: trailingStyle ?? TextStyle( fontSize: theme.font.labelMedium.fontSize, fontWeight: theme.font.labelMedium.fontWeight, color: theme.color.isDark ? theme.color.neutralColor7 : theme.color.neutralColor5, ), ), ), const SizedBox(width: 4), if (enableArrow) Icon( Icons.arrow_forward_ios, size: 16, color: theme.color.isDark ? theme.color.neutralColor95 : theme.color.neutralColor3, ), ], ), ); content = Padding( padding: const EdgeInsets.only(left: 16, right: 10), child: content, ); content = Stack( children: [ content, Positioned( left: imageWidget != null ? 36 : 16, right: 0, bottom: 0, child: Divider( height: 0.5, color: theme.color.isDark ? theme.color.neutralColor2 : theme.color.neutralColor9, ), ), ], ); content = InkWell( onTap: onTap, child: content, ); return content; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * * * This software consists of voluntary contributions made by many individuals on behalf of the * Apache Software Foundation. For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng <webmaster@buession.com> | * | Copyright @ 2013-2022 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.httpclient.core; import com.buession.core.utils.StringUtils; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * 响应头解析器抽象类 * * @param <T> * 原始响应头类型 * * @author Yong.Teng * @since 2.0.0 */ public abstract class AbstractResponseHeaderParse<T> implements ResponseHeaderParse<T> { @Override public List<Header> parse(final T headers){ if(headers == null){ return null; } final Multimap<String, String> headersMap = HashMultimap.create(); doParse(headers, headersMap); return Collections.unmodifiableList( headersMap.keySet().stream().map((name)->new Header(name, StringUtils.join(headersMap.get(name), ", "))) .collect(Collectors.toList())); } protected abstract void doParse(final T headers, final Multimap<String, String> headersMap); }
"use client"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { z } from "zod"; import Image from "next/image"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { useToast } from "@/components/ui/use-toast"; import Link from "next/link"; import { FaRegEyeSlash } from "react-icons/fa"; import { FaRegEye } from "react-icons/fa"; import { useState } from "react"; const FormSchema = z.object({ name: z.string().min(2, { message: "name must be at least 2 characters.", }), email: z.string().email({ message: "Invalid email address.", }), password: z.string().min(8, { message: "Password must be at least 8 characters.", }), }); function SignupForm() { const { toast } = useToast(); const [passwordType, setPasswordType] = useState("password"); const form = useForm({ resolver: zodResolver(FormSchema), defaultValues: { name: "", email: "", password: "", }, }); function onSubmit(data) { console.log(data); toast({ title: "You submitted the following values:", description: ( <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4"> <code className="text-white">{JSON.stringify(data, null, 2)}</code> </pre> ), }); } return ( <div className="flex justify-center items-center flex-col"> <h3 className="py-4 text-[#351120] text-3xl mb-4"> Sign Up as User </h3> <div className="flex space-x-4 mb-4"> <Button className="bg-white"> <Image src="/images/auth/search-2.png" alt="Google" className="mr-2" width={20} height={20} /> Sign up with Google </Button> <Button className="bg-white py-4"> <Image src="/images/auth/facebook-1.png" alt="Facebook" className="mr-2" width={20} height={20} /> Sign up with Facebook </Button> </div> <div className="text-center text-zinc-500 mb-4">- or -</div> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6 m-auto" > <SignupFormField name="name" placeholder="Full Name" formControl={form.control} /> <SignupFormField name="email" placeholder="Email" formControl={form.control} /> <div className=" relative"> <SignupFormField name="password" placeholder="Password" inputType={passwordType} formControl={form.control} /> <span className="absolute right-3 top-2 text-zinc-500 cursor-pointer"> {passwordType === "password" ? ( <FaRegEyeSlash onClick={() => setPasswordType("text")} className="cursor-pointer" /> ) : ( <FaRegEye onClick={() => setPasswordType("password")} className="cursor-pointer" /> )} </span> </div> <div className="text-zinc-500 mb-4"> Are you a business?{" "} <Link href="/auth/business" className=" text-[#351120] font-bold"> Sign Up here </Link> </div> <div className="flex justify-center items-center"> <Button type="submit" variant="myCustom" size="lg" className=" rounded-full" > Get Started </Button> </div> </form> </Form> </div> ); } const SignupFormField = ({ name, placeholder, inputType, formControl }) => { return ( <FormField control={formControl} name={name} render={({ field }) => ( <FormItem> <FormControl> <Input placeholder={placeholder} type={inputType || "text"} {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> ); }; export default SignupForm;
--- title: "\"2024 Approved Bring the Beat Home Add Songs to Your InShot App\"" date: 2024-06-27T10:04:16.232Z updated: 2024-06-28T10:04:16.232Z tags: - screen-recording - ai video - ai audio - ai auto categories: - ai - screen description: "\"This Article Describes 2024 Approved: Bring the Beat Home: Add Songs to Your InShot App\"" excerpt: "\"This Article Describes 2024 Approved: Bring the Beat Home: Add Songs to Your InShot App\"" keywords: "\"IPhone Filmmaking,DIY Short Films,Mobile Editing,Phone-Based Storytelling,Quick Mobile Projects,Creative Phone Content,Short Films on iOS\"" thumbnail: https://thmb.techidaily.com/5397c89a05d7c549e3c941ac0bcf9ef244a3e9feb2997b7fec4700344c4b271c.jpg --- ## Bring the Beat Home: Add Songs to Your InShot App Recording an aesthetic and classic video is never enough. Any recorded content always requires editing to make it shine. Nowadays, edited and attractive content is not the only requirement. Instead, maintaining the interest of your viewers is a crucial demand in this fancy social media era. This could be done by adding sound effects or music to your videos. InShot video editor helps the user add music to their content that can be shared on any social media platform. It has made the consumers' work easy. The only question left unanswered is how to add music to InShot on iPhone and Android devices. The article will share the answer to this question in detail. #### In this article 01 [How to Import Music from Spotify to InShot?](#part1) 02 [How to Import Music from Apple Music to InShot?](#part2) 03 [How to Add Music to InShot Videos?](#part3) ## Part 1\. How to Import Music from Spotify to InShot? You can add music and sound effects to your videos with InShot. Multiple music applications could be used for this purpose, yet Spotify does not support this. Spotify is only available for online streaming on the application and the web player. You cannot import music from Spotify to InShot directly, but with an indirect medium, the job could be done. The answer to how to import music from Spotify to InShot is using a third-party tool to convert Spotify music to the file format that is accepted by InShot. Tunelf Spotibeat Music Converter could be used to convert Spotify music. Now let us talk about the steps that will guide you to convert Spotify music to import it to InShot. Step 1: First of all, launch Tunelf and find the music or album you want to convert from the music converter. Then, you should right-click on the Spotify item and copy its URL. Move to Tunelf interface and paste the URL in the search bar, and hit the "+" button. ![add your spotify songs](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-1.jpg) Step 2: You can customize the parameters of the song by selecting the ‘Menu’ option and then moving to "Preferences." From there, you have to hit the "Convert" option and set the parameters. ![set the songs output format](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-2.jpg) Step 3: Once you have set the output parameters, you can now download the Spotify songs to any downloadable format by just clicking on the "Convert" button. ![spotify song is converting](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-3.jpg) Step 4: For Android users, connect your mobile device to your laptops using a USB wire and then transfer the downloaded music to their mobile. In comparison, iOS users can use iTunes to transfer the music to their iPhones. Step 5: Now, create a new project on InShot. Hit the "Video" title to create or load any video when you enter the editing interface, head over to the "Music" tab from the toolbar available at the bottom of the screen. Step 6: At this point, hit the "Track" button and move to the "My Music" section. Now browse the song that you converted from Spotify and click on the ‘Use’ button to load it. ![use spotify song in inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-4.jpg) ## Part 2\. How to Import Music from Apple Music to InShot? Apple Music offers a variety of tracks to its users. The only drawback of using Apple Music tracks is its DRM protection. Due to this protection, the tracks from Apple Music cannot be used on other platforms like InShot. Here, a question arises about how to import music to InShot if you cannot use it directly from Apple Music. The answer to this question is DRmare Apple Music Converter. This tool is used to convert the Apple Music tracks into plain audio formats that are supported by InShot editor. If you have never used the convertor before, then the following steps will help you learn it. Step 1: To start the process, set DRmare Apple Music Converter on your computer. Then open the convertor and start importing the already downloaded Apple Music files. This could be done by pressing the "Add Files" button. ![import apple music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-5.jpg) Step 2: You can set the output audio format for the files. For this, move to the "Format" icon and click on it. A new window will appear in front of you. You can change the audio format, adjust the bit rate, audio channel, etc. Once satisfied, hit the ‘OK’ button to save the changes. ![set apple music output](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-6.jpg) Step 3: Lastly, to download the converted files from DRmare Apple Music Converter, press the "Convert" button. You can find the converted files on your computer. ![apple music converted](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-7.jpg) Step 4: To import the files to InShot, firstly connect your Android phone or iPhone to your computer using a USB cable. Then locate and transfer the converted music files to your phone. Step 5: At this point, launch the InShot app on your phone and create a new project. When the editing interface opens, move to the "Music" tab from the bottom. Step 6: Click on the "Track" button and select the option of "My Music." You can now select the converted Apple Music file to add it into the InShot’s library and then select the "Use" option to add it to the video. ![add your apple music to inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-8.jpg) ## Part 3\. How to Add Music to InShot Videos? The brilliant editing application InShot is available for both Android phones and iPhones. You can [edit your videos from Inshot platform](https://tools.techidaily.com/wondershare/filmora/download/) and also add songs to it so that your content becomes interesting. People who are new to this might think about how to add music to InShot videos. So, here we are to clarify all your questions and confusion. The following section of this article will share the steps that will guide you in adding music to your InShot videos within minutes and with great ease. Step 1: To start the process, you should first install the InShot application on your Android phone or iPhone. Then, open the app. Step 2: From the main screen, you have to select the "Video" menu. Once that is selected, then create a new editing project. ![select the option of video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-9.jpg) Step 3: Once you are on the editing interface, locate and then import the video that you want to edit and add a song. ![choose your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-10.jpg) Step 4: Now, from the options at the bottom of the screen, move to the "Music" tab. Then click on the "Tracks" menu to select the song that you want to add to your video. ![tap on the option of music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-11.jpg) Step 5: You can either use the music provided by the InShot application by selecting the 'Featured' tab. Or else, by selecting the "My Music" tab, you can import your favorite music from your device to the app. ![choose your music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-12.jpg) Step 6: Once you have selected your music, hit the "Use" button so that it is added to your video. Lastly, you can customize and adjust the song the way you like it. ![insert music to your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-13.jpg) Click here to learn [how to add transitions on Inshot](https://tools.techidaily.com/wondershare/filmora/download/). ### Bottom Line The article talked about InShot musically and also taught you how to add music to InShot video on iPhone and Android, both phones. The article discussed in detail about how to use InShot but if you are looking for some other editors, then let us share about Wondershare Filmora. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a very powerful video editing software that is available for both Windows and macOS. You can easily download the software and use all its features for free. The software is not just an editor; but instead, it is more like a teaching platform where you can learn and polish your skills to become the best. Filmora owns a massive asset library that consists of hundreds of effects, filters, sound effects, stickers, and a lot more fun elements that can bring beauty to your content after editing. Wondershare Filmora has proved itself as the best editing software. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) 02 [How to Import Music from Apple Music to InShot?](#part2) 03 [How to Add Music to InShot Videos?](#part3) ## Part 1\. How to Import Music from Spotify to InShot? You can add music and sound effects to your videos with InShot. Multiple music applications could be used for this purpose, yet Spotify does not support this. Spotify is only available for online streaming on the application and the web player. You cannot import music from Spotify to InShot directly, but with an indirect medium, the job could be done. The answer to how to import music from Spotify to InShot is using a third-party tool to convert Spotify music to the file format that is accepted by InShot. Tunelf Spotibeat Music Converter could be used to convert Spotify music. Now let us talk about the steps that will guide you to convert Spotify music to import it to InShot. Step 1: First of all, launch Tunelf and find the music or album you want to convert from the music converter. Then, you should right-click on the Spotify item and copy its URL. Move to Tunelf interface and paste the URL in the search bar, and hit the "+" button. ![add your spotify songs](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-1.jpg) Step 2: You can customize the parameters of the song by selecting the ‘Menu’ option and then moving to "Preferences." From there, you have to hit the "Convert" option and set the parameters. ![set the songs output format](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-2.jpg) Step 3: Once you have set the output parameters, you can now download the Spotify songs to any downloadable format by just clicking on the "Convert" button. ![spotify song is converting](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-3.jpg) Step 4: For Android users, connect your mobile device to your laptops using a USB wire and then transfer the downloaded music to their mobile. In comparison, iOS users can use iTunes to transfer the music to their iPhones. Step 5: Now, create a new project on InShot. Hit the "Video" title to create or load any video when you enter the editing interface, head over to the "Music" tab from the toolbar available at the bottom of the screen. Step 6: At this point, hit the "Track" button and move to the "My Music" section. Now browse the song that you converted from Spotify and click on the ‘Use’ button to load it. ![use spotify song in inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-4.jpg) ## Part 2\. How to Import Music from Apple Music to InShot? Apple Music offers a variety of tracks to its users. The only drawback of using Apple Music tracks is its DRM protection. Due to this protection, the tracks from Apple Music cannot be used on other platforms like InShot. Here, a question arises about how to import music to InShot if you cannot use it directly from Apple Music. The answer to this question is DRmare Apple Music Converter. This tool is used to convert the Apple Music tracks into plain audio formats that are supported by InShot editor. If you have never used the convertor before, then the following steps will help you learn it. Step 1: To start the process, set DRmare Apple Music Converter on your computer. Then open the convertor and start importing the already downloaded Apple Music files. This could be done by pressing the "Add Files" button. ![import apple music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-5.jpg) Step 2: You can set the output audio format for the files. For this, move to the "Format" icon and click on it. A new window will appear in front of you. You can change the audio format, adjust the bit rate, audio channel, etc. Once satisfied, hit the ‘OK’ button to save the changes. ![set apple music output](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-6.jpg) Step 3: Lastly, to download the converted files from DRmare Apple Music Converter, press the "Convert" button. You can find the converted files on your computer. ![apple music converted](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-7.jpg) Step 4: To import the files to InShot, firstly connect your Android phone or iPhone to your computer using a USB cable. Then locate and transfer the converted music files to your phone. Step 5: At this point, launch the InShot app on your phone and create a new project. When the editing interface opens, move to the "Music" tab from the bottom. Step 6: Click on the "Track" button and select the option of "My Music." You can now select the converted Apple Music file to add it into the InShot’s library and then select the "Use" option to add it to the video. ![add your apple music to inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-8.jpg) ## Part 3\. How to Add Music to InShot Videos? The brilliant editing application InShot is available for both Android phones and iPhones. You can [edit your videos from Inshot platform](https://tools.techidaily.com/wondershare/filmora/download/) and also add songs to it so that your content becomes interesting. People who are new to this might think about how to add music to InShot videos. So, here we are to clarify all your questions and confusion. The following section of this article will share the steps that will guide you in adding music to your InShot videos within minutes and with great ease. Step 1: To start the process, you should first install the InShot application on your Android phone or iPhone. Then, open the app. Step 2: From the main screen, you have to select the "Video" menu. Once that is selected, then create a new editing project. ![select the option of video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-9.jpg) Step 3: Once you are on the editing interface, locate and then import the video that you want to edit and add a song. ![choose your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-10.jpg) Step 4: Now, from the options at the bottom of the screen, move to the "Music" tab. Then click on the "Tracks" menu to select the song that you want to add to your video. ![tap on the option of music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-11.jpg) Step 5: You can either use the music provided by the InShot application by selecting the 'Featured' tab. Or else, by selecting the "My Music" tab, you can import your favorite music from your device to the app. ![choose your music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-12.jpg) Step 6: Once you have selected your music, hit the "Use" button so that it is added to your video. Lastly, you can customize and adjust the song the way you like it. ![insert music to your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-13.jpg) Click here to learn [how to add transitions on Inshot](https://tools.techidaily.com/wondershare/filmora/download/). ### Bottom Line The article talked about InShot musically and also taught you how to add music to InShot video on iPhone and Android, both phones. The article discussed in detail about how to use InShot but if you are looking for some other editors, then let us share about Wondershare Filmora. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a very powerful video editing software that is available for both Windows and macOS. You can easily download the software and use all its features for free. The software is not just an editor; but instead, it is more like a teaching platform where you can learn and polish your skills to become the best. Filmora owns a massive asset library that consists of hundreds of effects, filters, sound effects, stickers, and a lot more fun elements that can bring beauty to your content after editing. Wondershare Filmora has proved itself as the best editing software. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) 02 [How to Import Music from Apple Music to InShot?](#part2) 03 [How to Add Music to InShot Videos?](#part3) ## Part 1\. How to Import Music from Spotify to InShot? You can add music and sound effects to your videos with InShot. Multiple music applications could be used for this purpose, yet Spotify does not support this. Spotify is only available for online streaming on the application and the web player. You cannot import music from Spotify to InShot directly, but with an indirect medium, the job could be done. The answer to how to import music from Spotify to InShot is using a third-party tool to convert Spotify music to the file format that is accepted by InShot. Tunelf Spotibeat Music Converter could be used to convert Spotify music. Now let us talk about the steps that will guide you to convert Spotify music to import it to InShot. Step 1: First of all, launch Tunelf and find the music or album you want to convert from the music converter. Then, you should right-click on the Spotify item and copy its URL. Move to Tunelf interface and paste the URL in the search bar, and hit the "+" button. ![add your spotify songs](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-1.jpg) Step 2: You can customize the parameters of the song by selecting the ‘Menu’ option and then moving to "Preferences." From there, you have to hit the "Convert" option and set the parameters. ![set the songs output format](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-2.jpg) Step 3: Once you have set the output parameters, you can now download the Spotify songs to any downloadable format by just clicking on the "Convert" button. ![spotify song is converting](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-3.jpg) Step 4: For Android users, connect your mobile device to your laptops using a USB wire and then transfer the downloaded music to their mobile. In comparison, iOS users can use iTunes to transfer the music to their iPhones. Step 5: Now, create a new project on InShot. Hit the "Video" title to create or load any video when you enter the editing interface, head over to the "Music" tab from the toolbar available at the bottom of the screen. Step 6: At this point, hit the "Track" button and move to the "My Music" section. Now browse the song that you converted from Spotify and click on the ‘Use’ button to load it. ![use spotify song in inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-4.jpg) ## Part 2\. How to Import Music from Apple Music to InShot? Apple Music offers a variety of tracks to its users. The only drawback of using Apple Music tracks is its DRM protection. Due to this protection, the tracks from Apple Music cannot be used on other platforms like InShot. Here, a question arises about how to import music to InShot if you cannot use it directly from Apple Music. The answer to this question is DRmare Apple Music Converter. This tool is used to convert the Apple Music tracks into plain audio formats that are supported by InShot editor. If you have never used the convertor before, then the following steps will help you learn it. Step 1: To start the process, set DRmare Apple Music Converter on your computer. Then open the convertor and start importing the already downloaded Apple Music files. This could be done by pressing the "Add Files" button. ![import apple music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-5.jpg) Step 2: You can set the output audio format for the files. For this, move to the "Format" icon and click on it. A new window will appear in front of you. You can change the audio format, adjust the bit rate, audio channel, etc. Once satisfied, hit the ‘OK’ button to save the changes. ![set apple music output](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-6.jpg) Step 3: Lastly, to download the converted files from DRmare Apple Music Converter, press the "Convert" button. You can find the converted files on your computer. ![apple music converted](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-7.jpg) Step 4: To import the files to InShot, firstly connect your Android phone or iPhone to your computer using a USB cable. Then locate and transfer the converted music files to your phone. Step 5: At this point, launch the InShot app on your phone and create a new project. When the editing interface opens, move to the "Music" tab from the bottom. Step 6: Click on the "Track" button and select the option of "My Music." You can now select the converted Apple Music file to add it into the InShot’s library and then select the "Use" option to add it to the video. ![add your apple music to inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-8.jpg) ## Part 3\. How to Add Music to InShot Videos? The brilliant editing application InShot is available for both Android phones and iPhones. You can [edit your videos from Inshot platform](https://tools.techidaily.com/wondershare/filmora/download/) and also add songs to it so that your content becomes interesting. People who are new to this might think about how to add music to InShot videos. So, here we are to clarify all your questions and confusion. The following section of this article will share the steps that will guide you in adding music to your InShot videos within minutes and with great ease. Step 1: To start the process, you should first install the InShot application on your Android phone or iPhone. Then, open the app. Step 2: From the main screen, you have to select the "Video" menu. Once that is selected, then create a new editing project. ![select the option of video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-9.jpg) Step 3: Once you are on the editing interface, locate and then import the video that you want to edit and add a song. ![choose your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-10.jpg) Step 4: Now, from the options at the bottom of the screen, move to the "Music" tab. Then click on the "Tracks" menu to select the song that you want to add to your video. ![tap on the option of music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-11.jpg) Step 5: You can either use the music provided by the InShot application by selecting the 'Featured' tab. Or else, by selecting the "My Music" tab, you can import your favorite music from your device to the app. ![choose your music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-12.jpg) Step 6: Once you have selected your music, hit the "Use" button so that it is added to your video. Lastly, you can customize and adjust the song the way you like it. ![insert music to your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-13.jpg) Click here to learn [how to add transitions on Inshot](https://tools.techidaily.com/wondershare/filmora/download/). ### Bottom Line The article talked about InShot musically and also taught you how to add music to InShot video on iPhone and Android, both phones. The article discussed in detail about how to use InShot but if you are looking for some other editors, then let us share about Wondershare Filmora. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a very powerful video editing software that is available for both Windows and macOS. You can easily download the software and use all its features for free. The software is not just an editor; but instead, it is more like a teaching platform where you can learn and polish your skills to become the best. Filmora owns a massive asset library that consists of hundreds of effects, filters, sound effects, stickers, and a lot more fun elements that can bring beauty to your content after editing. Wondershare Filmora has proved itself as the best editing software. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) 02 [How to Import Music from Apple Music to InShot?](#part2) 03 [How to Add Music to InShot Videos?](#part3) ## Part 1\. How to Import Music from Spotify to InShot? You can add music and sound effects to your videos with InShot. Multiple music applications could be used for this purpose, yet Spotify does not support this. Spotify is only available for online streaming on the application and the web player. You cannot import music from Spotify to InShot directly, but with an indirect medium, the job could be done. The answer to how to import music from Spotify to InShot is using a third-party tool to convert Spotify music to the file format that is accepted by InShot. Tunelf Spotibeat Music Converter could be used to convert Spotify music. Now let us talk about the steps that will guide you to convert Spotify music to import it to InShot. Step 1: First of all, launch Tunelf and find the music or album you want to convert from the music converter. Then, you should right-click on the Spotify item and copy its URL. Move to Tunelf interface and paste the URL in the search bar, and hit the "+" button. ![add your spotify songs](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-1.jpg) Step 2: You can customize the parameters of the song by selecting the ‘Menu’ option and then moving to "Preferences." From there, you have to hit the "Convert" option and set the parameters. ![set the songs output format](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-2.jpg) Step 3: Once you have set the output parameters, you can now download the Spotify songs to any downloadable format by just clicking on the "Convert" button. ![spotify song is converting](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-3.jpg) Step 4: For Android users, connect your mobile device to your laptops using a USB wire and then transfer the downloaded music to their mobile. In comparison, iOS users can use iTunes to transfer the music to their iPhones. Step 5: Now, create a new project on InShot. Hit the "Video" title to create or load any video when you enter the editing interface, head over to the "Music" tab from the toolbar available at the bottom of the screen. Step 6: At this point, hit the "Track" button and move to the "My Music" section. Now browse the song that you converted from Spotify and click on the ‘Use’ button to load it. ![use spotify song in inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-4.jpg) ## Part 2\. How to Import Music from Apple Music to InShot? Apple Music offers a variety of tracks to its users. The only drawback of using Apple Music tracks is its DRM protection. Due to this protection, the tracks from Apple Music cannot be used on other platforms like InShot. Here, a question arises about how to import music to InShot if you cannot use it directly from Apple Music. The answer to this question is DRmare Apple Music Converter. This tool is used to convert the Apple Music tracks into plain audio formats that are supported by InShot editor. If you have never used the convertor before, then the following steps will help you learn it. Step 1: To start the process, set DRmare Apple Music Converter on your computer. Then open the convertor and start importing the already downloaded Apple Music files. This could be done by pressing the "Add Files" button. ![import apple music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-5.jpg) Step 2: You can set the output audio format for the files. For this, move to the "Format" icon and click on it. A new window will appear in front of you. You can change the audio format, adjust the bit rate, audio channel, etc. Once satisfied, hit the ‘OK’ button to save the changes. ![set apple music output](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-6.jpg) Step 3: Lastly, to download the converted files from DRmare Apple Music Converter, press the "Convert" button. You can find the converted files on your computer. ![apple music converted](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-7.jpg) Step 4: To import the files to InShot, firstly connect your Android phone or iPhone to your computer using a USB cable. Then locate and transfer the converted music files to your phone. Step 5: At this point, launch the InShot app on your phone and create a new project. When the editing interface opens, move to the "Music" tab from the bottom. Step 6: Click on the "Track" button and select the option of "My Music." You can now select the converted Apple Music file to add it into the InShot’s library and then select the "Use" option to add it to the video. ![add your apple music to inshot](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-8.jpg) ## Part 3\. How to Add Music to InShot Videos? The brilliant editing application InShot is available for both Android phones and iPhones. You can [edit your videos from Inshot platform](https://tools.techidaily.com/wondershare/filmora/download/) and also add songs to it so that your content becomes interesting. People who are new to this might think about how to add music to InShot videos. So, here we are to clarify all your questions and confusion. The following section of this article will share the steps that will guide you in adding music to your InShot videos within minutes and with great ease. Step 1: To start the process, you should first install the InShot application on your Android phone or iPhone. Then, open the app. Step 2: From the main screen, you have to select the "Video" menu. Once that is selected, then create a new editing project. ![select the option of video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-9.jpg) Step 3: Once you are on the editing interface, locate and then import the video that you want to edit and add a song. ![choose your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-10.jpg) Step 4: Now, from the options at the bottom of the screen, move to the "Music" tab. Then click on the "Tracks" menu to select the song that you want to add to your video. ![tap on the option of music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-11.jpg) Step 5: You can either use the music provided by the InShot application by selecting the 'Featured' tab. Or else, by selecting the "My Music" tab, you can import your favorite music from your device to the app. ![choose your music](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-12.jpg) Step 6: Once you have selected your music, hit the "Use" button so that it is added to your video. Lastly, you can customize and adjust the song the way you like it. ![insert music to your video](https://images.wondershare.com/filmora/article-images/2021/import-music-to-inshot-video-editor-13.jpg) Click here to learn [how to add transitions on Inshot](https://tools.techidaily.com/wondershare/filmora/download/). ### Bottom Line The article talked about InShot musically and also taught you how to add music to InShot video on iPhone and Android, both phones. The article discussed in detail about how to use InShot but if you are looking for some other editors, then let us share about Wondershare Filmora. [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a very powerful video editing software that is available for both Windows and macOS. You can easily download the software and use all its features for free. The software is not just an editor; but instead, it is more like a teaching platform where you can learn and polish your skills to become the best. Filmora owns a massive asset library that consists of hundreds of effects, filters, sound effects, stickers, and a lot more fun elements that can bring beauty to your content after editing. Wondershare Filmora has proved itself as the best editing software. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://article-knowledge.techidaily.com/2024-approved-camera-essentials-for-rookie-filmmakers/"><u>2024 Approved Camera Essentials for Rookie Filmmakers</u></a></li> <li><a href="https://article-knowledge.techidaily.com/2024-approved-echo-music-into-your-whatsapp-narrative/"><u>2024 Approved Echo Music Into Your WhatsApp Narrative</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-hottest-online-spots-customized-packaging-at-your-fingertips-for-2024/"><u>[New] Hottest Online Spots Customized Packaging at Your Fingertips for 2024</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-innovating-connectivity-the-moto-z2-reviewed/"><u>[New] Innovating Connectivity The Moto Z2 Reviewed</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-in-2024-auditory-anchors-exploring-the-art-of-sound-blending/"><u>[New] In 2024, Auditory Anchors Exploring the Art of Sound Blending</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-frugal-cloud-cradle-for-copious-file-collection/"><u>[New] Frugal Cloud Cradle for Copious File Collection</u></a></li> <li><a href="https://article-knowledge.techidaily.com/updated-in-2024-pristine-teaser-trailer-trove/"><u>[Updated] In 2024, Pristine Teaser Trailer Trove</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-step-by-step-download-and-personalize-whatsapp-ringtones-on-mobile-for-2024/"><u>[New] Step-by-Step Download & Personalize WhatsApp Ringtones on Mobile for 2024</u></a></li> <li><a href="https://article-knowledge.techidaily.com/2024-approved-mastering-adventure-the-best-6-gopro-mounts-revealed/"><u>2024 Approved Mastering Adventure The Best 6 GoPro Mounts Revealed</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-innovative-methods-to-access-apples-podcast-library-for-2024/"><u>[New] Innovative Methods to Access Apple's Podcast Library for 2024</u></a></li> <li><a href="https://ios-unlock.techidaily.com/in-2024-the-best-methods-to-unlock-the-iphone-locked-to-owner-for-apple-iphone-xr-by-drfone-ios/"><u>In 2024, The Best Methods to Unlock the iPhone Locked to Owner for Apple iPhone XR</u></a></li> <li><a href="https://screen-sharing-recording.techidaily.com/updated-pro-tips-making-your-ipad-screen-capture-faster-and-hassle-free-for-2024/"><u>[Updated] Pro Tips Making Your iPad Screen Capture Faster and Hassle-Free for 2024</u></a></li> <li><a href="https://extra-guidance.techidaily.com/in-2024-revolutionize-gaming-sounds-ps5ps4-edition/"><u>In 2024, Revolutionize Gaming Sounds PS5/PS4 Edition</u></a></li> <li><a href="https://extra-guidance.techidaily.com/revolutionizing-your-fpv-flight-with-optimal-blades-for-2024/"><u>Revolutionizing Your FPV Flight with Optimal Blades for 2024</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/everything-you-need-to-know-about-unlocked-apple-iphone-12-mini-drfone-by-drfone-ios/"><u>Everything You Need To Know About Unlocked Apple iPhone 12 mini | Dr.fone</u></a></li> <li><a href="https://facebook-video-share.techidaily.com/new-in-2024-crafting-comedy-the-art-of-parody-videos/"><u>[New] In 2024, Crafting Comedy The Art of Parody Videos</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-beginners-guide-top-cartoon-video-makers-online-and-offline/"><u>Updated 2024 Approved Beginners Guide Top Cartoon Video Makers Online and Offline</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-how-i-transferred-messages-from-oppo-a2-to-iphone-12xs-max-in-seconds-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, How I Transferred Messages from Oppo A2 to iPhone 12/XS (Max) in Seconds | Dr.fone</u></a></li> <li><a href="https://youtube-help.techidaily.com/new-propel-your-youtube-content-faster-render-and-efficient-upload-processes/"><u>[New] Propel Your YouTube Content Faster Render & Efficient Upload Processes</u></a></li> <li><a href="https://unlock-android.techidaily.com/how-to-reset-a-locked-vivo-s18-phone-by-drfone-android/"><u>How to Reset a Locked Vivo S18 Phone</u></a></li> </ul></div>
package com.lani.boj.silver; import java.io.*; import java.util.*; public class S1431 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] arr = new String[n]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) arr[i] = br.readLine(); Comparator<String> comparator = new Comparator<>() { @Override public int compare(String o1, String o2) { if (o1.length() != o2.length()) return o1.length() - o2.length(); else { int o1sum = 0, o2sum = 0; for (int i = 0; i < o1.length(); i++) { if (Character.isDigit(o1.charAt(i))) o1sum += o1.charAt(i) - '0'; if (Character.isDigit(o2.charAt(i))) o2sum += o2.charAt(i) - '0'; } if (o1sum != o2sum) return o1sum - o2sum; else return o1.compareTo(o2); } } }; Arrays.sort(arr, comparator); for (String s : arr) sb.append(s).append('\n'); System.out.println(sb); br.close(); } }
@extends('admin.layouts.view_content') @section('content-blog') <link rel="stylesheet" href="{{ asset('admin/css/all.css') }}"> <div class="col-12 mx-auto" id="index_article"> <div class="form-group row"> <label for="staticEmail" class="col-sm-1 col-form-label">Search</label> <div class="col-sm-11"> <input value="" name="title" type="text" class="form-control" id="search" aria-describedby="titleHelp" placeholder="Search"> </div> </div> <table class="table"> <thead class="thead-light"> <tr> <th scope="col">#</th> <th scope="col"><i class="fa-solid fa-blog mr-2"></i> Title</th> <th scope="col"><i class="fa-solid fa-at mr-2"></i> User</th> <th scope="col"><i class="fa-solid fa-bars-staggered mr-2"></i> Features</th> </tr> </thead> <tbody id="body-article"> @foreach ($comments as $index => $comment) <tr> <th>{{ $comments->perPage() * ($comments->currentPage() - 1) + $index + 1 }}</th> <td>{{ \Illuminate\Support\Str::limit($comment->content, 69, '...') }}</td> <td>{{ $comment->name }}</td> <td> <form method="POST" action="{{ route('admin.delete_comment', $comment->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this comment ?');"> @csrf <button type="submit" class="btn btn-outline-danger"><i class="fa-solid fa-trash"></i> Delete</button> </form> </td> </tr> @endforeach </tbody> </table> <div id="pagination_container"> {{ $comments->links() }} </div> </div> <script src="{{ asset('admin/js/search-all-cmt.js') }}"></script> @endsection @push('styles-index') <style> </style> @endpush @push('scripts-index') <script> console.log('Hello INDEX'); </script> @endpush
import { useState } from 'react'; import styles from './App.module.css'; import poweredImage from './assets/powered.png'; import {levels, calculateBMI, Level} from './helpers/imc'; import { GridItem } from './components/GridItem'; import leftArrow from './assets/leftarrow.png'; function App() { const [heightField, setHeightField] = useState<number>(0); const [weightField, setWeightField] = useState<number>(0); const [toShow,setToShow] = useState<Level|null>(null); const handleCalculteButton = () => { if(heightField && weightField){ setToShow(calculateBMI(heightField, weightField)); }else { window.alert("Por favor preencha todos os campos") } } const handleArrow = ()=> { setToShow(null); setHeightField(0); setWeightField(0); } return ( <div className={styles.main}> <header> <div className={styles.headerContainer}> <img src={poweredImage} alt="Logo" width={150}/> </div> </header> <div className={styles.container}> <div className={styles.leftSide}> <h1>Calcule o seu IMC</h1> <p>IMC é a singla para Índice de Massa Corpórea, parâmetro adotado pela Organização Mundial da Saúde para calcular o peso ideal de cada pessoa.</p> <input disabled={toShow? true: false} type="number" placeholder='Digite a sua altura. Ex: 1.5 (em metros) ' value={heightField>0?heightField:''} onChange={e => setHeightField(parseFloat(e.target.value))} /> <input disabled={toShow? true: false} type="number" placeholder='Digite o seu peso. Ex: 70.5 (em kilos) ' value={weightField>0?weightField:''} onChange={e => setWeightField(parseFloat(e.target.value))} /> <button onClick={handleCalculteButton} disabled={toShow? true: false} >Calcular</button> </div> <div className={styles.rightSide}> {!toShow && <div className={styles.grid}> {levels.map((item, key )=>( <GridItem key={key} item={item}/> ))} </div> } { toShow && <div className={styles.rightBig}> <div className={styles.rightArrow} onClick={handleArrow}> <img src={leftArrow} alt="Left Arrow" width={30}/> </div> <GridItem item={toShow}/> </div> } </div> </div> </div> ); } export default App;
############################## # Data visualization in base R ############################## df = data.frame(months = rep(month.abb, length.out = 100), alphabet = rep(LETTERS, length.out = 100), binary = sample(c(0,1), 100, replace = TRUE), sex = rep(as.factor(c("male", "female")), 50), count = sample(0:100, 100, replace = TRUE), count2 = sample(0:100, 100, replace = TRUE), year = as.factor(sample(2010:2020, 100, replace = TRUE))) #------------- # scatter plot plot(df$count, df$count2) #---------- # histogram hist(df$count) #--------- # bar plot counts = table(df$binary) # store frequencies of the variable you want to plot barplot(counts) abundance = aggregate(df$count, by=list(Group=df$months), FUN=sum) # stores sums of count by month barplot(abundance$x) #--------- # box plot boxplot(count ~ months, data = df) # here we use the formula syntax (y ~ x) to specify we want counts plotted by month #----------------------------------- # arranging different plots together ?par par(mfrow = c(2,2)) # set graphical parameters to be 2 rows and 2 columns plot(df$count, df$count2) hist(df$count) barplot(counts) boxplot(count ~ months, data = df) #------------- # saving plots pdf("base_plots.pdf", width = 12, height = 8) par(mfrow = c(2,2)) # set graphical parameters to be 2 rows and 2 columns plot(df$count, df$count2) hist(df$count) barplot(counts) boxplot(count ~ months, data = df) dev.off() ################################# # Data visualization using ggplot ################################# library(ggplot2) library(dplyr) #------------------- # ggplot components ### geom: a geometric object which defines the type of graph you are making. e.g., geom_point(), geom_boxplot(), geom_histogram() ### aes: short for aesthetics. Usually placed within a geom_, this is where you specify your data source and variables, AND the properties of the graph ### stat: a stat layer applies some statistical transformation to the underlying data: for instance, stat_smooth(method = 'lm') displays a linear regression line and confidence interval ribbon on top of a scatter plot ### theme: a theme is made of a set of visual parameters that control the background, borders, grid lines, axes, text size, legend position, etc #------------- # scatter plot gg_scatter = ggplot(df, aes(x = count, y = count2, colour = sex)) + # linking colour to a factor inside aes() ensures that the points' colour will vary according to the factor levels geom_point() #---------- # histogram gg_hist = ggplot(df, aes(x = count)) + geom_histogram() #--------- # bar plot gg_barplot <- ggplot(df, aes(x = binary)) + geom_bar() abundance <- df %>% group_by(months) %>% mutate(abundance = (sum(count))) # create new column based on sum of counts by month gg_barplot2 <- ggplot(abundance, aes(x = months, y = abundance)) + geom_bar(stat = "identity") #-------- # boxplot gg_boxplot = ggplot(df, aes(months, count)) + geom_boxplot() #----------------------------------- # arranging different plots together library(ggpubr) # need to load an additional package for arranging grids gg_combine = ggarrange( gg_hist, gg_barplot, gg_boxplot, gg_scatter, ncol = 2, nrow = 2) #------- # themes # the ggpubr package also has a clean theme that we can apply to any plot gg_hist + theme_pubr() gg_combine2 = ggarrange( gg_hist + theme_pubr(), gg_barplot + theme_pubr(), gg_boxplot + theme_pubr(), gg_scatter + theme_pubr(), ncol = 2, nrow = 2) #---------------- # saving the plot ggsave(gg_combine2, file = "gg_plots.pdf", width = 12, height = 8) ############################################################################################### # the 2 things that ggplot excels at is 1) quick and dirty regressions and 2) multi-panel plots #---------------------------------- # scatter plot with regression line gg_regression = ggplot(df, aes (x = count, y = count2, colour = sex)) + geom_point() + geom_smooth(method = "lm", aes(fill = sex)) #------------------ # multi-panel plots gg_facets <- ggplot(df, aes (x = count, y = count2, colour = months)) + geom_point() + geom_smooth(method = "lm", aes(fill = months)) + # Adding linear model fit, colour-code by country facet_wrap(~ months, scales = "free_y") # THIS LINE CREATES THE FACETTING ##################### # now it's your turn! # 1. with your own data, make each of the 4 types of plot in base R # 2. combine the 4 plots in a single image and save it in the file type of your choice # 3. do 1) and 2) but using ggplot # 4. add a regression line to your gg scatter plot (if you want a challenge, try replicating in base R) # 5. create a facet plot in ggplot
// src/Pages/EditSong.js import { useState, useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { useParams, useNavigate } from 'react-router-dom'; import { UPDATE_SONG_REQUEST } from '../features/songs/songsActionTypes'; import { styles } from '../Components/Emotions'; const EditSong = ({ onEditComplete }) => { const { id } = useParams(); const navigate = useNavigate(); const dispatch = useDispatch(); const song = useSelector(state => state.songs.songs.find(song => song.id === id)); const [title, setTitle] = useState(''); const [artist, setArtist] = useState(''); const [img, setImg] = useState(''); const [audioUrl, setAudioUrl] = useState(''); const [error, setError] = useState({}); // Add audio URL state useEffect(() => { if (song) { setTitle(song.title); setArtist(song.artist); setImg(song.img); setAudioUrl(song.audioUrl); // Set audio URL } }, [song]); const handleSubmit = (e) => { e.preventDefault(); const newError = {}; if (!title) newError.title = "Music title required"; if (!artist) newError.artist = "Artist name required"; if (!img) newError.img = "Cover image required"; if (!audioUrl) newError.audioUrl = "Audio URL required"; setError(newError); if (Object.keys(newError).length > 0) return; // In handleSubmit dispatch({ type: UPDATE_SONG_REQUEST, payload:{ id, title, artist, img, audioUrl } }); if (onEditComplete) { onEditComplete(); } navigate('/'); }; if (!song) { return <p>Enter Correct Id number of your music.</p>; } return ( <form className={styles.formStyle} onSubmit={handleSubmit}> <input className={styles.inputStyle} type="text" placeholder="Song Title" value={title} onChange={(e) => setTitle(e.target.value)} /> {error.title && <p className={ styles.red }>{error.title}</p>} <input className={styles.inputStyle} type="text" placeholder="Artist" value={artist} onChange={(e) => setArtist(e.target.value)} /> {error.artist && <p className={styles.red}>{error.artist}</p>} <input className={styles.inputStyle} type="text" placeholder="Image URL" value={img} onChange={(e) => setImg(e.target.value)} /> {error.img && <p className={styles.red}>{error.img}</p>} <input className={styles.inputStyle} type="text" placeholder="Audio URL" value={audioUrl} onChange={(e) => setAudioUrl(e.target.value)} /> {error.audioUrl && <p className={styles.red}>{error.audioUrl}</p>} <button className={styles.buttonStyle} type="submit">Update Song</button> </form> ); }; export default EditSong;
import { FaSignInAlt, FaSignOutAlt, FaUser } from "react-icons/fa"; import { useDispatch, useSelector } from "react-redux"; import { Link, useNavigate } from "react-router-dom"; import { logout, reset } from "../features/auth/authSlice"; const Header = () => { const dispatch = useDispatch(); const navigate = useNavigate(); const { user } = useSelector((state) => state.auth); const logoutHandler = () => { dispatch(logout()); dispatch(reset()); navigate("/login"); }; return ( <div className="header"> <div className="logo"> <Link to="/">GoalSetter</Link> </div> <ul> {user ? ( <li> <button className="btn" onClick={logoutHandler}> <FaSignOutAlt /> Logout </button> </li> ) : ( <> <li> <Link to="/login"> <FaSignInAlt /> Login </Link> </li> <li> <Link to="/register"> <FaUser /> Register </Link> </li> </> )} </ul> </div> ); }; export default Header;
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <th:block th:include="base/base :: base_head"/> <title>EDM附件管理</title> <link rel="stylesheet" href="/css/bootstrap/bootstrap.min.css" th:href="${baseUrl + '/css/bootstrap/bootstrap.min.css'}"> <style type="text/css"> .centerEle { height: 60px; display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; } </style> </head> <body> <div class="centerEle"> <div class="form-group col-md-3 mb-2"> <form id="fileForm" action="/file/upload" th:action="${baseUrl + '/file/upload'}" enctype="multipart/form-data" method="post"> <input type="text" name="viewfile" id="viewfile" placeholder="未选择文件" disabled autocomplete="off" class="form-control"> <input type="file" name="file" style="display: none" onchange="reShow();" id="upload"/> </form> </div> <label class="btn btn-primary mb-2" for="upload" style="cursor:pointer;">浏览</label> &nbsp;&nbsp;&nbsp;&nbsp; <label class="btn btn-success mb-2" style="cursor:pointer;" onclick="upload()">上传</label> &nbsp;&nbsp;&nbsp;&nbsp; <label class="mb-2" style="color: red;" id="msg"></label> </div> <div class="centerEle"> <label class="btn btn-link mb-2" style="cursor:pointer;" onclick="download();">下载</label> &nbsp;&nbsp;&nbsp;&nbsp; <label class="btn btn-info mb-2" style="cursor:pointer;" onclick="preview();">预览</label> &nbsp;&nbsp;&nbsp;&nbsp; <label class="btn btn-danger mb-2" style="cursor:pointer;" onclick="pdf2Img();">PDF转图片预览</label> &nbsp;&nbsp;&nbsp;&nbsp; <label class="btn btn-warning mb-2" style="cursor:pointer;" onclick="ocr('Barcode');">识别Barcode</label> &nbsp;&nbsp;&nbsp;&nbsp; <label class="btn btn-warning mb-2" style="cursor:pointer;" onclick="ocr('InvoiceQr');">识别Qr</label> </div> <div style="height: 960px"> <iframe src="" height="100%" width="100%" frameborder="0" ></iframe> </div> </body> <script type="text/javascript" th:inline="javascript"> var docId = ""; function reShow() { document.getElementById('viewfile').value = document.getElementById('upload').value; } function upload() { $("#msg").html(" "); var viewfile = $("#viewfile").val(); if (viewfile === "") { $("#msg").html("文件名不能为空"); return; } $("#fileForm").ajaxSubmit({ url: _ctxPath + "/file/upload", success: function (data) { if (data.success) { docId = data.data.docId; $("#msg").html("文件上传成功!"); } else { docId = ""; $("#msg").html(data.message); } } }); } function download() { if (docId == "") { $("#msg").html("请先上传文件."); return; } window.open(_ctxPath + '/file/download?docIds=' + docId); } function preview() { if (docId == "") { $("#msg").html("请先上传文件."); return; } document.getElementsByTagName('iframe')[0].src = _ctxPath + "/preview?markText=SEI业务协同平台6.0&docId=" + docId; } function pdf2Img() { if (docId == "") { $("#msg").html("请先上传文件."); return; } document.getElementsByTagName('iframe')[0].src = _ctxPath + "/pdf2Img/" + docId; } function ocr(type) { var viewfile = $("#viewfile").val(); if (viewfile === "") { $("#msg").html("文件名不能为空"); return; } $("#fileForm").ajaxSubmit({ url: _ctxPath + "/file/upload?ocr=" + type, success: function (data) { if (data.success) { docId = data.data.docId; alert(data.data.ocrData); } else { docId = ""; alert(data.message); } } }); } </script> <script src="/js/jquery.min.js" th:src="${baseUrl + '/js/jquery-3.0.0.min.js'}"></script> <script src="/js/jquery.form.js" th:src="${baseUrl + '/js/jquery.form.min.js'}"></script> </html>
import { ComponentMeta, ComponentStory } from '@storybook/react'; import React from 'react'; import LoginForm from './LoginForm'; import { StoreDecorator } from '@/shared/config/storybook/StoreDecorator/StoreDecorator'; import { ThemeDecorator } from '@/shared/config/storybook/ThemeDecorator/ThemeDecorator'; import { Theme } from '@/shared/const/theme'; export default { title: 'features/LoginForm', component: LoginForm, argTypes: { backgroundColor: { control: 'color' }, }, } as ComponentMeta<typeof LoginForm>; const Template: ComponentStory<typeof LoginForm> = args => ( <LoginForm {...args} /> ); export const Primary = Template.bind({}); Primary.args = {}; Primary.decorators = [ StoreDecorator({ loginForm: { username: 'admin', password: '123' }, }), ]; export const PrimaryDark = Template.bind({}); PrimaryDark.args = {}; PrimaryDark.decorators = [ StoreDecorator({ loginForm: { username: 'admin', password: '123' } }), ThemeDecorator(Theme.DARK), ]; export const withError = Template.bind({}); withError.args = {}; withError.decorators = [ StoreDecorator({ loginForm: { username: 'admin111', password: '122222', error: 'Some error text', }, }), ]; export const withErrorDark = Template.bind({}); withErrorDark.args = {}; withErrorDark.decorators = [ StoreDecorator({ loginForm: { username: 'error', password: 'error', error: 'Some error text', }, }), ThemeDecorator(Theme.DARK), ]; export const loading = Template.bind({}); loading.args = {}; loading.decorators = [StoreDecorator({ loginForm: { isLoading: true } })]; export const loadingDark = Template.bind({}); loadingDark.args = {}; loadingDark.decorators = [ StoreDecorator({ loginForm: { isLoading: true } }), ThemeDecorator(Theme.DARK), ];
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Recreate Web Page 2</title> </head> <body> <div class="container"> <!-- HEADER --> <div class="header"> <div class="wrapper"> <!-- LOGO --> <div class="logo"> <img src="img/surf.png" alt="" class="surfLogo"> </div> <!-- TITLE --> <div class="title">The Best Surf Camp, Costa Rica</div> </div> <!-- NAVBAR --> <div class="navBar"> <div class="nav"> <div class="navItem"> <ul> <li><a href="#">Home</a></li> <li><a href="#">Adults</a></li> <li><a href="#">Groms</a></li> <li><a href="#">Groups</a></li> <li><a href="#">Surf Report</a></li> <li><a href="#">Surf Shop</a></li> </ul> </div> </div> </div> <!-- FAUX CAROUSEL --> <div class="carousel"> <div class="carouselText">The best surfer out there is the one having the most fun.</div> <img src="img/dots-horizontal-custom (2).png"> </div> <hr> <!-- MAIN --> <!-- CARD ONE --> <div class="main"> <div class="cards"> <h3>News & Events</h3> <p>Straight from surfer.com</p> <ul class="body"> <li>Kelly Slater Returns to Pipeline After Hip Surgery</li> <li>Surf World Calls BS to Toledo's Claim for Pipeline Pull-Out</li> <li>Surfers Wore Helmets on Opening Day of Pipe Pro</li> <li>Watch Mamiya Toy With Pipeline</li> <li>Gory Gash on McNamara's Helmet Sparks Redesign Convo</li> </ul> </div> <!-- CARD TWO --> <div class="cardsTwo"> <h3>Find a Surfcamp</h3> <p>Let's discover the best surf spots for your next surf camp</p> <label for="FirstName">First Name:</label> <input type="text" id="firstName" maxlength="30" required placeholder="First Name"> <label for="lastName">Last Name:</label> <input type="text" id="lastName" maxlength="30" required placeholder="Last Name"> <label for="location">Location:</label> <input type="text" id="location" maxlength="30" required placeholder="Location"> <p>What experience level are you?</p> <div class="checkbox"> <label for="optionOne"><input type="checkbox" id="optionOne">Beginner</label> </div> <div class="checkbox"> <label for="optionTwo"><input type="checkbox" id="optionTwo">Intermediate</label> </div> </div> <!-- CARD THREE --> <div class="cardsThree"> <h3>Quick Tips</h3> <ul class="last"> <li>Find Equipment That Suits You</li> <li>Check The Tides</li> <li>Remember The Rules Of The Line-Up</li> <li>Listen To Your Body</li> <li>Wear a Surf Leash</li> <li>Duck Diving</li> <li>Use Failure To Learn</li> </ul> </div> </div> </div> </body> </html>
import { Component, OnInit } from '@angular/core'; import { Employee } from 'src/app/interfaces/employee.interface'; import { ImputationsService } from 'src/app/services/imputations.service'; import * as moment from 'moment' @Component({ selector: 'app-imputation', templateUrl: './imputation.component.html', styleUrls: ['./imputation.component.css'] }) export class ImputationComponent implements OnInit { employee = JSON.parse(localStorage.getItem('employee')!); // el (!) evita el null imputationsWeek: any; // Carga las imputaciones de TODA LA SEMANA que corresponda arrImputationsWeek: any; currentWeek = moment().format('ww'); week: any; constructor( private imputationsService: ImputationsService ) { } // Cuando carga el componente tengo que detectar en q semana estoy y currentWeek tendra que almacenar el valor de la semana. // Averiguamos cual es la semana actual para pasarselo a LoadImputations async ngOnInit() { try { this.imputationsWeek = await this.imputationsService.LoadImputations(this.currentWeek); // console.log('ngOnInit', this.imputationsWeek); } catch (error) { console.log(error); } } // Event del Output del componente calendar-Week para emitir la semana que seleccionemos. async getWeek($event: any) { // console.log('emitido', $event.week); this.week = $event.week; try { this.imputationsWeek = await this.imputationsService.LoadImputations($event.week); } catch (error) { console.log(error); } } async recharge($event: string) { if ($event === 'ok') { // console.log('this.week', this.week); try { if (this.week) { this.imputationsWeek = await this.imputationsService.LoadImputations(this.week); } else { this.imputationsWeek = await this.imputationsService.LoadImputations(this.currentWeek); } // console.log('recharge', this.imputationsWeek); } catch (error) { console.log(error); } } } }
"C:\Program Files\MongoDB\Server\4.4\bin\mongod" --dbpath "C:\data\db" "C:\Program Files\MongoDB\Server\4.4\bin\mongo" "C:\Program Files\MongoDB\Tools\100\bin\mongoimport" --db products --collection zipcodes --type json --file zips.json 1. Write a MongoDB query to display all the documents in the collection restaurants. Ans. db.data.find().pretty() 2. Write a MongoDB query to display the fields restaurant_id, name, borough and cuisine for all the documents in the collection restaurant. Ans. db.data.find({}, {'restaurant_id': 1, name: 1, borough: 1, cuisine: 1}) 3. Write a MongoDB query to display the fields restaurant_id, name, borough and cuisine, but exclude the field _id for all the documents in the collection restaurant. Ans. db.data.find({}, {'_id': 0, 'restaurant_id': 1, name: 1, borough: 1, cuisine: 1}) 4. Write a MongoDB query to display the fields restaurant_id, name, borough and zip code, but exclude the field _id for all the documents in the collection restaurant. Ans. db.data.find({}, {'_id': 0, 'restaurant_id': 1, name: 1, borough: 1, 'address.zipcode': 1}) 5. Write a MongoDB query to display all the restaurant which is in the borough Bronx. Ans. db.data.find({'borough': 'Bronx'}).pretty() 6. Write a MongoDB query to display the first 5 restaurant which is in the borough Bronx. Ans. db.data.find({'borough': 'Bronx'}).limit(5).pretty() 7. Write a MongoDB query to display the next 5 restaurants after skipping first 5 which are in the borough Bronx. Ans. db.data.find({'borough': 'Bronx'}).skip(5).limit(5).pretty() 8. Write a MongoDB query to find the restaurants who achieved a score more than 90. Ans. db.data.find({'grades.score': {'$gt': 90}}).pretty() 9. Write a MongoDB query to find the restaurants that achieved a score, more than 80 but less than 100. Ans. db.data.find({grades: {'$elemMatch': {'score': {'$gt': 80 , '$lt': 100}}}}).pretty() 10. Write a MongoDB query to find the restaurants which locate in longitude value less than -95.754168.Go to the editor Latitudes range from -90 to 90, and longitudes range from -180 to 180. [longitude, latitude] Ans. db.data.find({'address.coord.0': {'$lt': -95.754168}}).pretty() 11. Write a MongoDB query to find the restaurants that do not prepare any cuisine of 'American' and their grade score more than 70 and latitude less than -65.754168. Ans. db.data.find({'$and': [{'cuisine': {'$ne': 'American '}}, {'grades.score': {'$gt': 70}}, {'address.coord.1': {'$gt': -65.754168}}]}).pretty() 12. Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American' and achieved a score more than 70 and located in the longitude less than -65.754168. Note : Do this query without using $and operator. Ans. db.data.find({'cuisine': {'$ne': 'American '}, 'grades.score': {'$gt': 70}, 'address.coord.0': {'$lt': -65.754168}}).pretty() 13. Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American ' and achieved a grade point 'A' not belongs to the borough Brooklyn. The document must be displayed according to the cuisine in descending order. Ans. db.data.find({'cuisine': {'$ne': 'American '}, 'grades.grade': {'$eq': 'A'}, 'borough': {'$ne': 'Brooklyn'}}).sort({'cuisine': -1}).pretty() 14. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which contain 'Wil' as first three letters for its name. Ans. db.data.find({'name': {'$regex': '^Wil.*'}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1}).pretty() 15. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which contain 'ces' as last three letters for its name. Ans. db.data.find({'name': {'$regex': '.*ces$'}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1}).pretty() 16. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which contain 'Reg' as three letters somewhere in its name. Ans. db.data.find({'name': {'$regex': 'Reg'}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1}).pretty() 17. Write a MongoDB query to find the restaurants which belong to the borough Bronx and prepared either American or Chinese dish. Ans. db.data.find({'borough': 'Bronx', 'cuisine': {'$in': ['American ', 'Chinese']}}).pretty() 18. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which belong to the borough Staten Island or Queens or Bronxor Brooklyn. Ans. db.data.find({'borough': {'$in': ['Staten Island', 'Queens', 'Brooklyn']}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1}) 19. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which are not belonging to the borough Staten Island or Queens or Bronxor Brooklyn. Ans. db.data.find({'borough': {'$nin': ['Staten Island', 'Queens', 'Brooklyn']}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1}) 20. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which achieved a score which is not more than 10. Ans. db.data.find({'grades.score': {'$lte': 10}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1, 'grades': 1}).pretty() 21. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which prepared dish except 'American' and 'Chinese' or restaurant's name begins with letter 'Wil'. Ans. db.data.find({'$or': [{'cuisine': {'$nin': ['American ', 'Chinese']}}, {'name': {'$regex': '^Wil.*'}}]}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1}) 22. Write a MongoDB query to find the restaurant Id, name, and grades for those restaurants which achieved a grade of "A" and scored 11 on an ISODate "2014-08-11T00:00:00Z" among many of survey dates.. Ans. db.data.find({'grades': {'$elemMatch': {'date': ISODate("2014-08-11T00:00:00Z"), 'grade': 'A', 'score': 11}}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'grades': 1}) 23. Write a MongoDB query to find the restaurant Id, name and grades for those restaurants where the 2nd element of grades array contains a grade of "A" and score 9 on an ISODate "2014-08-11T00:00:00Z". Ans. db.data.find({'grades.1.date': ISODate("2014-08-11T00:00:00Z"), 'grades.1.score': 9, 'grades.1.grade': 'A'}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'borough': 1, 'cuisine': 1}) 24. Write a MongoDB query to find the restaurant Id, name, address and geographical location for those restaurants where 2nd element of coord array contains a value which is more than 42 and upto 52.. Ans. db.data.find({'address.coord.1': {'$gt': 42, '$lte': 52}}, {'_id': 0, 'restaurant_id': 1, 'name': 1, 'address.coord': 1}).pretty() 25. Write a MongoDB query to arrange the name of the restaurants in ascending order along with all the columns. Ans. db.data.find().sort({'name': 1}).pretty() 26. Write a MongoDB query to arrange the name of the restaurants in descending along with all the columns. Ans. db.data.find().sort({'name': -1}).pretty() 27. Write a MongoDB query to arranged the name of the cuisine in ascending order and for that same cuisine borough should be in descending order. Ans. db.data.find().sort({'cuisine': 1, 'borough': -1}).pretty() 28. Write a MongoDB query to know whether all the addresses contains the street or not. Ans. db.data.find({'address.street': {'$exists': true}}) # If we need count then use countDocuments() 29. Write a MongoDB query which will select all documents in the restaurants collection where the coord field value is Double. Ans. db.data.find({'address.coord': {'$type': 'double'}}) 30. Write a MongoDB query which will select the restaurant Id, name and grades for those restaurants which returns 0 as a remainder after dividing the score by 7. Ans. db.data.find({'grades': {'$elemMatch': {'score': {'$mod': [7, 0]}}}}, {'_id': 0, 'name': 1, 'restaurant_id': 1, 'grades': 1}).pretty() 31. Write a MongoDB query to find the restaurant name, borough, longitude and attitude and cuisine for those restaurants which contains 'mon' as three letters somewhere in its name. Ans. db.data.find({'name': {'$regex': 'mon'}}, {'name': 1, '_id': 0, 'borough': 1, 'address.coord': 1, 'cuisine': 1}) 32. Write a MongoDB query to find the restaurant name, borough, longitude and latitude and cuisine for those restaurants which contain 'Mad' as first three letters of its name. Ans. db.data.find({'name': {'$regex': '^Mad.*'}}, {'name': 1, '_id': 0, 'borough': 1, 'address.coord': 1, 'cuisine': 1})
package ru.gb.web.dto.mapper; import org.mapstruct.Context; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import ru.gb.api.product.dto.ProductDto; import ru.gb.dao.CategoryDao; import ru.gb.dao.ManufacturerDao; import ru.gb.entity.Category; import ru.gb.entity.Manufacturer; import ru.gb.entity.Product; import ru.gb.web.dto.ProductManufacturerDto; import java.util.NoSuchElementException; @Mapper(uses = ManufacturerMapper.class) public interface ProductMapper { Product toProduct(ProductDto productDto, @Context ManufacturerDao manufacturerDao, @Context CategoryDao categoryDao); ProductDto toProductDto(Product product); @Mapping(source = "manufacturer", target = "manufacturerDto") ProductManufacturerDto toProductManufacturerDto(Product product); default Manufacturer getManufacturer(String manufacturer, @Context ManufacturerDao manufacturerDao) { return manufacturerDao.findByName(manufacturer).orElseThrow(NoSuchElementException::new); } default String getManufacturer(Manufacturer manufacturer) { return manufacturer.getName(); } default Category getCategory(String category, @Context CategoryDao categoryDao) { return categoryDao.findByTitle(category).orElseThrow(NoSuchElementException::new); } default String getCategory(Category category) { return category.getTitle(); } }
import React, { useState } from 'react' import { Typography, Button, Form, Input} from 'antd' import FileUpload from '../../utils/FileUpload'; import Axios from 'axios'; const { Title } = Typography; const { TextArea } = Input; const Continents = [ {key:1, value:'Africa'}, {key:2, value:'Europe'}, {key:3, value:'Asia'}, {key:4, value:'North America'}, {key:5, value:'South America'}, {key:6, value:'Australia'}, {key:7, value:'Antarctica'}, ] function UploadProductPage(props) { const [Title, setTitle] = useState('') const [Description, setDescription] = useState('') const [Price, setPrice] = useState(0) const [Continent, setContinent] = useState(1) const [Img, setImg] = useState([]) const titleChange = (e) => { setTitle(e.currentTarget.value) } const descriptionChange = (e) => { setDescription(e.currentTarget.value) } const priceChange = (e) => { setPrice(e.currentTarget.value) } const continentChange = (e) => { setContinent(e.currentTarget.value) } const updateImg = (newImg) => { setImg(newImg) } const submitHandler = (e) => { e.preventDefault(); if( !Title || !Description || !Price || !Continent || !Img ) { return alert(' 모든 값을 넣어주세요... ') } const body = { writer : props.user.userData._id, title : Title, description : Description, price : Price, img : Img, continent : Continent } //서버 데이터 전송 Axios.post('/api/product', body) .then(res => { if(res.data.success) { alert('업로드 성공') props.history.push('/') } else { alert('업로드 실패') } }) } return ( <div style={{maxWidth: '700px', margin: '2rem auto'}}> <div style={{textAlign: 'center', marginBottom: '2rem'}}> <h2 level={2}>여행 상품 업로드</h2> </div> <Form > {/* 드랍존 */} <FileUpload refreshFunction={updateImg}/> <br/> <br/> <label>이름</label> <Input value={Title} onChange={titleChange}/> <br/> <br/> <label>설명</label> <TextArea value={Description} onChange={descriptionChange}></TextArea> <br/> <br/> <label>가격 ($)</label> <Input type='number' value={Price} onChange={priceChange}/> <br/> <br/> <select onChange={continentChange} value={Continent}> {Continents.map( item => ( <option key={item.key} value={item.key}>{item.value}</option> ))} </select> <br/> <br/> <Button type='submit' onClick={submitHandler}> 확인 </Button> </Form> </div> ) } export default UploadProductPage
from django.db import models from django.utils.safestring import mark_safe from django.contrib.auth import get_user_model class Category(models.Model): name = models.CharField('Название', max_length=100) description = models.TextField('Описание', null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' class Manufacture(models.Model): name = models.CharField('Имя', max_length=100) description = models.TextField('Описание', null=True, blank=True) url = models.URLField('Сайт', blank=True) def __str__(self): return self.name class Meta: verbose_name = 'Производитель' verbose_name_plural = 'Производители' class Product(models.Model): name = models.CharField('Название', max_length=100) description = models.TextField('Описание', null=True, blank=True) price = models.PositiveIntegerField('Стоимость', help_text='Указывать стоимость в рублях') category = models.ForeignKey(Category, models.DO_NOTHING, related_name='products', verbose_name='Категория') manufacture = models.ForeignKey(Manufacture, models.DO_NOTHING, related_name='products', verbose_name='Производитель') def __str__(self): return self.name class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' class ProductImage(models.Model): title = models.CharField('Заголовок', max_length=100, null=True, blank=True) image = models.ImageField('Изображение', upload_to='product/') product = models.ForeignKey(Product, models.CASCADE, related_name='images', verbose_name='Продукт') def get_title(self): return self.title or '(Нет заголовка)' def get_image(self): return mark_safe(f'<img src="{self.image.url}" alt="{self.title}" height="150">') get_title.short_description = 'Заголовок' get_image.short_description = 'Изображение' class Meta: verbose_name = 'Фотография продукта' verbose_name_plural = 'Фотографии продуктов'
import express from "express"; import "dotenv/config"; import cors from "cors"; import Controller from "application/controllers/Controller"; class App { public app: express.Application; public port: number; constructor(controllers: Controller[], port: number) { this.app = express(); this.port = port; this.initializeMiddlewares(); this.setProperties(); this.initializeControllers(controllers); } private initializeMiddlewares() { this.app.use(cors()); this.app.use(express.urlencoded({ extended: true })); } private setProperties() { this.app.set("json spaces", 2); } private initializeControllers(controllers: Controller[]) { for (const controller of controllers) { this.app.use("/api", controller.router); } } public listen() { this.app.listen(this.port, () => { console.log(`App listening on the port ${this.port}`); }); } } export default App;
<?php /** * JUPWA plugin * * @version 1.x * @package JUPWA\Helpers * @author Denys D. Nosov (denys@joomla-ua.org) * @copyright (C) 2023 by Denys D. Nosov (https://joomla-ua.org) * @license GNU General Public License version 2 or later; see LICENSE.md * **/ namespace JUPWA\Helpers; use Joomla\CMS\Factory; use Joomla\CMS\Filesystem\File; use Joomla\CMS\Uri\Uri; use JUPWA\Data\Data; class META { /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function render(array $option = []): void { self::manifest(); self::preconnect([ 'params' => $option[ 'params' ] ]); self::preloads([ 'params' => $option[ 'params' ] ]); self::meta_apple([ 'params' => $option[ 'params' ] ]); self::meta_ms([ 'params' => $option[ 'params' ] ]); self::icons(); self::splash([ 'params' => $option[ 'params' ] ]); self::tags([ 'params' => $option[ 'params' ] ]); self::pwa([ 'params' => $option[ 'params' ] ]); } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function facebook(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); if($option[ 'params' ]->get('fbpage') !== '') { $doc->setMetaData('article:publisher', $option[ 'params' ]->get('fbpage'), 'property'); } if($option[ 'params' ]->get('fbapp') !== '') { $doc->setMetaData('fb:app_id', $option[ 'params' ]->get('fbapp'), 'property'); } $fbadmins = (array) $option[ 'params' ]->get('fbadmin'); $i = 0; foreach($fbadmins as $fbadmin) { if($fbadmin->id) { $doc->setMetaData('fb:admins_' . ($i + 1), $fbadmin->id, 'property'); } $i++; } } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function preloads(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); $preloads = (array) $option[ 'params' ]->get('preloads'); foreach($preloads as $preload) { if($preload->url) { $preload_as = [ 'as' => $preload->as ]; $preload_type = []; if($preload->type) { $preload_type = [ 'type' => $preload->type ]; } $preload_co = []; if($preload->crossorigin) { $preload_co = [ 'crossorigin' => $preload->crossorigin ]; } $preload_media = []; if($preload->media) { $preload_media = [ 'media' => $preload->media ]; } $_preload = array_merge($preload_as, $preload_type, $preload_co, $preload_media); $doc->addHeadLink($preload->url, 'preload prefetch', 'rel', [ $_preload ]); } } } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function preconnect(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); $preconnect = Data::$preconnect; foreach($preconnect as $key => $val) { if($option[ 'params' ]->get('precnct-' . $key) == 1) { foreach($val as $link) { $doc->addHeadLink($link, 'dns-prefetch preconnect'); } } } $preconnects = (array) $option[ 'params' ]->get('preconnect'); foreach($preconnects as $preconnect) { if($preconnect->url) { $doc->addHeadLink($preconnect->url, 'dns-prefetch preconnect'); } } } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function splash(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); $icons = Data::$splash; foreach($icons as $icon) { $file = 'favicons/splash_' . $icon[ 'width' ] . 'x' . $icon[ 'height' ] . '.png'; if(File::exists(JPATH_SITE . '/' . $file)) { $href = Uri::root() . $file; $doc->addHeadLink($href, 'apple-touch-startup-image', 'rel', [ 'media' => 'screen and (device-width: ' . $icon[ 'd_width' ] . 'px) and (device-height: ' . $icon[ 'd_height' ] . 'px) and (-webkit-device-pixel-ratio: 2) and (orientation: ' . $icon[ 'orientation' ] . ')' ]); } } } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function meta_apple(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); $icons = Data::$favicons; foreach($icons[ 'apple-touch-icon' ] as $icon) { $file = 'favicons/icon_' . $icon . '.png'; if(File::exists(JPATH_SITE . '/' . $file)) { $href = Uri::root() . $file; $doc->addHeadLink($href, 'apple-touch-icon', 'rel', [ 'sizes' => $icon . 'x' . $icon ]); } } $doc->setMetaData('mobile-web-app-capable', 'yes'); $doc->setMetaData('apple-mobile-web-app-capable', 'yes'); $doc->setMetaData('application-name', ($option[ 'params' ]->get('manifest_sname') ? : $option[ 'params' ]->get('manifest_name'))); $doc->setMetaData('apple-mobile-web-app-title', ($option[ 'params' ]->get('manifest_sname') ? : $option[ 'params' ]->get('manifest_name'))); $doc->setMetaData('apple-mobile-web-app-status-bar-style', 'black-translucent'); if($option[ 'params' ]->get('source_icon_svg_pin') !== '' && $option[ 'params' ]->get('maskiconcolor') !== '') { $file = $option[ 'params' ]->get('source_icon_svg_pin'); if(File::exists(JPATH_SITE . '/' . $file)) { $href = Uri::root() . $file; $doc->addHeadLink($href, 'mask-icon', 'rel', [ 'color' => $option[ 'params' ]->get('maskiconcolor') ]); } } } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function meta_ms(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); if($option[ 'params' ]->get('msapplication_tilecolor')) { $doc->setMetaData('msapplication-TileColor', $option[ 'params' ]->get('msapplication_tilecolor')); } if($option[ 'params' ]->get('theme_color')) { $doc->setMetaData('theme-color', $option[ 'params' ]->get('theme_color')); } $file = 'favicons/browserconfig.xml'; if(File::exists(JPATH_SITE . '/' . $file)) { $href = Uri::root() . $file; $doc->setMetaData('msapplication-config', $href); } } /** * * @return void * * @throws \Exception * @since 1.0 */ public static function icons(): void { $app = Factory::getApplication(); $doc = $app->getDocument(); $icons = Data::$favicons; foreach($icons[ 'icon' ] as $icon) { $file = 'favicons/icon_' . $icon . '.png'; if(File::exists(JPATH_SITE . '/' . $file)) { $href = Uri::root() . $file; $doc->addHeadLink($href, 'icon', 'rel', [ 'sizes' => $icon . 'x' . $icon, 'type' => 'image/png' ]); } } $file = 'favicons/favicon.ico'; if(File::exists(JPATH_SITE . '/' . $file)) { $href = Uri::root() . $file; $doc->addHeadLink($href, 'shortcut icon'); } } /** * * @return void * * @throws \Exception * @since 1.0 */ public static function manifest(): void { $app = Factory::getApplication(); $doc = $app->getDocument(); $file = 'manifest.webmanifest'; if(File::exists(JPATH_SITE . '/' . $file)) { $href = Uri::root() . $file; $doc->addHeadLink($href, 'manifest'); } } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function tags(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); if($option[ 'params' ]->get('theme_color') != '') { $doc->setMetaData('theme-color', $option[ 'params' ]->get('theme_color')); } } /** * * @param array $option * * @return void * * @throws \Exception * @since 1.0 */ public static function pwa(array $option = []): void { $app = Factory::getApplication(); $doc = $app->getDocument(); if($option[ 'params' ]->get('usepwa', 0) == 1) { $pwa_version = Manifest::getVersion(); $pwajs = "if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('" . Uri::base() . "sw.js?v=" . $pwa_version . "'); }); }"; $doc->addScriptDeclaration($pwajs); } } }
/* eslint-disable no-restricted-globals */ /* eslint-disable implicit-arrow-linebreak */ import 'regenerator-runtime/runtime' import { setCacheNameDetails } from 'workbox-core' import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching' import { registerRoute } from 'workbox-routing' import { StaleWhileRevalidate, CacheFirst, NetworkFirst } from 'workbox-strategies' import { ExpirationPlugin } from 'workbox-expiration' setCacheNameDetails({ prefix: 'resto-app', suffix: 'v1', precache: 'precache', runtime: 'runtime' }) precacheAndRoute(self.__WB_MANIFEST) // Cache page navigations (html) with a Network First strategy registerRoute( // Check to see if the request is a navigation to a new page ({ request }) => request.mode === 'navigate', // Use a Network First caching strategy new NetworkFirst({ // Put all cached files in a cache named 'pages' cacheName: 'my-pages-cache' }) ) // cache dynamic routes (API) when the user visits the page that calls API registerRoute( /^https:\/\/restaurant-api\.dicoding\.dev\/(?:(list|detail))/, new NetworkFirst({ cacheName: 'dicoding-restaurant-api-caches', plugins: [ // Don't cache more than 100 items, and expire them after 30 days new ExpirationPlugin({ maxAgeSeconds: 60 * 60 * 24 * 30, maxEntries: 100 }) ] }) ) // Cache images with a Cache First strategy registerRoute( ({ request }) => console.log('kiw', request), new CacheFirst({ cacheName: 'my-images-cache', plugins: [ new ExpirationPlugin({ maxAgeSeconds: 60 * 60 * 24 * 30, // Cache gambar selama 30 hari maxEntries: 50 }), { cacheDidNotMatch: async ({ request }) => { // Callback ini akan dipanggil ketika permintaan tidak cocok dengan cache apa pun // Disini Anda bisa menyimpan hasil ke dalam cache untuk pemakaian berikutnya const cache = await caches.open('my-images-cache') const response = await fetch(request) await cache.put(request, response.clone()) return response } } ] }) ) // cache font-awesome registerRoute( /https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/font-awesome\/5.15.3\/css\/all.css/, new CacheFirst({ cacheName: 'my-font-awesome-css-cache' }) ) // cache fonts request registerRoute( ({ url }) => url.origin === 'https://fonts.googleapis.com' || url.origin === 'https://fonts.gstatic.com', new StaleWhileRevalidate({ cacheName: 'my-google-fonts-cache', // Don't cache more than 50 items plugins: [new ExpirationPlugin({ maxEntries: 50 })] }) ) // Cache CSS, JS, and Web Worker requests with a Stale While Revalidate strategy registerRoute( ({ request }) => request.destination === 'style' || request.destination === 'script' || request.destination === 'worker', // Use a Stale While Revalidate caching strategy new StaleWhileRevalidate({ // Put all cached files in a cache named 'assets' cacheName: 'my-assets-cache' }) ) cleanupOutdatedCaches() self.addEventListener('message', (event) => { if (event.data && event.data.type === 'SKIP_WAITING') { self.skipWaiting() } })
// // MyBookListView.swift // MyBooks // // Created by Suh on 14/09/22. import SwiftUI struct MyBookListView: View { @StateObject var viewModel: MyBookListViewModel @State private var isShowingLibrary = false var body: some View { VStack { NavigationView { VStack(alignment: .center) { Spacer() Group { if viewModel.haveNoBooks { Text( """ Biblioteca vazia! Clique e adicione livros. """) .foregroundColor(.gray) .font(.title) } else { List(viewModel.books, id: \.id) { book in NavigationLink { BookDetailView( viewModel: viewModel.makeBookDetailViewModel(book: book) ).onDisappear { viewModel.fetchBooks() } } label: { MyBookRow(book: book) } } } } Spacer(minLength: 50) Button { isShowingLibrary = true } label: { Text("Biblioteca") .font(.title2) } .foregroundColor(.white) .tint(.mint) .buttonStyle(.borderedProminent) .buttonBorderShape(.roundedRectangle) } .navigationTitle(Text("Meus Livros")) .navigationBarTitleDisplayMode(.large) .padding() .sheet(isPresented: $isShowingLibrary) { LibraryView(viewModel: viewModel.makeLibraryViewModel()) .onDisappear { viewModel.fetchBooks() } } } .listStyle(.plain) .onAppear { self.viewModel.fetchBooks() } } } } // // struct MyBookList_Previews: PreviewProvider { // static var previews: some View { // MyBookListView() // } // }
import React, { useEffect, useState } from "react"; import "./EditPet.css" const EditPet = ({ pet, updatePet }) => { const [editedPet, setEditedPet] = useState({ ...pet }); const handleInputChange = (event) => { const { name, value } = event.target; setEditedPet((petlist) => ({ ...petlist, [name]: value, })); }; useEffect(() => { let formattedDate; if (editedPet && editedPet.birthdate) { const dateObject = new Date(editedPet.birthdate); const month = parseInt(dateObject.getMonth()) + 1; formattedDate = `${dateObject.getFullYear()}-${( "0" + month ).slice(-2)}-${("0" + dateObject.getDate()).slice(-2)}`; setEditedPet((editedPet) => ({ ...editedPet, birthdate: formattedDate, })); } return () => { formattedDate; }; }, []); const handleSubmit = (event) => { event.preventDefault(); updatePet(editedPet); }; return ( <div className="EditForm"> <form className="EditPet" onSubmit={handleSubmit}> <div className="mb-3"> <label htmlFor="name" className="form-label"> Name: </label> <input type="text" name="name" className="form-control" value={editedPet.name} onChange={handleInputChange} /> </div> <div className="mb-3"> <label htmlFor="type" className="form-label"> Type: </label> <select name="type" className="form-control" value={editedPet.type} onChange={handleInputChange} > <option value="">Select pet type</option> <option value="cat">Cat</option> <option value="dog">Dog</option> <option value="bird">Bird</option> <option value="fish">Fish</option> </select> </div> <div className="mb-3"> <label htmlFor="birthdate" className="form-label"> Birthdate: </label> <input type="date" name="birthdate" className="form-control" value={editedPet.birthdate} onChange={handleInputChange} /> </div> <div className="mb-3"> <label htmlFor="notes" className="form-label"> Notes: </label> <textarea name="notes" className="form-control" value={editedPet.notes} onChange={handleInputChange} ></textarea> </div> <button type="submit" className="btn btn-outline-warning btn-sm"> Save </button> </form> </div> ) }; export default EditPet;
/* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <fredrik@dolda2000.com>, and * Björn Johannessen <johannessen.bjorn@gmail.com> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * 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. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import com.google.common.flogger.FluentLogger; import haven.sloth.util.Timer; public class RemoteUI implements UI.Receiver, UI.Runner { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); final Session sess; Session ret; UI ui; public RemoteUI(Session sess) { this.sess = sess; Widget.initnames(); } public void rcvmsg(int id, String name, Object... args) { PMessage msg = new PMessage(RMessage.RMSG_WDGMSG); msg.adduint16(id); msg.addstring(name); msg.addlist(args); sess.queuemsg(msg); } public void ret(Session sess) { synchronized (this.sess) { this.ret = sess; this.sess.notifyAll(); } } public Session run(final UI ui) throws InterruptedException { this.ui = ui; ui.setreceiver(this); while (true) { PMessage msg; final Timer timer = new Timer(); synchronized (ui) { while ((msg = sess.getuimsg()) != null) { timer.start(); if (msg.type == RMessage.RMSG_NEWWDG) { int id = msg.uint16(); String type = msg.string(); int parent = msg.uint16(); Object[] pargs = msg.list(); Object[] cargs = msg.list(); timer.tick("decode"); ui.newwidget(id, type, parent, pargs, cargs); timer.tick("newwidget"); if (timer.total() > 1000) { logger.atSevere().log("RemoteUI newwdg [id %d] [type %s] summary: \n%s", id, type, timer.summary()); } else { logger.atFine().log("RemoteUI newwdg [id %d] [type %s] summary: \n%s", id, type, timer.summary()); } } else if (msg.type == RMessage.RMSG_WDGMSG) { int id = msg.uint16(); String name = msg.string(); timer.tick("decode"); ui.uimsg(id, name, msg.list()); timer.tick("uimsg"); if (timer.total() > 500) logger.atSevere().log("RemoteUI uimsg [id %d] [name %s] summary: \n%s", id, name, timer.summary()); else logger.atFine().log("RemoteUI uimsg [id %d] [name %s] summary: \n%s", id, name, timer.summary()); } else if (msg.type == RMessage.RMSG_DSTWDG) { int id = msg.uint16(); timer.tick("decode"); ui.destroy(id); timer.tick("destroy"); logger.atFine().log("RemoteUI destroy [id %d] summary: \n%s", id, timer.summary()); } else if (msg.type == RMessage.RMSG_ADDWDG) { int id = msg.uint16(); int parent = msg.uint16(); Object[] pargs = msg.list(); timer.tick("decode"); ui.addwidget(id, parent, pargs); timer.tick("addwidget"); logger.atFine().log("RemoteUI addwdg [id %d] [par %d] summary: \n%s", id, parent, timer.summary()); } } } synchronized (sess) { if (ret != null) { sess.close(); return (ret); } if (!sess.alive()) return (null); sess.wait(); } } } }
// Type your code here, or load an example. #include <stdio.h> #ifndef __TEST_UTILS_H # define __TEST_UTILS_H # define RED "\x1b[31m" # define GREEN "\x1b[32m" typedef bool (*test_func_t)(void); typedef struct func_ptr_s { test_func_t cb; /* function callback */ } func_ptr_t; # define ADD_FUNC(group, func_cb) \ static func_ptr_t ptr_##func_cb __attribute((used, section(#group))) = { \ .cb = func_cb, \ } # define RUN_TESTS(group) \ do { \ DEBUG_PRINTF("RUNNING %s TESTS\n", #group); \ int succeeded = 0; \ int total = 0; \ for (func_ptr_t *elem = ({ \ extern func_ptr_t __start_##group; \ &__start_##group; \ }); \ elem != ({ \ extern func_ptr_t __stop_##group; \ &__stop_##group; \ }); \ ++elem) { \ succeeded += elem->cb(); \ total++; \ } \ if (succeeded == total) { \ DEBUG_PRINTF(GREEN "All %d/%d tests in %s succeeded.\n" COLOR_RESET, succeeded, \ total, #group); \ } else { \ DEBUG_PRINTF(RED "%d/%d tests in %s failed.\n" COLOR_RESET, total - succeeded, \ total, #group); \ } \ } while (0) # define CREATE_TEST(name, group, code_block) \ __attribute__((unused)) static bool test_##name##group(void) \ { \ __unused const char *test_name = #name; \ __unused const char *group_name = #group; \ __unused bool __any_check_failed = false; \ { \ code_block \ } \ if (__any_check_failed) { \ goto __error; \ } \ return true; \ __error: \ __attribute__((cold, unused)); \ DEBUG_PRINTF(RED "Test %s in %s failed.\n" COLOR_RESET, test_name, group_name); \ return false; \ } \ ADD_FUNC(group, test_##name##group); # define TEST_REQUIRE_FAIL_WITH(was, want) \ do { \ errval_t __was = was; \ errval_t __want = want; \ if (__was != __want) { \ DEBUG_PRINTF(RED "%s:%d: %s \n" COLOR_RESET, __FILE__, __LINE__, __func__); \ DEBUG_ERR(__was, "WAS:\n"); \ DEBUG_ERR(__want, "WANT\n"); \ goto __error; \ } \ } while (0) # define TEST_REQUIRE_OK(err) \ do { \ errval_t __err = err; \ if (err_is_fail(__err)) { \ DEBUG_ERR(__err, RED "%s:%d: %s failed\n" COLOR_RESET, __FILE__, __LINE__, __func__); \ goto __error; \ } \ } while (0) # define TEST_REQUIRE(test) \ do { \ bool __result = test; \ if (!__result) { \ DEBUG_PRINTF(RED "%s:%d: %s failed\n" COLOR_RESET, __FILE__, __LINE__, #test); \ goto __error; \ } \ } while (0) # define TEST_CHECK(test) \ do { \ bool __result = test; \ if (!__result) { \ __any_check_failed = true; \ DEBUG_PRINTF(RED "%s:%d: %s failed\n" COLOR_RESET, __FILE__, __LINE__, #test); \ } \ } while (0) # define TEST_EXIT_EARLY() return true #endif // __TEST_UTILS_H
import ApiService from '../utils/apiService'; import i18n from '../locales/i18n'; // 假设你的i18n实例在这个路径下 import JSEncrypt from 'jsencrypt'; class AuthService { constructor() { this.apiService = new ApiService(); } validateCredentials(credentials) { if (!credentials.username || !credentials.password) { throw new Error(i18n.t('error.mailAndPasswordRequired')); } // 这里可以添加更多的验证逻辑,例如检查用户名和密码的格式等 } login(credentials) { this.validateCredentials(credentials); return new Promise((resolve, reject) => { this.apiService.post('/auth/login', credentials, false) .then(response => { console.log(response); if (response.data) { localStorage.setItem('username', credentials.username); localStorage.setItem('token', response.data); resolve(response); } else { reject(response.data.msg) } }) .catch((err) => { reject(err); }); }) } encryptPassword(credentials) { return this.apiService.get('/auth/pubKey').then(res => { let encrypt = new JSEncrypt(); console.log(res); encrypt.setPublicKey(res.data.pubKey); credentials.password = encrypt.encrypt(credentials.password); console.log(credentials); }) } validateUser(user) { if (!user.password || !user.mail) { throw new Error(i18n.t('error.PasswordAndEmailRequired')); } // 这里可以添加更多的验证逻辑,例如检查用户名、密码和邮箱的格式等 } register(user) { this.validateUser(user); return this.apiService.post('/register', user, false) .catch(error => { console.error(i18n.t('error.failedToRegister'), error); throw error; }); } validateEmail(email) { if (!email) { throw new Error(i18n.t('error.emailRequired')); } // 这里可以添加更多的验证逻辑,例如检查邮箱的格式等 } forgotPassword(email) { this.validateEmail(email); return this.apiService.post('/forgot-password', { email }, false) .catch(error => { console.error(i18n.t('error.failedToSendForgotPasswordEmail'), error); throw error; }); } logout() { localStorage.removeItem('token'); // 这里可以添加更多的逻辑,例如向服务器发送注销请求等 } } export default AuthService;
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:qna_list/data/qna_data_provider.dart'; import 'package:qna_list/presentation/qna_screen/qna_first_screen.dart'; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final qnaData = Provider.of<QnaDataProvider>( context); //Provider.of를 사용해서 QnaDataProvider 클래스의 인스턴스를 가져옴 즉. 데이터를 관리하고 UI를 업데이트 final data = qnaData.data; if (data == null) { //데이터가 아직 로드되지 않거나 null 경우를 확인하는 조건문 return const CircularProgressIndicator(); //만약에 데이터가 null이면 로딩중을 나타냄 } final qnaList = (data['qnaList'] as List<dynamic>) ?? []; //List<Map<String, dynamic>>으로 변환 return MaterialApp( home: Scaffold( appBar: AppBar( centerTitle: true, title: const Text('FAQ'), ), body: SafeArea( child: SizedBox( width: double.infinity, child: ListView.builder( itemCount: qnaList.length, itemBuilder: (context, index) { final item = qnaList[index] as Map<String, dynamic>; final user = item['user'] as Map<String, dynamic>; final questionDate = DateTime.parse(item['questionDate']); return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => QnaFirstScreen()), ); }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: double.infinity, color: Colors.yellow, child: Text( '닉네임: ${user['username']}', style: const TextStyle(fontSize: 20), ), ), Container( width: double.infinity, color: const Color(0xFFFFF9B0), child: Text( '질문내용: ${item['question']}', style: const TextStyle(fontSize: 17), maxLines: 4, overflow: TextOverflow.ellipsis, ), ), Container( width: double.infinity, color: const Color(0xFFFFF9B0), child: Text( '등록날짜: ${DateFormat('yyyy-MM-dd').format(questionDate)}', style: const TextStyle(fontSize: 17), ), ), const SizedBox(height: 2), ], ), ); }, ), ), ), ), ); } }
import React, {useState} from 'react'; import styles from './listTickets.module.css'; import {useNavigate} from "react-router-dom"; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableHead from '@mui/material/TableHead'; import TableRow from '@mui/material/TableRow'; import Paper from '@mui/material/Paper'; import {GetAllTickets, UpdateTicket} from "../../service/serviceTicket"; import Select from 'react-select' import IconButton from "@mui/material/IconButton"; import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp"; import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"; import Collapse from "@mui/material/Collapse"; import Box from "@mui/material/Box"; import Typography from "@mui/material/Typography"; function createData( uuid: string, name: string, email: string, description: string, status: string, response: string, ) { return { uuid, name, email, description, status, response }; } /*WORKING WITH SELECT*/ const options = [ { value: 'new', label: 'new' }, { value: 'in progress', label: 'in progress' }, { value: 'resolved', label: 'resolved' } ] const additionalData = { isUpdateResponse: false, }; const ListTickets = () => { /*NAVIGATE*/ const navigate = useNavigate() const navigateToHome = () => { navigate('/') } /*FETCH DATA FROM TABLE*/ const LIST_ENDPOINT = process.env.REACT_APP_LIST_ENDPOINT; const handleGetAll = GetAllTickets(LIST_ENDPOINT); const rows = []; if (handleGetAll) { handleGetAll.map((element) => ( rows.push( createData( element.uuid, element.name, element.email, element.description, element.status, element.response ) ) )); } /*HTML*/ return ( <div> <div className={styles.row}> <span className={styles.value}>TICKETS</span> </div> <div align ='center'> <TableContainer component={Paper} style={{width: '80%'}} > <Table sx={{ minWidth: 300 }} aria-label="simple table" stickyHeader> <TableHead> <TableRow> <TableCell></TableCell> <TableCell><b>Name</b></TableCell> <TableCell><b>Email</b></TableCell> <TableCell><b>Description</b></TableCell> <TableCell align="right"><b>Status</b></TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <Row key={row.name} row={row} /> ))} </TableBody> </Table> </TableContainer> </div> <br/> <div className={styles.row}> <button className={styles.button} onClick={navigateToHome}>Home</button> </div> </div> )}; /*ROWS COLLAPSE*/ function Row(props: { row: ReturnType<typeof createData> }) { const { row } = props; const [open, setOpen] = React.useState(false); const UPDATE_ENDPOINT = process.env.REACT_APP_UPDATE_ENDPOINT; const navigate = useNavigate() const navigateToConfirmation = () => { navigate('/confirmation') } /*CHANGE SELECT*/ const [selected, setSelected] = useState(null); const handleChange = (selectedOption) => { setSelected(selectedOption); row.status = selectedOption.value UpdateTicket(UPDATE_ENDPOINT, 'POST', row, {additionalData}); }; /*UPDATE RESPONSE*/ const handleUpdate = () => { additionalData.isUpdateResponse = true; row.response = document.getElementById('newResponse').value; const res = UpdateTicket(UPDATE_ENDPOINT, 'POST', row, {additionalData}); if (res === 200) { navigateToConfirmation() } } /*HTML ROW COLLAPSE*/ return ( <React.Fragment> <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}> <TableCell> <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)} > {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />} </IconButton> </TableCell> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell>{row.email}</TableCell> <TableCell>{row.description}</TableCell> <TableCell> <Select options={options} defaultValue = { options.filter(option => option.value === row.status) } onChange={handleChange} /> </TableCell> </TableRow> <TableRow> <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}> <Collapse in={open} timeout="auto" unmountOnExit> <Box sx={{ margin: 1 }}> <Typography variant="h6" gutterBottom component="div"> Response </Typography> <textarea defaultValue={row.response} className={styles.textbox} name='newResponse' id='newResponse' /> <br/> <button type="submit" className={styles.button} onClick={handleUpdate}>Send</button> </Box> </Collapse> </TableCell> </TableRow> </React.Fragment> ); } ListTickets.propTypes = {}; ListTickets.defaultProps = {}; export default ListTickets;
/*global describe, it, expect, beforeEach */ describe('Function', function () { 'use strict'; describe('apply', function () { it('works with arraylike objects', function () { var arrayLike = { length: 4, 0: 1, 2: 4, 3: true }; var expectedArray = [1, undefined, 4, true]; var actualArray = (function () { return Array.prototype.slice.apply(arguments); }.apply(null, arrayLike)); expect(actualArray).toEqual(expectedArray); }); }); describe('bind', function () { var actual; var testSubject = { push: function (o) { this.a.push(o); } }; function func() { Array.prototype.forEach.call(arguments, function (a) { this.push(a); }, this); return this; } beforeEach(function () { actual = []; testSubject.a = []; }); it('binds properly without a context', function () { var context; testSubject.func = function () { context = this; }.bind(); testSubject.func(); expect(context).toBe(function () { return this; }.call()); }); it('binds properly without a context, and still supplies bound arguments', function () { var a, context; testSubject.func = function () { a = Array.prototype.slice.call(arguments); context = this; }.bind(undefined, 1, 2, 3); testSubject.func(1, 2, 3); expect(a).toEqual([1, 2, 3, 1, 2, 3]); expect(context).toBe(function () { return this; }.call()); }); it('binds a context properly', function () { testSubject.func = func.bind(actual); testSubject.func(1, 2, 3); expect(actual).toEqual([1, 2, 3]); expect(testSubject.a).toEqual([]); }); it('binds a context and supplies bound arguments', function () { testSubject.func = func.bind(actual, 1, 2, 3); testSubject.func(4, 5, 6); expect(actual).toEqual([1, 2, 3, 4, 5, 6]); expect(testSubject.a).toEqual([]); }); it('returns properly without binding a context', function () { testSubject.func = function () { return this; }.bind(); var context = testSubject.func(); expect(context).toBe(function () { return this; }.call()); }); it('returns properly without binding a context, and still supplies bound arguments', function () { var context; testSubject.func = function () { context = this; return Array.prototype.slice.call(arguments); }.bind(undefined, 1, 2, 3); actual = testSubject.func(1, 2, 3); expect(context).toBe(function () { return this; }.call()); expect(actual).toEqual([1, 2, 3, 1, 2, 3]); }); it('returns properly while binding a context properly', function () { var ret; testSubject.func = func.bind(actual); ret = testSubject.func(1, 2, 3); expect(ret).toBe(actual); expect(ret).not.toBe(testSubject); }); it('returns properly while binding a context and supplies bound arguments', function () { var ret; testSubject.func = func.bind(actual, 1, 2, 3); ret = testSubject.func(4, 5, 6); expect(ret).toBe(actual); expect(ret).not.toBe(testSubject); }); it('has the new instance\'s context as a constructor', function () { var actualContext; var expectedContext = { foo: 'bar' }; testSubject.func = function () { actualContext = this; }.bind(expectedContext); var result = new testSubject.func(); expect(result).toBeTruthy(); expect(actualContext).not.toBe(expectedContext); }); it('passes the correct arguments as a constructor', function () { var expected = { name: 'Correct' }; testSubject.func = function (arg) { expect(this.hasOwnProperty('name')).toBe(false); return arg; }.bind({ name: 'Incorrect' }); var ret = new testSubject.func(expected); expect(ret).toBe(expected); }); it('returns the return value of the bound function when called as a constructor', function () { var oracle = [1, 2, 3]; var Subject = function () { expect(this).not.toBe(oracle); return oracle; }.bind(null); var result = new Subject(); expect(result).toBe(oracle); }); it('returns the correct value if constructor returns primitive', function () { var oracle = [1, 2, 3]; var Subject = function () { expect(this).not.toBe(oracle); return oracle; }.bind(null); var result = new Subject(); expect(result).toBe(oracle); oracle = {}; result = new Subject(); expect(result).toBe(oracle); oracle = function () {}; result = new Subject(); expect(result).toBe(oracle); oracle = 'asdf'; result = new Subject(); expect(result).not.toBe(oracle); oracle = null; result = new Subject(); expect(result).not.toBe(oracle); oracle = true; result = new Subject(); expect(result).not.toBe(oracle); oracle = 1; result = new Subject(); expect(result).not.toBe(oracle); }); it('returns the value that instance of original "class" when called as a constructor', function () { var ClassA = function (x) { this.name = x || 'A'; }; var ClassB = ClassA.bind(null, 'B'); var result = new ClassB(); expect(result instanceof ClassA).toBe(true); expect(result instanceof ClassB).toBe(true); }); it('sets a correct length without thisArg', function () { var Subject = function (a, b, c) { return a + b + c; }.bind(); expect(Subject.length).toBe(3); }); it('sets a correct length with thisArg', function () { var Subject = function (a, b, c) { return a + b + c + this.d; }.bind({ d: 1 }); expect(Subject.length).toBe(3); }); it('sets a correct length with thisArg and first argument', function () { var Subject = function (a, b, c) { return a + b + c + this.d; }.bind({ d: 1 }, 1); expect(Subject.length).toBe(2); }); it('sets a correct length without thisArg and first argument', function () { var Subject = function (a, b, c) { return a + b + c; }.bind(undefined, 1); expect(Subject.length).toBe(2); }); it('sets a correct length without thisArg and too many argument', function () { var Subject = function (a, b, c) { return a + b + c; }.bind(undefined, 1, 2, 3, 4); expect(Subject.length).toBe(0); }); }); });
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "data_types.h" #include "disable_dlib_warnings.h" POSEBASEDSOLVER_DISABLE_DLIB_WARNINGS #include <dlib/matrix.h> POSEBASEDSOLVER_RENABLE_WARNINGS namespace cm { using namespace dlib; template <template<typename...> class R = std::vector, typename Top, typename Sub = typename Top::value_type> R<typename Sub::value_type> flatten(Top const& all) { using std::begin; using std::end; R<typename Sub::value_type> accum; for (const auto &sub : all) accum.insert(end(accum), begin(sub), end(sub)); return accum; } /*! Amends the input vector by appending the item to it n times - Requires: - - Ensures: - vec.size() becomes [input] vec.size()+n where the last n elements are copies of item. */ template<typename T> void append_item_to_vector_multiple_times(std::vector<T>& vec, const T& item, int n) { std::vector<T> vec_to_append(n,item); vec.insert(vec.end(),vec_to_append.begin(),vec_to_append.end()); } /*! Returns vector of vectors where each inner vector contains one item from each of the input vectors - Requires: - - Ensures: - the result is vector of vectors where each inner vector contains one item from each of the input vectors - e.g. if the input is {{1,2,3},{4,5}} the output is {{1,4},{2,4},{3,4},{1,5},{2,5},{3,5}} */ template<typename T> std::vector<std::vector<T>> all_combinations_of_one_item_from_each_vector(const std::vector<std::vector<T>>& a) { std::vector<std::vector<T>> r(1); for (const auto& x : a) { std::vector<std::vector<T>> t; for (const T& y : x) { for (const std::vector<T>& i : r) { std::vector<T> ia(i); ia.emplace_back(y); t.emplace_back(ia); } } r = std::vector<std::vector<T>>(t); } return r; } /*! Returns a subvector consisting of the items in the original vector at the listed indices - Requires: - every item in 'indices' is less than input.size() - Ensures: - Returns a subvector consisting of the items in 'input' at the positions listed in 'indices' - Note that indices needn't contain unique elements so technically the "subvector" can be longer than the input vector. */ template<typename T> std::vector<T> subvector(const std::vector<T>& input, const std::vector<int>& indices) { DLIB_ASSERT(std::all_of(indices.begin(), indices.end(), [input](size_t i) {return i < input.size(); }), "\t subvector(...)" << "\n\t Perhaps some of the items in 'indices' where larger than the size of 'input'"); std::vector<T> output(indices.size()); auto count = 0; for(const auto &ind : indices) { output[count++] = input[ind]; } return output; } /* Splits a string into a vector of strings according to a delimiter string. - Ensures: - Returns vector of strings - input split according to a delimiter string. - If no instances of the delimiter are found, the vector will contain just the original string - The returned strings do not contain the delimiter itself. */ inline std::vector<std::string> split_by_string(const std::string &input, const std::string &delimiter) { std::vector<std::string> result; result.reserve(4); // little boost for most common input such as 'frame_number,point_id,x,y' size_t begin_pos = 0, end_pos = 0, delimiter_len = delimiter.length(); while ((end_pos = input.find(delimiter, begin_pos)) != std::string::npos) { result.push_back(input.substr(begin_pos, end_pos - begin_pos)); begin_pos = end_pos + delimiter_len; } if (begin_pos < input.size()) { result.push_back(input.substr(begin_pos)); } return result; } /* It collapses a vector of vectors to a single vector. The order of the elements is not changed. - Ensures: - Returns a vector of strings. */ template <typename T> std::vector<T> collapse_vectors(std::vector<std::vector<T>> input_vec) { std::vector<T> output_vec; std::for_each(input_vec.begin(), input_vec.end(), [&](std::vector<T> i) {output_vec.insert(output_vec.end(), i.begin(), i.end());}); return output_vec; } /*! Calculates Hamming distance between two unsigned integers. */ inline int calc_hamming_dist(unsigned patch1, unsigned patch2) { unsigned xor_res = patch1 ^ patch2; int hamming_dist = 0; while (xor_res > 0) { hamming_dist += xor_res & 1; xor_res >>= 1; } return hamming_dist; } /*! Calculates an rms point to point error between 2 sets of points. - Requires: - points_1.size() == points_2.size() - Ensures: - Returns the rms errors per point for current frame. */ inline std::vector<double> calc_rms_point_error(const point2_vector<double>& points_1, const point2_vector<double>& points_2) { DLIB_ASSERT(points_1.size() == points_2.size(), "\n\t Invalid inputs were given to calculate_error_per_point function."); std::vector<double> error_per_point; for (std::size_t idx = 0; idx < points_1.size(); idx++) { double tmp = sqrt((points_1[idx].x() - points_2[idx].x()) * (points_1[idx].x() - points_2[idx].x()) + (points_1[idx].y() - points_2[idx].y()) * (points_1[idx].y() - points_2[idx].y())); error_per_point.emplace_back(tmp); } return error_per_point; } /*! Returns the indices of the elements according to a sort - Requirements: - Comparer must be a functor implementing the (const T&, const T&) -> bool operator which compares two elements T belonging to b, deciding in which order to sort the indices. - Ensures: - Returns a vector of indices giving the sort order of the elements in v - For example sort_indices({3,4,1}) would return {2,0,1} - For example sort_indices({3,4,1}, std::greater<>()) would return {1,0,2} */ template <typename T, typename Comparer = std::less<>> std::vector<int> sort_indices(const std::vector<T> &v, Comparer comp = Comparer()) { // initialize original index locations std::vector<int> idx(v.size()); for (unsigned i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v std::sort(idx.begin(), idx.end(), [&v, &comp](int i1, int i2) {return comp(v[i1], v[i2]); }); return idx; } /*! Returns the indices of the elements according to a partial sort for the top number_to_sort values - Requirements: - Comparer must be a functor implementing the (const T&, const T&) -> bool operator which compares two elements T belonging to b, deciding in which order to sort the indices. - Ensures: - Returns a vector of indices giving the sort order of the elements in v - For example sort_indices({3,4,1}) would return {2,0,1} - For example sort_indices({3,4,1}, std::greater<>()) would return {1,0,2} */ template <typename T, typename Comparer = std::less<>> std::vector<int> partial_sort_indices(const std::vector<T> &v, unsigned number_to_sort, Comparer comp = Comparer()) { // initialize original index locations std::vector<int> idx(v.size()); for (unsigned i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v std::partial_sort(idx.begin(), idx.begin() + number_to_sort, idx.end(), [&v, &comp](int i1, int i2) {return comp(v[i1], v[i2]); }); return idx; } /*! Returns the indices of the elements according to a sort - Requirements: - Comparer must be a functor implementing the (const T&, const T&) -> bool operator which compares two elements T belonging to b, deciding in which order to sort the indices. - Ensures: - Returns a vector of indices giving the sort order of the elements in v - For example sort_indices({3,4,1}) would return {2,0,1} - For example sort_indices({3,4,1}, std::greater<>()) would return {1,0,2} */ template <typename T, typename Comparer = std::less<>> std::vector<int> sort_indices(const col_vector<T> &v, Comparer comp = Comparer()) { // initialize original index locations std::vector<int> idx(v.size()); for (unsigned i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v std::sort(idx.begin(), idx.end(), [&v, &comp](int i1, int i2) {return comp(v(i1), v(i2)); }); return idx; } /*! Converts a point2_vector to a dlib column matrix - Ensures: - Returns a dlib column matrix of the form: - [shape[0].x(), shape[0].y(), shape[1].x(), shape[1].y() ... shape[n].x(), shape[n].y()] - where n is the size of 'shape' (the number of points) */ template<typename T> dlib::matrix<T, 0, 1> point2_vector_to_col_matrix(const point2_vector<T>& shape) { matrix<T, 0, 1> pts_data(shape.size() * 2); for (auto p = 0; p < static_cast<int>(shape.size()); ++p) { pts_data(p * 2) = shape[p].x(); pts_data(p * 2 + 1) = shape[p].y(); } return pts_data; } /*! Converts a dlib column matrix to a point2_vector - Requires - data.nr() % 2 == 0 - Ensures: - Returns a point2_vector of size data.nr()/2; */ template<typename T> point2_vector<T> col_matrix_to_point2_vector(const dlib::matrix<T, 0, 1>& data) { DLIB_ASSERT(data.nr() % 2 == 0, "\t col_matrix_to_point2_vector(const dlib::matrix<T, 0, 1>& data)" << "\n\t Invalid column matrix was passed to this function." << "\n\t Data should have even number of elements." << "\n\t data.nr(): " << data.nr()); point2_vector<T> shape(data.size() / 2); for (auto p = 0; p < static_cast<int>(data.size() / 2); ++p) { shape[p] = point2<T>(data(p * 2), data(p * 2 + 1)); } return shape; } /*! Converts a dlib row matrix to a point2_vector - Requires - data.nc() % 2 == 0 - Ensures: - Returns a point2_vector of size data.nr()/2; */ template<typename T> point2_vector<T> row_matrix_to_point2_vector(const dlib::matrix<T, 1, 0>& data) { DLIB_ASSERT(data.nc() % 2 == 0, "\t row_matrix_to_point2_vector(const dlib::matrix<T, 1, 0>& data)" << "\n\t Invalid column matrix was passed to this function." << "\n\t Data should have even number of elements." << "\n\t data.nc(): " << data.nc()); point2_vector<T> shape(data.size() / 2); for (auto p = 0; p < static_cast<int>(data.size() / 2); ++p) { shape[p] = point2<T>(data(p * 2), data(p * 2 + 1)); } return shape; } /*! Converts a point3_vector to a dlib column matrix. See also col_matrix_to_point3_vector (the inverse operation) - Ensures: - Returns a dlib column matrix of the form: - [shape[0].x(), shape[0].y(), shape[0].z(), shape[1].x(), shape[1].y(), shape[1].z() ... shape[n-1].x(), shape[n-1].y(), shape[n-1].z()] - where n is the size of 'shape' (the number of points) */ template<typename T> dlib::matrix<T, 0, 1> point3_vector_to_col_matrix(const point3_vector<T>& shape) { matrix<T, 0, 1> pts_data(shape.size() * 3); for (unsigned p = 0; p < shape.size(); ++p) { pts_data(p * 3) = shape[p].x(); pts_data(p * 3 + 1) = shape[p].y(); pts_data(p * 3 + 2) = shape[p].z(); } return pts_data; } /*! Converts a dlib column matrix to a point3_vector. See also point3_vector_to_col_matrix (the inverse operation) - Requires - data.nr() % 3 == 0 - Ensures: - Returns a point3_vector of size data.nr()/3; */ template<typename T> point3_vector<T> col_matrix_to_point3_vector(const dlib::matrix<T, 0, 1>& data) { DLIB_ASSERT(data.nr() % 3 == 0, "\t col_matrix_to_point3_vector(const dlib::matrix<T, 0, 1>& data)" << "\n\t Invalid column matrix was passed to this function." << "\n\t Data should have number of elements divisible by 3." << "\n\t data.nr(): " << data.nr()); point3_vector<T> shape(data.size() / 3); for (int p = 0; p < data.size() / 3; ++p) { shape[p] = point3<T>(data(p * 3), data(p * 3 + 1), data(p * 3 + 2)); } return shape; } /*! Apply a piecewise linear mapping to a value - REQUIREMENTS ON T - Must be either float, double, or long double, ie: is_float_type<T>::value == true - Requires: - joints.size() > 2 - joints.rbegin()->first > joints.begin()->first (i.e. the keys are not identical) - Ensures: - Returns the original value x mapped through the pwl transform defined in 'joints'. - The mapping will extrapolate outside the range of the joints. - Each key in 'joints' is a sample input value point, each value is the desired output at that given input. */ template<typename T> double piecewise_linear_transform(const std::map<T, T>& joints, T x) { COMPILE_TIME_ASSERT(is_float_type<T>::value); DLIB_ASSERT(joints.size() > 1 && joints.rbegin()->first > joints.begin()->first, "\t double piecewise_linear_transform(const std::map<T, T>& joints, T& input_val)" << "\n\t Invalid joints were passed to this function."); auto it = joints.lower_bound(x); if (it == joints.end()) { it = joints.begin(); } else if (it != joints.begin()) { --it; } const auto low_in = it->first; const auto low_out = it->second; ++it; auto high_in = it->first; auto high_out = it->second; const auto m = (high_out - low_out) / (high_in - low_in); const auto c = low_out - m * low_in; return m * x + c; } /*! * Checks if every item in a vector is less-than a given value. * * - REQUIREMENTS ON T * - Must support less-than operator (<) * - Ensures * - Returns true if all the items in data are less than the limit */ template <class T> bool all_items_less_than(const std::vector<T>& data, const T& limit) { for (const auto& item : data) { if (item >= limit) { return false; } } return true; } /*! * Finds any duplicates in a string vector. * * - Ensures * - Returns a map with the duplicate point ids and their indices in the input vector. */ inline std::map<std::string, std::vector<unsigned>> find_duplicate_ids(const std::vector<std::string>& point_ids) { std::map<std::string, std::vector<unsigned>> duplicate_ids; for (unsigned idx1 = 0; idx1 < point_ids.size() - 1; idx1++) { for (unsigned idx2 = idx1 + 1; idx2 < point_ids.size(); idx2++) { if (point_ids[idx1] == point_ids[idx2]) { //The point id is not already found in the map. if (duplicate_ids.find(point_ids[idx1]) == duplicate_ids.end()) { duplicate_ids.insert({ point_ids[idx1], {idx1, idx2} }); } else { duplicate_ids.at(point_ids[idx1]).emplace_back(idx2); } break; } } } return duplicate_ids; } /*! Checks if every item in a vector is unique - Ensures - Returns true if all the items in the vector are unique, else false */ template <class T> bool is_unique(std::vector<T> x) { std::set<T> y(x.begin(), x.end()); return x.size() == y.size(); } /*! Checks if all keys in one map are present in another map - Ensures - Returns true if all the keys in key_map are keys of input_map else returns false */ template<typename T1, typename T2, typename K> bool all_keys_present(const std::map<K, T1>& input_map, const std::map<K, T2> & key_map) { for (const auto& item : key_map) { if (input_map.find(item.first) == input_map.end()) { return false; } } return true; } /*! Checks if every item in a list of keys exists as keys of a map - Ensures - Returns true if all the items in keys are keys of input_map else returns false */ template<typename T, typename K> bool all_keys_present(const std::map<K, T>& input_map, const std::vector<K>& keys) { for(const auto& key : keys) { if(input_map.find(key)==input_map.end()) { return false; } } return true; } /*! Check if any extra keys present in the map which aren't in the list of keys - Ensures - Returns true if there are extra keys present in the map which aren't in the list of keys, false otherwise */ template<typename T, typename K> bool extra_keys_present(const std::map<K, T>& input_map, const std::vector<K>& keys) { std::map < K, bool > extra; for (const auto& item : input_map) { extra[item.first] = true; } for (const auto& key : keys) { extra[key] = false; } for (const auto & item : extra) { if (item.second) { return true; } } return false; } /*! Find any keys that are not keys of the given map - Ensures - Returns a vector of items in keys which are missing from input map. */ template<typename T, typename K> std::vector<K> find_missing_keys(const std::map<K, T>& input_map, const std::vector<K>& keys) { std::vector<K> missing; for (const auto& key : keys) { if (input_map.find(key) == input_map.end()) { missing.push_back(key); } } return missing; } /*! Check if all keys are same in two maps - Ensures - Returns true if all keys are the same, false otherwise */ template<typename T, typename K> bool map_keys_identical(const std::map<K, T>& map1, const std::map<K, T>& map2) { if (map1.size() != map2.size()) { return false; } // check the keys are the same auto it1 = map1.begin(); auto it2 = map2.begin(); // bool finished = false; while (it1 != map1.end()) { if (it1->first != it2->first) { return false; } it1++; it2++; } return true; } /*! Creates a vector of the items in a std::map at given keys. - Requires Every element in keys is a key in input_map, i.e. all_keys_present(input_map, keys) == true - Ensures - Returns a vector of the items in a std::vector at given indices. - Return items can be duplicated. */ template<typename T, typename K> std::vector<T> get_map_items_at(const std::map<K,T>& input_map, const std::vector<K>& keys) { DLIB_ASSERT(all_keys_present(input_map, keys), "\t std::vector<T> get_map_items_at(const std::map<K,T>& input_map, std::vector<K>& keys)" << "\n\t Invalid inputs were given to this function, " << "\n\t It would appear that not all the given keys exist in the map. "); std::vector<T> result(keys.size()); auto count = 0; for (const auto& key : keys) { result[count++] = input_map.at(key); } return result; } /*! Check if all the column vectors have the same size - REQUIREMENTS ON T - Must be either float, double, or long double, ie: is_float_type<T>::value == true - Ensures - returns true if all the matrices in the vector have the same shape */ template<typename T> bool all_col_vectors_are_same_size(const std::vector<col_vector<T>>& data_set) { COMPILE_TIME_ASSERT(is_float_type<T>::value); auto first_size = data_set[0].size(); for (size_t s = 1; s < data_set.size(); s++) { const auto& item = data_set[s]; if(item.size() != first_size) { return false; } } return true; } /*! Check if all the elements in a vector have the same size - REQUIREMENTS ON T - Must be a object with a .size() method - Ensures - Returns true if all elements in the vector have the same size, else false. */ template<typename T> bool all_vectors_are_same_size(const std::vector<T>& data_set) { auto first_size = data_set[0].size(); for (size_t s = 1; s < data_set.size(); s++) { const auto& item = data_set[s]; if(item.size() != first_size) { return false; } } return true; } /*! Check if two image pyramids have the same size. - Ensures - Returns true if pyramids have the same number of pyramid levels and contain arrays of the same size in each level. Else false. */ inline bool image_pyramids_same_size(const std::vector<std::unique_ptr<array2d<unsigned char>>>& img1_pyramid, const std::vector<std::unique_ptr<array2d<unsigned char>>>& img2_pyramid) { if (img1_pyramid.size() != img2_pyramid.size()) return false; for (size_t level = 0; level < img1_pyramid.size(); level++) { if (img1_pyramid[level]->size() != img2_pyramid[level]->size()) return false; } return true; } /*! Check if the size of chips is equal for each pyramid level. - Ensures - Returns true if the two inputs have the same number of levels and contain chips of the same size in each level. Else false. */ inline bool all_chips_same_size(const std::vector<array2d<unsigned char>>& reference_chips, const std::vector<dlib::array<array2d<unsigned char>>>& stereo_chips) { if (reference_chips.size() != stereo_chips.size()) return false; for (std::size_t level = 0; level < stereo_chips.size(); level++) { for (const auto& chip : stereo_chips[level]) { if (chip.nc() != reference_chips[level].nc() || chip.nr() != reference_chips[level].nr()) { return false; } } } return true; } /*! Find minimum values seen in each row of items in a data set - REQUIREMENTS ON T - Must be either float, double, or long double, ie: is_float_type<T>::value == true - Requires - data_set.size() > 0 - all_col_vectors_are_same_size(data_set) - Ensures - Returns a column vector containing the minimum values seen in each corresponding row of data_set. */ template<typename T> col_vector<T> element_wise_min(const std::vector<col_vector<T>>& data_set) { COMPILE_TIME_ASSERT(is_float_type<T>::value); DLIB_ASSERT(data_set.size() > 0 && all_col_vectors_are_same_size(data_set), "\t element_wise_min(const std::vector<matrix<T, 0, 1>>& data_set)" << "\n\t Invalid inputs were given to this function " << "\n\t data_set.size(): " << data_set.size() << "\n\t all_col_vectors_are_same_size(data_set): " << all_col_vectors_are_same_size(data_set)); matrix<T, 0, 1> result = data_set.front(); for (size_t s = 1; s < data_set.size(); s++) { const col_vector<T>& item = data_set[s]; for (long i = 0; i < item.nr(); i++) { result(i) = std::min(result(i), item(i)); } } return result; } /*! Find maximum values seen in each row of items in a data set - REQUIREMENTS ON T - Must be either float, double, or long double, ie: is_float_type<T>::value == true - Requires - data_set.size() > 0 - all_col_vectors_are_same_size(data_set) - Ensures - Returns a column vector containing the maximum values seen in each corresponding row of data_set. */ template<typename T> col_vector<T> element_wise_max(const std::vector<col_vector<T>>& data_set) { COMPILE_TIME_ASSERT(is_float_type<T>::value); DLIB_ASSERT(data_set.size() > 0 && all_col_vectors_are_same_size(data_set), "\t element_wise_max(const std::vector<matrix<T, 0, 1>>& data_set)" << "\n\t Invalid inputs were given to this function " << "\n\t data_set.size(): " << data_set.size() << "\n\t all_col_vectors_are_same_size(data_set): " << all_col_vectors_are_same_size(data_set)); matrix<T, 0, 1> result = data_set.front(); for (size_t s = 1; s < data_set.size(); s++) { const col_vector<T>& item = data_set[s]; for (long i = 0; i < item.nr(); i++) { result(i) = std::max(result(i), item(i)); } } return result; } /*! Find minimum and maximum values seen in each row of items in a data set - REQUIREMENTS ON T - Must be either float, double, or long double, ie: is_float_type<T>::value == true - Requires - data_set.size() > 0 - all_col_vectors_are_same_size(data_set) - Ensures - Output is two column vectors containing the minimum and maximum values seen in each corresponding row of data_set. */ template<typename T> void element_wise_min_max(const std::vector<col_vector<T>>& data_set, col_vector<T>& min_result, col_vector<T>& max_result) { COMPILE_TIME_ASSERT(is_float_type<T>::value); DLIB_ASSERT(data_set.size() > 0 && all_col_vectors_are_same_size(data_set), "\t element_wise_max(const std::vector<matrix<T, 0, 1>>& data_set)" << "\n\t Invalid inputs were given to this function " << "\n\t data_set.size(): " << data_set.size() << "\n\t all_col_vectors_are_same_size(data_set): " << all_col_vectors_are_same_size(data_set)); min_result = max_result = data_set.front(); for (size_t s = 1; s < data_set.size(); s++) { const col_vector<T>& item = data_set[s]; for (long i = 0; i < item.nr(); i++) { min_result(i) = std::min(min_result(i), item(i)); max_result(i) = std::max(max_result(i), item(i)); } } } /*! Turns a std::vector of dlib column vectors into a dlib matrix - REQUIREMENTS ON T - Must be either float, double, or long double, ie: is_float_type<T>::value == true - Requires - data_as_col_vectors.size() > 0 - Every element of data_as_col_vectors must be same size and have nr() > 0 - Ensures - Turns the std::vector of dlib column vectors into a dlib matrix, each column of which is the corresponding element of the std::vector */ template <typename T> matrix<T> col_vectors_to_single_mat(const std::vector<col_vector<T>>& data_as_col_vectors) { COMPILE_TIME_ASSERT(is_float_type<T>::value); DLIB_ASSERT(data_as_col_vectors.size() > 0 && all_col_vectors_are_same_size(data_as_col_vectors) && data_as_col_vectors[0].size() > 0 , "\t col_vectors_to_single_mat(const std::vector<col_vector<T>>& data_as_col_vectors)" << "\n\t Invalid inputs were given to this function " << "\n\t (data_as_col_vectors.size(): " << data_as_col_vectors.size() << "\n\t (all_col_vectors_are_same_size(data_as_col_vectors): " << all_col_vectors_are_same_size(data_as_col_vectors) << "\n\t (data_as_col_vectors[0].size(): " << data_as_col_vectors[0].size()); matrix<T> mat; auto nr = data_as_col_vectors[0].nr(); auto nc = static_cast<int>(data_as_col_vectors.size()); mat.set_size(nr, nc ); auto count = 0; for (const auto& vec : data_as_col_vectors) { set_colm(mat, count++) = vec; } return mat; } /*! Converts a vector to a map according the given keys. - Requires - keys.size()==values.size() - is_unique(keys) - Ensures - Returns a map in which the corresponding items in 'keys' index the ordered items in 'values'. */ template<class T, class U> std::map<T, U> vector_to_map(const std::vector<U>& values, const std::vector<T>& keys) { DLIB_ASSERT(keys.size()==values.size(), "\t vector_to_map(const std::vector<U>& values, const std::vector<T>& keys)" << "\n\t Invalid inputs were given to this function " << "\n\t keys.size(): " << keys.size() << "\n\t values.size(): " << values.size() << "\n\t is_unique(keys): " << is_unique(keys)); std::map<T, U> output; for (size_t i = 0; i < keys.size(); i++) { output[keys[i]] = values[i]; } return output; } /*! Converts a map to a vector corresponding to the given keys, in order - Requires - All items in selected_keys must be in the map, i.e. all_items_are_keys(const std::map<T, U>& input, const std::vector<T>& keys) == true - Ensures - Returns the items from the map, selected by selected_keys, as a vector. - The returned vector has the same size as 'keys'. */ template<class T, class U> std::vector<U> map_to_vector(const std::map<T, U>& input, const std::vector<T>& keys) { DLIB_ASSERT(all_keys_present(input, keys) == true, "\t map_to_vector(const std::map<T, U>& input, const std::vector<T>& keys)" << "\n\t Invalid inputs were given to this function " << "\n\t all_keys_present(const std::map<T, U>& input, const std::vector<T>& keys): " << all_keys_present(input, keys)); std::vector<U> output; output.reserve(keys.size()); for (const auto& key : keys) { output.push_back(input.at(key)); } return output; } /*! Lists all keys in a given map - Ensures - Returns a vector of all keys in a given map */ template<typename T, typename U> std::vector<T> list_all_keys(const std::map<T, U>& input) { std::vector<T> output(input.size()); auto count = 0; for (const auto &imap : input) { output[count++] = imap.first; } return output; } /*! Checks existence of an element in a vector - Ensures - Returns true if the vector contains the specified element. */ template <typename T> bool does_vector_contain_element(const std::vector<T> & vec, const T& element) { return std::find(vec.begin(), vec.end(), element) != vec.end(); } /*! Checks if elements of one vector are contained within another - Ensures - Returns true if the specified vector is a subset. */ template <typename T> bool does_vector_contain_vector(std::vector<T> superset, std::vector<T> subset) { if (superset.size() < subset.size()) return false; std::sort(superset.begin(), superset.end()); std::sort(subset.begin(), subset.end()); return std::includes(superset.begin(), superset.end(), subset.begin(), subset.end()); } /*! Checks if two vectors are equal. - Ensures - Returns true if the vectors contain the same elements. */ template <typename T> bool vectors_contain_same_elements(std::vector<T> vec1, std::vector<T> vec2) { if (vec1.size() != vec2.size()) return false; std::sort(vec1.begin(), vec1.end()); std::sort(vec2.begin(), vec2.end()); return (vec1 == vec2 ? true : false); } /*! Finds the index of the element in the vector - Ensures - Returns the zero-based index of the specified element in the vector, or -1 if the element does not exist */ template <typename T> int index_of_item_in_vector(const std::vector<T> & vec, const T& value) { int index = static_cast<int>(vec.size() - 1); for (; index >= 0 && vec[index] != value; index--); return index; } /*! Extends a vector with the elements from another vector - Ensures - Returns a vector containing the elements of the first vector followed by the elements of the second vector. */ template <typename T> void extend_vector(std::vector<T>& vec_to_extend, const std::vector<T> & items_to_add) { vec_to_extend.reserve(vec_to_extend.size() + items_to_add.size()); std::copy(items_to_add.begin(), items_to_add.end(), back_inserter(vec_to_extend)); } /*! Given a vector of std::pairs a new vector is created containing just the first part of each pair - Ensures - Returns a vector of the first parts of the pairs */ template<typename T, typename U> std::vector<T> extract_first_element_in_vector_of_pairs(const std::vector<std::pair<T, U>> & vec) { std::vector<T> result; result.reserve(vec.size()); for (const auto& this_pair : vec) { result.push_back(this_pair.first); } return result; } /*! Given a vector of std::pairs a new vector is created containing just the second part of each pair - Ensures - Returns a vector of the first parts of the pairs */ template<typename T, typename U> std::vector<U> extract_second_element_in_vector_of_pairs(const std::vector<std::pair<T, U>> & vec) { std::vector<U> result; result.reserve(vec.size()); for (const auto & this_pair : vec) { result.push_back(this_pair.second); } return result; } /*! Find next position in the vector where target is found. - Ensures - Returns the next position in the vector where target is found, starting at start_pos (not including start_pos) - note, the position is returned as the absolute position in the vector, NOT the positions relative to start_pos - if target is not found, returns -1 - if start pos is outside the vector, returns -1 */ template<typename T> int find_next_case(const std::vector<T>& vec, const T& target, const int start_pos) { if (start_pos >= 0 && start_pos < vec.size() - 1) { for (auto i = start_pos + 1; i < vec.size(); ++i) { if (target == vec[i]) { return i; } } } return -1; } /*! Find previous position in the vector where target is found. - Ensures - Returns the previous position in the vector where target is found, starting at start_pos (not including start_pos) - note, the position is returned as the absolute position in the vector, NOT the positions relative to start_pos - if target is not found, returns -1 - if start pos is outside the vector, returns -1 */ template<typename T> int find_prev_case(const std::vector<T>& vec, const T& target, const int start_pos) { if (start_pos > 0 && start_pos < vec.size()) { for (auto i = start_pos - 1; i >= 0; --i) { if (target == vec[i]) { return i; } } } return -1; } /*! Check if all vectors in a vector of vectors have the same size, and are bigger than a minimum size - Ensures - Returns true iff input has at least one entry, each entry has the same size, and each entry has at least n elements - Returns false if input.empty() */ template<typename T> bool vectors_all_same_size_with_at_least_n_elements(const std::vector<std::vector<T>>& input, const size_t n) { if (input.empty()) { return false; } const size_t first_size = input[0].size(); if (first_size < n) { return false; } return all_vectors_are_same_size(input); } /*! Extracts the unique elements in a vector - Ensures - Returns a new vector containing only the unique elements in input */ template<typename T> std::vector<T> unique_elements(const std::vector<T>& input) { std::vector<T> output(input); std::sort(output.begin(), output.end()); output.erase(std::unique(output.begin(), output.end()), output.end()); return output; } /*! Checks that all maps in a vector of maps contain the same keys. - Ensures - Returns true if all the maps in the vector have the same keys. */ template <typename K, typename T> bool all_maps_have_same_keys(const std::vector<std::map<K, T>>& maps) { if (maps.empty()) return false; const auto& maps_0 = maps[0]; for (size_t s = 1; s < maps.size(); s++) { const auto& maps_s = maps[s]; if (maps_s.size() != maps_0.size()) return false; for (auto it_0 = maps_0.begin(), it_s = maps_s.begin(); it_0 != maps_0.end(); ++it_0, ++it_s) { if (it_0->first != it_s->first) return false; } } return true; } /*! Converts a vector of maps to a map of vectors - Requires - every item in input must contain the same keys - Ensures - returns a map of vectors by transposing the vector of maps */ template<typename K, typename T> std::map<K,std::vector<T>> vector_of_maps_to_map_of_vectors(const std::vector<std::map<K, T>>& input) { DLIB_ASSERT(all_maps_have_same_keys(input) == true, "\t vector_of_maps_to_map_of_vectors(std::vector<std::map<K, T>>& input)" << "\n\t Invalid inputs were given to this function " << "\n\t all_maps_have_same_keys(input): " << all_maps_have_same_keys(input)); std::map<K, std::vector<T>> output; if (input.empty()) return output; auto keys = list_all_keys(input[0]); for(const auto& key : keys) { output[key] = std::vector<T>(input.size()); auto count = 0; for(const auto& item : input) { output[key][count++] = item.at(key); } } return output; } /*! ensures - returns a std::vector of int ranging from 0 to n-1 !*/ inline std::vector<int> zero_based_int_range(unsigned int n) { std::vector<int> result(n); for (unsigned int i = 0; i < n; ++i) { result[i] = i; } return result; } /* Returns the median of an input vector. */ template<typename T> T calc_median(std::vector<T> input_vec) { std::size_t middle_idx = input_vec.size() / 2; std::nth_element(input_vec.begin(), input_vec.begin() + middle_idx, input_vec.end()); if (input_vec.size() % 2 != 0) return input_vec[middle_idx]; else { T tmp = input_vec[middle_idx]; middle_idx = middle_idx - 1; std::nth_element(input_vec.begin(), input_vec.begin() + middle_idx, input_vec.end()); return (tmp + input_vec[middle_idx]) / 2.0; } } /*! Calculates the median filter for all points across all frames. - Requires: - all frames contain the same points. - Ensures: - Returns the smoothed points over time by taking their median values at a user defined window size. */ template<typename T> std::vector<std::map<std::string, point2<T>>> calc_median_filter(std::vector<std::map<std::string, point2<T>>> input_points, unsigned window_size) { DLIB_ASSERT(all_maps_have_same_keys(input_points), "\n\t Input vector should contain maps with the same point ids."); std::vector<std::map<std::string, point2<T>>> smoothed_input_points(input_points.size()); //Loop for all points. for (const auto& pt : input_points[0]) { //Loop for all frames. for (unsigned fr = 0; fr < input_points.size(); fr++) { std::vector<T> temp_vec_x, temp_vec_y; if (fr < std::floor(window_size / 2)) { for (unsigned i = 0; i < window_size; i++) { temp_vec_x.emplace_back(input_points[i].at(pt.first).x()); temp_vec_y.emplace_back(input_points[i].at(pt.first).y()); } } else if (fr > input_points.size() - std::floor(window_size / 2) - 1) { for (unsigned i = input_points.size() - window_size; i < input_points.size(); i++) { temp_vec_x.emplace_back(input_points[i].at(pt.first).x()); temp_vec_y.emplace_back(input_points[i].at(pt.first).y()); } } else { if (window_size % 2 == 0) { for (unsigned i = fr - std::floor(window_size / 2); i <= fr + std::floor(window_size / 2); i++) { temp_vec_x.emplace_back(input_points[i].at(pt.first).x()); temp_vec_y.emplace_back(input_points[i].at(pt.first).y()); } } else { for (unsigned i = fr - std::floor(window_size / 2); i < fr + std::floor(window_size / 2); i++) { temp_vec_x.emplace_back(input_points[i].at(pt.first).x()); temp_vec_y.emplace_back(input_points[i].at(pt.first).y()); } } } T median_val_x = calc_median(temp_vec_x); T median_val_y = calc_median(temp_vec_y); smoothed_input_points[fr].emplace(pt.first, point2<T>(median_val_x, median_val_y)); } } return smoothed_input_points; } /* A constraint on vector components of arbitrary dimensionality. Particularly suited for constrained PCA encoding and reconstruction. */ template <typename T=double> class subvector_constraint { public: /* Overload for point2 vectors */ inline subvector_constraint(size_t index, const point2<T>& pt2):index_(index) { constraint_vector_ = col_vector<T>({ pt2.x(), pt2.y() }); } /* Overload for col_vector<T> */ inline subvector_constraint(size_t index, const col_vector<T>& vec) :index_(index) { constraint_vector_ = vec; } /* Returns the index of the constraint in the big data vector */ inline size_t index() const { return index_; } /* Dimension of the constraint vector */ inline size_t dimension() const { return constraint_vector_.nr(); } /* Get the constraint vector */ inline col_vector<T> constraint_vector()const { return constraint_vector_; } /* Returns the dimensionality of a vector of constraints */ template <typename P> inline static size_t dimensionality(const std::vector<subvector_constraint<P>>& constraints) { if (constraints.empty()) return 0; size_t dim = 0; for (size_t i = 0; i < constraints.size(); i++) { dim += constraints[i].dimension(); } return dim; } private: // Index of the constraint in the vector. To compute the 0-based position in the vector: // index in vector = dimension_ * index (see position_in_vector() ) size_t index_; // The constraint (sub)vector col_vector<T> constraint_vector_; }; }
import { Injectable, Inject } from '@angular/core'; import { AppConfiguration } from '../../configuration'; import { HttpHeaders } from '@angular/common/http'; import { SESSION_STORAGE, StorageService } from 'ngx-webstorage-service'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; @Injectable() export class ItemStatusService { public serviceURL = AppConfiguration.typeStatusRestURL + 'status'; public isProd = false; private authToken = sessionStorage.getItem('auth_token') ? sessionStorage.getItem('auth_token') : ''; private httpOptions = { headers: new HttpHeaders({ Authorization: 'Bearer ' + this.authToken, }), }; constructor( @Inject(SESSION_STORAGE) private storage: StorageService, private http: HttpClient ) {} saveItemStatus(itemStatus: any) { return this.http .post(this.serviceURL, itemStatus, this.httpOptions) .pipe(catchError(this.handleError)); } updateItemStatus(itemStatus: { statusid: string }) { return this.http .put( this.serviceURL + '/' + itemStatus.statusid, itemStatus, this.httpOptions ) .pipe(catchError(this.handleError)); } getItemStatus(index: number) { return this.http .get(this.serviceURL + '/' + index, this.httpOptions) .pipe(catchError(this.handleError)); } getAllItemStatuses(companyId: string) { return this.http .get( this.serviceURL + '/getAllStatusByCompanyId/itemtype/' + companyId, this.httpOptions ) .pipe(catchError(this.handleError)); } removeItemStatus(id: number, userName: string) { return this.http .delete(this.serviceURL + '/' + id + '/' + userName, this.httpOptions) .pipe(catchError(this.handleError)); } private handleError(error: any) { if (error.error instanceof ErrorEvent) { console.error('An error occurred:', error.error.message); } else { console.error(error.error); } return throwError(() => 'Something bad happened; please try again later.'); } }
// // GetBanAsync.cs // // Author: // Jarl Gullberg <jarl.gullberg@gmail.com> // // Copyright (c) Jarl Gullberg // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #pragma warning disable SA1600 #pragma warning disable CS1591 #pragma warning disable SA1649 using System.Threading.Tasks; using DIGOS.Ambassador.Tests.Plugins.Moderation.Bases; using Remora.Rest.Core; using Xunit; namespace DIGOS.Ambassador.Tests.Plugins.Moderation.Services.BanService; public partial class BanService { public class GetBanAsync : BanServiceTestBase { private readonly Snowflake _guild = new(1); private readonly Snowflake _otherGuild = new(2); private readonly Snowflake _user = new(3); private readonly Snowflake _author = new(4); [Fact] public async Task ReturnsSuccessfulIfBanExists() { var ban = (await this.Bans.CreateBanAsync(_author, _user, _guild, "Dummy thicc")).Entity; var result = await this.Bans.GetBanAsync(_guild, ban.ID); Assert.True(result.IsSuccess); } [Fact] public async Task ReturnsUnsuccessfulIfNoBanExists() { var result = await this.Bans.GetBanAsync(_guild, 1); Assert.False(result.IsSuccess); } [Fact] public async Task ReturnsUnsuccessfulIfBanExistsButServerIsWrong() { var ban = (await this.Bans.CreateBanAsync(_author, _user, _guild, "Dummy thicc")).Entity; var result = await this.Bans.GetBanAsync(_otherGuild, ban.ID); Assert.False(result.IsSuccess); } [Fact] public async Task ActuallyReturnsBan() { var ban = (await this.Bans.CreateBanAsync(_author, _user, _guild, "Dummy thicc")).Entity; var result = await this.Bans.GetBanAsync(_guild, ban.ID); Assert.Same(ban, result.Entity); } } }
package com.maoxian.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; import java.util.Date; import java.util.UUID; /** * JWT工具类 */ public class JwtUtil { //有效期 public static final Long JWT_TTL = 7 * 24 * 60 * 60 * 1000L; //密钥明文 public static final String JWT_KEY = "maoxian"; /** * 生成随机的字符串,作为JWT的唯一标识 * * @return UUID唯一标识 */ public static String getUUID() { return UUID.randomUUID().toString().replaceAll("-", ""); } /** * 创建JWT * * @param subject 主题 * @return jwt */ public static String createJWT(String subject) { JwtBuilder builder = getJwtBuilder(subject, null, getUUID()); return builder.compact(); } /** * 创建JWT * * @param subject 主题 * @param ttlMillis 过期时间 * @return jwt */ public static String createJWT(String subject, Long ttlMillis) { JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID()); return builder.compact(); } /** * 创建JWT * * @param subject 主题 * @param ttlMillis 过期时间 * @param id id * @return jwt */ public static String createJWT(String subject, Long ttlMillis, String id) { JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id); return builder.compact(); } /** * 构建JWT * * @param subject 主题 * @param ttlMills 过期时间 * @param uuid UUID唯一标识 * @return JWT构建器 */ private static JwtBuilder getJwtBuilder(String subject, Long ttlMills, String uuid) { //JWT签名算法和密钥 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; SecretKey secretKey = generalKey(); //过期时间 long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); if (ttlMills == null) { ttlMills = JwtUtil.JWT_TTL; } long expMillis = nowMillis + ttlMills; Date expDate = new Date(expMillis); return Jwts.builder()//jwt构建器 .setId(uuid)//UUID唯一标识 .setSubject(subject)//主题,可以是JSON数据 .setIssuer("maoxian")//签发者 .setIssuedAt(now)//签发时间 .signWith(signatureAlgorithm, secretKey)//使用指定签名算法和密钥签名 .setExpiration(expDate);//设置过期时间 } /** * 生成加密后的密钥 * * @return secretKey */ public static SecretKey generalKey() { byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY); return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); } /** * 解析jwt * * @param jwt jwt字符串 * @return claims 声明信息 */ public static Claims parseJWT(String jwt) { SecretKey secretKey = generalKey(); return Jwts.parser()//jwt解析器 .setSigningKey(secretKey)//验证签名 .parseClaimsJws(jwt)//解析jwt,返回JWT的所有声明信息和签名 .getBody();//获取声明信息 } }
package com.example.appxemphim.fragments import android.annotation.SuppressLint import android.app.AlertDialog import android.app.Dialog import android.content.Intent import android.content.pm.ActivityInfo import android.content.res.Configuration import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.os.Handler import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.example.appxemphim.R import com.example.appxemphim.activities.MainActivity import com.example.appxemphim.activities.ThanhToanActivity import com.example.appxemphim.adapters.CommentAdapter import com.example.appxemphim.adapters.EpisodeAdapter import com.example.appxemphim.adapters.MovieAdapter import com.example.appxemphim.adapters.PersonAdapter import com.example.appxemphim.databinding.DialogBuyMovieBinding import com.example.appxemphim.databinding.FragmentPhimBinding import com.example.appxemphim.model.Movie import com.example.appxemphim.util.CONFIG import com.example.appxemphim.util.Resource import com.example.appxemphim.viewModel.CollectionViewModel import com.example.appxemphim.viewModel.CommentViewModel import com.example.appxemphim.viewModel.MovieViewModel import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.MediaItem import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import java.util.Calendar @AndroidEntryPoint class PhimFragment : Fragment() { private lateinit var binding: FragmentPhimBinding private val movieViewModel by viewModels<MovieViewModel>() private val collectionViewModel by viewModels<CollectionViewModel>() private val commentViewModel by viewModels<CommentViewModel>() private lateinit var player: ExoPlayer private lateinit var episodeAdapter: EpisodeAdapter private lateinit var personAdapter: PersonAdapter private lateinit var randomMovieAdapter: MovieAdapter private lateinit var commentAdapter: CommentAdapter private var phimDaDuocLuu = false private var movieId: Int = 0 private var ratingStar = 5 private var pageCmt = 0 private val calendar = Calendar.getInstance() private var nam = calendar[Calendar.YEAR] private var thang = calendar[Calendar.MONTH] // Tháng bắt đầu từ 0 private var ngay = calendar[Calendar.DAY_OF_MONTH] private lateinit var fullScreenDialog: Dialog private var fullscreen = false private lateinit var selectedMovie: Movie override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { player = ExoPlayer.Builder(requireContext()).build() binding = FragmentPhimBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //onBackPressed() iniFullScreenDialog() binding.videoRatioLayout.setAspectRatio(16f / 9f) var bundle = arguments if (bundle != null) { movieId = bundle.getInt("movieId") movieViewModel.loadPhim(movieId) } lifecycleScope.launchWhenStarted { movieViewModel.phim.collectLatest { when (it) { is Resource.Loading -> {} is Resource.Success -> { setUpMovie(it.data!!) } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } lifecycleScope.launch { movieViewModel.phimNgauNhien.collectLatest { when (it) { is Resource.Loading -> {} is Resource.Success -> { randomMovieAdapter.differ.submitList(it.data) } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } lifecycleScope.launch { collectionViewModel.phimDaLuu.collectLatest { when (it) { is Resource.Loading -> {} is Resource.Success -> { phimDaDuocLuu = it.data!! if (phimDaDuocLuu) { binding.btnLuuPhim.setImageResource(R.drawable.baseline_favorite_24) } else { binding.btnLuuPhim.setImageResource(R.drawable.baseline_favorite_border_24) } } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } lifecycleScope.launch { collectionViewModel.luuPhim.collectLatest { when (it) { is Resource.Loading -> {} is Resource.Success -> { phimDaDuocLuu = true binding.btnLuuPhim.setImageResource(R.drawable.baseline_favorite_24) Toast.makeText(requireContext(), "Đã lưu phim ", Toast.LENGTH_SHORT).show() } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } lifecycleScope.launch { collectionViewModel.xoaPhim.collectLatest { when (it) { is Resource.Loading -> {} is Resource.Success -> { if (it.data!!) { phimDaDuocLuu = false binding.btnLuuPhim.setImageResource(R.drawable.baseline_favorite_border_24) Toast.makeText( requireContext(), "Đã xoá phim khỏi danh sách lưu ", Toast.LENGTH_SHORT ).show() } } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } lifecycleScope.launch { commentViewModel.luuBinhLuan.collectLatest { when (it) { is Resource.Loading -> {} is Resource.Success -> { Toast.makeText( requireContext(), "Đã gửi bình luận", Toast.LENGTH_SHORT ).show() pageCmt = 0 commentViewModel.loadCmt(0, movieId) } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } lifecycleScope.launch { commentViewModel.taiBinhLuan.collectLatest { when (it) { is Resource.Loading -> { binding.progressBar.visibility = View.VISIBLE binding.tvKoCmt.visibility = View.GONE } is Resource.Success -> { commentAdapter.differ.submitList(it.data) if (pageCmt == 0) { binding.btnCmtBefore.visibility = View.GONE } else { binding.btnCmtBefore.visibility = View.VISIBLE } if (it.data!!.size < 5) { binding.btnCmtAfter.visibility = View.GONE } else { binding.btnCmtAfter.visibility = View.VISIBLE } if (pageCmt == 0 && it.data.size == 0) { binding.tvKoCmt.visibility = View.VISIBLE } binding.progressBar.visibility = View.GONE } is Resource.Error -> { binding.progressBar.visibility = View.GONE binding.tvKoCmt.visibility = View.VISIBLE Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } lifecycleScope.launch { movieViewModel.existBuyMovie.collectLatest { when (it) { is Resource.Loading -> { binding.progressBar.visibility = View.VISIBLE } is Resource.Success -> { binding.progressBar.visibility = View.GONE if (!it.data!!) { openBuyMovieDialog(selectedMovie) } else { movieViewModel.loadPhim(selectedMovie.movieId) } } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> {} } } } binding.btnFullScreen.setOnClickListener { openFullscreenDialog() } binding.btnLuuPhim.setOnClickListener { if (!phimDaDuocLuu) collectionViewModel.luuPhim(movieId, dinhDangNgayAPI(ngay, thang, nam)) else { collectionViewModel.xoaPhim(movieId) } } binding.ratingBar.setOnRatingBarChangeListener { ratingBar, rating, fromUser -> ratingStar = rating.toInt() } binding.btnGuiBinhLuan.setOnClickListener { commentViewModel.saveComment( binding.etBinhLuan.text.toString().trim(), movieId, ratingStar, dinhDangNgayAPI(ngay, thang, nam) ) binding.etBinhLuan.setText("") } binding.btnCmtBefore.setOnClickListener { pageCmt -= 1 commentViewModel.loadCmt(pageCmt, movieId) } binding.btnCmtAfter.setOnClickListener { pageCmt += 1 commentViewModel.loadCmt(pageCmt, movieId) } } @SuppressLint("SetTextI18n") private fun setUpMovie(movie: Movie) { pageCmt = 0 movieId = movie.movieId collectionViewModel.kiemTraPhimDaLuu(movieId) commentViewModel.loadCmt(pageCmt, movieId) movieViewModel.loadPhimNgauNhien() binding.apply { Glide.with(requireContext()).load(CONFIG.CLOUD_URL + movie.image).into(ivHinh) tvTenPhim.text = movie.name tvLuotXem.text = "Lượt xem: " + movie.views.toString() tvSoSao.text = "Đánh giá: " + movie.star.toString() + "/5" tvQuocGia.text = "Quốc gia: " + movie.country.name tvThongTin.text = movie.movieContent if (movie.episodeList.size > 0) { setUpPlayerView(movie.episodeList[0].link) videoPlayer.visibility = View.VISIBLE ivError.visibility = View.GONE } else { player.stop() videoPlayer.visibility = View.INVISIBLE ivError.visibility = View.VISIBLE } if (movie.episodes == 1) { linearChonTapPhim.visibility = View.GONE } else if (movie.episodes > 1) { linearChonTapPhim.visibility = View.VISIBLE } if (movie.persons.size > 0) { rvDienVien.visibility = View.VISIBLE tvUpdate.visibility = View.GONE } else { rvDienVien.visibility = View.GONE tvUpdate.visibility = View.VISIBLE } } initAdapter(movie) } override fun onStop() { super.onStop() player.playWhenReady = false } override fun onStart() { super.onStart() player.playWhenReady = true } override fun onDestroy() { super.onDestroy() player.release() } private fun onBackPressed() { view?.setFocusableInTouchMode(true) view?.requestFocus() view?.setOnKeyListener(object : View.OnKeyListener { override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { if (v != null) { //Navigation.findNavController(requireActivity(),R.id.fragmentContainerView).navigateUp() // (activity as MainActivity).replaceFragment(HomeFragment()) if ((activity as MainActivity).supportFragmentManager.backStackEntryCount > 0) { (activity as MainActivity).supportFragmentManager.popBackStack() } } } return true } }) } private fun initAdapter(movie: Movie) { //tập phim if (movie.episodes > 1) { episodeAdapter = EpisodeAdapter() binding.rvTapPhim.apply { adapter = episodeAdapter layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) } episodeAdapter.differ.submitList(movie.episodeList.sortedBy { it.episode }) episodeAdapter.setOnItemClickListener(object : EpisodeAdapter.OnItemClickListener { override fun onItemClick(link: String) { setUpPlayerView(link) } }) } // diễn viên personAdapter = PersonAdapter() binding.rvDienVien.apply { adapter = personAdapter layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) } personAdapter.differ.submitList(movie.persons) randomMovieAdapter = MovieAdapter() binding.rvPhimNgauNhien.apply { adapter = randomMovieAdapter layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) } randomMovieAdapter.setOnItemClickListener(object : MovieAdapter.OnItemClickListener { override fun onItemClick(movie: Movie, price: Int) { checkMovie(movie, price) } }) commentAdapter = CommentAdapter() binding.rvBinhLuan.apply { adapter = commentAdapter layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) } } private fun setUpPlayerView(link: String) { binding.videoPlayer.player = player val mediaItem = MediaItem.fromUri(CONFIG.CLOUD_URL + link.trim()) player.setMediaItem(mediaItem) player.prepare() player.play() } fun iniFullScreenDialog() { fullScreenDialog = object : Dialog(requireContext(), android.R.style.Theme_Black_NoTitleBar_Fullscreen) { override fun onBackPressed() { if (fullscreen) { closeFullscreenDialog() } super.onBackPressed() } } } private fun closeFullscreenDialog() { requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT val parentView = binding.videoPlayer.parent as ViewGroup parentView.removeView(binding.videoPlayer) binding.videoRatioLayout.addView(binding.videoPlayer) fullscreen = false fullScreenDialog.dismiss() requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR } private fun openFullscreenDialog() { requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE val parentView = binding.videoPlayer.parent as ViewGroup parentView.removeView(binding.videoPlayer) fullScreenDialog.addContentView( binding.videoPlayer, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) fullscreen = true fullScreenDialog.show() Handler().postDelayed({ requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR }, 3000) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { openFullscreenDialog() } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { closeFullscreenDialog() } } private fun dinhDangNgayAPI(ngay: Int, thang: Int, nam: Int): String { var temp = "" temp += nam temp += "-" temp += if (thang + 1 < 10) "0" + (thang + 1).toString() else (thang + 1).toString() temp += "-" temp += if (ngay < 10) "0$ngay" else ngay.toString() return temp } fun openBuyMovieDialog(movie: Movie) { val dialogBuyMovieBinding: DialogBuyMovieBinding = DialogBuyMovieBinding.inflate(layoutInflater) val mDialog = AlertDialog.Builder(activity).setView(dialogBuyMovieBinding.root) .create() mDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialogBuyMovieBinding.tvMoneyPrice.text = movie.price.toString() mDialog.show() // mDialog.dismiss() dialogBuyMovieBinding.btnConfirm.setOnClickListener { val intent = Intent(requireActivity(), ThanhToanActivity::class.java) intent.putExtra("movie", movie) startActivity(intent) mDialog.dismiss() } dialogBuyMovieBinding.btnHuy.setOnClickListener { mDialog.dismiss() } } fun checkMovie(movie: Movie, price: Int) { selectedMovie = movie if (price > 0) { movieViewModel.checkExistMovieBuy(selectedMovie) } else { var b: Bundle = Bundle() b.putInt("movieId", selectedMovie.movieId) val phimFragment = PhimFragment() phimFragment.arguments = b (activity as MainActivity).replaceFragment(phimFragment, "MOVIE") movieViewModel.loadPhim(selectedMovie.movieId) } } }
import mergeCallbacksAndSerializable from './mergeCallbacksAndSerializable'; describe('mergeCallbacksAndSerializable', () => { test('should create functions from given callback IDs while preserving values', () => { const callbacks = { foo: { fn1: 'some-id-here', fn2: 'another-id-here', }, test: [ 'test[0]', undefined, 'test[2]', ], }; // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied const data: any = { foo: { fn1: undefined, fn2: undefined, value1: 1, }, test: [ undefined, 'Test', undefined, ], }; const callMethodWithId = jest.fn(); // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied const merged: any = mergeCallbacksAndSerializable(data, callbacks, callMethodWithId, ()=>{}); // Should have created functions merged.foo.fn1(3, 4); expect(callMethodWithId).toHaveBeenLastCalledWith('some-id-here', [3, 4]); merged.foo.fn2(); expect(callMethodWithId).toHaveBeenLastCalledWith('another-id-here', []); merged.test[2](); expect(callMethodWithId).toHaveBeenLastCalledWith('test[2]', []); // Should have preserved values expect(merged.test[1]).toBe('Test'); expect(merged.foo.value1).toBe(1); }); });
import { toast } from "react-hot-toast"; import { apiConnector } from "../apiconnector"; import { categories } from "../apis"; import { courseEndPoints } from "../apis"; const { CATEGORIES_API, CATEGORIES_PAGEDETAILS_API } = categories; const { CREATE_COURSE, UPDATE_COURSE_API, DELETE_COURSE_API, GET_COURSEDETAILS_API, CREATE_SECTION_API, DELETE_SECTION_API, UPDATE_SECTION_API, CREATE_SUBSECTION_API, DELETE_SUBSECTION_API, UPDATE_SUBSECTION_API, GET_ALL_INSTRUCTOR_COURSES_API, } = courseEndPoints; export const fetchCourseCategories = async () => { const toastId = toast.loading("loading..."); var result = []; try { const response = await apiConnector("GET", CATEGORIES_API, null, {}); if (!response.data.success) { throw new Error(response.data.message); } result = response.data.allCategory; } catch (error) { console.log("GET_USER_ENROLLED_COURSES_API API ERROR............", error); toast.error("Could Not Get Enrolled Courses"); } toast.dismiss(toastId); return result; }; export const fetchCategoryDetails = async (data) => { const toastId = toast.loading("loading..."); var result = []; try { const response = await apiConnector( "GET", CATEGORIES_PAGEDETAILS_API, null, {}, { categoryId: data, } ); // console.log(response); if (!response.data.success) { throw new Error(response.data.message); } result = response.data; } catch (error) { console.log("GET_USER_ENROLLED_COURSES_API API ERROR............", error); toast.error("Could Not Get Enrolled Courses"); } toast.dismiss(toastId); return result; }; export const createCourse = async (formData, token) => { const toastId = toast.loading("loading..."); let result = null; try { const response = await apiConnector("POST", CREATE_COURSE, formData, { Authorization: `Bearer ${token}`, }); console.log(response); if (!response.data.success) { throw new Error(response.data.message); } result = response?.data?.data; } catch (error) { console.log("CREATE_COURSE API ERROR............", error); toast.error("Could not create Courses"); } toast.dismiss(toastId); return result; }; export const updateCourse = async (formData, token) => { const toastId = toast.loading("loading..."); let result = null; try { const response = await apiConnector("PUT", UPDATE_COURSE_API, formData, { Authorization: `Bearer ${token}`, }); console.log(response); if (!response.data.success) { throw new Error(response.data.message); } result = response?.data?.data; } catch (error) { console.log("CREATE_COURSE API ERROR............", error); toast.error("Could not create Courses"); } toast.dismiss(toastId); return result; }; export const getFullDetailsOfCourse = async (data, token) => { console.log(data); const toastId = toast.loading("loading..."); let result = null; try { const response = await apiConnector( "GET", GET_COURSEDETAILS_API, null, { Authorization: `Bearer ${token}`, }, { courseId: data, } ); console.log(response); if (!response.data.success) { throw new Error(response.data.message); } result = response?.data?.courseDetails; } catch (error) { console.log("GET_COURSE API ERROR............", error); toast.error("Could not GET Courses Details"); } toast.dismiss(toastId); return result; }; export const deleteCourse = async (courseId, token) => { const toastId = toast.loading("loading..."); try { const response = await apiConnector("DELETE", DELETE_COURSE_API, courseId, { Authorization: `Bearer ${token}`, }); console.log(response); if (!response.data.success) { throw new Error(response.data.message); } } catch (error) { console.log("DELETE COURSE API ERROR............", error); toast.error("Could not DELETE Courses"); } toast.dismiss(toastId); }; export const createSection = async (data, token) => { const toastId = toast.loading("loading..."); let result = null; try { const response = await apiConnector("POST", CREATE_SECTION_API, data, { Authorization: `Bearer ${token}`, }); console.log(response); if (!response.data.success) { throw new Error(response.data.message); } result = response?.data?.updatedCourseDetails; } catch (error) { console.log("CREATE_COURSE_SECTION API ERROR............", error); toast.error("Could not create Course section"); } toast.dismiss(toastId); return result; }; export const deleteSection = async (data, token) => { const toastId = toast.loading("loading..."); let result = null; try { const response = await apiConnector("DELETE", DELETE_SECTION_API, data, { Authorization: `Bearer ${token}`, }); console.log(response); result = response?.data?.updatedCourseDetails; if (!response.data.success) { throw new Error(response.data.message); } } catch (error) { console.log("Delete Section API ERROR............", error); toast.error("Could not Delete Course Section"); } toast.dismiss(toastId); return result; }; export const updateSection = async (data, token) => { const toastId = toast.loading("loading..."); let result = null; try { const response = await apiConnector("PUT", UPDATE_SECTION_API, data, { Authorization: `Bearer ${token}`, }); console.log(response); result = response?.data?.updatedCourse; if (!response.data.success) { throw new Error(response.data.message); } } catch (error) { console.log("updating Section API ERROR............", error); toast.error("Could not update Course Section"); } toast.dismiss(toastId); return result; }; export const createSubSection = async (data, token) => { let result = null; const toastId = toast.loading("Loading..."); try { const response = await apiConnector("POST", CREATE_SUBSECTION_API, data, { Authorization: `Bearer ${token}`, }); console.log("CREATE SUB-SECTION API RESPONSE............", response); if (!response?.data?.success) { throw new Error("Could Not Add Lecture"); } toast.success("Lecture Added"); result = response?.data?.sectionUpdate; } catch (error) { console.log("CREATE SUB-SECTION API ERROR............", error); toast.error(error.message); } toast.dismiss(toastId); return result; }; export const updateSubSection = async (data, token) => { let result = null; const toastId = toast.loading("Loading..."); try { const response = await apiConnector("PUT", UPDATE_SUBSECTION_API, data, { Authorization: `Bearer ${token}`, }); console.log("update SUB-SECTION API RESPONSE............", response); if (!response?.data?.success) { throw new Error("Could Not update Lecture"); } toast.success("Lecture Updated"); result = response?.data?.updatedSection; } catch (error) { console.log("update SUB-SECTION API ERROR............", error); toast.error(error.message); } toast.dismiss(toastId); return result; }; export const deleteSubSection = async (data, token) => { let result = null; const toastId = toast.loading("Loading..."); try { const response = await apiConnector("DELETE", DELETE_SUBSECTION_API, data, { Authorization: `Bearer ${token}`, }); console.log("delete SUB-SECTION API RESPONSE............", response); if (!response?.data?.success) { throw new Error("Could Not delete Lecture"); } toast.success("Lecture Deleted"); result = response?.data?.updatedSection; } catch (error) { console.log("delete SUB-SECTION API ERROR............", error); toast.error(error.message); } toast.dismiss(toastId); return result; }; export const fetchInstructorCourses = async (token) => { let result = []; const toastId = toast.loading("Loading..."); try { const response = await apiConnector( "GET", GET_ALL_INSTRUCTOR_COURSES_API, null, { Authorization: `Bearer ${token}`, } ); console.log("INSTRUCTOR COURSES API RESPONSE............", response); if (!response?.data?.success) { throw new Error("Could Not Fetch Instructor Courses"); } result = response?.data?.data; } catch (error) { console.log("INSTRUCTOR COURSES API ERROR............", error); toast.error(error.message); } toast.dismiss(toastId); return result; };
/* Copyright 2021. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vaultresourcecontroller import ( "context" vaultutils "github.com/redhat-cop/vault-config-operator/api/v1alpha1/utils" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) type VaultResource struct { vaultEndpoint *vaultutils.VaultEndpoint reconcilerBase *ReconcilerBase } func NewVaultResource(reconcilerBase *ReconcilerBase, obj client.Object) *VaultResource { return &VaultResource{ reconcilerBase: reconcilerBase, vaultEndpoint: vaultutils.NewVaultEndpoint(obj), } } func (r *VaultResource) Reconcile(ctx context.Context, instance client.Object) (ctrl.Result, error) { log := log.FromContext(ctx) log.Info("starting reconcile cycle") log.V(1).Info("reconcile", "instance", instance) if !instance.GetDeletionTimestamp().IsZero() { if !controllerutil.ContainsFinalizer(instance, vaultutils.GetFinalizer(instance)) { return reconcile.Result{}, nil } err := r.manageCleanUpLogic(ctx, instance) if err != nil { log.Error(err, "unable to delete instance", "instance", instance) return ManageOutcome(ctx, *r.reconcilerBase, instance, err) } controllerutil.RemoveFinalizer(instance, vaultutils.GetFinalizer(instance)) err = r.reconcilerBase.GetClient().Update(ctx, instance) if err != nil { log.Error(err, "unable to update instance", "instance", instance) return ManageOutcome(ctx, *r.reconcilerBase, instance, err) } return reconcile.Result{}, nil } err := r.manageReconcileLogic(ctx, instance) if err != nil { log.Error(err, "unable to complete reconcile logic", "instance", instance) return ManageOutcome(ctx, *r.reconcilerBase, instance, err) } return ManageOutcome(ctx, *r.reconcilerBase, instance, err) } func (r *VaultResource) manageCleanUpLogic(context context.Context, instance client.Object) error { log := log.FromContext(context) if conditionAware, ok := instance.(vaultutils.ConditionsAware); ok { for _, condition := range conditionAware.GetConditions() { if condition.Status == metav1.ConditionTrue && condition.Type == ReconcileSuccessful { err := r.vaultEndpoint.DeleteIfExists(context) if err != nil { log.Error(err, "unable to delete vault resource", "instance", instance) return err } } } } return nil } func (r *VaultResource) manageReconcileLogic(context context.Context, instance client.Object) error { log := log.FromContext(context) // prepare internal values err := instance.(vaultutils.VaultObject).PrepareInternalValues(context, instance) if err != nil { log.Error(err, "unable to prepare internal values", "instance", instance) return err } err = instance.(vaultutils.VaultObject).PrepareTLSConfig(context, instance) if err != nil { log.Error(err, "unable to prepare TLS Config values", "instance", instance) return err } err = r.vaultEndpoint.CreateOrUpdate(context) if err != nil { log.Error(err, "unable to create/update vault resource", "instance", instance) return err } return nil }
import streamlit as st from audio_recorder_streamlit import audio_recorder import tempfile import requests import api_functional_call st.title('🤖 Voice Assistant 🎙️') audio_bytes = audio_recorder( text="Tap to start recording", recording_color="#ff5733", neutral_color="#3498db", icon_name="microphone-alt", icon_size="2x", ) if audio_bytes: print(type(audio_bytes)) st.audio(audio_bytes, format="audio/wav") # Save audio to a temporary file with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio: temp_audio.write(audio_bytes) temp_audio_path = temp_audio.name if st.button('🎙️Get Rsponse🎙️'): #Converting speech to text converted_text_openai = api_functional_call.speech_to_text_conversion(temp_audio_path) print("Transcribed text",converted_text_openai) st.write("Transcription:",converted_text_openai) textmodel_response = api_functional_call.text_chat(converted_text_openai) # Generating actor's response print("Response:",textmodel_response) audio_data = api_functional_call.text_to_speech_conversion(textmodel_response) #Convert final text response to audio format and get the audio file path print("Converted Text:", converted_text_openai) st.write("Converted Text:", converted_text_openai) text_model_response = api_functional_call.text_chat(converted_text_openai) # Generating virtual assistant's response print("Virtual assistant's Response:", text_model_response) audio_data = api_functional_call.text_to_speech_conversion(text_model_response) # Convert virtual assistant's response to audio format with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmpfile: # Creating temporary file tmpfile.write(audio_data) # Writing file contents to temporary file tmpfile_path = tmpfile.name st.write("Response:",textmodel_response) st.audio(tmpfile_path)
package session.demo1; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * http://localhost:8080/ServletDemo_war_exploded/sessionTest1 * http://localhost:8080/ServletDemo_war_exploded/sessionTest2 */ @WebServlet({"/sessionTest1", "/sessionTest2"}) public class SessionTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out=resp.getWriter(); String servletPath = req.getServletPath(); if("/sessionTest1".equals(servletPath)){ //获取当前请求jsessionid所关联的session对象, 如果服务器中的这个session不存在,那么服务器就会创建一个新的session对象和对应的jsessionid,jsessionid会通过set-cookie返还给客户端 //不断刷新: 因为所有请求中的cookie中的jsessionid相同,所以会对应同一个session对象 //HttpSession session = req.getSession(); 等价HttpSession session = req.getSession(true); HttpSession session1 = req.getSession(); out.println("session1="+session1); }else if ("/sessionTest2".equals(servletPath)){ HttpSession session2 = req.getSession(); out.println("session2="+session2);//和上面是同一个session, 因为请求中的cookie中jsessionid相同 //前请求所在的session设置为无效 //客户端会删除浏览器中cookie对应的jsessionid,其中包括通常用于跟踪会话的JSESSIONID cookie //服务端HttpSession 对象被标记为无效,并且不能再使用该对象来访问会话中的属性或调用会话相关的 API。任何尝试这样做的操作都会抛出 IllegalStateException 异常。 session2.invalidate(); //当前请求cookie已经不存在jsessionid,所以服务端会生成新的session对象和jsessionid,jsessionid会通过set-cookie返还给客户端 HttpSession session3 = req.getSession(); out.println("session3="+session3); //req.getSession(false): 获取当前请求关联的会话对象,如果会话已经存在,则返回会话对象,会话存在就是说服务端存在请求jsessionid所关联的对象,服务端认识这次请求 // 如果会话不存在,则返回 null。会话不存在就是说服务端不存在请求jsessionid所关联的对象,服务端不认识这次请求 //false 参数,告诉服务器不要创建新的会话对象 session3.invalidate(); HttpSession session4 = req.getSession(false); out.println("session4="+session4); } else { out.println("url is wrong"); } } }
/********************************************************************\ * gncInvoice.h -- the Core Business Invoice Interface * * * * 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 program; if not, contact: * * * * Free Software Foundation Voice: +1-617-542-5942 * * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 * * Boston, MA 02110-1301, USA gnu@gnu.org * * * \********************************************************************/ /** @addtogroup Business @{ */ /** @addtogroup Invoice An invoice holds a list of entries, a pointer to the customer, and the job, the dates entered and posted, as well as the account, transaction and lot for the posted invoice. @{ */ /** @file gncInvoice.h @brief Business Invoice Interface @author Copyright (C) 2001,2006 Derek Atkins <warlord@MIT.EDU> @author Copyright (c) 2005 Neil Williams <linux@codehelp.co.uk> */ #ifndef GNC_INVOICE_H_ #define GNC_INVOICE_H_ struct _gncInvoice; typedef struct _gncInvoice GncInvoice; typedef struct _gncInvoiceClass GncInvoiceClass; typedef GList GncInvoiceList; #include <glib.h> #include "gncBillTerm.h" #include "gncEntry.h" #include "gncOwner.h" #include "gnc-lot.h" #include "qofbook.h" #include "qofbook.h" #include "gnc-pricedb.h" #define GNC_ID_INVOICE "gncInvoice" typedef enum { GNC_INVOICE_UNDEFINED , GNC_INVOICE_CUST_INVOICE , /* Invoice */ GNC_INVOICE_VEND_INVOICE , /* Bill */ GNC_INVOICE_EMPL_INVOICE , /* Voucher */ GNC_INVOICE_CUST_CREDIT_NOTE , /* Credit Note for a customer */ GNC_INVOICE_VEND_CREDIT_NOTE , /* Credit Note from a vendor */ GNC_INVOICE_EMPL_CREDIT_NOTE , /* Credit Note from an employee, not sure this makes sense, but all code is symmetrical so I've added it to prevent unexpected errors */ GNC_INVOICE_NUM_TYPES } GncInvoiceType; /* --- type macros --- */ #define GNC_TYPE_INVOICE (gnc_invoice_get_type ()) #define GNC_INVOICE(o) \ (G_TYPE_CHECK_INSTANCE_CAST ((o), GNC_TYPE_INVOICE, GncInvoice)) #define GNC_INVOICE_CLASS(k) \ (G_TYPE_CHECK_CLASS_CAST((k), GNC_TYPE_INVOICE, GncInvoiceClass)) #define GNC_IS_INVOICE(o) \ (G_TYPE_CHECK_INSTANCE_TYPE ((o), GNC_TYPE_INVOICE)) #define GNC_IS_INVOICE_CLASS(k) \ (G_TYPE_CHECK_CLASS_TYPE ((k), GNC_TYPE_INVOICE)) #define GNC_INVOICE_GET_CLASS(o) \ (G_TYPE_INSTANCE_GET_CLASS ((o), GNC_TYPE_INVOICE, GncInvoiceClass)) GType gnc_invoice_get_type(void); /** @name Create/Destroy Functions @{ */ GncInvoice *gncInvoiceCreate (QofBook *book); void gncInvoiceDestroy (GncInvoice *invoice); /** Create a new GncInvoice object as a deep copy of the given other * invoice. * * The returned new invoice has everything copied from the other * invoice, including the ID string field. All GncEntries are newly * allocated copies of the original invoice's entries. */ GncInvoice *gncInvoiceCopy (const GncInvoice *other_invoice); /** @} */ /** @name Set Functions @{ */ void gncInvoiceSetID (GncInvoice *invoice, const char *id); void gncInvoiceSetOwner (GncInvoice *invoice, GncOwner *owner); /** Set the DateOpened using a GDate argument. (Note: Internally this stores the date in a Timespec as created through timespecCanonicalDayTime()). */ void gncInvoiceSetDateOpenedGDate (GncInvoice *invoice, const GDate *date); void gncInvoiceSetDateOpened (GncInvoice *invoice, Timespec date); void gncInvoiceSetDatePosted (GncInvoice *invoice, Timespec date); void gncInvoiceSetTerms (GncInvoice *invoice, GncBillTerm *terms); void gncInvoiceSetBillingID (GncInvoice *invoice, const char *billing_id); void gncInvoiceSetNotes (GncInvoice *invoice, const char *notes); void gncInvoiceSetCurrency (GncInvoice *invoice, gnc_commodity *currency); void gncInvoiceSetActive (GncInvoice *invoice, gboolean active); void gncInvoiceSetIsCreditNote (GncInvoice *invoice, gboolean credit_note); void gncInvoiceSetBillTo (GncInvoice *invoice, GncOwner *billto); void gncInvoiceSetToChargeAmount (GncInvoice *invoice, gnc_numeric amount); /** @} */ void gncInvoiceAddEntry (GncInvoice *invoice, GncEntry *entry); void gncInvoiceRemoveEntry (GncInvoice *invoice, GncEntry *entry); void gncInvoiceAddPrice (GncInvoice *invoice, GNCPrice *price); /** Call this function when adding an entry to a bill instead of an invoice */ void gncBillAddEntry (GncInvoice *bill, GncEntry *entry); void gncBillRemoveEntry (GncInvoice *bill, GncEntry *entry); /** Call this function when an Entry is changed and you want to re-sort the list of entries */ void gncInvoiceSortEntries (GncInvoice *invoice); /** Remove all entries from an invoice. To be called before * destroying an invoice. */ void gncInvoiceRemoveEntries (GncInvoice *invoice); /** @name Get Functions @{ */ const char * gncInvoiceGetID (const GncInvoice *invoice); const GncOwner * gncInvoiceGetOwner (const GncInvoice *invoice); Timespec gncInvoiceGetDateOpened (const GncInvoice *invoice); Timespec gncInvoiceGetDatePosted (const GncInvoice *invoice); Timespec gncInvoiceGetDateDue (const GncInvoice *invoice); GncBillTerm * gncInvoiceGetTerms (const GncInvoice *invoice); const char * gncInvoiceGetBillingID (const GncInvoice *invoice); const char * gncInvoiceGetNotes (const GncInvoice *invoice); GncOwnerType gncInvoiceGetOwnerType (const GncInvoice *invoice); GList * gncInvoiceGetTypeListForOwnerType (const GncOwnerType type); GncInvoiceType gncInvoiceGetType (const GncInvoice *invoice); const char * gncInvoiceGetTypeString (const GncInvoice *invoice); gnc_commodity * gncInvoiceGetCurrency (const GncInvoice *invoice); GncOwner * gncInvoiceGetBillTo (GncInvoice *invoice); gnc_numeric gncInvoiceGetToChargeAmount (const GncInvoice *invoice); gboolean gncInvoiceGetActive (const GncInvoice *invoice); gboolean gncInvoiceGetIsCreditNote (const GncInvoice *invoice); GNCLot * gncInvoiceGetPostedLot (const GncInvoice *invoice); Transaction * gncInvoiceGetPostedTxn (const GncInvoice *invoice); Account * gncInvoiceGetPostedAcc (const GncInvoice *invoice); /** @} */ /** Return the "total" amount of the invoice as seen on the document * (and shown to the user in the reports and invoice ledger). */ gnc_numeric gncInvoiceGetTotal (GncInvoice *invoice); gnc_numeric gncInvoiceGetTotalOf (GncInvoice *invoice, GncEntryPaymentType type); gnc_numeric gncInvoiceGetTotalSubtotal (GncInvoice *invoice); gnc_numeric gncInvoiceGetTotalTax (GncInvoice *invoice); typedef GList EntryList; EntryList * gncInvoiceGetEntries (GncInvoice *invoice); GNCPrice * gncInvoiceGetPrice(GncInvoice *invoice, gnc_commodity* commodity); /** Depending on the invoice type, invoices have a different effect * on the balance. Customer invoices increase the balance, while * vendor bills decrease the balance. Credit notes have the opposite * effect. * * Returns TRUE if the invoice will increase the balance or FALSE * otherwise. */ gboolean gncInvoiceAmountPositive (const GncInvoice *invoice); /** Return an overview of amounts on this invoice that will be posted to * accounts in currencies that are different from the invoice currency. * These accounts can be the accounts referred to in invoice entries * or tax tables. This information is returned in the from of a hash * table. The keys in the hash table are the foreign currencies, the * values are the accumulated amounts in that currency. * Drop the reference to the hash table with g_hash_table_unref when * no longer needed. */ GHashTable *gncInvoiceGetForeignCurrencies (const GncInvoice *invoice); /** Post this invoice to an account. Returns the new Transaction * that is tied to this invoice. The transaction is set with * the supplied posted date, due date, and memo. The Transaction * description is set to the name of the company. * * If accumulate splits is TRUE, entries in the same account * will be merged into one single split in that account. * Otherwise each entry will be posted as a separate split, * possibly resulting in multiple splits in one account. * * If autopay is TRUE, the code will try to find pre-payments, * invoices or credit notes that can reduce the amount due for this * invoice, marking the invoice as fully or partially paid, depending * on the amounts on all documents involved. If autopay is FALSE, * it's the user's responsibility to explicitly pay the invoice. * */ Transaction * gncInvoicePostToAccount (GncInvoice *invoice, Account *acc, Timespec *posted_date, Timespec *due_date, const char *memo, gboolean accumulatesplits, gboolean autopay); /** * Unpost this invoice. This will destroy the posted transaction and * return the invoice to its unposted state. It may leave empty lots * out there. If reset_tax_tables is TRUE, then it will also revert * all the Tax Tables to the parent, which will potentially change the * total value of the invoice. It may also leave some orphaned Tax * Table children. * * Returns TRUE if successful, FALSE if there is a problem. */ gboolean gncInvoiceUnpost (GncInvoice *invoice, gboolean reset_tax_tables); /** * Attempt to pay the invoice using open payment lots and * lots for documents of the opposite sign (credit notes versus * invoices). */ void gncInvoiceAutoApplyPayments (GncInvoice *invoice); /** * A convenience function to apply a payment to an invoice. * It creates a lot for a payment optionally based on an existing * transaction and then tries to balance it with * the given invoice. * Contrary to gncOwnerApplyPayment, no other open documents * or payments for the owner will be considered * to balance the payment. * * This code is actually a convenience wrapper around gncOwnerCreatePaymentLot * and gncOwnerAutoApplyPaymentsWithLots. See their descriptions for more * details on what happens exactly. */ void gncInvoiceApplyPayment (const GncInvoice *invoice, Transaction *txn, Account *xfer_acc, gnc_numeric amount, gnc_numeric exch, Timespec date, const char *memo, const char *num); /** Given a transaction, find and return the Invoice */ GncInvoice * gncInvoiceGetInvoiceFromTxn (const Transaction *txn); /** Given a LOT, find and return the Invoice attached to the lot */ GncInvoice * gncInvoiceGetInvoiceFromLot (GNCLot *lot); /** Return a pointer to the instance gncInvoice that is identified * by the guid, and is residing in the book. Returns NULL if the * instance can't be found. * Equivalent function prototype is * GncInvoice * gncInvoiceLookup (QofBook *book, const GncGUID *guid); */ static inline GncInvoice * gncInvoiceLookup (const QofBook *book, const GncGUID *guid) { QOF_BOOK_RETURN_ENTITY(book, guid, GNC_ID_INVOICE, GncInvoice); } void gncInvoiceBeginEdit (GncInvoice *invoice); void gncInvoiceCommitEdit (GncInvoice *invoice); int gncInvoiceCompare (const GncInvoice *a, const GncInvoice *b); gboolean gncInvoiceIsPosted (const GncInvoice *invoice); gboolean gncInvoiceIsPaid (const GncInvoice *invoice); #define INVOICE_ID "id" #define INVOICE_OWNER "owner" #define INVOICE_OPENED "date_opened" #define INVOICE_POSTED "date_posted" #define INVOICE_DUE "date_due" #define INVOICE_IS_POSTED "is_posted?" #define INVOICE_IS_PAID "is_paid?" #define INVOICE_TERMS "terms" #define INVOICE_BILLINGID "billing_id" #define INVOICE_NOTES "notes" #define INVOICE_ACC "account" #define INVOICE_POST_TXN "posted_txn" #define INVOICE_POST_LOT "posted_lot" #define INVOICE_IS_CN "credit_note" #define INVOICE_TYPE "type" #define INVOICE_TYPE_STRING "type_string" #define INVOICE_BILLTO "bill-to" #define INVOICE_ENTRIES "list_of_entries" #define INVOICE_JOB "invoice_job" #define INVOICE_FROM_LOT "invoice-from-lot" #define INVOICE_FROM_TXN "invoice-from-txn" QofBook *gncInvoiceGetBook(GncInvoice *x); /** deprecated functions */ #define gncInvoiceGetGUID(x) qof_instance_get_guid(QOF_INSTANCE(x)) #define gncInvoiceRetGUID(x) (x ? *(qof_instance_get_guid(QOF_INSTANCE(x))) : *(guid_null())) #define gncInvoiceLookupDirect(G,B) gncInvoiceLookup((B),&(G)) /** Test support function used by test-dbi-business-stuff.c */ gboolean gncInvoiceEqual(const GncInvoice *a, const GncInvoice *b); #endif /* GNC_INVOICE_H_ */ /** @} */ /** @} */
import { Web3Provider } from "@ethersproject/providers"; import { useWeb3React } from "@web3-react/core"; import { getErrorMessage } from "../lib/utils"; import { ethers } from "ethers"; import { useCallback, useEffect, useMemo, useState } from "react"; import { toast } from "react-toastify"; import { useEtherContext } from "../components/EtherContext"; import { IAreaInfo } from "../lib/types"; import useConnectWallet from "./useConnectWallet"; import { ContractTypes } from "../dapp/bsc.config"; type LandData = { info: Partial<IAreaInfo>; isFetchingInfo: boolean; boughtTokenId: number; boughtTokenURI: string; isBuying: boolean; }; const useLandContract = (area?: string) => { const { getContract } = useEtherContext(); const { account } = useWeb3React<Web3Provider>(); const { connectWallet } = useConnectWallet(); const [data, setData] = useState<LandData>({ info: {}, isFetchingInfo: false, boughtTokenId: 0, boughtTokenURI: "", isBuying: false, }); const getOpenAreaInfo = useCallback(async () => { if (!area) { return; } setData((prevData) => ({ ...prevData, isFetchingInfo: true, info: {} })); try { const contract = getContract(ContractTypes.LAND); const info = await contract.getInfoOpenArea(area); const [tokens, price, limit, startTime, endTime] = info; setData((prevData) => ({ ...prevData, info: { price: ethers.utils.formatEther(price), limit: limit.toNumber(), startTime: startTime.toNumber(), endTime: endTime.toNumber(), currentQuantity: tokens.length, }, isFetchingInfo: false, })); } catch (error: any) { setData((prevData) => ({ ...prevData, isFetchingInfo: false })); console.log(`Failed to get info for area ${area}`, error); } finally { } }, [area, getContract]); const buyLand = useCallback(async () => { if (!area || !data.info.price) { console.log("No area to buy"); return; } setData((prevData) => ({ ...prevData, isBuying: true })); try { if (!account) { await connectWallet(); } const contract = getContract(ContractTypes.LAND, true); console.log(data.info.price, ethers.utils.parseEther(data.info.price)); const contractTx: ethers.ContractTransaction = await contract.buyLand( area, { value: ethers.utils.parseEther(data.info.price), } ); const receipt: ethers.ContractReceipt = await contractTx.wait(); const buyLandEvent = receipt?.events?.find( (event: ethers.Event) => event.event === "BuyLand" ); const [, tokenId] = buyLandEvent?.args || []; const tokenURI = await contract.tokenURI(tokenId); setData((prevData) => ({ ...prevData, boughtTokenId: tokenId.toNumber(), boughtTokenURI: tokenURI, isBuying: false, })); } catch (error: any) { setData((prevData) => ({ ...prevData, isBuying: false })); console.log(`Error buying land:`, error); toast.error(getErrorMessage(error)); } }, [account, area, connectWallet, data.info.price, getContract]); useEffect(() => { getOpenAreaInfo(); }, [getOpenAreaInfo]); return useMemo( () => ({ ...data, buyLand, getOpenAreaInfo, }), [buyLand, data, getOpenAreaInfo] ); }; export default useLandContract;
"use client"; import { cn } from "@/lib/utils"; import { ChevronDown, ChevronRightIcon, LucideIcon } from "lucide-react"; import React, { useState } from "react"; interface ItemProps { documentIcon?: string; active?: boolean; label: string; onClick?: () => void; icon: LucideIcon; children?: React.ReactNode; } const Item = ({ label, onClick, icon: Icon, active, documentIcon, children, }: ItemProps) => { const [isDropdownOpen, setIsDropdownOpen] = useState(false); return ( <> <div role="button" className={cn( "group min-h-[27px] text-sm pl-3 py-1 pr-3 w-full hover:bg-primary/5 flex items-center justify-between text-muted-foreground font-medium", active && "bg-primary/5 text-primary" )} onClick={() => { onClick?.(); if (children) { setIsDropdownOpen(!isDropdownOpen); // Toggle dropdown } }} > <div className="flex"> {documentIcon ? ( <div className="shrink-0 mr-2 text-[18px]">{documentIcon}</div> ) : ( <Icon className="shrink-0 h-[18px] mr-2 text-muted-foreground" /> )} <span className="truncate">{label}</span> </div> <div role="button" className="h-full rounded-sm hover:bg-neutral-300 dark:bg-neutral-600 mr-1" > {children ? ( <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground/50" /> ) : ( <ChevronRightIcon className="h-4 w-4 shrink-0 text-muted-foreground/50" /> )} </div> </div> {isDropdownOpen && children && <div className="pl-6">{children}</div>} </> ); }; export default Item;
package com.batuhan.interv.presentation.interview.enter import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun InterviewButton( @StringRes title: Int, @DrawableRes icon: Int, sendEvent: () -> Unit, ) { Column( Modifier .fillMaxSize() .padding(8.dp).clickable(role = Role.Button) { sendEvent.invoke() }, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Icon(painterResource(id = icon), contentDescription = null) Text(stringResource(id = title), textAlign = TextAlign.Center) } }
package com.example.unsplashattestationproject.data.dto.collections import com.example.unsplashattestationproject.data.dto.photos.UnsplashUrls import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class CoverPhoto( val id:String, @Json(name="created_at")val createdAt:String, @Json(name="updated_at")val updatedAt:String?, @Json(name="width")val width:Int, @Json(name="height")val height:Int, @Json(name="color")val color:String?, @Json(name="blur_hash")val blurHash:String?, @Json(name="description")val description:String?, @Json(name="alt_description")val altDescription:String?, @Json(name="urls")val urls : UnsplashUrls )
The extract pass ---------------- - Like the :cmd:ref:`techmap` pass, the :cmd:ref:`extract` pass is called with a map file. It compares the circuits inside the modules of the map file with the design and looks for sub-circuits in the design that match any of the modules in the map file. - If a match is found, the :cmd:ref:`extract` pass will replace the matching subcircuit with an instance of the module from the map file. - In a way the :cmd:ref:`extract` pass is the inverse of the techmap pass. .. todo:: add/expand supporting text, also mention custom pattern matching and pmgen Example code can be found in |code_examples/macc|_. .. |code_examples/macc| replace:: :file:`docs/source/code_examples/macc` .. _code_examples/macc: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/macc .. literalinclude:: /code_examples/macc/macc_simple_test.ys :language: yoscrypt :lines: 1-2 .. figure:: /_images/code_examples/macc/macc_simple_test_00a.* :class: width-helper invert-helper before :cmd:ref:`extract` .. literalinclude:: /code_examples/macc/macc_simple_test.ys :language: yoscrypt :lines: 6 .. figure:: /_images/code_examples/macc/macc_simple_test_00b.* :class: width-helper invert-helper after :cmd:ref:`extract` .. literalinclude:: /code_examples/macc/macc_simple_test.v :language: verilog :caption: :file:`macc_simple_test.v` .. literalinclude:: /code_examples/macc/macc_simple_xmap.v :language: verilog :caption: :file:`macc_simple_xmap.v` .. literalinclude:: /code_examples/macc/macc_simple_test_01.v :language: verilog :caption: :file:`macc_simple_test_01.v` .. figure:: /_images/code_examples/macc/macc_simple_test_01a.* :class: width-helper invert-helper .. figure:: /_images/code_examples/macc/macc_simple_test_01b.* :class: width-helper invert-helper .. literalinclude:: /code_examples/macc/macc_simple_test_02.v :language: verilog :caption: :file:`macc_simple_test_02.v` .. figure:: /_images/code_examples/macc/macc_simple_test_02a.* :class: width-helper invert-helper .. figure:: /_images/code_examples/macc/macc_simple_test_02b.* :class: width-helper invert-helper The wrap-extract-unwrap method ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Often a coarse-grain element has a constant bit-width, but can be used to implement operations with a smaller bit-width. For example, a 18x25-bit multiplier can also be used to implement 16x20-bit multiplication. A way of mapping such elements in coarse grain synthesis is the wrap-extract-unwrap method: wrap Identify candidate-cells in the circuit and wrap them in a cell with a constant wider bit-width using :cmd:ref:`techmap`. The wrappers use the same parameters as the original cell, so the information about the original width of the ports is preserved. Then use the :cmd:ref:`connwrappers` command to connect up the bit-extended in- and outputs of the wrapper cells. extract Now all operations are encoded using the same bit-width as the coarse grain element. The :cmd:ref:`extract` command can be used to replace circuits with cells of the target architecture. unwrap The remaining wrapper cell can be unwrapped using :cmd:ref:`techmap`. Example: DSP48_MACC ~~~~~~~~~~~~~~~~~~~ This section details an example that shows how to map MACC operations of arbitrary size to MACC cells with a 18x25-bit multiplier and a 48-bit adder (such as the Xilinx DSP48 cells). Preconditioning: :file:`macc_xilinx_swap_map.v` Make sure ``A`` is the smaller port on all multipliers .. todo:: add/expand supporting text .. literalinclude:: /code_examples/macc/macc_xilinx_swap_map.v :language: verilog :caption: :file:`macc_xilinx_swap_map.v` Wrapping multipliers: :file:`macc_xilinx_wrap_map.v` .. literalinclude:: /code_examples/macc/macc_xilinx_wrap_map.v :language: verilog :lines: 1-46 :caption: :file:`macc_xilinx_wrap_map.v` Wrapping adders: :file:`macc_xilinx_wrap_map.v` .. literalinclude:: /code_examples/macc/macc_xilinx_wrap_map.v :language: verilog :lines: 48-89 :caption: :file:`macc_xilinx_wrap_map.v` Extract: :file:`macc_xilinx_xmap.v` .. literalinclude:: /code_examples/macc/macc_xilinx_xmap.v :language: verilog :caption: :file:`macc_xilinx_xmap.v` ... simply use the same wrapping commands on this module as on the design to create a template for the :cmd:ref:`extract` command. Unwrapping multipliers: :file:`macc_xilinx_unwrap_map.v` .. literalinclude:: /code_examples/macc/macc_xilinx_unwrap_map.v :language: verilog :lines: 1-30 :caption: ``$__mul_wrapper`` module in :file:`macc_xilinx_unwrap_map.v` Unwrapping adders: :file:`macc_xilinx_unwrap_map.v` .. literalinclude:: /code_examples/macc/macc_xilinx_unwrap_map.v :language: verilog :lines: 32-61 :caption: ``$__add_wrapper`` module in :file:`macc_xilinx_unwrap_map.v` .. literalinclude:: /code_examples/macc/macc_xilinx_test.v :language: verilog :lines: 1-6 :caption: ``test1`` of :file:`macc_xilinx_test.v` .. figure:: /_images/code_examples/macc/macc_xilinx_test1a.* :class: width-helper invert-helper .. figure:: /_images/code_examples/macc/macc_xilinx_test1b.* :class: width-helper invert-helper .. literalinclude:: /code_examples/macc/macc_xilinx_test.v :language: verilog :lines: 8-13 :caption: ``test2`` of :file:`macc_xilinx_test.v` .. figure:: /_images/code_examples/macc/macc_xilinx_test2a.* :class: width-helper invert-helper .. figure:: /_images/code_examples/macc/macc_xilinx_test2b.* :class: width-helper invert-helper Wrapping in ``test1``: .. figure:: /_images/code_examples/macc/macc_xilinx_test1b.* :class: width-helper invert-helper .. literalinclude:: /code_examples/macc/macc_xilinx_test.ys :language: yoscrypt :start-after: part c :end-before: end part c .. figure:: /_images/code_examples/macc/macc_xilinx_test1c.* :class: width-helper invert-helper Wrapping in ``test2``: .. figure:: /_images/code_examples/macc/macc_xilinx_test2b.* :class: width-helper invert-helper .. literalinclude:: /code_examples/macc/macc_xilinx_test.ys :language: yoscrypt :start-after: part c :end-before: end part c .. figure:: /_images/code_examples/macc/macc_xilinx_test2c.* :class: width-helper invert-helper Extract in ``test1``: .. figure:: /_images/code_examples/macc/macc_xilinx_test1c.* :class: width-helper invert-helper .. literalinclude:: /code_examples/macc/macc_xilinx_test.ys :language: yoscrypt :start-after: part d :end-before: end part d .. figure:: /_images/code_examples/macc/macc_xilinx_test1d.* :class: width-helper invert-helper Extract in ``test2``: .. figure:: /_images/code_examples/macc/macc_xilinx_test2c.* :class: width-helper invert-helper .. literalinclude:: /code_examples/macc/macc_xilinx_test.ys :language: yoscrypt :start-after: part d :end-before: end part d .. figure:: /_images/code_examples/macc/macc_xilinx_test2d.* :class: width-helper invert-helper Unwrap in ``test2``: .. figure:: /_images/code_examples/macc/macc_xilinx_test2d.* :class: width-helper invert-helper .. literalinclude:: /code_examples/macc/macc_xilinx_test.ys :language: yoscrypt :start-after: part e :end-before: end part e .. figure:: /_images/code_examples/macc/macc_xilinx_test2e.* :class: width-helper invert-helper
<template> <div> <Input label="Titre de l'évènement" class="input-time" :disabled="!props.editMode" :vmodel="data.title" name-input="title" @input="handleChange" /> <InputDate label="Date" class="input-time" name="date" :disabled="!props.editMode" :placeholder="formatDate(data.start)" @handle-date-format="handleChange" /> <div v-if="!props.data.allDay" class="event-modal__inputs"> <TimePicker label="Heure de début" :disabled="!props.editMode" class="input-time" :placeholder="getTimeFromDate(data.start)" :name="'startTime'" @change="handleChange" /> <TimePicker label="Heure de fin" :disabled="!props.editMode" class="input-time" :placeholder="getTimeFromDate(data.end)" :name="'endTime'" @change="handleChange" /> </div> <Input v-if="editMode || data.place" label="Lieu" class="input-item" :disabled="!props.editMode" :vmodel="data.place" name-input="place" @input="handleChange" /> </div> </template> <script lang="ts" setup> import Input from "@/components/Common/Input/Input.vue"; import InputDate from "@/components/Common/InputDate/InputDate.vue"; import TimePicker from '@/components/Common/TimePicker/TimePicker.vue'; const emit = defineEmits(["handle-change"]); const props = defineProps({ data: { type: Object, default: {} }, editMode: { type: Boolean, default: true } }) function handleChange(value: any) { emit("handle-change", value); } function getTimeFromDate(dateString: string) { const date = new Date(dateString); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); return `${hours}:${minutes}`; } function formatDate(dateString?: string) { if (dateString) { const date = new Date(dateString); const year = date.getFullYear(); let month: any = date.getMonth() + 1; let day: any = date.getDate(); if (month < 10) { month = `0${month}`; } if (day < 10) { day = `0${day}`; } return `${year}-${month}-${day}`; } } </script> <style lang="scss" scoped> .event-modal { &__inputs { @apply flex flex-row gap-x-4; &:deep() { .paragraphe__normal { @apply font-semibold mb-2; } } } } .input-time { @apply mb-2; } </style>
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { SharedModule } from './shared/shared.module'; import { CoreModule } from './core/core.module'; import { FeatureModule } from './feature/feature.module'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { ErrorInterceptor } from './core/interceptors/ErrorInterceptors'; import {BrowserAnimationsModule} from "@angular/platform-browser/animations"; import { NgxSpinnerModule } from 'ngx-spinner'; import { LoadingInterceptor } from './core/interceptors/loading.interceptors'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule, HttpClientModule, SharedModule, CoreModule, FeatureModule, NgxSpinnerModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
//define global value and mixin $device_type_desktop : "Desktop"; $device_type_desktop_and_laptop : "DesktopAndLaptop"; $device_type_tablet_and_ipad : "TabletAndIpad"; $device_type_tablet_and_mobile : "TabletAndMobile"; $device_type_mobile_phone : "MobilePhone"; $device_type_smaller_laptop : "SmallerThenLaptop"; $device_type_smaller_tablet : "SmallerTablet"; $device_type_smaller_ipad : "SmallerIpad"; $device_type_smaller_mobile : "SmallerMobile"; @mixin mediaSizeForDevice($deviceType) { /* Device = Desktop Screen = 1281px to higher resolution desktops */ @if $deviceType==$device_type_desktop { @media screen and (min-width:1281px) { @content; } } /* Device = Laptops, Desktops Screen = 1280px to 1025px */ @else if $deviceType==$device_type_desktop_and_laptop { @media screen and (min-width:1025px) and (max-width:1280px) { @content; } } /* Device = Tablets, Ipads, Screen = 1024px to 768px */ @else if $deviceType==$device_type_tablet_and_ipad { @media screen and (min-width:768px) and (max-width:1024px) { @content; } } /* Device = Low Resolution Tablets, Mobiles Screen = 767px to 481px */ @else if $deviceType==$device_type_tablet_and_mobile { @media screen and (min-width:481px) and (max-width:767px) { @content; } } /* Device = Most of the Smartphones Mobiles Screen = 479px to 320px */ @else if $deviceType==$device_type_mobile_phone { @media screen and (min-width:320px) and (max-width:479px) { @content; } } /* Device = smaller than Laptops Screen = min width 1280px */ @else if $deviceType==$device_type_smaller_laptop { @media screen and (max-width:1280px) { @content; } } /* Device = smaller than Tablets Screen = min width 1024px */ @else if $deviceType==$device_type_smaller_tablet { @media screen and (max-width:1024px) { @content; } } /* Device = smaller than Ipads Screen = min width 768px */ @else if $deviceType==$device_type_smaller_ipad { @media screen and (max-width:768px) { @content; } } /* Device = smaller than Mobiles Screen = min width 481px */ @else if $deviceType==$device_type_smaller_mobile { @media screen and (max-width:481px) { @content; } } } @mixin mediaSize($size) { @media screen and (max-width:$size){ @content; } }
// Задание 2. Интерфейс io.Reader // Что нужно сделать: // -Напишите программу, которая читает и выводит в консоль строки из файла, созданного в предыдущей практике, без использования ioutil. Если файл отсутствует или пуст, выведите в консоль соответствующее сообщение. package main import ( "fmt" "io" "os" ) func main() { r := NewReader() r.Read("information.txt") } type Reader interface { Read(path string) error Display() error } func NewReader() Reader { return &reader{} } type reader struct { r io.Reader } func (r *reader) Read(path string) error { stat, err := os.Stat(path) if err != nil { return fmt.Errorf("Файл не найден") } if stat.IsDir() { return fmt.Errorf("Файл не найден: %w", err) } b, err := os.ReadFile(path) if err != nil { return fmt.Errorf("Не удалось прочесть файл: %w", err) } fmt.Printf("Размер файла: %d изменен: %v\n\n", stat.Size(), stat.ModTime()) fmt.Println(string(b)) return nil } func (r *reader) Display() error { return nil }
package org.example.calculator; import java.util.Arrays; public enum ArithmeticOperator { ADDITION("+") { @Override public int arithmeticCalculate(int operand1, int operand2) { return operand1 + operand2; } }, SUBTRACTION("-") { @Override public int arithmeticCalculate(int operand1, int operand2) { return operand1 - operand2; } }, MULTIPLICATION("*") { @Override public int arithmeticCalculate(int operand1, int operand2) { return operand1 * operand2; } }, DIVISION("/") { @Override public int arithmeticCalculate(int operand1, int operand2) { return operand1 / operand2; } }; private final String operator; ArithmeticOperator(String operator) { this.operator = operator; } public abstract int arithmeticCalculate(final int operand1, final int operand2); public static int calculate(final int operand1, final String operator, final int operand2) { ArithmeticOperator arithmeticOperator = Arrays.stream(values()) .filter(ao -> ao.operator.equals(operator)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("올바른 연산자가 아닙니다")); return arithmeticOperator.arithmeticCalculate(operand1, operand2); } }
<?php namespace Drupal\node_layout_builder\Entity; use Drupal\Core\Entity\ContentEntityBase; use Drupal\Core\Field\BaseFieldDefinition; use Drupal\Core\Entity\EntityTypeInterface; use Drupal\Core\Entity\ContentEntityInterface; /** * Defines the LayoutBuilder entity. * * @ingroup layout_builder * * @ContentEntityType( * id = "node_layout_builder_template", * label = @Translation("Node Layout Builder Template"), * base_table = "node_layout_builder_template", * entity_keys = { * "id" = "id", * }, * ) */ class NodeLayoutBuilderTemplate extends ContentEntityBase implements ContentEntityInterface { /** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields['id'] = BaseFieldDefinition::create('integer') ->setLabel(t('ID')) ->setDescription(t('The ID of the template entity.')) ->setReadOnly(TRUE); $fields['title'] = BaseFieldDefinition::create('string') ->setLabel(t('Title')) ->setDescription(t('The title of template.')) ->setReadOnly(TRUE); $fields['preview'] = BaseFieldDefinition::create('string') ->setLabel(t('Preview')) ->setDescription(t('Image preview of template.')) ->setReadOnly(TRUE); $fields['data'] = BaseFieldDefinition::create('map') ->setLabel(t('Data')) ->setDescription(t('Data of template.')) ->setReadOnly(TRUE); return $fields; } }
<div class="login-page"> <%= render "devise/shared/error_messages", resource: resource%> <div class="signup-container"> <div class="signup-box"> <h3>New User? Sign up</h3> <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <div class="field"> <%= f.text_field :first_name, autofocus: true, autocomplete: "first-name", placeholder: "First name" %> </div> <div class="field"> <%= f.text_field :last_name, autofocus: true, autocomplete: "last-name", placeholder: "Last Name" %> </div> <div class="field"> <%= f.text_field :user_name, autofocus: true, autocomplete: "user-name", placeholder: "UserName" %> </div> <div class="field"> <%= f.email_field :email, autofocus: true, autocomplete: "email", placeholder: "Email" %> </div> <div class="field"> <% if @minimum_password_length %> <em>(<%= @minimum_password_length %> characters minimum)</em> <% end %><br /> <%= f.password_field :password, autocomplete: "new-password", placeholder: "Password" %> </div> <div class="field"> <%= f.password_field :password_confirmation, autocomplete: "new-password", placeholder: "Confirm password" %> </div> <div class="actions"> <%= f.submit "Sign up", class: "signup-bttn" %> </div> <% end %> <%= render "devise/shared/links" %> </div> </div> <div class="left-signup-container"> <img src='<%= asset_path('alexis-brown-omeaHbEFlN4-unsplash.jpeg') %>'> </div> </div>
import { Component, NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { CanDeactivateGuardService } from './candeactivate-guard.service'; import { AddStudentComponent } from './components/add-student/add-student.component'; import { EditStudentComponent } from './components/edit-student/edit-student.component'; import { ListStudentComponent } from './components/list-student/list-student.component'; import { LoginStudentComponent } from './components/login-student/login-student.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { StudentGuardService } from './student-guard.service'; const routes: Routes = [ { //Default route. In this case component name will not show in url. only root url will show path: '', component: LoginStudentComponent }, /*{ //Default route with redirect. In this case component name will show in url path:'', redirectTo:'login', pathMatch:'full' }, */ { path: 'add', component: AddStudentComponent, canDeactivate:[CanDeactivateGuardService] /* Lazy loading path define syntax. Components has to be standalone for lazy loading. Here AddStudentComponent is not standalone components. That's why lazy loading is not working for AddStudentComponent component */ //loadComponent:()=>import('./components/add-student/add-student.component').then(opt=>opt.AddStudentComponent) }, { path: 'edit/:id', component: EditStudentComponent, canActivate: [StudentGuardService] }, { path: 'list', component: ListStudentComponent, canActivate: [StudentGuardService] }, { path: 'login', component: LoginStudentComponent }, { path:"**", component:PageNotFoundComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
.. Author: Stefan Feuz; http://www.laboratoridenvol.com .. Copyright: General Public License GNU GPL 3.0 Pre-Processor cells distribution In the window cells distribution the parameters out of the last section of the pre-processor input file can be edited. There are four different possibilities to define the cells distribution. Type 1: uniform --------------- .. image:: /images/preproc/cellsDistrMode1.png :width: 350 :height: 243 Raw data:: ********************************** * 4. Cells distribution ********************************** 1 45 The wing does have 45 cells everyone with identical width. Type 2: linear with reduction ----------------------------- .. image:: /images/preproc/cellsDistrMode2.png :width: 350 :height: 243 Raw data:: ********************************** * 4. Cells distribution ********************************** 2 0.7 40 The wing does have 40 cells. The coefficient of 0.7 defines the liear cell reduction towards the wing tip. * Value = 1: cell with is uniform * Value = 0: the width of the last cell is minimal Type 3: Reduction proportional to chord --------------------------------------- .. image:: /images/preproc/cellsDistrMode3.png :width: 350 :height: 243 Raw data:: ********************************** * 4. Cells distribution ********************************** 3 0.3 33 The wing does have 33 cells. The coefficient of 0.3 defines the width reduction proportional to chord. * Value = 1: all cells are uniform, independent of the chord * Value = 0: the cell width will be reduced strictly proportional to chord Type 4: ecplicit definition --------------------------- .. image:: /images/preproc/cellsDistrMode4.png :width: 350 :height: 243 Raw data:: ********************************** * 4. Cells distribution ********************************** 4 17 1 38 2 38 3 38 4 38 5 38 6 37 7 37 8 37 9 36 10 35 11 35 12 30 13 28 14 27 15 25 16 24 17 20.2 The example above defines a wing with 33 cells. Number 1 is the central one, then 16 cells to each side. The second column defines the cell with in cm. If the sum of the cell with defined in here does not match the total wing span, lep will fix this during the processing. The example below shows a wing with 18 cells. To define a even number of cells we need a trick: we define a center cell with the width of 0.0. Tho both sides we have then 9 cells which makes a total of 18.:: ********************************** * 4. Cells distribution ********************************** 4 10 1 0.0 2 38 3 38 4 38 5 38 6 37 7 37 8 37 9 36 10 35 A more detailed description you can find here |pere_link|. .. |pere_link| raw:: html <a href="http://laboratoridenvol.com/leparagliding/pre.en.html#2" target="_blank">Laboratori d'envol website</a>
import React from 'react'; import { ScopeService } from '@neon/core'; import { useInject } from '../hooks/useInject'; export interface ScopedProps { scopes: string[]; children: React.ReactElement; } export const Scoped: React.FC<ScopedProps> = ({ scopes, children }) => { const [areScopesAttached, setScopesAttached] = React.useState(false); const scopeService = useInject(ScopeService); React.useEffect(() => { scopes.forEach(scope => { scopeService.attach(scope); }); setScopesAttached(true); return () => { scopes.forEach(scope => { scopeService.detach(scope); }); }; }, []); return areScopesAttached ? children : null; };
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace SSDLDotNetCore.RestApiWithNLayer.Features.MyanmarProverbs { [Route("api/[controller]")] [ApiController] public class MyanmarProverbsController : ControllerBase { public async Task<bl_Mmproverbs> GetDataFromApi() { HttpClient client = new HttpClient(); var response = await client.GetAsync("https://raw.githubusercontent.com/sannlynnhtun-coding/Myanmar-Proverbs/main/MyanmarProverbs.json"); if (!response.IsSuccessStatusCode) return null; string jsonStr = await response.Content.ReadAsStringAsync(); var model = JsonConvert.DeserializeObject<bl_Mmproverbs>(jsonStr); return model; } [HttpGet] public async Task<IActionResult> Get() { var model = await GetDataFromApi(); return Ok(model.Tbl_MMProverbsTitle); } [HttpGet("{titleName}")] public async Task<IActionResult> Get(string titleName) { var model = await GetDataFromApi(); var item = model.Tbl_MMProverbsTitle.FirstOrDefault(x => x.TitleName == titleName); if (item is null) return NotFound(); var titleId = item.TitleId; var result = model.Tbl_MMProverbs.Where(x => x.TitleId == titleId); List<Tbl_MmproverbsHead> lst = result.Select(x => new Tbl_MmproverbsHead { TitleId = x.TitleId, ProverbId = x.ProverbId, ProverbName = x.ProverbName }).ToList(); return Ok(lst); } [HttpGet("{TitleId}/{ProverbId}")] public async Task<IActionResult> Get(int TitleId, int ProverbId) { var model = await GetDataFromApi(); var item = model.Tbl_MMProverbs.FirstOrDefault(x => x.TitleId == TitleId && x.ProverbId == ProverbId); return Ok(item); } public class bl_Mmproverbs { public Tbl_Mmproverbstitle[] Tbl_MMProverbsTitle { get; set; } public Tbl_MmproverbsDetail[] Tbl_MMProverbs { get; set; } } public class Tbl_Mmproverbstitle { public int TitleId { get; set; } public string TitleName { get; set; } } public class Tbl_MmproverbsDetail { public int TitleId { get; set; } public int ProverbId { get; set; } public string ProverbName { get; set; } public string ProverbDesp { get; set; } } // Remove "ProverbDesp" property because we don't need this in this page or Api yet public class Tbl_MmproverbsHead { public int TitleId { get; set; } public int ProverbId { get; set; } public string ProverbName { get; set; } } } }
#ifndef BABELTRACE_REF_INTERNAL_H #define BABELTRACE_REF_INTERNAL_H /* * Babeltrace - Reference Counting * * Copyright 2013, 2014 Jérémie Galarneau <jeremie.galarneau@efficios.com> * * Author: Jérémie Galarneau <jeremie.galarneau@efficios.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <babeltrace/babeltrace-internal.h> #include <assert.h> struct bt_object; typedef void (*bt_object_release_func)(struct bt_object *); struct bt_ref { long count; bt_object_release_func release; }; static inline void bt_ref_init(struct bt_ref *ref, bt_object_release_func release) { assert(ref); ref->count = 1; ref->release = release; } static inline void bt_ref_get(struct bt_ref *ref) { assert(ref); ref->count++; } static inline void bt_ref_put(struct bt_ref *ref) { assert(ref); /* Only assert if the object has opted-in for reference counting. */ assert(!ref->release || ref->count > 0); if ((--ref->count) == 0 && ref->release) { ref->release((struct bt_object *) ref); } } #endif /* BABELTRACE_REF_INTERNAL_H */
// App.tsx import React, { useState } from "react"; import "./App.css"; // Import your CSS file for styling import TaskList from "./tasklist"; import TaskForm from "./TaskForm"; const App: React.FC = () => { const [tasks, setTasks] = useState([ { id: 1, title: "Sample Task 1", description: "Description of task 1", deadline: "2023-12-31", priority: "High", completed: false, }, // Add more sample tasks as needed ]); // function to delete a task const deleteTask = (id: number) => { setTasks(tasks.filter((task) => task.id !== id)); }; // function to toggle a task complete const toggleTask = (id: number) => { setTasks( tasks.map((task) => task.id === id ? { ...task, completed: !task.completed } : task ) ); }; // function to add a task const addTask = (newTask: any) => { const newTaskWithId = { ...newTask, id: tasks.length + 1 }; setTasks([...tasks, newTaskWithId]); }; // Render Tasklist component with tasks and event handlers return ( <div className="App"> <h1>Task Management App</h1> <TaskForm onTaskAdd={addTask} /> <TaskList tasks={tasks} onDelete={deleteTask} onToggle={toggleTask} /> </div> ); }; export default App;
package com.petkoivanov.carCatalog.controllers; import com.petkoivanov.carCatalog.models.dtos.ModelDto; import com.petkoivanov.carCatalog.models.entities.Model; import com.petkoivanov.carCatalog.models.requests.ModelRequest; import com.petkoivanov.carCatalog.services.ModelService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.util.List; import static com.petkoivanov.carCatalog.utils.URIConstants.BRANDS_ID_PATH; import static com.petkoivanov.carCatalog.utils.URIConstants.MODELS_ID_PATH; import static com.petkoivanov.carCatalog.utils.URIConstants.MODELS_PATH; @RestController public class ModelController { private static final Logger log = LoggerFactory.getLogger(ModelController.class); private final ModelService modelService; @Autowired public ModelController(ModelService modelService){ this.modelService = modelService; } @PostMapping(MODELS_PATH) public ResponseEntity<Void> addModel(@RequestBody @Valid ModelRequest modelRequest){ log.info("A request for a model to be added was submitted"); Model model = modelService.addModel(modelRequest); URI location = UriComponentsBuilder .fromUriString(MODELS_ID_PATH) .buildAndExpand(model.getId()) .toUri(); return ResponseEntity.created(location).build(); } @GetMapping(MODELS_PATH) public ResponseEntity<List<ModelDto>> getAllModels(){ log.info("All models were requested from the database"); List<ModelDto> models = modelService.getAllModels(); return ResponseEntity.ok(models); } @GetMapping(MODELS_PATH+BRANDS_ID_PATH) public ResponseEntity<List<ModelDto>> getAllModelsWithBrandId(@PathVariable int id){ log.info(String.format("All models with brand id %d requested from the database",id)); List<ModelDto> models =modelService.getAllModelsByBrandId(id); return ResponseEntity.ok(models); } @GetMapping(value = MODELS_PATH , params = "modelName") public ResponseEntity<ModelDto> getModelByName(@RequestParam String modelName){ log.info(String.format("Model with name %s requested from database",modelName)); ModelDto model = modelService.getModelDtoByName(modelName); return ResponseEntity.ok(model); } @PutMapping(MODELS_ID_PATH) public ResponseEntity<ModelDto> updateModel( @RequestBody @Valid ModelRequest modelRequest , @PathVariable int id , @RequestParam(required = false) boolean returnOld){ ModelDto model = modelService.updateModel(modelRequest , id); log.info(String.format("Model with id %d was updated" , id)); return returnOld ? ResponseEntity.ok(model) : ResponseEntity.noContent().build(); } @DeleteMapping(MODELS_ID_PATH) public ResponseEntity<ModelDto> deleteModel( @PathVariable int id , @RequestParam(required = false) boolean returnOld){ ModelDto model = modelService.deleteModel(id); log.info(String.format("Model with id %d was deleted" , id)); return returnOld ? ResponseEntity.ok(model) : ResponseEntity.noContent().build(); } }
package com.occulue.aggregate; import com.occulue.api.*; import com.occulue.entity.*; import com.occulue.exception.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import org.axonframework.commandhandling.CommandHandler; import org.axonframework.modelling.command.AggregateMember; import org.axonframework.eventsourcing.EventSourcingHandler; import org.axonframework.modelling.command.AggregateIdentifier; import static org.axonframework.modelling.command.AggregateLifecycle.apply; import org.axonframework.spring.stereotype.Aggregate; import org.springframework.context.annotation.Profile; /** * Aggregate handler for GovSteamCC as outlined for the CQRS pattern, all write responsibilities * related to GovSteamCC are handled here. * * @author your_name_here * */ @Aggregate public class GovSteamCCAggregate { // ----------------------------------------- // Axon requires an empty constructor // ----------------------------------------- public GovSteamCCAggregate() { } // ---------------------------------------------- // intrinsic command handlers // ---------------------------------------------- @CommandHandler public GovSteamCCAggregate(CreateGovSteamCCCommand command) throws Exception { LOGGER.info( "Handling command CreateGovSteamCCCommand" ); CreateGovSteamCCEvent event = new CreateGovSteamCCEvent(command.getGovSteamCCId(), command.getDhp(), command.getDlp(), command.getFhp(), command.getFlp(), command.getMwbase(), command.getPmaxhp(), command.getPmaxlp(), command.getRhp(), command.getRlp(), command.getT1hp(), command.getT1lp(), command.getT3hp(), command.getT3lp(), command.getT4hp(), command.getT4lp(), command.getT5hp(), command.getT5lp()); apply(event); } @CommandHandler public void handle(UpdateGovSteamCCCommand command) throws Exception { LOGGER.info( "handling command UpdateGovSteamCCCommand" ); UpdateGovSteamCCEvent event = new UpdateGovSteamCCEvent(command.getGovSteamCCId(), command.getDhp(), command.getDlp(), command.getFhp(), command.getFlp(), command.getMwbase(), command.getPmaxhp(), command.getPmaxlp(), command.getRhp(), command.getRlp(), command.getT1hp(), command.getT1lp(), command.getT3hp(), command.getT3lp(), command.getT4hp(), command.getT4lp(), command.getT5hp(), command.getT5lp()); apply(event); } @CommandHandler public void handle(DeleteGovSteamCCCommand command) throws Exception { LOGGER.info( "Handling command DeleteGovSteamCCCommand" ); apply(new DeleteGovSteamCCEvent(command.getGovSteamCCId())); } // ---------------------------------------------- // association command handlers // ---------------------------------------------- // single association commands // multiple association commands // ---------------------------------------------- // intrinsic event source handlers // ---------------------------------------------- @EventSourcingHandler void on(CreateGovSteamCCEvent event) { LOGGER.info( "Event sourcing CreateGovSteamCCEvent" ); this.govSteamCCId = event.getGovSteamCCId(); this.dhp = event.getDhp(); this.dlp = event.getDlp(); this.fhp = event.getFhp(); this.flp = event.getFlp(); this.mwbase = event.getMwbase(); this.pmaxhp = event.getPmaxhp(); this.pmaxlp = event.getPmaxlp(); this.rhp = event.getRhp(); this.rlp = event.getRlp(); this.t1hp = event.getT1hp(); this.t1lp = event.getT1lp(); this.t3hp = event.getT3hp(); this.t3lp = event.getT3lp(); this.t4hp = event.getT4hp(); this.t4lp = event.getT4lp(); this.t5hp = event.getT5hp(); this.t5lp = event.getT5lp(); } @EventSourcingHandler void on(UpdateGovSteamCCEvent event) { LOGGER.info( "Event sourcing classObject.getUpdateEventAlias()}" ); this.dhp = event.getDhp(); this.dlp = event.getDlp(); this.fhp = event.getFhp(); this.flp = event.getFlp(); this.mwbase = event.getMwbase(); this.pmaxhp = event.getPmaxhp(); this.pmaxlp = event.getPmaxlp(); this.rhp = event.getRhp(); this.rlp = event.getRlp(); this.t1hp = event.getT1hp(); this.t1lp = event.getT1lp(); this.t3hp = event.getT3hp(); this.t3lp = event.getT3lp(); this.t4hp = event.getT4hp(); this.t4lp = event.getT4lp(); this.t5hp = event.getT5hp(); this.t5lp = event.getT5lp(); } // ---------------------------------------------- // association event source handlers // ---------------------------------------------- // ------------------------------------------ // attributes // ------------------------------------------ @AggregateIdentifier private UUID govSteamCCId; private String dhp; private String dlp; private String fhp; private String flp; private String mwbase; private String pmaxhp; private String pmaxlp; private String rhp; private String rlp; private String t1hp; private String t1lp; private String t3hp; private String t3lp; private String t4hp; private String t4lp; private String t5hp; private String t5lp; private static final Logger LOGGER = Logger.getLogger(GovSteamCCAggregate.class.getName()); }
import glob import PyPDF2 import pdfplumber import xlwings as xw import requests import os import re import traceback # pip install PyMuPDF import fitz # PyMuPDF import re import pdf2image from PIL import Image import pytesseract import os import threading from queue import Queue import hashlib excel_file = 'Trust DFM.xlsm' pdf_folder = 'Trust DFM PDFs' def get_data_addition(pdf): def extract_top_left_text(pdf_path): with pdfplumber.open(pdf_path) as pdf: all_text = "" # Use enumerate to get the page index for i, page in enumerate(pdf.pages): # Check if the page is one of 1, 4, 8, etc. (keeping in mind that indices start from 0) if (i+1) % 4 != 1: continue # Calculate dimensions for the top-left quadrant x0, top, x1, bottom = page.bbox width = x1 - x0 height = bottom - top crop_box = (x0, top, x0 + width * 0.5, top + height * 0.5) # Crop the page to the top-left quadrant and extract text cropped_page = page.crop(bbox=crop_box) all_text += cropped_page.extract_text() + "\n" return all_text.strip().split('\n') # Example text = extract_top_left_text(pdf) assets_categories = ['Equity', 'Fixed Income', 'Cash', 'Multi Asset ', 'Alternatives'] assets_groups = [] assets_current_group = [] found_assets_holdings = False for i, line in enumerate(text): if 'ASSET CLASS' in line : found_assets_holdings = True continue # Пропускаем текущую строку, чтобы она не добавлялась в current_group # Если находим строку 'Important Information', останавливаем добавление elif 'OBJECTIVES AND POLICY' in line: found_assets_holdings = False if assets_current_group: assets_groups.append(assets_current_group) # print(groups) assets_current_group = [] # Если мы внутри интересующего нас блока, добавляем строки elif found_assets_holdings: assets_current_group.append(line.strip()) assets_categories_pattern = "|".join(assets_categories) assets_result = [] # print(current_group) for group in assets_groups: i = 0 while i < len(group): if i < len(group) - 1 and "Fixed Income Multi Asset" in group[i] and group[i + 1] == "Credit": percentage_part = group[i].split('Fixed Income Multi Asset ')[1] group[i] = 'Fixed Income Multi Asset Credit ' + percentage_part group.pop(i + 1) i += 1 # print(groups, '-- groups \n') for lst in assets_groups: category_values = [] # Сombine all in one string joined_string = " ".join(lst) # Ищем все вхождения категорий в объединенной строке for match in re.finditer(assets_categories_pattern, joined_string): category = match.group(0) # Получаем название категории # Получаем подстроку после найденной категории string_after_category = joined_string[match.end():] # Ищем первое число в подстроке (значение категории) value_match = re.search(r'\b\d+(\.\d+)?', string_after_category) if value_match: value = value_match.group(0) # Получаем значение # Добавляем категорию и значение в список category_values.append(f"{category} {value}%") assets_result.append(category_values) for i in range(len(assets_result)): assets_result[i] = list(dict.fromkeys(assets_result[i])) # print('\n'*2, result, '-- result \n') assets_grouped_assets = [] for group in assets_result: keys = [] values = [] for line in group: key, value = line.rsplit(' ', 1) # Разделяем строку на две части по последнему пробелу keys.append(key) values.append(value) assets = dict(zip(keys, values)) assets_grouped_assets.append(assets) return assets_grouped_assets def get_data(file): filenames = [] date = [] ongoing_costs = [] one_month = [] one_year = [] three_years = [] five_years = [] with pdfplumber.open(file) as pdf: text = '' for page in pdf.pages: text += page.extract_text(use_text=True) text = text.split('\n') # print(text) # breakpoint() for i, line in enumerate(text): if i == 0: filenames.append(text[0]) elif i == len(text) - 1: continue else: if '4 of 4' in line: filenames.append(line.split('4 of 4')[-1].strip()) # print(filenames) for i,line in enumerate(text): if 'Ongoing Costs' in line: oc_match = re.search(r'(\d+\.\d+)', line) ongoing_costs.append(float(oc_match.group(1))/100) date.append(text[1]) if "Time Period" in line: # print(text[i+1]) values_line = text[i+1] values = [match[0] for match in re.findall(r'(-?\d+(\.\d+)?)%', values_line)] print(values) one_month.append(float(values[0])/100) one_year.append(float(values[3])/100) if '5yr' in line: values_line = text[i+1] values = [match[0] for match in re.findall(r'(-?\d+(\.\d+)?)%', values_line)] print(values_line) if len(values) >= 6: three_years.append((float(values[4])/100)) five_years.append((float(values[5])/100)) else: print(f"Error in file {filename}: Expected at least 6 matches but found {len(values)}") three_years.append(None) # or a default value of your choice five_years.append(None) # or a default value of your choice # print(filenames) # print(date) # print(ongoing_costs) # print(one_month) # print(one_year) # print(three_years) # print(five_years) unsorted_categories = [ 'Global Equities', 'Corporate Bonds', 'Global Multi Asset', 'UK Equities', 'Cash', 'Alternatives', 'Asia Pacific Ex Japan Equities', 'European Equities', 'Fixed Income Multi Asset', 'Fixed Income Multi Asset Credit', 'Japanese Equities', 'Emerging Market Equities', 'Global Government Bonds', 'US Equities', ] categories = sorted(unsorted_categories, key=lambda x: len(x), reverse=True) groups = [] current_group = [] found_portfolio_holdings = False for i, line in enumerate(text): if 'WEIGHTS BY ASSET' in line : found_portfolio_holdings = True continue # Пропускаем текущую строку, чтобы она не добавлялась в current_group # Если находим строку 'Important Information', останавливаем добавление elif 'TOP 10 PERFORMANCE CONTRIBUTORS OVER 1 YEAR' in line: found_portfolio_holdings = False if current_group: groups.append(current_group) # print(groups) current_group = [] # Если мы внутри интересующего нас блока, добавляем строки elif found_portfolio_holdings: current_group.append(line.strip()) categories_pattern = "|".join(categories) result = [] # print(current_group) for group in groups: i = 0 while i < len(group): if i < len(group) - 1 and "Fixed Income Multi Asset" in group[i] and group[i + 1] == "Credit": percentage_part = group[i].split('Fixed Income Multi Asset ')[1] group[i] = 'Fixed Income Multi Asset Credit ' + percentage_part group.pop(i + 1) i += 1 # print(groups, '-- groups \n') for lst in groups: category_values = [] # Сombine all in one string joined_string = " ".join(lst) # Ищем все вхождения категорий в объединенной строке for match in re.finditer(categories_pattern, joined_string): category = match.group(0) # Получаем название категории # Получаем подстроку после найденной категории string_after_category = joined_string[match.end():] # Ищем первое число в подстроке (значение категории) value_match = re.search(r'\b\d+(\.\d+)?', string_after_category) if value_match: value = value_match.group(0) # Получаем значение # Добавляем категорию и значение в список category_values.append(f"{category} {value}%") result.append(category_values) for i in range(len(result)): result[i] = list(dict.fromkeys(result[i])) # print('\n'*2, result, '-- result \n') grouped_assets = [] for group in result: keys = [] values = [] for line in group: key, value = line.rsplit(' ', 1) # Разделяем строку на две части по последнему пробелу keys.append(key) values.append(value) assets = dict(zip(keys, values)) grouped_assets.append(assets) # print(grouped_assets) def merge_lists(list1, list2): # Initialize an empty list to store the merged dictionaries merged_list = [] # Loop over pairs of dictionaries from list1 and list2 for dict1, dict2 in zip(list1, list2): # Create a copy of the dictionary from list1 to avoid modifying the original merged_dict = dict1.copy() # Update the merged dictionary with key-value pairs from dict2, only if the key doesn't exist in dict1 for key, value in dict2.items(): if key not in merged_dict: merged_dict[key] = value # Add the merged dictionary to the merged list merged_list.append(merged_dict) return merged_list assets_grouped_assets = get_data_addition(file) combined_list = merge_lists(assets_grouped_assets, grouped_assets) # print(combined_list) result2 = {} for i, filename in enumerate(filenames): result2[filename] = { 'Date': date[i] if i < len(date) else None, 'Ongoing Costs*': ongoing_costs[i] if i < len(ongoing_costs) else None, '1yr': one_year[i] if i < len(one_year) else None, '1m': one_month[i] if i < len(one_month) else None, '3yr': three_years[i] if i < len(three_years) else None, '5yr': five_years[i] if i < len(five_years) else None, 'Assets': combined_list[i] if i < len(combined_list) else None } print( 'Date', date[i], "\n", 'One month', one_month[i],"\n", '12 months', one_year[i],"\n", # '3yr', three_years[i],"\n", # '5yr', five_years[i],"\n", 'Ongoing Costs', ongoing_costs[i],"\n", 'Assets', combined_list[i],"\n", ) # print(result) return result2 def download_worker(q, folder_name): headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', 'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none', 'sec-fetch-user': '?1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', } while not q.empty(): row_data = q.get() link, filename = row_data["link"], row_data["filename"] response = requests.get(link, headers=headers) if not filename: filename = link.split('/')[-1] file_path = os.path.join(folder_name, filename) with open(file_path, 'wb') as f: f.write(response.content) print(f"PDF downloaded: {filename}") q.task_done() def download_pdfs(spreadsheet): print('Downloading PDFs...') app = xw.App(visible=False) wb = app.books.open(spreadsheet, update_links=False, read_only=False) sheet = wb.sheets[1] folder_name = pdf_folder if not os.path.exists(folder_name): os.makedirs(folder_name) last_row = sheet.range('B' + str(sheet.cells.last_cell.row)).end('up').row q = Queue(maxsize=0) for row in range(3, last_row+1): link = sheet.range(f'B{row}').value filename = sheet.range(f'A{row}').value + '.pdf' q.put({"link": link, "filename": filename}) num_threads = 4 for _ in range(num_threads): worker_thread = threading.Thread( target=download_worker, args=(q, folder_name)) worker_thread.start() q.join() wb.close() app.quit() print('All PDFs downloaded!') return folder_name def write_to_sheet(data, excel_file): try: app = xw.App(visible=False) wb = app.books.open(excel_file, update_links=False, read_only=False) # breakpoint() for filename, values in data.items(): print('Writing data of', filename) # Find the row that matches filename sheet = wb.sheets[2] row = None for cell in sheet.range('A:A'): if cell.value and cell.value.strip() == filename.strip(): row = cell.row break if row is None: print(f"Filename '{filename}' not found in the sheet.") continue for key in values: if key == 'Assets': continue # Find the matching column column = None for cell in sheet.range('1:1'): if cell.value and cell.value.strip() == key.strip(): column = cell.column break if column is None: print(f"Column '{key}' not found in the sheet.") continue # Write the key's value to the cell at the intersection of the row and column sheet.cells(row, column).value = values[key] sheet = wb.sheets[3] column_headings = sheet.range('A1').expand('right').value for asset, value in values['Assets'].items(): if asset not in column_headings: sheet.range( f'{column_letter_from_index(len(column_headings)+1)}1').value = asset # Update the column_headings list after adding the new column column_headings = sheet.range('A1').expand('right').value for asset, value in values['Assets'].items(): column_index = column_headings.index(asset) + 1 cell = sheet.range( f'{column_letter_from_index(column_index)}{row}') cell.value = float(value.replace('%','')) / 100 cell.number_format = '0,00%' except Exception as e: print(f"An error occurred: {str(e)}") traceback.print_exc() finally: wb.save() wb.close() app.quit() def column_letter_from_index(index): result = "" while index > 0: index -= 1 remainder = index % 26 result = chr(65 + remainder) + result index = index // 26 return result def calculate_sha256(file_path): """Calculate the SHA256 hash of a file.""" sha256_hash = hashlib.sha256() with open(file_path, "rb") as f: # Read and update hash in chunks for large files for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest() if __name__ == '__main__': pdf_folder = download_pdfs(excel_file) pdfs = glob.glob(pdf_folder + '/*.pdf') # Calculate hashes for all PDFs hashes = {pdf: calculate_sha256(pdf) for pdf in pdfs} # Group PDFs by their hashes grouped_pdfs = {} for pdf, pdf_hash in hashes.items(): if pdf_hash not in grouped_pdfs: grouped_pdfs[pdf_hash] = [] grouped_pdfs[pdf_hash].append(pdf) # From each group of identical PDFs, remove all but one for pdf_group in grouped_pdfs.values(): for pdf in pdf_group[1:]: os.remove(pdf) new_pdfs = glob.glob(pdf_folder + '/*.pdf') for file in new_pdfs: try: data = get_data(file) write_to_sheet(data, excel_file) except Exception as e: print(f"Error while processing {file}: {str(e)}") traceback.print_exc() print('\nDone!')
class Heap: def __init__(self, arr=None): if arr is None: self.heap = [] else: self.heapify(arr) def parentIndex(self, crrIdx): return (crrIdx - 1) // 2 if crrIdx > 0 else 0 def leftChildIndex(self, crrIdx): left_idx = (crrIdx * 2) + 1 return left_idx def rightChildIndex(self, crrIdx): right_idx = (crrIdx * 2) + 2 return right_idx def heapify(self, arr): for item in arr: self.insert(item) def size(self): # return num of nodes in the heap return len(self.heap) def height(self): temp = self.size() cnt = 0 while temp > 0: temp //= 2 cnt += 1 return cnt def printHeap(self): crr_depth = self.height() from_top = 0 gap = 2 ** crr_depth - 1 start = 0 end = 1 while crr_depth > 0: print(' ' * (2 ** (crr_depth - 1)) + (' ' * gap).join(map(str, self.heap[start:end]))) gap = gap // 2 crr_depth -= 1 from_top += 1 start = end end = end + (2 ** from_top) print("--------------------------") def peek(self): root_node = self.heap[0] print("Current root node is ", root_node) return root_node def insert(self, item): print("overwrite insert function on its child class") class MinHeap(Heap): def insert(self, item): self.heap.append(item) # crrIdx is the very last index crrIdx = len(self.heap) - 1 while self.heap[self.parentIndex(crrIdx)] > item: parentIdx = self.parentIndex(crrIdx) self.heap[crrIdx] = self.heap[parentIdx] self.heap[parentIdx] = item crrIdx = parentIdx print(f"------ '{item}' INSERTED ------") print(self.heap) self.printHeap() def delete(self, item): if item not in self.heap: print(f"***** {item} NOT IN THE HEAP ******") return # find the index of item to remove item_idx = self.heap.index(item) # remove the root node and place the last node at the root node temp_node = self.heap.pop() # item removed self.heap[item_idx] = temp_node # find the right place for the temp_node by swapping with smaller child try: while temp_node > self.heap[self.leftChildIndex(item_idx)] or temp_node > self.heap[self.rightChildIndex(item_idx)]: left_idx = self.leftChildIndex(item_idx) right_idx = self.rightChildIndex(item_idx) left_node = self.heap[left_idx] right_node = self.heap[right_idx] if left_node > right_node: self.heap[right_idx] = temp_node self.heap[item_idx] = right_node item_idx = right_idx else: self.heap[left_idx] = temp_node self.heap[item_idx] = left_node item_idx = left_idx # IndexError occurs when current node is a leaf node # in this case, there is no more node to swap # So stop swapping except IndexError: pass print(f"------ '{item}' REMOVED ------") print(self.heap) self.printHeap() class MaxHeap(Heap): def insert(self, item): self.heap.append(item) # crrIdx is the very last index crrIdx = len(self.heap) - 1 while self.heap[self.parentIndex(crrIdx)] < item: parentIdx = self.parentIndex(crrIdx) self.heap[crrIdx] = self.heap[parentIdx] self.heap[parentIdx] = item crrIdx = parentIdx print(f"------ '{item}' INSERTED ------") print(self.heap) self.printHeap() def delete(self, item): if item not in self.heap: print(f"***** {item} NOT IN THE HEAP ******") return # find the index of item to remove item_idx = self.heap.index(item) # remove the root node and place the last node at the root node temp_node = self.heap.pop() # item removed self.heap[item_idx] = temp_node # find the right place for the temp_node by swapping with larger child try: while temp_node < self.heap[self.leftChildIndex(item_idx)] or temp_node < self.heap[self.rightChildIndex(item_idx)]: left_idx = self.leftChildIndex(item_idx) right_idx = self.rightChildIndex(item_idx) left_node = self.heap[left_idx] right_node = self.heap[right_idx] if left_node < right_node: self.heap[right_idx] = temp_node self.heap[item_idx] = right_node item_idx = right_idx else: self.heap[left_idx] = temp_node self.heap[item_idx] = left_node item_idx = left_idx # IndexError occurs when current node is a leaf node # in this case, there is no more node to swap # So stop swapping except IndexError: pass print(f"------ '{item}' REMOVED ------") print(self.heap) self.printHeap() def testMaxHeap(): print("TEST MAX HEAP") max_heap = MaxHeap() max_heap.insert(1) max_heap.insert(2) max_heap.insert(3) max_heap.insert(4) max_heap.delete(2) max_heap.insert(9) max_heap.insert(7) max_heap.insert(8) max_heap.delete(100) max_heap.delete(9) max_heap.insert(0) max_heap.insert(5) max_heap.insert(6) max_heap.delete(7) max_heap.delete(3) def testMinHeap(): print("TEST MIN HEAP") min_heap = MinHeap() min_heap.insert(1) min_heap.insert(2) min_heap.insert(3) min_heap.insert(4) min_heap.delete(2) min_heap.insert(9) min_heap.insert(7) min_heap.insert(8) min_heap.delete(100) min_heap.delete(9) min_heap.insert(0) min_heap.insert(5) min_heap.insert(6) min_heap.delete(7) min_heap.delete(3) min_heap.peek() if __name__ == "__main__": testMaxHeap() testMinHeap()
import pygame, sys from pygame.locals import QUIT import playsound import threading import os import ui import countdown import play_sound pygame.init() WIDTH, HEIGHT = 500, 300 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Eye-saver') def set_font(font_type:str="Segoe-UI", font_size:int=24): font = pygame.font.SysFont(font_type, font_size) return font times_up_sound_file_name = os.path.join("sound", "times_up.mp3") bell_chime_sound_file_name = os.path.join("sound", "bell_chime.mp3") file_repeat_count = 0 time_info_file = "time_count.txt" def read_file(out_info_1, out_info_2, out_info_3): with open(time_info_file, "r") as file: out_info_1 = int(file.readline()) out_info_2 = int(file.readline()) out_info_3 = int(file.readline()) file.close() return (out_info_1, out_info_2, out_info_3) def write_file(lst): with open(time_info_file, "w") as file: file.write('\n'.join(lst)) file.close() line_1 = None line_2 = None line_3 = None list_in = [] thread = None time_status = "Type in your time to start!" def countdown_restart(hrs:int, mins:int, secs:int, times_up:str, thread, file_repeat_count): hrs, mins, secs = read_file(out_info_1=hrs, out_info_2=mins, out_info_3=secs) file_repeat_count = 0 if (times_up == "Times up!" or times_up =="Type in your time to start!"): times_up = "You still have time" thread = threading.Thread(target=countdown.cdown, args=(hrs, mins, secs)) thread.start() print(f"There are {threading.active_count()} threads running currently.") return times_up, hrs, mins, secs, file_repeat_count text_color = ui.COLORS["LIGHT_BLUE"] passive_color = ui.COLORS["DARKEST_BLUE"] active_color = ui.COLORS["MEDIUM_BLUE"] bg_color = ui.COLORS["NAVY"] if (line_1 and line_2 and line_3) != None: preset_time = f"{line_1}:{line_2}:{line_3}" else: preset_time = "0:30:0" control_box_info = {"button_color_passive":passive_color, "button_color_active":active_color, "button_x":(WIDTH*0.025), "button_y":(HEIGHT*0.66), "button_width":(WIDTH*0.45), "button_height":(HEIGHT*0.2), "button_border":5, "button_border_radius":10, "text":"START", "text_color":text_color, "text_x":(WIDTH*0.25), "text_y":(HEIGHT*0.76)} input_box_info = {"box_color_passive":passive_color, "box_color_active":active_color, "box_x":(WIDTH*0.525), "box_y":(HEIGHT*0.66), "box_width":(WIDTH*0.45), "box_height":(HEIGHT*0.2), "box_border":None, "box_border_radius":10, "text":preset_time, "text_color":text_color, "text_x":(WIDTH*0.75), "text_y":(HEIGHT*0.76)} user_input_text = input_box_info["text"] input_box_click_active = False FPS = 60 while True: control_button_click_active = False pygame.time.Clock().tick(FPS) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if (event.type == pygame.KEYDOWN and input_box_click_active): if event.key == pygame.K_BACKSPACE: user_input_text = user_input_text[:-1] elif event.key == pygame.K_RETURN: list_in = user_input_text.split(':') if ((int(list_in[1]) <= 60)and (int(list_in[2]) <= 60)): write_file(lst=list_in) if threading.active_count() < 2: time_status, line_1, line_2, line_3, file_repeat_count = countdown_restart(hrs=line_1, mins=line_2, secs=line_3, times_up=time_status, thread=thread, file_repeat_count=file_repeat_count) else: print("Too many minutes or seconds. There are only 60 seconds in a minute, 60 minutes in an hour!!! Go do some math.") input_box_click_active = False else: if (((event.unicode.isdigit()) or ((event.unicode == ':') and (user_input_text.count(':') < 2))) and (len(user_input_text) < 17)): user_input_text += event.unicode if event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() zone_x = ((input_box_info["box_x"]<=mouse_pos[0]) and (mouse_pos[0]<=(input_box_info["box_x"]+input_box_info["box_width"]))) zone_y = ((input_box_info["box_y"]<=mouse_pos[1]) and (mouse_pos[1]<=(input_box_info["box_y"]+input_box_info["box_height"]))) if (zone_x and zone_y): input_box_click_active = not(input_box_click_active) zone_x = ((control_box_info["button_x"]<=mouse_pos[0]) and (mouse_pos[0]<=(control_box_info["button_x"]+control_box_info["button_width"]))) zone_y = ((control_box_info["button_y"]<=mouse_pos[1]) and (mouse_pos[1]<=(control_box_info["button_y"]+control_box_info["button_height"]))) if zone_x and zone_y and (threading.active_count() == 1): time_status, line_1, line_2, line_3, file_repeat_count = countdown_restart(hrs=line_1, mins=line_2, secs=line_3, times_up=time_status, thread=thread, file_repeat_count=file_repeat_count) control_button_click_active = not(control_button_click_active) if (time_status == "Type in your time to start!"): list_in = user_input_text.split(':') if ((int(list_in[1]) <= 60)and (int(list_in[2]) <= 60)): write_file(lst=list_in) if threading.active_count() < 2: time_status, line_1, line_2, line_3, file_repeat_count = countdown_restart(hrs=line_1, mins=line_2, secs=line_3, times_up=time_status, thread=thread, file_repeat_count=file_repeat_count) else: print("Too many minutes or seconds. There are only 60 seconds in a minute, 60 minutes in an hour!!! Go do some math.") input_box_click_active = False if control_button_click_active: control_button_color = control_box_info["button_color_active"] else: control_button_color = control_box_info["button_color_passive"] if input_box_click_active: box_color = input_box_info["box_color_active"] else: box_color = input_box_info["box_color_passive"] #Drawing the background ui.draw_bg(WIN=WIN, bg_color=bg_color, win_width=WIDTH, win_height=HEIGHT) #Drawing the control button ui.draw_button(WIN=WIN, button_color=control_button_color, button_x=control_box_info["button_x"], button_y=control_box_info["button_y"], button_width=control_box_info["button_width"], button_height=control_box_info["button_height"], button_border=control_box_info["button_border"], button_border_radius=control_box_info["button_border_radius"]) #Drawing the outline font = set_font() #Specify the font ui.write_ui_text(WIN=WIN, font=font, text=control_box_info["text"], color=control_box_info["text_color"], text_x=control_box_info["text_x"], text_y=control_box_info["text_y"]) #Drawing the text of the control button #Drawing the input box ui.draw_button(WIN=WIN, button_color=box_color, button_x=input_box_info["box_x"], button_y=input_box_info["box_y"], button_width=input_box_info["box_width"], button_height=input_box_info["box_height"], button_border_radius=input_box_info["box_border_radius"]) font = set_font(font_type="Segoe_UI", font_size=24) ui.write_ui_text(WIN=WIN, font=font, text=user_input_text, color=text_color, text_x=input_box_info["text_x"], text_y=input_box_info["text_y"]) try: t_up = countdown.times_up except AttributeError: t_up = False if t_up: font = set_font(font_type="Segoe-UI", font_size=48) time_status = "Times up!" control_box_info["text"] = "RESET" try: times_up_sound_thread.join() except NameError: pass finally: bell_chime_sound_thread = threading.Thread(target=play_sound.psound, args=(str(bell_chime_sound_file_name))) bell_chime_sound_thread.start() print(f"There are {threading.active_count()} threads running currently.") bell_chime_sound_thread.join() while file_repeat_count < 1: times_up_sound_thread = threading.Thread(target=play_sound.psound, args=(str(times_up_sound_file_name))) times_up_sound_thread.start() print(f"There are {threading.active_count()} threads running currently.") file_repeat_count += 1 elif time_status == "You still have time": font = set_font(font_type="Segoe-UI", font_size=24) ui.write_ui_text(WIN=WIN, font=font, text=(f"Your reminder is for {line_1} hrs, {line_2} mins, {line_3} secs."), color=text_color, text_x=(WIDTH*0.5), text_y=(HEIGHT*0.1)) ui.write_ui_text(WIN=WIN, font=font, text=time_status, color=text_color, text_x=(WIDTH*0.5), text_y=(HEIGHT*0.5)) pygame.display.update()
--- title: 知识图谱 date: 2024-06-07 15:59:42 categories: - NLP tags: --- ## 知识图谱的定义 - 是结构化的语义知识库,用于以符号形式描述物理世界中的概念及其相互关系.其基本组成单位是 “实体-关系-实体” 三元组, 以及实体及其相关属性-值对,实体间通过关系相互联结,构成网状的知识结构。 ## 知识图谱的理解 1. 知识图谱本身是一个具有属性的实体通过关系链接而成的网状知识库。从图的角度来看,知识图谱在本质上是一种概念网络,其中的节点表示物理世界的实体(或概念),而实体间的各种语义关系则构成网络中的边。由此,知识图谱是对物理世界的一种符号表达。 2. 知识图谱的研究价值在于,它是构建在当前Web基础之上的一层覆盖网络(overlay network)(所以实体都是使用uri表示),借助知识图谱,能够在Web网页之上建立概念间的链接关系,从而以最小的代价将互联网中积累的信息组织起来,成为可以被利用的知识。 3. 知识图谱的应用价值在于,它能够改变现有的信息检索方式,一方面通过推理实现概念检索(相对于现有的字符串模糊匹配方式而言);另一方面以图形化方式向用户展示经过分类整理的结构化知识,从而使人们从人工过滤网页寻找答案的模式中解脱出来。 ## 知识图谱的技术架构 ![](/img/note/202406121212.png) - 知识图谱的构建过程是从原始数据出发,采用一系列自动或半自动的技术手段,从原始数据中提取出知识要素(即事实),并将其存入知识库的数据层和模式层的过程。这是一个迭代更新的过程,根据知识获取的逻辑,每一轮迭代包含3个阶段:信息抽取、知识融合以及知识加工 - 知识图谱有自顶向下和自底向上2种构建方式 1. 自顶向下构建是指借助百科类网站等结构化数据源,从高质量数据中提取本体和模式信息,加入到知识库中 2. 自底向上构建,则是借助一定的技术手段,从公开采集的数据中提取出资源模式,选择其中置信度较高的新模式,经人工审核之后,加入到知识库中。 ## 知识图谱的构建技术 - 自底而上的方式构建知识图谱是一个迭代更新的过程,每一轮更新包括三个步骤。 1. 信息抽取:关键问题是如何从异构数据源中自动抽取信息得到候选知识单元。信息抽取是一种自动化地从半结构化和无结构数据中抽取实体、关系以及实体属性等结构化信息的技术。涉及的关键技术包括:实体抽取、关系抽取和属性抽取。 2. 知识融合:在获得新知识之后,需要对其进行整合, 以消除矛盾和歧义, 比如某些实体可能有多种表达, 某个特定称谓也许对应于多个不同的实体等。包括2部分内容:实体链接和知识合并。通过知识融合,可以消除概念的歧义,剔除冗余和错误概念,从而确保知识的质量。 3. 知识合并:在构建知识图谱时, 可以从第三方知识库产品或已有结构化数据获取知识输入。例如,关联开放数据项目(linked opendata)会定期发布其经过积累和整理的语义知识数据,其中既包括前文介绍过的通用知识库DBpedia YAGO,也包括面向特定领域的知识库产品,如MusicBrainz和DrugBank等. 3. 知识加工:对于经过融合的新知识,需要经过质量评估之后(部分需要人工参与甄别),才能将合格的部分加入到知识库中,以确保知识库的质量。新增数据之后, 可以进行知识推理、拓展现有知识、得到新知识。 ## 问题与挑战 1. 在信息抽取环节,面向开放域的信息抽取方法研究还处于起步阶段,部分研究成果虽然在特定(语种、领域、主题等)数据集上取得了较好的结果,但普遍存在算法准确性和召回率低、限制条件多、扩展性不好的问题。 2. 在知识融合环节,如何实现准确的实体链接是一个主要挑战。 3. 知识加工是最具特色的知识图谱技术,同时也是该领域最大的挑战之所在。主要的研究问题包括:本体的自动构建、知识推理技术、知识质量评估手段以及推理技术的应用。 4. 在知识更新环节,增量更新技术是未来的发展方向,然而现有的知识更新技术严重依赖人工干预。可以预见随着知识图谱的不断积累,依靠人工制定更新规则和逐条检视的 旧模式将会逐步降低比重,自动化程度将不断提高,如何确保自动化更新的有效性,是该领域面临的又一重大挑战。 5. 最具基础研究价值的挑战是如何解决知识的表达、存储与查询问题,这个问题将伴随知识图谱技术发展的始终,对该问题的解决将反过来影响前面提出的挑战和关键问题。当前的知识图谱主要采用图数据库进行存储,在受益于图数据库带来的查询效率的同时,也失去了关系型数据库的优点,如SQL语言支持和集合查询效率等。
import { Routes } from '@angular/router'; import { DashboardIndexComponent } from './app-index/app-index.component'; import { EditProfileComponent } from 'app/shared/modules/dashboard/edit-profile/edit-profile.component'; import { DataImportingComponent } from 'app/shared/modules/dashboard/data-importing/data-importing.component'; import { LoyaltyPlanFormComponent } from './loyalty-plans/form/loyalty-plan-form.component'; import { LoyaltyPlanDetailComponent } from './loyalty-plans/detail/loyalty-plan-detail.component'; import { ProfileComponent } from 'app/shared/modules/dashboard/profile/profile.component'; import { TermsAndConditionsComponent } from 'app/shared/features/terms-and-conditions/terms-and-conditions.component'; import { MedicationsIncludedByCountryComponent } from './loyalty-plans/medications-included-by-country/medications-included-by-country.component'; import { ParticipatingDrugstoresComponent } from './loyalty-plans/participating-drugstores/participating-drugstores.component'; export const DashboardRoutes: Routes = [ { path: '', children: [ { path: 'profile', component: ProfileComponent, data: { title: 'PROFILE', breadcrumb: 'PROFILE' }, }, { path: 'edit_profile', component: EditProfileComponent, data: { title: 'EDIT_PROFILE', breadcrumb: 'EDIT_PROFILE' } }, { path: 'data-importing/:type', component: DataImportingComponent, data: { title: 'IMPORT_DATA', breadcrumb: 'IMPORT_DATA' } }, { path: '/', component: DashboardIndexComponent, data: { title: 'Blank', breadcrumb: 'BLANK' } }, { path: 'loyalty-plan', data: { title: 'LOYALTY_PLAN', breadcrumb: 'LOYALTY_PLAN' }, children: [ { path: '', component: LoyaltyPlanDetailComponent, data: { title: 'DETAIL', breadcrumb: 'DETAIL' } }, { path: 'new', data: { title: 'ADD', breadcrumb: 'ADD' }, component: LoyaltyPlanFormComponent }, { path: 'edit', data: { title: 'MODIFY', breadcrumb: 'MODIFY' }, component: LoyaltyPlanFormComponent } ] }, { path: 'loyalty-plan-country/:loyalty_plan_country_id/medications-included-by-country', data: { title: 'MEDICATIONS_INCLUDED_BY_COUNTRY', breadcrumb: 'MEDICATIONS_INCLUDED_BY_COUNTRY' }, component: MedicationsIncludedByCountryComponent }, { path: 'loyalty-plan-country/:loyalty_plan_country_id/participating-drugstores', data: { title: 'PARTICIPATING_DRUGSTORES', breadcrumb: 'PARTICIPATING_DRUGSTORES' }, component: ParticipatingDrugstoresComponent }, { path: 'terms-and-conditions', data: { title: 'TERMS_AND_CONDITIONS', breadcrumb: 'TERMS_AND_CONDITIONS', }, component: TermsAndConditionsComponent }, ] } ];
# Loop De Loop ## Introduction In this activity, you will practice using nested loops and nested conditionals while storing information about an amusement park's rides and prices. ## Instructions * Open the starter code and notice that two empty lists have been created: `rides` and `prices`. * Create a continuous loop that exits when the user types the specific prompt `q`. Inside this loop, perform the following actions: * Ask the user for the name of a ride and append it to the `rides` list. * Create another continuous loop that will be used to check for a valid input. Inside this loop, perform the following actions: * Ask the user for the price of the ride they just input. * Check if the input can be converted to a float using `replace()` (see hint below) and `isdigit()`. If it can't, print an error and return to the start of the loop. If the input can be converted to a float, perform the following actions: * Check if the number is less than or equal to 15. If it is, convert the number to a float and append it to the `prices` list, then exit the loop using the `break` keyword. If it isn't, prompt the user to input a number that is less than or equal to 15. * Prompt the user to check if they want to continue adding rides or exit. If the user inputs `q`, exit the loop. * You may use the following pseudocode as a guide: ```python # Continuous loop until user chooses to exit # Ask user what ride to add to the amusement park and append to rides list # Continuous loop # Ask user the price of the ride # Conditional: If input can be converted to float # Conditional: If input is <= 15 # Convert input to float and append to prices list # Exit loop # Else # Prompt user about condition # Else # Print an error # Prompt the user to type 'q' to exit if they don't have another ride to add # Conditional: If user input = 'q' # Exit loop ``` ## Bonus If you have time, try this bonus problem to print out the values of the lists you created. * Create a `for` loop that checks the length of the `rides` list to loop through the values of each item in both of the `rides` and `prices` lists. * Inside this `for` loop, perform the following actions: * Create a Boolean variable called `discount` and set it to `False`. * Check if the value of the `prices` list is greater than $5. If it is, apply a 10% discount to the price, and set the `discount` variable to `True`. * Print the name of the ride and the associated price on the same line. The price should be formatted to two decimal places. * Check if the discount was applied. If it was, print out a notice about the 10% discount. * Print out a dash on the same line (`-`) 40 times. * The output may be formatted as follows: ```text Rollercoaster costs $13.50 to ride. A discount of 10% is applied. ---------------------------------------- Helicopter costs $3.50 to ride. ---------------------------------------- ``` ## Hint * `.isdigit()` will only return True for strings that can be converted to positive integers. In order to test for strings that can be converted to floats, we need to check if the string contains a single `.`, and remove it from the string before checking `.isdigit()`. We can do this with the `replace()` method (see [documentation](https://docs.python.org/3/library/stdtypes.html?#str.replace)). `replace()` takes in 2-3 parameters: `replace(find_substring, replace_substring[,max_number_to_replace])`. To remove a single `.`, we would use `replace(".", "", 1)`. --- © 2023 edX Boot Camps LLC. Confidential and Proprietary. All Rights Reserved.
// Copyright (C) 2017 - IIT Bombay - FOSSEE // // This file must be used under the terms of the CeCILL. // This source file is licensed as described in the file COPYING, which // you should have received as part of this distribution. The terms // are also available at // http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt // Organization: FOSSEE, IIT Bombay // Email: toolbox@scilab.in function RPI_lcdClear(fd) // Function to clear the lcd screen // // Calling Sequence // RPI_lcdClear(fd) // // Parameters // fd: file-descriptor obtained using RPI_lcdInit function // // Description // This function clears the lcd screen. // // Examples // RPI_lcdClear(13) // See also // RPI_lcdCursorBlink, RPI_lcdCharDef, RPI_lcdCursor, RPI_lcdDisplay, RPI_lcdHome, RPI_lcdInit, RPI_lcdPutchar, RPI_lcdPosition, RPI_lcdPrintf, RPI_lcdPuts, RPI_lcdSendCommand // // Authors // Jorawar Singh // // Bibliography // http://wiringpi.com/reference/ commande="lCl#1#"+string(fd)+"#"; if getos=="Linux" then unix_w("python -c ""import socket;s=socket.socket();s.connect((''"+RPI_piAdress+"'',9077));s.send(''"+commande+"'');print(s.recv(1024));s.close()"""); elseif getos=="Windows" then RPI_winR=dos("python -c ""import socket;s=socket.socket();s.connect((''"+RPI_piAdress+"'',9077));s.send(''"+commande+"'');print(s.recv(1024));s.close()"""); end endfunction
#include <iostream> using namespace std; //Creating a class node as done in the earlier code class Node{ public: int data; Node* next; Node () { data = 0; next = NULL; } Node (int data) { this->data = data; next = NULL; } }; //get Length function int getLength(Node* head) { int len = 0; while(head != NULL) { head = head->next; len++; } return len; } //Insert at head void insertatHead(Node* &head, int data) { //Step 1 Node* newnode = new Node(data); //Step 2 newnode -> next = head; //Step 3 head = newnode; } //Insert at Tail void insertatTail(Node* &tail , int data) { //Step 1 Node* newnode = new Node(data); //Step 2 tail -> next = newnode; //Step 3 tail = newnode; } //Insert at Position void insertatPos(Node* &head, Node* &tail, int pos, int data) { //Step 1 : Check empty if(head == NULL) return; //Step 2 : Check for the position if(pos == 1) { insertatHead(head, data); return; } else if(pos > getLength(head)) { insertatTail(tail, data); return; } //Step 3 : Insert at any position //subStep 1 : Find prev and curr Node* prev = head; Node* curr = head; int cnt = 0; while(cnt < pos-1) { prev = curr; curr = curr -> next; cnt++; } //subStep 2 : Create a new node Node* newnode = new Node(data); //subSTep 3 : newNode->next = ucrr; newnode -> next = curr; //subStep 4 : prev->next = newNode; prev -> next = newnode; } //Print function as use din previous code void print ( Node* &head) { Node* temp = head; while(temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } int main() { //Making a node Node* first; //Created a node in heap memory first = new Node(10); Node* second; second = new Node(20); Node* third; third = new Node(30); Node* fourth; fourth = new Node(40); Node* fifth; fifth = new Node(50); first->next = second; second->next = third; third->next = fourth; fourth->next = fifth; print(first); insertatPos(first, fifth, 2, 100); print(first); }
class RemoveBtn { constructor(removeCallback) { this.removeBtn = document.createElement("button"); this.removeBtn.className = "removeBtn"; this.removeBtn.innerHTML = removeBtnText; this.removeBtn.onclick = () => { this.removeBtn.parentElement.remove(); // remove the note from the DOM removeCallback(); // remove the note from the notesList }; } } class Note { constructor(id, noteMsg, readOnly, removeCallback) { this.id = id; this.noteMsg = noteMsg; this.createNote(noteMsg, readOnly, removeCallback); } createNote(noteMsg, readOnly, removeCallback) { const note = document.createElement("div"); note.className = "note"; const noteContainer = document.createElement("div"); noteContainer.className = "noteContainer"; noteContainer.contentEditable = !readOnly; noteContainer.textContent = noteMsg; if (!readOnly) { // Chat-GPT generated code: Prevent pasting formatted text noteContainer.addEventListener("paste", (e) => { e.preventDefault(); const text = e.clipboardData.getData("text/plain"); document.execCommand("insertHTML", false, text); }); // update the noteMsg when the user stops typing noteContainer.addEventListener("input", () => { this.noteMsg = noteContainer.textContent; }); } note.appendChild(noteContainer); if (!readOnly) { // If the note is not read only, add the remove button note.appendChild(new RemoveBtn(removeCallback).removeBtn); } document.getElementById("notesList").appendChild(note); return note; } } class NotesList { constructor(readOnly = true) { this.notesList = []; this.readOnly = readOnly; this.clear(); } add(note) { this.notesList.push(note); } remove(noteId) { const index = this.notesList.findIndex((note) => note.id === noteId); if (index > -1) this.notesList.splice(index, 1); } clear() { this.notesList = []; document.getElementById("notesList").innerHTML = ""; } // check if notes exist in localstorage then prepopulate the notesList getNotes() { const storedNotes = JSON.parse(localStorage.getItem("notes")) || []; if (storedNotes.length === 0) return; storedNotes.forEach((note) => { const { id, noteMsg } = note; this.add(new Note(id, noteMsg, this.readOnly, () => this.remove(id))); }); } } function getCurrentTime() { return new Date().toLocaleTimeString("en-US", { hour12: true, hour: "numeric", minute: "numeric", second: "numeric", }); } // If on production, redirect to the base url // else, redirect to the root function returnHome() { const origin = window.location.origin; const baseUrl = window.location.origin + "/COMP4537/labs/1/"; window.location.href = origin.includes("towaquimbayo.com") ? baseUrl : "/"; } function renderWriterPage() { const writeUpdateTimeDom = document.getElementById("writeUpdateTime"); document.getElementById("homeBtn").innerHTML = homeBtnText; const notesList = new NotesList(false); notesList.getNotes(); // prepopulate the notesList const addNoteBtn = document.getElementById("addNoteButton"); addNoteBtn.innerHTML = addNoteBtnText; addNoteBtn.addEventListener("click", () => { const noteId = Date.now().toString(); // Chat-GPT generated code: Generate a unique id notesList.add(new Note(noteId, "", false, () => notesList.remove(noteId))); }); setInterval(() => { localStorage.setItem("notes", JSON.stringify(notesList.notesList)); writeUpdateTimeDom.innerHTML = storedAtText + getCurrentTime(); }, 2000); } function renderReaderPage() { const readUpdateTimeDom = document.getElementById("readUpdateTime"); document.getElementById("homeBtn").innerHTML = homeBtnText; const notesList = new NotesList(); notesList.getNotes(); // prepopulate the notesList setInterval(() => { notesList.clear(); notesList.getNotes(); readUpdateTimeDom.innerHTML = storedAtText + getCurrentTime(); }, 2000); } function renderLandingPage() { document.getElementById("landingTitle").innerHTML = landingTitle; document.getElementById("landingSubtitle").innerHTML = landingSubtitle; document.getElementById("writerBtn").innerHTML = writerBtnText; document.getElementById("readerBtn").innerHTML = readerBtnText; } // Run when the page is loaded window.onload = () => { const path = window.location.pathname.replace("/COMP4537/labs/1", ""); switch (path) { case "/writer/": renderWriterPage(); break; case "/reader/": renderReaderPage(); break; default: renderLandingPage(); break; } };
#include <stdio.h> #include <stdlib.h> struct employee{ int employeeID; char firstName[100]; char lastName[100]; int age; float salary; struct employee *next; }*head=NULL,*tail=NULL,*temp=NULL, *prevtemp=NULL; int countNode(){ temp=head; int count=0; while(temp!=NULL){ temp = temp->next; count++; } return count; } void delete_Employee(){ int ID; printf("Enter Employee ID: "); scanf("%d", &ID); temp = head; if(temp->employeeID == ID){ head = temp->next; return; } while(temp->employeeID != ID){ prevtemp = temp; temp = temp->next; } prevtemp->next = temp->next; } void add_Employee(){ struct employee *newRecord; newRecord = malloc(sizeof(struct employee)); newRecord->next = NULL; printf("\nEnter First Name: "); scanf("%s", newRecord->firstName); printf("Enter Last Name: "); scanf("%s", newRecord->lastName); printf("Enter age: "); scanf("%d", &newRecord->age); printf("Enter Salary: "); scanf("%f", &newRecord->salary); if(head==NULL){ newRecord->employeeID=1; head=newRecord; tail=newRecord; } else { newRecord->employeeID=tail->employeeID+1; // insert newNode in the begining // newRecord -> next = head; // head = newRecord; //inser newNode in the end tail -> next = newRecord; tail=newRecord; } } void display_record(){ int count = countNode(); temp = head; printf("\n***Exist Data OF Employee***"); while(temp !=NULL){ printf("\n\nEmployee ID: %d", temp->employeeID); printf("\nFirst Name: %s", temp->firstName); printf("\nLast Name: %s", temp->lastName); printf("\nAge: %d", temp->age); printf("\nSalary: %.2f", temp->salary); temp = temp -> next; } } int main(){ int menu; while(1){ printf("\n### Single Linked List ###"); printf("\n[1] Create and insert record\n"); printf("[2] Remove or delete existing record\n"); printf("[3] Display records\n"); printf("[4] Count Node\n"); printf(": "); scanf("%d", &menu); switch (menu){ case 1: add_Employee(); break; case 2: delete_Employee(); break; case 3: display_record(); break; case 4: printf("%d", countNode()); break; default: break; } } }
--- import SectionContainer from "../components/landing/SectionContainer.astro"; import EndpointCard from "../components/landing/EndpoitInfo/EnpointCard.astro"; import EndpointItem from "../components/landing/EndpoitInfo/EndpointItem.astro"; import Layout from "../layouts/Layout.astro"; import InfoCard from "../components/landing/apiInfo/InfoCard.astro"; import InfoContent from "../components/landing/apiInfo/InfoContent.astro"; --- <Layout title="Avatar: The Last Airbender API" description="Welcome to the Avatar: The Last Airbender API. This API provides information about the characters of the show." > <main class="px-4"> <SectionContainer class="md:pt-44 pt-32"> <h1 class="md:text-4xl text-2xl font-bold text-center text-transparent bg-clip-text bg-gradient-to-r from-[#E5A052] via-[#E46C5B] to-[#0E579A]" > Avatar: The Last Airbender API </h1> <p class="mt-4 md:text-lg text-center text-pretty"> Welcome to the <strong>Avatar: The Last Airbender API</strong>. This API provides information about the characters, locations, and episodes from the Avatar: The Last Airbender TV show. </p> </SectionContainer> <SectionContainer> <h2 class="text-3xl font-bold text-center text-[#0E579A]">About the API</h2> <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-8"> <InfoCard bgColor="bg-[#E5A052]"> <InfoContent title="Get Character's information" text="Get information about the characters from the show." /> </InfoCard> <InfoCard bgColor="bg-[#0E579A]"> <InfoContent title="Get Episode's information" text="Get information about the episodes from the show." /> </InfoCard> <InfoCard bgColor="bg-[#E46C5B]"> <InfoContent title="To know" text=`For various reasons we do not permit any kind of POST, PUT, or DELETE requests on our API. For those requests, we just send the correct HTTP status code and a message.` /> </InfoCard> <InfoCard bgColor="bg-red-500"> <InfoContent title="Important" text=`This API exclusively includes characters from Avatar: The Last Airbender, and does not encompass characters or versions from The Legend of Korra.` /> </InfoCard> </div> </SectionContainer> <SectionContainer> <h2 class="text-3xl font-bold text-center text-[#0E579A]">How to use?</h2> <h3 class="mt-4 text-center text-pretty mb-8 text-xl"> To get the information, you can use the following endpoints </h3> <EndpointCard cardTitle="Characters" cardColor="bg-[#E5A052]"> <EndpointItem color="bg-[#E46C5B]" title="To get the list of characters, you can use the following endpoint" content="GET /api/characters" /> <EndpointItem color="bg-[#E46C5B]" title="To get a certain character by it's id, you can use the following endpoint" content="GET /api/characters/:id" /> <EndpointItem color="bg-[#E46C5B]" title="To get a certain character by it's name, you can use the following endpoint" content="GET /api/characters/:id" /> </EndpointCard> <p class="text-pretty text-center"> These endpoints returns a JSON that you can use in your app to get any information about any character that we have available. To get more information please visit our <a href="/docs" class="text-blue-600 underline">docs</a >. </p> </SectionContainer> </main> </Layout>
# Audit Log Service This is a mock API intended to capture and query audit events. Built with Golang and MongoDB, it leverages JWT for authentication. ## Overview The API allows users to: - Obtain a **JWT** token for protected routes. - **Create** an audit log event. - **Query** audit log events based on specific parameters. ## Getting started ### Installation This is a **dockerized** service. 1. Clone repository 2. Cd to **./canonicalAuditlog** 3. run `./deploy.sh` in terminal 4. The shell script is designed to set up the service in **ubuntu**. 5. The script installs **docker** and **docker-compose** if not already installed. 6. A **docker daemond** is also spun up with `sudo systemctl start docker` 7. A **binary** is also built and run automatically. 8. **Dockerfile** handles the remaining dependencies. ## API ### JWT - GET The API uses **JWT authentication**. A token must be acquired first by hitting the **/jwt** endpoint. \ This token must then be used in the Authorization header with the **"Bearer"** prefix for other API calls. ### Usage ```bash curl -X GET http://localhost:8080/jwt ``` ```bash # Example Response {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTg2ODcyODl9.xUgLlNSCMOJsxFJwWDvl8RiMhMaY73tFnkezp7bGacw"} ``` This **JWT token** will be used to authenticate the remaining endpoints. ### EVENTS/CREATE - POST Creates a new audit log event. Requires a **JWT token** in the Authorization header. ### Usage ```bash curl -X POST http://localhost:8080/events/create \ -H "Authorization: Bearer <TOKEN>" \ -H "Content-Type: application/json" \ -d '{"event_type": "type", "service_name": "service", "customer_id": "12345", "event_details": {"key": "value"}}' ``` ```bash curl -X POST http://localhost:8080/events/create \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTc0MjQwODJ9.yRJklHq-UqUENmgdpB4UEopfT9JiJKL9L3T-fS4VCZA" \ -H "Content-Type: application/json" \ -d '{ "event_type": "item_review", "service_name": "review_service", "customer_id": "cus_118", "event_details": { "action": "submitted_review", "item_id": "item892", "rating": 0, "comment": "Bad" } }' ``` ```bash # Example Response 200 ``` **All** fields shown in the request are required. ### EVENTS/QUERY - GET Retrieves events based on query parameters. Requires a **JWT token** in the Authorization header. ### Usage ```bash curl -X GET http://localhost:8080/events/query?param=value \ -H 'Content-Type: text/plain' \ -H "Authorization: Bearer <TOKEN>" ``` ```bash curl -X GET http://localhost:8080/events/query?customer_id=cus_118 \ -H 'Content-Type: text/plain' \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ0b2tlbiI6ImV5SmhiR2NpT2lKSVV6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUpsZUhBaU9qRTJPVGcyT0RjeU9EbDkueFVnTGxOU0NNT0pzeEZKd1dEdmw4UmlNaE1hWTczdEZua2V6cDdiR2FjdyJ9.Qk1z90_ZMvf-l2IoTJ8rZIbh_uTLEbC3Fgj0aEmNHHU" ``` ```bash # Example Response [{"event_id":"652c96550ea634877babe4d9","event_type":"item_review","timestamp":"2023-10-16T01:48:05.073Z","service_name":"review_service","customer_id":"cus_118","event_details":{"action":"submitted_review","comment":"Very satisfactory!","item_id":"item892","rating":4}}, {"event_id":"652c978b0ea634877babe4da","event_type":"item_review","timestamp":"2023-10-16T01:53:15.164Z","service_name":"review_service","customer_id":"cus_118","event_details":{"action":"submitted_review","comment":"Bad","item_id":"item892","rating":0}}] ``` **Multiple query parameters are supported.** ## Schema ```go type Event struct { EventID primitive.ObjectID `json:"event_id" bson:"_id,omitempty"` EventType string `json:"event_type" bson:"event_type"` Timestamp time.Time `json:"timestamp" bson:"timestamp"` ServiceName string `json:"service_name" bson:"service_name"` CustomerID string `json:"customer_id" bson:"customer_id"` EventDetails map[string]interface{} `json:"event_details" bson:"event_details"` } ``` The **Event schema** is designed to capture audit log events with the following fields: - **EventID:** A unique identifier for each event. Using MongoDB's ObjectID ensures uniqueness across any distributed scenario. **Filled automatically** - **EventType:** Helps categorize the event. Useful in filtering and querying events of a certain type. e.g. **profile_updated**, **account_created**, **customer_billed** - **Timestamp:** Automatically set to the current time when an event is created. Essential for audit logs to track when events occurred. **Filled automatically** - **ServiceName:** Identifies which service in your infrastructure caused the event. e.g. **account_service**, **billing_service**, **resource_service** - **CustomerID:** Helps tie an event to a particular customer/user. Useful for understanding user behavior and auditing specific user actions. - **EventDetails:** A flexible map for any additional information about the event. This ensures the schema is extensible for future needs. This schema is versatile and can be adapted to accommodate various event types and details. - **Schema Flexibility:** MongoDB is schema-less. Given the nature of audit logs, over time, the data that needs to be logged might evolve. New types of events or additional fields might need to be logged. With MongoDB, this is easily possible without having to change the schema or run migrations. - **Scalability:** MongoDB is designed to be scalable. It can handle huge amounts of data and offers horizontal scalability via sharding. This is particularly useful for logging systems which tend to generate large amounts of data over time. - **High Write Throughput:** Audit logging systems typically have high write operations compared to read operations. MongoDB performs very well in scenarios with high write loads, thanks to its asynchronous write operations. - **Indexing:** To make read operations faster, especially in scenarios where specific logs need to be retrieved based on certain criteria, MongoDB offers indexing. This ensures that logs can be queried efficiently even as the volume grows.
INPUT FILES: conf.h: Header containing data structures and other headers used for distributed computing dcs.c: Program file containing code to implement distributed computing algorithm Makefile: makefile to build the code and link to executable COMPILATION: Have both dcs.c and conf.h in the same directory. Run below commands to generate object as well as executable. make -f Makefile EXECUTABLE: dcs OUTPUT FILES: OUTPUT<processid>.txt ==> contains the latency and messages exchanged at each stage and at the end of computation. rw.txt ==> File containing critical section operations of processes. ASSUMPTIONS: Tests are run on linux machines. Since 10 processes are the requirement, 10 nodes are taken(DC01, DC02, DC03, DC04, DC05, DC06, DC07, DC08, DC09, DC10). Distributed System initial setup phase is out of scope. IPs are hardcoded and proceses are to start from 0 to 9 in the same order. Mutual Exclusion algorithm doesn't start until all processes are connected to each other. There is no recovery mechanism after mutual exclusion starts. Distributed system ends computation even if one process exits during execution. INITIAL CONNECTION PHASE: 1. Each process connects to server IP address above its IP address in serverIPs and waits for connection from other processes in serverIPs. So, it is expected to run dcs in the same order as given below. 2. After connection to other servers as a client, each process starts its own server and waits for connection from other servers. 3. Server on receiving connection from a client, checks client state in channel[i].outgoingState and connects to it if state is DISCONNECTED/INITED as client. 4. On successful connection to all processes(9 processes), each process starts a timer based on random values between [5, 10]. 5. Once timer expires, mutual execution algorithm is run (COMPUTATION START). Example: 1. process 0 starts on DC01. 2. process 0 checks other server IP address above DC01 ip address. Since there are no ip addresses above it, it will stop trying to connect as client. 3. process 0 starts server and waits for connection. 4. process 1 starts on DC02. 5. process 1 checks other server IP addresses above DC02 ip address and finds DC01 ip address. process 1 then connects to DC01 server and starts server on DC02. 6. process 0 on receiving connection from process 1, process 0 connects to process 1 as client. 7. Two way connections are established and ready. INSTRUCTIONS TO RUN DCS(Distributed Computing System): Run the following command on terminals of (DC01, DC02, DC03, DC04, DC05, DC06, DC07, DC08, DC09, DC10) in the SAME STRICT order. ./dcs 0 #==> DC01 ./dcs 1 #==> DC02 ./dcs 2 #==> DC03 ./dcs 3 #==> DC04 ./dcs 4 #==> DC05 ./dcs 5 #==> DC06 ./dcs 6 #==> DC07 ./dcs 7 #==> DC08 ./dcs 8 #==> DC09 ./dcs 9 #==> DC10 FUTURE IMPROVEMENTS: 1. Improve initial setup phase. IPs are hardcoded to run 10 processes between DC01...DC10. Improvements can be attained by mDns to identify the type of service the server runs and attach to it. 2. System halts if even one processes gives up. Fault tolerance to be added to recover from such situations and continue with the computation. 3. Reduce the redundant code in various routines and move it to one routine. THEORITICAL OBSERVATIONS: With given instructions for critical section entry, each process exchanges maximum of 1440(40 rounds critical section entries with 2*(10-1) exchanged per critical section) messages in total. Computation ends after process 0 receives 9 COMPUTATION_END messages from rest of the processes and process 0 computation end. OBSERVATIONS AFTER RUNNING DCS: 1. Since all processes running PHASE1(10 in phase1, 5 in phase1 when phase2 is running) and/or PHASE2(5 in phase2) fall under [5,10] and [45,50] time interval range, effect of holding the token is not seen. 2. If only, 2 or 3 processes are run in PHASE1 and/or PHASE2, effect of holding token is seen and messages exchanged during such section entry is zero. OUTPUTS: As seen in OUTPUT<process id>.txt and computed in theoritical observations: process 0 sends 720 messages, receives 720 + 9 messages ==> 1440(critical section) + 9(computation end messages) process 1 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 2 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 3 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 4 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 5 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 6 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 7 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 8 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) process 9 sends 720 + 1 messages, receives 720 messages ==> 1440(critical section) + 1(computation end message) rw.txt ==> contains the critical section entry of each process and its timestamp
// Copyright 2024 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert} from 'chrome://resources/js/assert.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.js'; import {createCustomEvent} from '../utils/event_utils.js'; import {getPrintPreviewPageHandler} from '../utils/mojo_data_providers.js'; import {PrinterStatusReason, type PrintPreviewPageHandler, PrintTicket, SessionContext} from '../utils/print_preview_cros_app_types.js'; import {DESTINATION_MANAGER_ACTIVE_DESTINATION_CHANGED, DestinationManager} from './destination_manager.js'; import {DEFAULT_PARTIAL_PRINT_TICKET} from './ticket_constants.js'; /** * @fileoverview * 'print_ticket_manager' responsible for tracking the active print ticket and * signaling updates to subscribed listeners. */ export const PRINT_REQUEST_STARTED_EVENT = 'print-ticket-manager.print-request-started'; export const PRINT_REQUEST_FINISHED_EVENT = 'print-ticket-manager.print-request-finished'; export const PRINT_TICKET_MANAGER_SESSION_INITIALIZED = 'print-ticket-manager.session-initialized'; export class PrintTicketManager extends EventTarget { private static instance: PrintTicketManager|null = null; static getInstance(): PrintTicketManager { if (PrintTicketManager.instance === null) { PrintTicketManager.instance = new PrintTicketManager(); } return PrintTicketManager.instance; } static resetInstanceForTesting(): void { PrintTicketManager.instance = null; } // Non-static properties: private printPreviewPageHandler: PrintPreviewPageHandler|null; private printRequestInProgress = false; private printTicket: PrintTicket|null = null; private sessionContext: SessionContext; private destinationManager: DestinationManager = DestinationManager.getInstance(); private eventTracker = new EventTracker(); // Prevent additional initialization. private constructor() { super(); // Setup mojo data providers. this.printPreviewPageHandler = getPrintPreviewPageHandler(); } // `initializeSession` is only intended to be called once from the // `PrintPreviewCrosAppController`. initializeSession(sessionContext: SessionContext): void { assert( !this.sessionContext, 'SessionContext should only be configured once'); this.sessionContext = sessionContext; // TODO(b/323421684): Uses session context to configure ticket properties // and validating ticket matches policy requirements. this.printTicket = { // Set print ticket defaults. ...DEFAULT_PARTIAL_PRINT_TICKET, printPreviewId: this.sessionContext.printPreviewId, previewModifiable: this.sessionContext.isModifiable, shouldPrintSelectionOnly: this.sessionContext.hasSelection, } as PrintTicket; const activeDest = this.destinationManager.getActiveDestination(); if (activeDest === null) { this.printTicket.destination = ''; this.eventTracker.add( this.destinationManager, DESTINATION_MANAGER_ACTIVE_DESTINATION_CHANGED, (): void => this.onActiveDestinationChanged()); } else { this.printTicket.destination = activeDest.id; this.printTicket.printerType = activeDest.printerType; this.printTicket.printerManuallySelected = activeDest.printerManuallySelected; this.printTicket.printerStatusReason = activeDest.printerStatusReason || PrinterStatusReason.UNKNOWN_REASON; } // TODO(b/323421684): Apply default settings from destination capabilities // once capabilities manager has fetched active destination capabilities. this.dispatchEvent( createCustomEvent(PRINT_TICKET_MANAGER_SESSION_INITIALIZED)); } // Handles notifying start and finish print request. Sends latest print ticket // state along with request. // TODO(b/323421684): Update print ticket prior to sending to set // headerFooterEnabled to false to align with Chrome preview behavior. sendPrintRequest(): void { assert(this.printPreviewPageHandler); if (this.printTicket === null) { // Print Ticket is not ready to be sent. return; } if (this.printRequestInProgress) { // Print is already in progress, wait for request to resolve before // allowing a second attempt. return; } this.printRequestInProgress = true; this.dispatchEvent(createCustomEvent(PRINT_REQUEST_STARTED_EVENT)); // TODO(b/323421684): Handle result from page handler and update UI if error // occurred. this.printPreviewPageHandler!.print(this.printTicket).finally(() => { this.printRequestInProgress = false; this.dispatchEvent(createCustomEvent(PRINT_REQUEST_FINISHED_EVENT)); }); } // Does cleanup for print request. cancelPrintRequest(): void { assert(this.printPreviewPageHandler); this.printPreviewPageHandler!.cancel(); } isPrintRequestInProgress(): boolean { return this.printRequestInProgress; } // Returns true only after the `initializeSession` function has been called // with a valid `SessionContext`. isSessionInitialized(): boolean { return !!this.sessionContext; } getPrintTicketForTesting(): PrintTicket|null { return this.printTicket; } // Handles setting initial active destination in print ticket if not already // set. Removes listener once destination is set in print ticket. After the // initial change, future updates to active destination will start in the // print ticket manager. private onActiveDestinationChanged(): void { // Event listener added by initializeSession; print ticket will not be null. assert(this.printTicket); const activeDest = this.destinationManager.getActiveDestination(); if (activeDest === null) { return; } if (this.printTicket!.destination === '') { this.printTicket!.destination = activeDest.id; this.printTicket!.printerType = activeDest.printerType; this.printTicket!.printerManuallySelected = activeDest.printerManuallySelected; this.printTicket!.printerStatusReason = activeDest.printerStatusReason || PrinterStatusReason.UNKNOWN_REASON; } this.eventTracker.remove( this.destinationManager, DESTINATION_MANAGER_ACTIVE_DESTINATION_CHANGED); } } declare global { interface HTMLElementEventMap { [PRINT_REQUEST_FINISHED_EVENT]: CustomEvent<void>; [PRINT_REQUEST_STARTED_EVENT]: CustomEvent<void>; } }
import { Exclude } from "class-transformer"; import { Entity, Column, CreateDateColumn, UpdateDateColumn, PrimaryGeneratedColumn, JoinTable, OneToMany, } from "typeorm"; import { v4 as uuid } from "uuid"; //generate random id import { UserJWTToken } from "./UserJWTToken"; @Entity("users") export class User { @PrimaryGeneratedColumn("uuid") readonly id: string; @Column({ nullable: false }) name: string; @Column({ nullable: false }) email: string; @Column({ nullable: true }) admin: boolean; @Exclude() @Column({ nullable: false }) password: string; @Column({ nullable: false, default: true }) is_active: boolean; @CreateDateColumn() created_at: Date; @UpdateDateColumn() updated_at: Date; @OneToMany(() => UserJWTToken, (userJWTToken) => userJWTToken.user) @JoinTable() userJWTToken: UserJWTToken; constructor() { if (!this.id) { this.id = uuid(); } } }
/* @HEADER@ */ // ************************************************************************ // // Sundance // Copyright 2011 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Kevin Long (kevin.long@ttu.edu) // /* @HEADER@ */ #ifndef SUNDANCE_SPARSITYSUPERSET_H #define SUNDANCE_SPARSITYSUPERSET_H #include "SundanceDefs.hpp" #include "SundanceDefs.hpp" #include "SundanceDerivSet.hpp" #include "SundanceDeriv.hpp" #include "SundanceMultipleDeriv.hpp" #include "SundanceMap.hpp" #include "SundanceEvalVector.hpp" #include "Teuchos_RefCountPtr.hpp" #include "Teuchos_Array.hpp" namespace Sundance { using namespace Sundance; using namespace Teuchos; /** * DerivState can be used to classify the known state of * each functional derivative at any node in the expression * tree. ZeroDeriv means the derivative is structurally * zero at that node -- note that derivatives that are * nonzero at a root node can be structurally zero at some * child node. ConstantDeriv means that the derivative is * known to be a constant (in space) at that * node. VectorDeriv means that the derivative is non-zero, * non-constant, i.e., a vector of values. */ enum DerivState {ZeroDeriv, ConstantDeriv, VectorDeriv}; /** * */ class SparsitySuperset : public ObjectWithClassVerbosity<SparsitySuperset> { public: /** Create a sparsity set */ SparsitySuperset(const Set<MultipleDeriv>& C, const Set<MultipleDeriv>& V); /** \name Access to information about individual derivatives */ //@{ /** Detect whether a given derivative exists in this set */ bool containsDeriv(const MultipleDeriv& d) const ; /** Find the index at which the results for the given functional derivative are stored in the results array */ int getIndex(const MultipleDeriv& d) const ; /** Return the results stored at index i */ inline const MultipleDeriv& deriv(int i) const {return derivs_[i];} /** Return the constancy state of deriv i */ inline const DerivState& state(int i) const {return states_[i];} /** */ inline int numDerivs() const {return derivs_.size();} /** */ int numConstantDerivs() const {return numConstantDerivs_;} /** */ int numVectorDerivs() const {return numVectorDerivs_;} /** */ int maxOrder() const {return maxOrder_;} /** Indicate whether the specified derivative is * spatially constant at this node */ bool isConstant(int i) const {return states_[i]==ConstantDeriv;} /** Indicate whether the specified multiple derivative contains * at least one order of spatial differentiation */ bool isSpatialDeriv(int i) const { return multiIndex_[i].order() != 0; } /** Return the spatial multi index for the i-th derivative */ const MultiIndex& multiIndex(int i) const {return multiIndex_[i];} //@} /** */ void print(std::ostream& os) const ; /** */ void print(std::ostream& os, const Array<RCP<EvalVector> >& vecResults, const Array<double>& constantResults) const ; /** */ std::string toString() const ; /** */ DerivSet derivSet() const ; private: /** Add a derivative to the set. Called by the subset's addDeriv() * method. */ void addDeriv(const MultipleDeriv& d, const DerivState& state); /** Add a derivative to the set. Called by the subset's addDeriv() * method. */ void addDeriv(const Deriv& d, const DerivState& state); /** */ int maxOrder_; /** Map from deriv to position of the derivative's * value in the results array */ Sundance::Map<MultipleDeriv, int> derivToIndexMap_; /** The list of functional derivatives whose values are * stored in this results set */ Array<MultipleDeriv> derivs_; /** The state of each derivative at this node in the expression */ Array<DerivState> states_; /** Multiindices */ Array<MultiIndex> multiIndex_; /** */ int numConstantDerivs_; /** */ int numVectorDerivs_; }; } namespace std { /** \relates SparsitySuperset */ inline std::ostream& operator<<(std::ostream& os, const Sundance::SparsitySuperset& s) { s.print(os); return os; } } #endif
package com.example.lab3 import android.app.DatePickerDialog import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.view.inputmethod.EditorInfo import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.ImageButton import android.widget.RadioButton import android.widget.RadioGroup import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.constraintlayout.widget.Group import com.example.lab3.model.Person import com.example.lab3.model.Student import com.example.lab3.model.Worker import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.util.Calendar /** * @authors : Rayane Annen et Hugo Ducommun */ class PersonController : AppCompatActivity() { // base widgets private lateinit var nameEditText: EditText private lateinit var firstNameEditText: EditText private lateinit var birthDayEditText: EditText private lateinit var cakeButton: ImageButton private lateinit var nationalitySpinner: Spinner private lateinit var occupationRadioGroup: RadioGroup private lateinit var studentRadioButton: RadioButton private lateinit var workerRadioButton: RadioButton // student widgets private lateinit var studentGroup: Group private lateinit var schoolEditText: EditText private lateinit var graduationYearEditText: EditText // worker widgets private lateinit var workerGroup: Group private lateinit var companyEditText: EditText private lateinit var sectorSpinner: Spinner private lateinit var experienceEditText: EditText // Additional information private lateinit var additionalTitle: TextView private lateinit var emailEditText: EditText private lateinit var remarkEditText: EditText // Buttons private lateinit var cancelButton: Button private lateinit var saveButton: Button // Setup DatePicker private val pickedDate: Calendar = Calendar.getInstance() private lateinit var datePickerDialog: DatePickerDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // load widgets loadWidgets() // manage visibility when radio button is clicked handleVisibilityGroup() // setup spinner with default text setupSpinner(nationalitySpinner, R.string.nationality_empty, R.array.nationalities) setupSpinner(sectorSpinner, R.string.sectors_empty, R.array.sectors) // setup click events cancelButton.setOnClickListener { resetGui() } saveButton.setOnClickListener { createPerson() } cakeButton.setOnClickListener { showDatePicker() } // Load the person with the object passed in argument in the form with its value remarkEditText.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { createPerson() true } false } // load default example loadPerson(Person.exampleWorker) } // prevent memory leak when changing device orientation override fun onDestroy(){ super.onDestroy(); if (datePickerDialog != null && datePickerDialog.isShowing()) { datePickerDialog.dismiss(); } } private fun loadPerson(obj: Person) { // load fields based on obj nameEditText.setText(obj.name) firstNameEditText.setText(obj.firstName) setPickedDate(obj.birthDay.get(Calendar.YEAR), obj.birthDay.get(Calendar.MONTH), obj.birthDay.get(Calendar.DAY_OF_MONTH)) emailEditText.setText(obj.email) val nationalities = resources.getStringArray(R.array.nationalities) nationalitySpinner.setSelection(nationalities.indexOf(obj.nationality) + 1) if (obj is Student) { // load student fields studentRadioButton.isChecked = true studentRadioButton.callOnClick() schoolEditText.setText(obj.university) graduationYearEditText.setText(obj.graduationYear.toString()) } else if (obj is Worker) { // load worker fields val sectors = resources.getStringArray(R.array.sectors) sectorSpinner.setSelection(sectors.indexOf(obj.sector) + 1) workerRadioButton.isChecked = true workerRadioButton.callOnClick() companyEditText.setText(obj.company) experienceEditText.setText(obj.experienceYear.toString()) } if (obj.remark.isNotEmpty()) { remarkEditText.setText(obj.remark) } } // function to create a person based on the form private fun createPerson() { Log.d("createPerson", nationalitySpinner.selectedItemId.toString()) // if basic fields are empty, show a toast and return if (nameEditText.text.isEmpty() || firstNameEditText.text.isEmpty() || birthDayEditText.text.isEmpty() || nationalitySpinner.selectedItemId < 1 || emailEditText.text.isEmpty()) { Toast.makeText(this, resources.getString(R.string.missing_fields), Toast.LENGTH_LONG).show() return } if (studentRadioButton.isChecked) { if (schoolEditText.text.isEmpty() || graduationYearEditText.text.isEmpty()) { Toast.makeText(this, resources.getString(R.string.missing_fields), Toast.LENGTH_LONG).show() return } val s = Student ( nameEditText.text.toString(), firstNameEditText.text.toString(), pickedDate, nationalitySpinner.selectedItem.toString(), schoolEditText.text.toString(), graduationYearEditText.text.toString().toInt(), emailEditText.text.toString(), remarkEditText.text.toString() ) Log.i("Student", s.toString()) Toast.makeText(this, resources.getString(R.string.success), Toast.LENGTH_LONG).show() } else { if (companyEditText.text.isEmpty() || sectorSpinner.selectedItemId < 1 || experienceEditText.text.isEmpty()) { Toast.makeText(this, resources.getString(R.string.missing_fields), Toast.LENGTH_LONG).show() return } val w = Worker ( nameEditText.text.toString(), firstNameEditText.text.toString(), pickedDate, nationalitySpinner.selectedItem.toString(), companyEditText.text.toString(), sectorSpinner.selectedItem.toString(), experienceEditText.text.toString().toInt(), emailEditText.text.toString(), remarkEditText.text.toString() ) Log.d("Worker", w.toString()) Toast.makeText(this, resources.getString(R.string.success), Toast.LENGTH_LONG).show() } } private fun loadWidgets() { nameEditText = findViewById(R.id.edit_main_base_name_title) firstNameEditText = findViewById(R.id.edit_main_base_firstname_title) birthDayEditText = findViewById(R.id.edit_main_base_birthday_title) cakeButton = findViewById(R.id.btn_main_base_birthday_title) nationalitySpinner = findViewById(R.id.spinner_main_base_nationality) occupationRadioGroup = findViewById(R.id.radio_group_occupation) studentRadioButton = findViewById(R.id.occupation_choice_1) workerRadioButton = findViewById(R.id.occupation_choice_2) studentGroup = findViewById(R.id.group_Student_Specific) schoolEditText = findViewById(R.id.edit_main_specific_school_title) graduationYearEditText = findViewById(R.id.edit_main_specific_graduationyear_title) workerGroup = findViewById(R.id.group_Worker_Specific) companyEditText = findViewById(R.id.edit_main_specific_compagny) sectorSpinner = findViewById(R.id.spinner_main_specific_sector) experienceEditText = findViewById(R.id.edit_main_specific_experience_title) additionalTitle = findViewById(R.id.additional_title) emailEditText = findViewById(R.id.edit_additional_email_title) remarkEditText = findViewById(R.id.edit_additional_remark_title) cancelButton = findViewById(R.id.btn_cancel) saveButton = findViewById(R.id.btn_ok) } // setup a spinner with a default text that is not selectable // adapted from https://www.tutorialspoint.com/how-to-make-an-android-spinner-with-initial-default-text private fun setupSpinner(spinner: Spinner, defaultTextId: Int, options: Int) { val optionsArray = arrayOf(resources.getString(defaultTextId)) + resources.getStringArray(options) val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, optionsArray) arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = arrayAdapter } // reset the form private fun resetGui() { nameEditText.text.clear() firstNameEditText.text.clear() birthDayEditText.text.clear() nationalitySpinner.setSelection(0) occupationRadioGroup.clearCheck() schoolEditText.text.clear() graduationYearEditText.text.clear() companyEditText.text.clear() sectorSpinner.setSelection(0) experienceEditText.text.clear() emailEditText.text.clear() remarkEditText.text.clear() // set picked date to today pickedDate.time = Calendar.getInstance().time // hide student and worker group studentGroup.visibility = View.GONE workerGroup.visibility = View.GONE } // setup date picker dialog private fun showDatePicker() { // https://devendrac706.medium.com/date-picker-using-kotlin-in-android-studio-datepickerdialog-android-studio-tutorial-kotlin-3bbc606585a // Create a DatePickerDialog val listener = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth -> setPickedDate(year, month, dayOfMonth) } datePickerDialog = DatePickerDialog(this, listener, pickedDate.get(Calendar.YEAR), pickedDate.get(Calendar.MONTH), pickedDate.get(Calendar.DAY_OF_MONTH)) datePickerDialog.setTitle(resources.getString(R.string.main_base_birthdate_title)) // Show the DatePicker dialog datePickerDialog.show() } // define the picked date when selected from the date picker private fun setPickedDate(year: Int, month: Int, day: Int) { val date = LocalDate.of(year, month + 1, day) // month is 0-indexed pickedDate.set(year, month, day) val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) birthDayEditText.setText(dateFormat.format(date)) } // hide or show student and worker group based on radio button private fun handleVisibilityGroup() { studentGroup.visibility = View.GONE workerGroup.visibility = View.GONE studentRadioButton.setOnClickListener { studentGroup.visibility = View.VISIBLE workerGroup.visibility = View.INVISIBLE } workerRadioButton.setOnClickListener { studentGroup.visibility = View.GONE workerGroup.visibility = View.VISIBLE } } }
import LogoIcon from "../../branding/logo/icon/index"; import { HeaderStyle, UnitBalanceBox } from "./style"; import IconButton from "@mui/material/IconButton"; import DarkModeIcon from "@mui/icons-material/DarkMode"; import LightModeIcon from "@mui/icons-material/LightMode"; import { useContext, useEffect, useState } from "react"; import { useTheme } from "../../../theme/theme"; import themes from "../../../theme/schema"; import { Button } from "../../items/buttons/style"; import { useConnect } from "../../../hooks/useConnect"; import { useMoralis } from "react-moralis"; import AvatarPic from "../../core/avatar/index"; import { PopperEmpty } from "../../items/popper/index"; import { Title } from "../../items/typography/Title/index"; import { useAppNavigation } from "../../../hooks/useAppNavigation"; import Link from "../../../node_modules/next/link"; import { UserContext } from "../../../contexts/UserContextProvider"; import { useUnitBalance } from "../../../hooks/UnitToken/useUnitBalance"; import { useMintUnit } from "../../../hooks/UnitToken/useMintUnit"; import { toast } from "react-toastify"; export default function Header({ changeTheme, selectedTheme }) { const { login, disconnect } = useConnect(); const { isAuthenticated, user, account, refetchUserData } = useMoralis(); const { goToProfile, goToNewLoop } = useAppNavigation(); const { userDetail, getUserDetail, unitBalance } = useContext(UserContext); const { getUnitBalance } = useUnitBalance(); const { mintUnitToken } = useMintUnit({ amount: 2000 }); useEffect(() => { getUserDetail(); getUnitBalance(); }, [user, account]); return ( <HeaderStyle> <Link href={"/"}> <div className="flex align-items-center" style={{ gap: 10, cursor: "pointer" }} > <LogoIcon size="medium" /> <h1>Rainbows DAO</h1> </div> </Link>{" "} <div className="flex align-items-center" style={{ gap: 10 }}> <IconButton> {selectedTheme.name === "Light" ? ( <DarkModeIcon onClick={changeTheme} className="icon" /> ) : ( <LightModeIcon onClick={changeTheme} className="icon" /> )}{" "} </IconButton> {isAuthenticated && user && account ? ( <PopperEmpty autoOpen={true} opener={ <div className="flex align-items-center"> <UnitBalanceBox>{unitBalance} $UNIT</UnitBalanceBox> <AvatarPic size="medium" imgSrc={userDetail?.avatar} cursor={"pointer"} /> </div> } height="fit-content" > <> <Link href={`${goToProfile(userDetail?.wallet)}`}> <Title clickable small> Profile </Title> </Link>{" "} <Link href={`${goToNewLoop()}`}> <Title clickable small> Create a Loop </Title> </Link>{" "} <hr /> <Title clickable small onClick={() => { navigator.clipboard.writeText(userDetail?.wallet); toast.success( `Wallet address copied! Opening faucet page to a new tab!` ); setTimeout(function () { window.open("https://faucet.polygon.technology/", "_blank"); }, 3000); }} > Claim Testnet $MATIC </Title> <Title clickable small onClick={() => mintUnitToken()}> Mint $UNIT </Title> <hr /> <Title clickable small onClick={() => disconnect()}> Log out </Title> </> </PopperEmpty> ) : ( <Button outline onClick={() => login()}> Connect </Button> )} </div> <div className="line rainbow-background"></div> </HeaderStyle> ); }
from imports import * from datamodule import * from init import labels_to_int ,int_to_labels # For converting XML annotations to YOLO format for a single image def convert_xml_to_YOLOformat(source, destination,labels_to_int): """ Converts XML annotations to YOLO format for a single image. Parameters: - source (str): Path to the source XML file. - destination (str): Path to the destination TXT file (YOLO format). Returns: None """ tree = ET.parse(source) root = tree.getroot() # Get image size image_size = root.find("size") image_width = int(image_size.find("width").text) image_height = int(image_size.find("height").text) # Open a TXT file for writing txt_filename = destination with open(txt_filename, 'w') as txtfile: # Extract data and write lines for obj in root.findall("object"): tree_type = obj.find("tree").text damage = obj.find("damage").text bndbox = obj.find("bndbox") xmin = float(bndbox.find("xmin").text) ymin = float(bndbox.find("ymin").text) xmax = float(bndbox.find("xmax").text) ymax = float(bndbox.find("ymax").text) # Convert coordinates to YOLO format with normalization x_center = (xmin + xmax) / 2.0 / image_width y_center = (ymin + ymax) / 2.0 / image_height width = (xmax - xmin) / image_width height = (ymax - ymin) / image_height # Format the line based on tree type and damage if tree_type == "Other": label = labels_to_int[tree_type] line = f"{label} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n" else: label = labels_to_int[f"{tree_type}-{damage}"] line = f"{label} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n" txtfile.write(line) print(f"TXT file '{txt_filename}' has been created.") def resize_image(source,destination,new_size=(640,640)): """ Resize an image and save the resized image to the destination directory. Parameters: - source (str): Path to the source image file. - destination (str): Path to the destination directory. - new_size (tuple): Tuple specifying the new size (width, height) for the resized image. Returns: None """ filename =source.split("/")[-1] try: # Open the image file image_path = source img = Image.open(image_path) # Resize the image resized_img = img.resize(new_size) # Save the resized image to the destination directory destination_path = f"{destination}/{filename}" resized_img.save(destination_path) print(f"Resized {filename} successfully.") except Exception as e: print(f"Error processing {filename}: {e}") def clean_and_preprocess_data(source, train_dir, test_dir, val_dir, split_ratio=(0.8, 0.1, 0.1)): """ Cleans and preprocesses data by splitting them into training, testing, and validation sets. Converts XML annotations to YOLO format for each image. Parameters: - source (str): Path to the source directory. - train_dir (str): Path to the training set directory. - test_dir (str): Path to the testing set directory. - val_dir (str): Path to the validation set directory. - split_ratio (tuple): Split ratios for training, testing, and validation. Returns: None """ text_extension = ".txt" images_dir = "images" labels_dir = "labels" directory_to_create = [train_dir, test_dir, val_dir] for directory in directory_to_create: create_directory(f"{directory}/{images_dir}/") create_directory(f"{directory}/{labels_dir}/") # Iterate through the source directories for category in sorted(os.listdir(source)): annotation_files, image_files, annotation_path, image_path = get_files_and_path(source, category, directory_to_create) if annotation_files == 0: continue gathered_list = gather_image_annotation(annotation_files, image_files) shuffled_list = random.sample(gathered_list, len(gathered_list)) train_split, test_split = split_spot(gathered_list=gathered_list, split_ratio=split_ratio) # Move files to respective directories for i, anot_imag in enumerate(shuffled_list): try: root = anot_imag[0].split(".")[0] src_path_annotation, src_path_image = create_src_path(anot_imag, annotation_path, image_path) dest_path = ( train_dir if i < train_split else test_dir if i < test_split else val_dir ) convert_xml_to_YOLOformat(source=src_path_annotation, destination=f"{dest_path}/{labels_dir}/{root}{text_extension}",labels_to_int=labels_to_int) resize_image(source=src_path_image,destination=f"{dest_path}/{images_dir}") except Exception as e: print(f"Error {e}") if __name__ == "__main__": source_directory = "Larch_Dataset" destination_directory = "Data" train_directory = f"{destination_directory}/train" test_directory = f"{destination_directory}/test" val_directory = f"{destination_directory}/valid" clean_and_preprocess_data(source_directory, train_directory, test_directory, val_directory)
import 'package:final_project_firebase/Themes/app_colors.dart'; import 'package:final_project_firebase/router/app_router.dart'; import 'package:final_project_firebase/views/home/home2_screen.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; enum MenuState { home, favourite, message, profile } class CustomBottomNavBar extends StatelessWidget { const CustomBottomNavBar({ Key? key, required this.selectedMenu, }) : super(key: key); final MenuState selectedMenu; @override Widget build(BuildContext context) { final Color inActiveIconColor = Color(0xFFB6B6B6); return Container( padding: EdgeInsets.symmetric(vertical: 14), decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( offset: Offset(0, -15), blurRadius: 20, color: Color(0xFFDADADA).withOpacity(0.15), ), ], borderRadius: BorderRadius.only( topLeft: Radius.circular(40), topRight: Radius.circular(40), ), ), child: SafeArea( top: false, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ IconButton( icon: SvgPicture.asset( "assets/icons/Shop Icon.svg", color: MenuState.home == selectedMenu ? AppColors.kPrimaryColor : inActiveIconColor, ), onPressed: () => AppRouter.appRouter.goToWidget(HomePage())), IconButton( icon: SvgPicture.asset("assets/icons/Heart Icon.svg"), onPressed: () {}, ), IconButton( icon: SvgPicture.asset("assets/icons/Chat bubble Icon.svg"), onPressed: () {}, ), // IconButton( // icon: SvgPicture.asset( // "assets/icons/User Icon.svg", // color: MenuState.profile == selectedMenu // ?AppColors.kPrimaryColor // : inActiveIconColor, // ), // // onPressed: () => // // Navigator.pushNamed(context, ProfileScreen.routeName), // ), ], )), ); } }
package main import ( "fmt" "math/rand" "os" "text/template" "time" "github.com/mmcdole/gofeed" ) type Post struct { Title string URL string Date string } type TemplateData struct { Posts []Post Greeting string GeneratedAt string } var greetings = []string{"Hello", "Howdy", "Hi", "G'day", "Hey", "Hiya"} var t = template.Must(template.ParseFiles("readme-template.md")) func main() { rand.Seed(time.Now().UTC().UnixNano()) greetingNum := rand.Intn(len(greetings)) fp := gofeed.NewParser() feed, _ := fp.ParseURL("https://willbarkoff.dev/feed.xml") items := feed.Items posts := []Post{} for i, item := range items { if i > 3 { break } p := Post{} p.Title = item.Title p.URL = item.Link p.Date = item.PublishedParsed.Format("January 2, 2006") posts = append(posts, p) } _ = os.Remove("readme.md") f, err := os.Create("readme.md") defer f.Close() if err != nil { panic(err) } t.Execute(f, TemplateData{Posts: posts, Greeting: greetings[greetingNum], GeneratedAt: time.Now().Format("January 2, 2006 at 3:04PM")}) fmt.Println(feed.Title) }
计算机 应用 研究 APPLICATION RESEARCH OF COMPUTERS 2000   Vol.17   No.5   P.67 - 69 基于 三层 C / S 计算 模式 的 OPAC 的 设计 和 实现 王晔   张福炎   黄伟红   闵峰 摘 要 该文 详细 讨论 了 客户机 / 服务器 的 多层 计算 模式 , 阐述 了 基于 三层 客户机 / 服务器 模式 的 Oracle Application Server 的 结构 和 实现 机理 , 并 给出 了 设计 和 实现 联机 公共 查询 ( OPAC ) 的 方法 和 实例 。 关键词 客户机 服务器 Web 数据库 1 引言     计算机技术 和 网络 技术 的 迅猛发展 和 普及 正在 改变 着 传统 图书馆 的 服务 模式 , 同时 也 对 图书馆 自动化 系统 提出 了 更 高 的 要求 。 图书馆 的 信息 服务 正向 着 电子化 、 数字化 、 远程 化 、 资源共享 化 的 方向 发展 , 支持 Internet 服务 已经 成为 新一代 图书馆 自动化 系统 的 重要 标志 。     江苏省 教委 资助 开发 的 汇文 文献 信息 服务 系统 是 江苏 文献 保障系统 ( JALIS ) 的 一个 重要 组成部分 , 是 基于 多种 平台 ( Windows NT 、 UNIX 等 ) 和 大型 数据库 ( Oracle ) , 采用 客户 / 服务器 体系结构 的 新一代 图书馆 管理系统 。 该 系统 已 在 全国 范围 内 数十家 高校 及 公共 图书馆 安装 使用 , 推动 了 图书馆 业务 的 标准化 、 电子化 , 取得 了 巨大 的 社会效益 。 从 功能 上 , 该 系统 包括 采访 、 编目 、 典藏 、 流通 、 期刊 、 统计 、 Z39.50 和 OPAC 等 多个 子系统 。     在 OPAC ( Online Public Access Catalog ) 系统 中 , 我们 采用 Oracle Application Server 构建 了 三层 C / S 体系结构 , 以 提供 面向 Internet 的 高效 的 交互式 的 查询 访问 , 实现 了 书目 查询 、 读者 信息 服务 、 新书 通报 、 书刊 订购 征询 和 书刊 续借 预约 等 服务 。 2 客户 / 服务器 体系     客户 / 服务器 计算 体系 , 通常 被 描述 为 两层 或 多层模式 , 这 取决于 应用逻辑 层 在 客户端 和 服务端 如何 分布 。 最小 的 客户 / 服务器 体系 只有 客户端 和 服务端 。 应用逻辑 层 分散 于 客户端 和 服务端 。 如图 1 所示 。 图 1 普通 两层 C / S 模式     这种 C / S 模式 提高 了 数据处理系统 的 开放性 , 在 数据 资源 与 应用软件 之间 实现 了 较 好 的 独立 和 数据 应用 的 分离 。 现在 的 许多 应用 系统 中 , 这种 两层 的 C / S 模式 是 比较 成熟 的 技术 , 在 大部分 的 应用 中 也 获得 了 优越 的 性能 。 但是 这种 模式 有 许多 不足之处 , 客户端 同时 包括 表示 逻辑 和 部分 应用逻辑 , 是 一种 肥 客户 方式 。 随着 应用 的 复杂 , 对 分布 在 客户端 的 应用 系统 的 维护 代价 相当 大 。 同时 由于 应用逻辑 被 分散 在 客户 和 服务端 , 对系统 的 设计 和 实现 增加 了 复杂度 和 维护 的 难度 。     针对 两层 C / S 模式 的 不足 , 将 两层 结构 拓展 为 三层 结构 , 把 客户端 和 服务端 中 的 应用逻辑 剥离 出来 , 单独 驻留 在 中间层 , 即 应用逻辑 层 , 使得 服务端 只 负责 数据服务 , 客户端 只 负责 表示 逻辑 和 应用 程序界面 。 对 客户端 的 设计 和 开发 也 因此 变得 简单 , 同时 也 减轻 了 客户端 应用 的 负担 , 这种 模式 下 的 客户端 称为 瘦 客户端 。 在 实际 的 应用 中 , 作为 应用逻辑 一部分 的 存储 过程 和 触发器 等 还是 驻 存在 数据库 服务器 中 , 以 获得 数据库 全面 的 支持 和 优化 的 性能 。 本 系统 的 OPAC 子系统 就是 三层 C / S 结构 的 成功 范例 。 3 OAS 结构     Oracle 的 网络 计算 模式 ( NCA ) 是 一个三层 计算 模式 , 其中 Oracle Application Server ( OAS ) 作为 三层 模式 的 中间层 , 即 应用逻辑 层 , 其 结构 如图 2 。 图 2 基于 OAS 的 三层 C / S 模式     在 这个 瘦 客户端 的 3 层 结构 中 , 客户端 软件 是 轻量级 的 , 可以 按 需求 下载 , 主要 用于 表示 服务端 应用 的 用户 接口 。 应用逻辑 层 的 主体 在 中间层 实现 或 以 PL / SQL 存储 过程 和 JAVA 过程 的 形式 存储 在 数据库 中 。     作为 3 层 结构 的 中间层 , OAS 提供 了 与 客户端 和 数据库 之间 的 优化 接口 。 OAS 支持 以下 多种 应用 :     . 通用 网关 接口 ( CGI ) 应用     . 插件 服务器     . JCORBA 应用     . 企业 JAVABeans 应用     在 OPAC 的 实现 中 , 我们 只 需 支持 HTTP 的 访问 , 为了 动态 地 存取 Oracle 数据库 中 的 信息 , 选用 了 OAS 的 插件 ( Cartridge ) 服务 和 静态 HTML 文档 服务 。 下面 详细 介绍 OPAC 系统 中 所 使用 的 OAS 关键 组件 和 技术 :     监听器     OAS 提供 自己 的 Web 监听器 , 也 支持 其它 多种 监听器 。 并 能够 使 它们 共同 工作 , 并 和 分配器 紧密 集成 在 一起 , 获得 优化 的 性能 。     分配器     分配器 管理 一组 运行 在 一个 或 多个 节点 上 的 插件 实例 , 每个 插件 服务器 运行 一个 或 多个 插件 实例 ( 如图 2 ) 。 每个 节点 只有 一个 分配器 。 在 分配器 中 维持 一个 缓冲 表 , 记录 着 当前 可用 的 插件 。 当 一个 请求 某个 插件 的 访问 到达 时 , 分配器 把 它 传递 给 缓冲 表中 适当 类型 的 插件 。 如果 在 缓冲 表中 没有 可用 的 插件 , 分配器 请求 OAS 在 现存 的 插件 服务器 中 生成 一个 新 插件 。 如果 现存 的 插件 服务器 已经 不能 再 处理 更 多 的 插件 , OAS 就 生成 一个 新 的 插件 服务器 , 并且 在 这个 新 的 插件 服务器 中 生成 一个 新 的 插件 。 然后 分配器 把 这个 新 的 插件 加入 它 的 缓冲 , 并 把 将 到 的 访问 请求 分配 给 这个 插件 。 当 请求 完成 后 , 这个 新 的 插件 可以 继续 为 新 的 请求 所 使用 。     插件 和 插件 服务器     OAS 提供 了 一种 功能 更 强大 、 更 有效 的 服务端 应用 , 称为 插件 服务器 。 一个 插件 是 一个 共享 库 , 实现 了 程序逻辑 或 提供 了 对 存储 在 其它 地方 , 如 数据库 中 的 程序逻辑 访问 。 插件 服务器 是 一个 进程 , 其中 运行 一个 或 多个 插件 实例 。 插件 实例 是 在 插件 服务 进程 中 执行 插件 代码 的 CORBA 对象 。     不像 CGI 程序 , 插件 服务器 不必 为 每 一个 请求 重新启动 。 OAS 监听器 和 分配器 组件 根据 当前 的 服务 配置 对 进来 的 请求 分配 并 运行 插件 服务器 。 处理 请求 的 插件 服务器 不必 在 接收 访问 的 同一 机器 上 运行 , 而 允许 在 多台 机器 上 分配 。 这种 特性 插件 服务器 很 容易 扩展 , 能够 自动 适应 高 负载 需求 。     在 OAS 中 支持 多种 插件 服务 , 如 PL / SQL 插件 、 JWEB 插件 、 C 插件 、 LiveHTML 插件 和 Perl 插件 , 根据 不同 的 插件 可以 构建 不同 的 应用 。     应用 和 插件 是 在 应用服务器 环境 中 构建 应用 的 两个 主要 的 对象 。 一个 插件 包括 了 执行 应用逻辑 的 代码 和 定位 应用逻辑 的 配置 数据 。 比如 PL / SQL 插件 包含 了 使 之 能 连接 Oracle 数据库 和 执行 PL / SQL 存储 过程 的 执行 代码 。 插件 的 配置 数据 说明 连接 到 哪个 Oracle 数据库 及 连接 所用 的 用户 和 密码 。 同时 , 插件 也 能 与 应用服务器 的 其它 组件 通信 。 插件 包含 在 应用 内 。 一个 应用 包含 一个 或 多个 插件 , 但 这些 插件 必须 属于 同 一种 插件 类型 。 每个 应用 和 插件 运行 在 一个 插件 服务器 进程 内 。 每个 插件 服务器 进程 只能 运行 一个 应用 。     当 一个 应用 运行 时 , 其 插件 服务器 进程 使用 进程 的 插件 工厂 对象 初始化 插件 。 一旦 初始化 后 , 就 由 插件 处理 来自 客户端 的 请求 。 例如 , 在 图 3 所示 的 应用 中 , A 运行 了 三个 插件 服务器 , 两个 属于 应用 1 , 一个 属于 应用 2 。 在 插件 服务器 1 , 即 应用 1 的 一个 实例 中 , 运行 着 插件 C1 的 两个 实例 和 插件 C2 的 两个 实例 。 插件 服务器 中 的 插件 工厂 对象 负责 初始化 插件 C1 和 C2 。 图 3 插件 和 插件 服务器     在 OPAC 的 实现 中 我们 使用 了 PL / SQL 插件 , 最大 限度 的 利用 数据库 服务器 优异 的 性能 。 PL / SQL 插件 允许 用户 使用 在 Oracle 数据库 中 的 存储 过程 来 构建 应用 。 每个 PL / SQL 插件 都 伴随 着 一个 DAD , 用来 记录 访问 数据库 的 配置 数据 。 在 DAD 中 指定 数据库 的 DSN 和 用户 来 确定 一个 数据源 及其 对 该 数据源 的 访问 权限 。 一个 PL / SQL 插件 也 伴随 着 一个 虚拟 路径 。 通过 这个 虚拟 路径 来 调用 相关 的 PL / SQL 插件 。 可以 把 一个 或 多个 PL / SQL 插件 及 它们 的 配置 数据 组成 一个 应用 。 应用 的 概念 使得 一组 插件 可以 作为 一个 整体 来 管理 , 因为 所有 的 插件 都 在 同一个 插件 服务器 进程 中 运行 。     当 OAS 接收 到 一个 请求 时 :     1 ) 监听器 接收 到 客户端 的 一个 请求 , 决定 谁 应该 处理 它 。 在 OPAC 系统 中 , 它 把 请求 传递 给 WRB ( Web Request Broker ) , 因为 这个 请求 是 关于 插件 的 。     2 ) 根据 虚拟 路径 , WRB 决定 PL / SQL 插件 应该 处理 这个 请求 , 然后 把 这个 请求 传递 给 运行 这个 应用 的 插件 服务器 进程 。     3 ) 在 插件 服务器 内 , PL / SQL 插件 根据 DAD 的 配置 数据 确定 要 连接 的 数据库 、 设置 PL / SQL 客户 。     4 ) PL / SQL 插件 连接 数据库 , 准备 调用 参数 , 然后 调用 数据库 中 的 存储 过程 。     5 ) 存储 过程 生成 HTML 页面 , 其中 可能 包括 从 数据库 中 动态 获得 的 数据 和 静态数据 。     6 ) 存储 过程 的 输出 返回 到 PL / SQL 插件 和 客户端 。     插件 调用 的 存储 过程 必须 返回 HTML 格式 的 数据 到 客户端 。 为 简化 操作 , PL / SQL 插件 提供 了 一个 Web 开发工具 集 ( the PL / SQL Web Toolkit ) 。 可以 在 存储 过程 使用 , 以 获得 请求 信息 、 生成 HTML 标记 、 返回 头 信息 等等 。     使用 PL / SQL 插件 的 优点 :     . 应用逻辑 层以 存储 过程 的 形式 存储 在 数据库 中     . 最大 限度 地 重用 已有 的 存储 过程     . 可 伸缩 的 安全 解决方案     . 具有 方便使用 动态 生成 HTML 页面 的 工具集 4 OPAC 设计 与 实现     图书馆 的 OPAC ( Online Public Access Catalog ) 主要 面向 读者 , 提供 综合信息 查询 , 其 结构 如图 4 。 图 4OPAC 结构     下面 以 书目 查询 为例 说明 如何 运用 PL / SQL 插件 实现 数据库 与 客户端 的 连接 , 响应 客户端 的 请求 , 获取 数据库 中 相关 数据 , 动态 生成 HTML 页面 返回 给 客户端 的 过程 。 读者 通过 浏览器 进入 OPAC 中 的 书目 查询 画面 , 假设 URL 为 : http : / / libsys2000 . nju . edu . cn / opac / opac . complex _ search , OAS 响应 这个 请求 , 根据 请求 的 URL 中 的 虚拟 路径 ' opac ' 选择 PL / SQL 插件 来 处理 这个 请求 。 PL / SQL 连接 后台 Oracle 数据库 , 调用 数据库 端 opac 包中 的 存储 过程 complex _ search 。 在 这个 存储 过程 中 , 通过 OAS 的 Web 工具集 提供 函数 , 如 HTP , 动态 地 生成 HTML 页面 , 其中 直接 访问 文献 类型 表 , 读取 文献 类型 作为 生成 的 HTML 页面 中 书目 检索 的 一个 检索 条件 。     存储 过程 complex _ search 如下 所示 : create or replace procedure complex _ search is   cursor c is select doc _ type _ code , doc _ type _ name from     doc _ type _ code   where code _ use _ flag = ' 1 ' ; begin   htp . formOpen ( ' opac . adv _ search _ chk ' ) ;   htp . p ( ' < table border = " 0 " width = " 100% " cellpadding = " 3 " > ' ) ;   htp . p ( ' < caption align = " center " > < h1 > 书刊 目录 查询 < / h1 >     < / caption > ' ) ;   htp . p ( ' < tr > < td width = " 50% " height = " 24 " > < p align = " right " >     题 名 : < / td > ' ) ;   htp . p ( ' < td > < input TYPE = " text " NAME = " title " SIZE = " 20 " MAXLENGTH = " 80 " > < / td > < / tr > ' ) ;   htp . p ( ' < tr > < td width = " 50% " height = " 24 " > < p align = " right " >     索取 号 : < / td > ' ) ;   htp . p ( ' < td > < input TYPE = " text " NAME = " call _ no " SIZE = " 20 " MAXLENGTH = " 40 " > < / td > < / tr > ' ) ;   htp . p ( ' < tr > < td width = " 50% " height = " 24 " > < p align = " right " >   文献 类型 : < / td > ' ) ;   htp . p ( ' < td > < select name = " doctype " size = " 1 " > < option selected value = " * " > 所有 类型 < / option > ' ) ;   for r in c loop   htp . p ( ' < option value = " ' | | r . doc _ type _ code | | ' " > ' | | r . doc _ type _ name | | ' < / option > ' ) ;   end loop ;   htp . p ( ' < / select > < / td > < / tr > ' ) ;   htp . p ( ' < tr > < td width = " 100% " height = " 24 " colspan = " 2 " align = " center " > < input TYPE = " submit " VALUE = " 开始 查询 " > ' ) ;   htp . p ( ' < input TYPE = " reset " VALUE = " 重新 输入 " >     < / td > < / tr > < / table > ' ) ;   htp . formClose ; end complex _ search ;     存储 过程 complex _ search 动态 读取 数据库 中 数据 , 产生 HTML 标记 及 相关 信息 , 生成 的 HTML 文档 , 在 浏览器 IE 下 显示 如图 5 。 图 5 书刊 目录 查询 画面     在 OPAC 的 实现 中 , 并 不是 所有 的 HTML 文档 都 是 由 PL / SQL 存储 过程 动态 生成 。 对于 不 需要 访问 数据库 的 请求 , 我们 直接 使用 了 静态 的 HTML 页面 。 当 请求 到达 OAS 时 , 根据 虚拟 路径 的 不同 , 静态 HTML 文档 直接 从 OAS 服务器 中 返回 , 提高 了 响应 的 速度 的 效率 。 5 结束语     基于 三层 C / S 计算 模式 的 Oracle Application Server 与 Oracle 数据库 紧密结合 , 充分利用 了 Oracle 数据库 的 强大 功能 , 提供 了 快速 高效 的 Web 服务 。 OPAC 系统 在 全国 数十家 高校 图书馆 的 使用 中 , 其 优异 的 性能 获得 了 用户 的 一致 好评 。 王晔 ( 南京大学 计算机系 南京 210093 ) 张福炎 ( 南京大学 计算机系 南京 210093 ) 黄伟红 ( 南京大学 计算机系 南京 210093 ) 闵峰 ( 南京大学 计算机系 南京 210093 ) 参考文献 1 , Oracle Application Server Document 2 , Scott Urman 著 . Oracle8 PL / SQL 程序设计 . 北京 : 机械 工业 出版社 收稿 日期 : 1999 - 12 - 27
<template> <div class="container"> <div class="row g-0" style="background-color: #665494; min-height: 350px" > <div class="col-xl-4 col-lg-4 col-md-4 col-sm-3 col-3"> <MessageLeftSide @changeConversation="setCurrentConversation($event.conversation)"/> </div> <div class="col-xl-8 col-lg-8 col-md-8 col-sm-9 col-9"> <MessageRightSide v-if="currentConversation" ref="messageRightSide" @newMessage="scrollToNewMessage" /> </div> </div> </div> </template> <script setup lang="ts"> import {useConversationStore} from "~/store/conversation"; import MessageLeftSide from "~/components/profile/MessageLeftSide.vue"; import MessageRightSide from "~/components/profile/MessageRightSide.vue"; import {InterlocutorModel} from "~/app/models/conversation.model"; import {storeToRefs} from "pinia"; import ClientSSE from "~/app/client/sse/ClientSSE"; definePageMeta({ layout: 'profile', middleware: ['is-new-conversation'] }) useSeoMeta({ title: 'Messagerie' }) const route = useRoute() const conversationStore = useConversationStore() const { getUser } = useSecurity() const {conversations, currentConversation} = storeToRefs(conversationStore) const { fetchConversations, fetchCurrentConversationMessages, createNewConversation, initCurrentConversation, setCurrentConversation, messageHasArrived } = conversationStore conversationStore.$onAction(({ name, after }) => { if (name === 'setCurrentConversation') { after(() => { fillCurrentConversationMessages() }) } }) await useAsyncData('conversations-list', async () => { await fetchConversations() if (route.meta.user && !conversations.value.find((c) => c.interlocutor.id === route.meta.user.id)) { createNewConversation(route.meta.user as InterlocutorModel, route.meta.user.id) } initCurrentConversation() return true }) await useAsyncData( 'messages', async () => await fillCurrentConversationMessages(), ) onMounted(async () => { const clientSSE = new ClientSSE(getUser().id) clientSSE.connect() clientSSE.eventSource.onmessage = ({ data }) => { messageHasArrived(JSON.parse(data)) if (currentConversation.value && currentConversation.value.id === JSON.parse(data).id) { scrollToNewMessage(); } }; }) const messageRightSide = ref() async function fillCurrentConversationMessages() { if ( !currentConversation.value || currentConversation.value.id === 0 || (currentConversation.value.messages !== undefined && currentConversation.value.messages.length > 0) ) return await fetchCurrentConversationMessages() return true } function scrollToNewMessage() { const topPos = messageRightSide.value.messages.at(-1).offsetTop let chat = messageRightSide.value.chatContainer chat.scrollTop = topPos; } </script> <style lang="scss"> @import "assets/css/pages/profile/messageList"; </style>
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class BookingRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'full_name' => 'required', 'email' => 'required', 'phone' => 'required', 'check_in' => 'required', 'check_out' => 'required', ]; } public function messages() { return [ 'full_name.required' => 'Your full name is required.', 'email.required' => 'Your email is required.', 'phone.required' => 'Your phone number is required.', 'check_in.required' => 'Check-in day is required.', 'checkout.required' => 'Check-out day is required.', ]; } }
<?php /** * The plugin bootstrap file * * This file is read by WordPress to generate the plugin information in the plugin * admin area. This file also includes all of the dependencies used by the plugin, * registers the activation and deactivation functions, and defines a function * that starts the plugin. * * @link http://stewgle.com * @since 1.0.0 * @package Nhsjobs * * @wordpress-plugin * Plugin Name: Gavros Jobs * Plugin URI: http://turdpress.org/plugins/hello-gavros/ * Description: This is a short description of what the plugin does. It's displayed in the WordPress admin area. * Version: 1.0.0 * Author: Stewart Campbell * Author URI: http://stewgle.com * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt * Text Domain: nhsjobs * Domain Path: /languages */ // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } /** * Currently plugin version. * Start at version 1.0.0 and use SemVer - https://semver.org * Rename this for your plugin and update it as you release new versions. */ define( 'PLUGIN_NAME_VERSION', '1.0.0' ); /** * The code that runs during plugin activation. * This action is documented in includes/class-nhsjobs-activator.php */ function activate_nhsjobs() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-nhsjobs-activator.php'; Nhsjobs_Activator::activate(); } /** * The code that runs during plugin deactivation. * This action is documented in includes/class-nhsjobs-deactivator.php */ function deactivate_nhsjobs() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-nhsjobs-deactivator.php'; Nhsjobs_Deactivator::deactivate(); } register_activation_hook( __FILE__, 'activate_nhsjobs' ); register_deactivation_hook( __FILE__, 'deactivate_nhsjobs' ); /** * The core plugin class that is used to define internationalization, * admin-specific hooks, and public-facing site hooks. */ require plugin_dir_path( __FILE__ ) . 'includes/class-nhsjobs.php'; /** * Begins execution of the plugin. * * Since everything within the plugin is registered via hooks, * then kicking off the plugin from this point in the file does * not affect the page life cycle. * * @since 1.0.0 */ function run_nhsjobs() { $plugin = new Nhsjobs(); $plugin->run(); } run_nhsjobs();
import SourceryRuntime enum AutoRegistering { static func generate(types: Types, annotations: Annotations) -> String { var lines: [String] = [] lines.append(contentsOf: annotations.imports.map { "import \($0)" }) lines.append("") let containerName = annotations.containerName ?? "Container" lines.append("extension \(containerName): AutoRegistering {") lines.append("public func autoRegister() {".indent()) let sortedProtocols = types.protocols .sorted(by: { $0.name < $1.name }) .filter(\.isAutoRegisterable) sortedProtocols.forEach { type in if let implementingClass = types.classes.first(where: { $0.implements.contains(where: { $0.value == type }) }) { lines.append(contentsOf: generateClassRegistration(for: type, registeringClass: implementingClass)) } else if let registrationValue = type.registrationValue { let registrationName = type.name.withLowercaseFirst().withoutLastCamelCasedPart() lines.append("\(registrationName).register { \(registrationValue) }".indent(level: 2)) } } lines.append("}".indent()) lines.append("}") lines.append(.emptyLine) return lines.joined(separator: .newLine) + .newLine } } private extension AutoRegistering { static func generateClassRegistration(for type: Protocol, registeringClass: Class) -> [String] { let initMethods = registeringClass.methods.filter(\.isInitializer) let registrationName = type.name.withLowercaseFirst().withoutLastCamelCasedPart() var lines: [String] = [] // We only support up to 1 init method, otherwise we can't determine for what to generate the registration parameters. if initMethods.count > 1 { fatalError("Max 1 init method is supported for AutoRegisterable") } if let initMethod = initMethods.first { var canGenerateInit = true var initComponents: [String] = initMethod.parameters.compactMap { parameter in guard parameter.defaultValue == nil else { return nil } guard let type = parameter.type else { canGenerateInit = false return nil } let label = parameter.argumentLabel ?? parameter.name return "\(label): self.\(type.name.withLowercaseFirst().withoutLastCamelCasedPart())()" } guard canGenerateInit else { return lines } let joinedInitComponents = initComponents.joined(separator: ", ") lines.append("\(registrationName).register { \(registeringClass.name)(\(joinedInitComponents)) }".indent(level: 2)) } else { let isShared = registeringClass.staticVariables.contains { $0.name == "shared" } let instance = isShared ? ".shared" : "()" // If there is no init method in the protocol we can use the regular `Factory` lines.append("\(registrationName).register { \(registeringClass.name)\(instance) }".indent(level: 2)) } return lines } }
const express = require('express'); const router = express.Router(); // Sample book data const books = [ { id: 1, title: 'Book 1', author: 'Author 1', publishedYear: 2001 }, { id: 2, title: 'Book 2', author: 'Author 2', publishedYear: 2002 }, { id: 2, title: 'Book 3', author: 'Author 3', publishedYear: 2003 }, { id: 2, title: 'Book 4', author: 'Author 4', publishedYear: 2004 }, { id: 2, title: 'Book 5', author: 'Author 5', publishedYear: 2005 }, ]; // Get router.get('/', (req, res) => { res.json(books); }); // Get /:ID router.get('/:bookId', (req, res) => { const bookId = parseInt(req.params.bookId); const book = books.find((b) => b.id === bookId); if (!book) { res.status(404).json({ error: 'Book not found' }); } else { res.json(book); } }); // Post router.post('/', (req, res) => { const { title, author, publishedYear } = req.body; if (!title || !author || !publishedYear) { return res.status(400).json({ error: 'provide title, author, and publishedYear' }); } const newBookId = books.length + 1; const newBook = { id: newBookId, title, author, publishedYear, }; books.push(newBook); res.status(201).json(newBook); }); module.exports = router;
package Note.model; import javax.imageio.IIOException; import java.io.*; import java.util.ArrayList; import java.util.List; public class FileOperationImpl implements FileOperation { private String id; public FileOperationImpl (String id){ this.id = id; try (FileWriter writer = new FileWriter(id,true)){ writer.flush(); }catch (IOException ex){ System.out.println(ex.getMessage()); } } public List<String> readAllLines(){ List<String> lines = new ArrayList<>(); try{ File file = new File(id); // создаем объект FileReader для объекта File FileReader fr = new FileReader(file); //создаем BufferedReader с существующего FileReader для построчного считывания BufferedReader reader = new BufferedReader(fr); // считаем сначала первую строку String line = reader.readLine(); if(line != null){ lines.add(line); } while (line != null){ // считываем остальные строки в цикле line = reader.readLine(); if (line != null){ lines.add(line); } } fr.close(); } catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } return lines; } public void saveAllLines(List<String> lines) { try (FileWriter writer = new FileWriter(id, false)) { for (String line : lines) { // запись всей строки writer.write(line); // запись по символам writer.append('\n'); } writer.flush(); } catch (IOException ex) { System.out.println(ex.getMessage()); } } }
#pragma once #include <io_device.hpp> #include <istream> #include <vector> #include <memory> #include <mutex> class Disk { public: std::shared_ptr<std::istream> disk_stream; int last_sector; int current_sector; enum Status { STATUS_IDLE, STATUS_BUSY } status = STATUS_IDLE; std::shared_ptr<std::mutex> mutex; Disk(std::shared_ptr<std::istream> disk_stream) { this->disk_stream = disk_stream; disk_stream->seekg(0, std::ios::end); last_sector = (disk_stream->tellg() / 512); disk_stream->seekg(0); current_sector = 0; mutex = std::make_shared<std::mutex>(); } int get_status() { mutex->lock(); auto result = status; mutex->unlock(); return result; } void set_status(Status status) { mutex->lock(); this->status = status; mutex->unlock(); } }; class DiskCtrl : public IODevice { public: std::vector<Disk> disks; DiskCtrl(void *ctx); uint8_t in(uint16_t addr) override; void out(uint16_t addr, uint8_t val) override; struct Registers { uint8_t disk_select; uint8_t command; uint16_t data; } registers; enum Command { COMMAND_GET_PRESENCE, COMMAND_GET_LAST_SECTOR, COMMAND_GET_STATUS, COMMAND_SEEK, COMMAND_READ, COMMAND_WRITE }; };
import tkinter as tk from tkinter import filedialog, messagebox import soundfile as sf import numpy as np from pydub import AudioSegment from pydub.playback import play from pydub.effects import normalize import pyloudnorm as pyln from spleeter.separator import Separator import threading import librosa import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) class MasteringToolApp: def __init__(self, root): self.root = root self.root.title("Advanced Mastering Tool") # Create a menu bar menubar = tk.Menu(root) root.config(menu=menubar) file_menu = tk.Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=file_menu) file_menu.add_command(label="Load Unmastered Audio", command=self.load_audio) file_menu.add_command(label="Save Mastered Audio", command=self.save_audio) file_menu.add_separator() file_menu.add_command(label="Exit", command=root.quit) self.input_file = None self.output_file = None self.load_button = tk.Button(root, text="Load Unmastered Audio", command=self.load_audio) self.load_button.pack(pady=10) self.master_button = tk.Button(root, text="Apply Advanced Mastering", command=self.apply_advanced_mastering) self.master_button.pack() self.save_button = tk.Button(root, text="Save Mastered Audio", command=self.save_audio) self.save_button.pack() self.play_button = tk.Button(root, text="Play Mastered Audio", command=self.play_mastered_audio) self.play_button.pack() self.status_label = tk.Label(root, text="", bd=1, relief=tk.SUNKEN, anchor=tk.W) self.status_label.pack(side=tk.BOTTOM, fill=tk.X) def load_audio(self): self.input_file = filedialog.askopenfilename(filetypes=[("Audio Files", "*.wav *.mp3")]) if not self.input_file: return self.update_status("Audio loaded successfully!") def apply_advanced_mastering(self): if self.input_file is None: messagebox.showerror("Error", "Please load an audio file first.") return self.update_status("Applying advanced mastering...") threading.Thread(target=self.process_audio).start() def process_audio(self): try: audio, sr = self.load_audio_file(self.input_file) if audio is None: return processed_audio = self.apply_advanced_processing(audio, sr) if processed_audio is None: return self.output_file = "mastered_audio.wav" self.save_audio_file(processed_audio, sr, self.output_file) self.update_status("Advanced mastering complete!") except Exception as e: self.update_status(f"An error occurred: {str(e)}") def save_audio(self): if self.output_file: save_path = filedialog.asksaveasfilename(defaultextension=".wav", filetypes=[("WAV Files", "*.wav")]) if save_path: audio, sr = self.load_audio_file(self.output_file) self.save_audio_file(audio, sr, save_path) def play_mastered_audio(self): if self.output_file: normalized_audio = self.normalize_audio(AudioSegment.from_file(self.output_file)) play(normalized_audio) def load_audio_file(self, file_path): try: audio, sr = sf.read(file_path) return audio, sr except Exception as e: self.update_status(f"Error loading audio: {str(e)}") return None, None def save_audio_file(self, audio, sr, output_path): try: sf.write(output_path, audio, sr) self.update_status(f"Audio saved as: {output_path}") except Exception as e: self.update_status(f"Error saving audio: {str(e)}") def apply_advanced_processing(self, audio, sr): try: # Apply high-quality high-pass filter using librosa processed_audio = librosa.effects.preemphasis(audio) # Apply loudness normalization using LoudNorm meter = pyln.Meter(sr) loudness_target = -16.0 # LUFS integrated_loudness = meter.integrated_loudness(processed_audio) loudness_diff = loudness_target - integrated_loudness processed_audio = pyln.normalize.loudness(processed_audio, loudness_diff, target_loudness=loudness_target) # Apply source separation using Spleeter (5-stem model) separator = Separator('spleeter:5stems') separated_audio = separator.separate(processed_audio) # Process each stem separately (e.g., compression, EQ, etc.) # Combine the stems back together processed_audio = sum(separated_audio.values()) return processed_audio except Exception as e: self.update_status(f"Error applying advanced processing: {str(e)}") return None def normalize_audio(self, audio): normalized_audio = normalize(audio) return normalized_audio def update_status(self, message): self.status_label.config(text=message) if __name__ == "__main__": root = tk.Tk() app = MasteringToolApp(root) root.mainloop()
import { Client } from './Client' import { wrapError, PolybaseError } from './errors' import { Request, SenderResponse } from './types' export type SubscriptionFn<T> = ((data: T) => void) export type SubscriptionErrorFn = ((err: PolybaseError) => void) export type UnsubscribeFn = (() => void) export interface SubscriptionOptions { // Default timeout between long poll requests timeout: number // Max timeout after error backoff maxErrorTimeout: number } const defaultOptions: SubscriptionOptions = { timeout: 100, maxErrorTimeout: 60 * 1000, } export interface Listener<T> { fn: SubscriptionFn<T> errFn?: SubscriptionErrorFn } export type TransformerFn<T, R = any> = (res: SenderResponse<R>) => Promise<T> | T export class Subscription<T, R = any> { private _listeners: Listener<T>[] private req: Request private client: Client private since?: string private aborter?: () => void private _stopped = true private options: SubscriptionOptions private errors = 0 private data?: T private timer?: number private id = 0 private isPublicallyAccessible: Promise<boolean> private transformer: TransformerFn<T, R> constructor(req: Request, client: Client, isPublicallyAccessible: Promise<boolean>, transformer: TransformerFn<T, R>, options?: Partial<SubscriptionOptions>) { this.req = req this.client = client this.isPublicallyAccessible = isPublicallyAccessible ?? false this.transformer = transformer this._listeners = [] this.options = Object.assign({}, defaultOptions, options) } tick = async (id?: number) => { if (this._stopped || id !== this.id) return const params = this.req.params ? { ...this.req.params } : {} if (this.since && this.data) { params.since = `${this.since}` } try { const req = this.client.request({ ...this.req, params, }) this.aborter = req.abort const sixtyMinutes = 60 * 60 * 1000 const isPubliclyAccessible = await this.isPublicallyAccessible const res = await req.send(isPubliclyAccessible ? 'none' : 'required', sixtyMinutes) this.since = res.headers['x-polybase-timestamp'] ?? `${Date.now() / 1000}` this.data = await this.transformer(res) this._listeners.forEach(({ fn }) => { if (this.data) fn(this.data) }) } catch (err: any) { // Get the status code from the error const statusCode = err.statusCode ?? err.status ?? err.code ?? err.response?.status const isCancelledError = err && typeof err === 'object' && err instanceof PolybaseError && err.reason === 'request/cancelled' // Don't error for 304 if (statusCode !== 304 && !isCancelledError) { let e = err if (!(err instanceof PolybaseError)) { e = wrapError(err) } // Send error to listeners this._listeners.forEach(({ errFn }) => { if (errFn) errFn(e) }) // Also log to console // console.error(err) this.errors += 1 // Longer timeout before next tick if we // received an error const errTimeout = Math.min( 1000 * this.errors, this.options.maxErrorTimeout, ) this.timer = setTimeout(() => { this.tick(id) }, errTimeout) as unknown as number return } } this.errors = 0 // If no since has been stored, then we need to wait longer // because this.timer = setTimeout(() => { this.tick(id) }, this.options.timeout) as unknown as number } subscribe = (fn: SubscriptionFn<T>, errFn?: SubscriptionErrorFn) => { const l = { fn, errFn } this._listeners.push(l) if (this.data) { fn(this.data) } this.start() return () => { const index = this._listeners.indexOf(l) // Already removed, shouldn't happen if (index === -1) return // Remove the listener this._listeners.splice(index, 1) // Stop if no more listeners if (this._listeners.length === 0) { this.stop() } } } start = () => { if (this._stopped) { this._stopped = false this.id += 1 this.tick(this.id) } } // TODO: prevent race conditions by waiting for abort // before allowing start again stop = () => { this._stopped = true if (this.timer) clearTimeout(this.timer) this.since = undefined if (this.aborter) this.aborter() } get listeners() { return this._listeners } get stopped() { return this._stopped } }
/* * COPYRIGHT(c) 2023 MONTA * * This file is part of Monta. * * The Monta software is licensed under the Business Source License 1.1. You are granted the right * to copy, modify, and redistribute the software, but only for non-production use or with a total * of less than three server instances. Starting from the Change Date (November 16, 2026), the * software will be made available under version 2 or later of the GNU General Public License. * If you use the software in violation of this license, your rights under the license will be * terminated automatically. The software is provided "as is," and the Licensor disclaims all * warranties and conditions. If you use this license's text or the "Business Source License" name * and trademark, you must comply with the Licensor's covenants, which include specifying the * Change License as the GPL Version 2.0 or a compatible license, specifying an Additional Use * Grant, and not modifying the license in any other way. */ import React, { Suspense } from "react"; import { Box, Button, Group, Modal, Skeleton, Textarea, TextInput, } from "@mantine/core"; import { useFormStyles } from "@/assets/styles/FormStyles"; import { CommentType } from "@/types/dispatch"; import { useCommentTypeStore as store } from "@/stores/DispatchStore"; function ViewDelayCodeModalForm({ commentType }: { commentType: CommentType }) { const { classes } = useFormStyles(); return ( <Box className={classes.div}> <TextInput className={classes.fields} value={commentType.name} name="name" label="Name" placeholder="Name" readOnly variant="filled" withAsterisk /> <Textarea className={classes.fields} name="description" label="Description" placeholder="Description" readOnly variant="filled" value={commentType.description || ""} withAsterisk /> <Group position="right" mt="md"> <Button color="white" type="submit" className={classes.control} onClick={() => { store.set("selectedRecord", commentType); store.set("viewModalOpen", false); store.set("editModalOpen", true); }} > Edit Comment Type </Button> </Group> </Box> ); } export function ViewCommentTypeModal() { const [showViewModal, setShowViewModal] = store.use("viewModalOpen"); const [commentType] = store.use("selectedRecord"); if (!showViewModal) return null; return ( <Modal.Root opened={showViewModal} onClose={() => setShowViewModal(false)}> <Modal.Overlay /> <Modal.Content> <Modal.Header> <Modal.Title>View Comment Type</Modal.Title> <Modal.CloseButton /> </Modal.Header> <Modal.Body> <Suspense fallback={<Skeleton height={400} />}> {commentType && ( <ViewDelayCodeModalForm commentType={commentType} /> )} </Suspense> </Modal.Body> </Modal.Content> </Modal.Root> ); }
package com.example.medz2; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.ListAdapter; import androidx.recyclerview.widget.RecyclerView; public class BuyRVAdapter extends ListAdapter<BuyModal, BuyRVAdapter.ViewHolder> { private OnItemClickListener listener; BuyRVAdapter() { super(DIFF_CALLBACK); } private static final DiffUtil.ItemCallback<BuyModal> DIFF_CALLBACK = new DiffUtil.ItemCallback<BuyModal>() { @Override public boolean areItemsTheSame(BuyModal oldItem, BuyModal newItem) { return oldItem.getId() == newItem.getId(); } @Override public boolean areContentsTheSame(BuyModal oldItem, BuyModal newItem) { return oldItem.getPillName().equals(newItem.getPillName()) && oldItem.getPillQuantity().equals(newItem.getPillQuantity()); } }; @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View item = LayoutInflater.from(parent.getContext()) .inflate(R.layout.buy_rv_item, parent, false); return new ViewHolder(item); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // below line of code is use to set data to // each item of our recycler view. BuyModal model = getCourseAt(position); holder.pillNameTV.setText(model.getPillName()); holder.pillQuantityTV.setText(model.getPillQuantity()); } // creating a method to get course modal for a specific position. public BuyModal getCourseAt(int position) { return getItem(position); } public class ViewHolder extends RecyclerView.ViewHolder { // view holder class to create a variable for each view. TextView pillNameTV, pillQuantityTV; ViewHolder(@NonNull View itemView) { super(itemView); // initializing each view of our recycler view. pillNameTV = itemView.findViewById(R.id.idTVCourseName); pillQuantityTV = itemView.findViewById(R.id.idTVCourseDuration); // adding on click listener for each item of recycler view. itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener we are passing // position to our item of recycler view. int position = getAdapterPosition(); if (listener != null && position != RecyclerView.NO_POSITION) { listener.onItemClick(getItem(position)); } } }); } } public interface OnItemClickListener { void onItemClick(BuyModal model); } public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; } }
# Copyright (C) 2006-2007 Red Hat, Inc. # Copyright (C) 2009 Aleksey Lim # # 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 program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import os import logging from gi.repository import GConf from gi.repository import GObject from gi.repository import Gio import simplejson from sugar3.bundle.activitybundle import ActivityBundle from sugar3.bundle.contentbundle import ContentBundle from sugar3.bundle.bundleversion import NormalizedVersion from jarabe.journal.journalentrybundle import JournalEntryBundle from sugar3.bundle.bundle import MalformedBundleException, \ AlreadyInstalledException, RegistrationException from sugar3 import env from jarabe import config from jarabe.model import mimeregistry _instance = None class BundleRegistry(GObject.GObject): """Tracks the available activity bundles""" __gsignals__ = { 'bundle-added': (GObject.SignalFlags.RUN_FIRST, None, ([GObject.TYPE_PYOBJECT])), 'bundle-removed': (GObject.SignalFlags.RUN_FIRST, None, ([GObject.TYPE_PYOBJECT])), 'bundle-changed': (GObject.SignalFlags.RUN_FIRST, None, ([GObject.TYPE_PYOBJECT])), } def __init__(self): logging.debug('STARTUP: Loading the bundle registry') GObject.GObject.__init__(self) self._mime_defaults = self._load_mime_defaults() self._bundles = [] # hold a reference to the monitors so they don't get disposed self._gio_monitors = [] user_path = env.get_user_activities_path() for activity_dir in [user_path, config.activities_path]: self._scan_directory(activity_dir) directory = Gio.File.new_for_path(activity_dir) monitor = directory.monitor_directory( \ flags=Gio.FileMonitorFlags.NONE, cancellable=None) monitor.connect('changed', self.__file_monitor_changed_cb) self._gio_monitors.append(monitor) self._last_defaults_mtime = -1 self._favorite_bundles = {} client = GConf.Client.get_default() self._protected_activities = [] # FIXME, gconf_client_get_list not introspectable #681433 protected_activities = client.get( '/desktop/sugar/protected_activities') for gval in protected_activities.get_list(): activity_id = gval.get_string() self._protected_activities.append(activity_id) if self._protected_activities is None: self._protected_activities = [] try: self._load_favorites() except Exception: logging.exception('Error while loading favorite_activities.') self._merge_default_favorites() def __file_monitor_changed_cb(self, monitor, one_file, other_file, event_type): if not one_file.get_path().endswith('.activity'): return if event_type == Gio.FileMonitorEvent.CREATED: self.add_bundle(one_file.get_path(), install_mime_type=True) elif event_type == Gio.FileMonitorEvent.DELETED: self.remove_bundle(one_file.get_path()) def _load_mime_defaults(self): defaults = {} f = open(os.path.join(config.data_path, 'mime.defaults'), 'r') for line in f.readlines(): line = line.strip() if line and not line.startswith('#'): mime = line[:line.find(' ')] handler = line[line.rfind(' ') + 1:] defaults[mime] = handler f.close() return defaults def _get_favorite_key(self, bundle_id, version): """We use a string as a composite key for the favorites dictionary because JSON doesn't support tuples and python won't accept a list as a dictionary key. """ if ' ' in bundle_id: raise ValueError('bundle_id cannot contain spaces') return '%s %s' % (bundle_id, version) def _load_favorites(self): favorites_path = env.get_profile_path('favorite_activities') if os.path.exists(favorites_path): favorites_data = simplejson.load(open(favorites_path)) favorite_bundles = favorites_data['favorites'] if not isinstance(favorite_bundles, dict): raise ValueError('Invalid format in %s.' % favorites_path) if favorite_bundles: first_key = favorite_bundles.keys()[0] if not isinstance(first_key, basestring): raise ValueError('Invalid format in %s.' % favorites_path) first_value = favorite_bundles.values()[0] if first_value is not None and \ not isinstance(first_value, dict): raise ValueError('Invalid format in %s.' % favorites_path) self._last_defaults_mtime = float(favorites_data['defaults-mtime']) self._favorite_bundles = favorite_bundles def _merge_default_favorites(self): default_activities = [] defaults_path = os.path.join(config.data_path, 'activities.defaults') if os.path.exists(defaults_path): file_mtime = os.stat(defaults_path).st_mtime if file_mtime > self._last_defaults_mtime: f = open(defaults_path, 'r') for line in f.readlines(): line = line.strip() if line and not line.startswith('#'): default_activities.append(line) f.close() self._last_defaults_mtime = file_mtime if not default_activities: return for bundle_id in default_activities: max_version = '0' for bundle in self._bundles: if bundle.get_bundle_id() == bundle_id and \ NormalizedVersion(max_version) < \ NormalizedVersion(bundle.get_activity_version()): max_version = bundle.get_activity_version() key = self._get_favorite_key(bundle_id, max_version) if NormalizedVersion(max_version) > NormalizedVersion('0') and \ key not in self._favorite_bundles: self._favorite_bundles[key] = None logging.debug('After merging: %r', self._favorite_bundles) self._write_favorites_file() def get_bundle(self, bundle_id): """Returns an bundle given his service name""" for bundle in self._bundles: if bundle.get_bundle_id() == bundle_id: return bundle return None def __iter__(self): return self._bundles.__iter__() def __len__(self): return len(self._bundles) def _scan_directory(self, path): if not os.path.isdir(path): return # Sort by mtime to ensure a stable activity order bundles = {} for f in os.listdir(path): if not f.endswith('.activity'): continue try: bundle_dir = os.path.join(path, f) if os.path.isdir(bundle_dir): bundles[bundle_dir] = os.stat(bundle_dir).st_mtime except Exception: logging.exception('Error while processing installed activity' ' bundle %s:', bundle_dir) bundle_dirs = bundles.keys() bundle_dirs.sort(lambda d1, d2: cmp(bundles[d1], bundles[d2])) for folder in bundle_dirs: try: self._add_bundle(folder) except: # pylint: disable=W0702 logging.exception('Error while processing installed activity' ' bundle %s:', folder) def add_bundle(self, bundle_path, install_mime_type=False): bundle = self._add_bundle(bundle_path, install_mime_type) if bundle is not None: self._set_bundle_favorite(bundle.get_bundle_id(), bundle.get_activity_version(), True) self.emit('bundle-added', bundle) return True else: return False def _add_bundle(self, bundle_path, install_mime_type=False): logging.debug('STARTUP: Adding bundle %r', bundle_path) try: bundle = ActivityBundle(bundle_path) if install_mime_type: bundle.install_mime_type(bundle_path) except MalformedBundleException: logging.exception('Error loading bundle %r', bundle_path) return None bundle_id = bundle.get_bundle_id() installed = self.get_bundle(bundle_id) if installed is not None: if NormalizedVersion(installed.get_activity_version()) >= \ NormalizedVersion(bundle.get_activity_version()): logging.debug('Skip old version for %s', bundle_id) return None else: logging.debug('Upgrade %s', bundle_id) self.remove_bundle(installed.get_path()) self._bundles.append(bundle) return bundle def remove_bundle(self, bundle_path): for bundle in self._bundles: if bundle.get_path() == bundle_path: self._bundles.remove(bundle) self.emit('bundle-removed', bundle) return True return False def get_activities_for_type(self, mime_type): result = [] mime = mimeregistry.get_registry() default_bundle_id = mime.get_default_activity(mime_type) default_bundle = None for bundle in self._bundles: if mime_type in (bundle.get_mime_types() or []): if bundle.get_bundle_id() == default_bundle_id: default_bundle = bundle elif self.get_default_for_type(mime_type) == \ bundle.get_bundle_id(): result.insert(0, bundle) else: result.append(bundle) if default_bundle is not None: result.insert(0, default_bundle) return result def get_default_for_type(self, mime_type): return self._mime_defaults.get(mime_type) def _find_bundle(self, bundle_id, version): for bundle in self._bundles: if bundle.get_bundle_id() == bundle_id and \ bundle.get_activity_version() == version: return bundle raise ValueError('No bundle %r with version %r exists.' % \ (bundle_id, version)) def set_bundle_favorite(self, bundle_id, version, favorite): changed = self._set_bundle_favorite(bundle_id, version, favorite) if changed: bundle = self._find_bundle(bundle_id, version) self.emit('bundle-changed', bundle) def _set_bundle_favorite(self, bundle_id, version, favorite): key = self._get_favorite_key(bundle_id, version) if favorite and not key in self._favorite_bundles: self._favorite_bundles[key] = None elif not favorite and key in self._favorite_bundles: del self._favorite_bundles[key] else: return False self._write_favorites_file() return True def is_bundle_favorite(self, bundle_id, version): key = self._get_favorite_key(bundle_id, version) return key in self._favorite_bundles def is_activity_protected(self, bundle_id): return bundle_id in self._protected_activities def set_bundle_position(self, bundle_id, version, x, y): key = self._get_favorite_key(bundle_id, version) if key not in self._favorite_bundles: raise ValueError('Bundle %s %s not favorite' % (bundle_id, version)) if self._favorite_bundles[key] is None: self._favorite_bundles[key] = {} if 'position' not in self._favorite_bundles[key] or \ [x, y] != self._favorite_bundles[key]['position']: self._favorite_bundles[key]['position'] = [x, y] else: return self._write_favorites_file() bundle = self._find_bundle(bundle_id, version) self.emit('bundle-changed', bundle) def get_bundle_position(self, bundle_id, version): """Get the coordinates where the user wants the representation of this bundle to be displayed. Coordinates are relative to a 1000x1000 area. """ key = self._get_favorite_key(bundle_id, version) if key not in self._favorite_bundles or \ self._favorite_bundles[key] is None or \ 'position' not in self._favorite_bundles[key]: return (-1, -1) else: return tuple(self._favorite_bundles[key]['position']) def _write_favorites_file(self): path = env.get_profile_path('favorite_activities') favorites_data = {'defaults-mtime': self._last_defaults_mtime, 'favorites': self._favorite_bundles} simplejson.dump(favorites_data, open(path, 'w'), indent=1) def is_installed(self, bundle): # TODO treat ContentBundle in special way # needs rethinking while fixing ContentBundle support if isinstance(bundle, ContentBundle) or \ isinstance(bundle, JournalEntryBundle): return bundle.is_installed() for installed_bundle in self._bundles: if bundle.get_bundle_id() == installed_bundle.get_bundle_id() and \ NormalizedVersion(bundle.get_activity_version()) == \ NormalizedVersion(installed_bundle.get_activity_version()): return True return False def install(self, bundle, uid=None, force_downgrade=False): activities_path = env.get_user_activities_path() for installed_bundle in self._bundles: if bundle.get_bundle_id() == installed_bundle.get_bundle_id() and \ NormalizedVersion(bundle.get_activity_version()) <= \ NormalizedVersion(installed_bundle.get_activity_version()): if not force_downgrade: raise AlreadyInstalledException else: self.uninstall(installed_bundle, force=True) elif bundle.get_bundle_id() == installed_bundle.get_bundle_id(): self.uninstall(installed_bundle, force=True) install_dir = env.get_user_activities_path() if isinstance(bundle, JournalEntryBundle): install_path = bundle.install(uid) elif isinstance(bundle, ContentBundle): install_path = bundle.install() else: install_path = bundle.install(install_dir) # TODO treat ContentBundle in special way # needs rethinking while fixing ContentBundle support if isinstance(bundle, ContentBundle) or \ isinstance(bundle, JournalEntryBundle): pass elif not self.add_bundle(install_path): raise RegistrationException def uninstall(self, bundle, force=False, delete_profile=False): # TODO treat ContentBundle in special way # needs rethinking while fixing ContentBundle support if isinstance(bundle, ContentBundle) or \ isinstance(bundle, JournalEntryBundle): if bundle.is_installed(): bundle.uninstall() else: logging.warning('Not uninstalling, bundle is not installed') return act = self.get_bundle(bundle.get_bundle_id()) if not force and \ act.get_activity_version() != bundle.get_activity_version(): logging.warning('Not uninstalling, different bundle present') return if not act.is_user_activity(): logging.debug('Do not uninstall system activity') return install_path = act.get_path() bundle.uninstall(install_path, force, delete_profile) if not self.remove_bundle(install_path): raise RegistrationException def upgrade(self, bundle): act = self.get_bundle(bundle.get_bundle_id()) if act is None: logging.warning('Activity not installed') elif act.get_activity_version() == bundle.get_activity_version(): logging.debug('No upgrade needed, same version already installed.') return elif act.is_user_activity(): try: self.uninstall(bundle, force=True) except Exception: logging.exception('Uninstall failed, still trying to install' ' newer bundle:') else: logging.warning('Unable to uninstall system activity, ' 'installing upgraded version in user activities') self.install(bundle) def get_registry(): global _instance if not _instance: _instance = BundleRegistry() return _instance
import { shallow } from "enzyme"; import ReactDOM from "react-dom"; import { EventDetailOfSnippetApply } from "@next-core/editor-bricks-helper"; import { BuilderContainer } from "./BuilderContainer"; import { BuilderClipboard, BuilderClipboardType, BuilderPasteDetailOfCopy, BuilderPasteDetailOfCut, } from "./interfaces"; import { EventDownstreamType, EventStreamNode, } from "./EventStreamCanvas/interfaces"; import { BuilderContainerElement } from "./"; import "./"; jest.mock("./BuilderContainer"); const spyOnRender = jest .spyOn(ReactDOM, "render") .mockImplementation(() => void 0); const unmountComponentAtNode = jest .spyOn(ReactDOM, "unmountComponentAtNode") .mockImplementation(() => null); describe("next-builder.builder-container", () => { afterEach(() => { jest.clearAllMocks(); }); it("should create a custom element", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; // element.appId = "test-app"; expect(spyOnRender).not.toBeCalled(); document.body.appendChild(element); expect(spyOnRender).toBeCalled(); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); expect(wrapper.find(BuilderContainer).props()).toMatchObject({ initialFullscreen: false, initialToolboxTab: null, initialEventStreamNodeId: null, initialClipboardType: null, initialClipboardSource: null, }); document.body.removeChild(element); expect(unmountComponentAtNode).toBeCalled(); }); it("should init clipboard as copy", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; element.clipboardType = BuilderClipboardType.COPY; element.clipboardSource = "B-001"; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); expect(wrapper.find(BuilderContainer).props()).toMatchObject({ initialClipboardType: "copy", initialClipboardSource: "B-001", }); document.body.removeChild(element); }); it("should init clipboard as cut", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; element.clipboardType = BuilderClipboardType.CUT; element.clipboardSource = "instance-a"; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); expect(wrapper.find(BuilderContainer).props()).toMatchObject({ initialClipboardType: "cut", initialClipboardSource: "instance-a", }); document.body.removeChild(element); }); it("should handle clipboard change", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onClipboardChange = jest.fn(); element.addEventListener("clipboard.change", onClipboardChange); // No events triggered if clipboard not changed. wrapper.find(BuilderContainer).invoke("onClipboardChange")(null); expect(onClipboardChange).not.toBeCalled(); const clipboardOfCopy: BuilderClipboard = { type: BuilderClipboardType.COPY, sourceId: "B-001", nodeType: "brick", }; wrapper.find(BuilderContainer).invoke("onClipboardChange")(clipboardOfCopy); expect(onClipboardChange).toBeCalledWith( expect.objectContaining({ detail: { clipboard: clipboardOfCopy }, }) ); const clipboardOfCut: BuilderClipboard = { type: BuilderClipboardType.CUT, sourceInstanceId: "instance-a", nodeType: "brick", }; wrapper.find(BuilderContainer).invoke("onClipboardChange")(clipboardOfCut); expect(onClipboardChange).toBeCalledWith( expect.objectContaining({ detail: { clipboard: clipboardOfCut }, }) ); wrapper.find(BuilderContainer).invoke("onClipboardChange")(null); expect(onClipboardChange).toBeCalledWith( expect.objectContaining({ detail: { clipboard: null }, }) ); document.body.removeChild(element); }); it("should handle copy and paste", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onNodeCopy = jest.fn(); element.addEventListener("node.copy", onNodeCopy); const onNodeCopyPaste = jest.fn(); element.addEventListener("node.copy.paste", onNodeCopyPaste); const clipboard: BuilderClipboard = { type: BuilderClipboardType.COPY, sourceId: "B-001", nodeType: "brick", }; wrapper.find(BuilderContainer).invoke("onNodeCopy")(clipboard); expect(onNodeCopy).toBeCalledWith( expect.objectContaining({ detail: clipboard, }) ); const detail: BuilderPasteDetailOfCopy = { sourceId: "B-001", targetId: "B-002", }; wrapper.find(BuilderContainer).invoke("onNodeCopyPaste")(detail); expect(onNodeCopyPaste).toBeCalledWith( expect.objectContaining({ detail, }) ); document.body.removeChild(element); }); it("should handle cut and paste", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onNodeCut = jest.fn(); element.addEventListener("node.cut", onNodeCut); const onNodeCutPaste = jest.fn(); element.addEventListener("node.cut.paste", onNodeCutPaste); const clipboard: BuilderClipboard = { type: BuilderClipboardType.CUT, sourceInstanceId: "instance-a", nodeType: "brick", }; wrapper.find(BuilderContainer).invoke("onNodeCut")(clipboard); expect(onNodeCut).toBeCalledWith( expect.objectContaining({ detail: clipboard, }) ); const detail: BuilderPasteDetailOfCut = { sourceInstanceId: "instance-a", targetInstanceId: "instance-b", }; wrapper.find(BuilderContainer).invoke("onNodeCutPaste")(detail); expect(onNodeCutPaste).toBeCalledWith( expect.objectContaining({ detail, }) ); document.body.removeChild(element); }); it("should handle clear clipboard", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onClipboardClear = jest.fn(); element.addEventListener("clipboard.clear", onClipboardClear); wrapper.find(BuilderContainer).invoke("onClipboardClear")(); expect(onClipboardClear).toBeCalled(); document.body.removeChild(element); }); it("should handle event node click", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onEventNodeClick = jest.fn(); element.addEventListener("event.node.click", onEventNodeClick); const detail: EventStreamNode = { node: { type: "brick", brick: "brick-a", id: "id", }, type: EventDownstreamType.EVENT, eventType: "click", children: [], handlers: [ { target: "#modal", method: "open", }, ], }; wrapper.find(BuilderContainer).invoke("onEventNodeClick")({ node: { type: "brick", brick: "brick-a", id: "id", }, type: EventDownstreamType.EVENT, eventType: "click", children: [], handlers: [ { target: "#modal", method: "open", }, ], }); expect(onEventNodeClick).toBeCalledWith( expect.objectContaining({ detail, }) ); document.body.removeChild(element); }); it("should handle canvas index switch", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onSwitchCanvasIndex = jest.fn(); element.addEventListener("canvas.index.switch", onSwitchCanvasIndex); wrapper.find(BuilderContainer).invoke("onSwitchCanvasIndex")(1); expect(onSwitchCanvasIndex).toBeCalledWith( expect.objectContaining({ detail: { canvasIndex: 1, }, }) ); document.body.removeChild(element); }); it("should handle storyboard query update", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onStoryboardQueryUpdate = jest.fn(); element.addEventListener( "storyboard.query.update", onStoryboardQueryUpdate ); wrapper.find(BuilderContainer).invoke("onStoryboardQueryUpdate")("any"); expect(onStoryboardQueryUpdate).toBeCalledWith( expect.objectContaining({ detail: { storyboardQuery: "any", }, }) ); document.body.removeChild(element); }); it("should handle snippet apply", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; element.appId = "test-app"; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onSnippetApply = jest.fn(); element.addEventListener("snippet.apply", onSnippetApply); const event = new CustomEvent<EventDetailOfSnippetApply>( "internal.snippet.apply", { detail: { parentUid: 1, nodeUids: [2, 3], nodeIds: ["a", null], nodeDetails: [ { parentUid: 1, nodeUid: 3, nodeData: { type: "brick", parent: "a", brick: "my.test-brick", mountPoint: "any", }, children: [ { parentUid: 3, nodeUid: 4, nodeData: { type: "brick", brick: "my.another-brick", mountPoint: "another", }, children: [], }, ], }, ], }, } ); wrapper.find(BuilderContainer).invoke("onSnippetApply")(event); expect(onSnippetApply).toBeCalledWith( expect.objectContaining({ detail: { parentUid: 1, nodeUids: [2, 3], nodeIds: ["a", null], nodeDetails: [ { parentUid: 1, nodeUid: 3, nodeData: { appId: "test-app", type: "brick", parent: "a", brick: "my.test-brick", mountPoint: "any", }, children: [ { parentUid: 3, nodeUid: 4, nodeData: { appId: "test-app", type: "brick", brick: "my.another-brick", mountPoint: "another", }, children: [], }, ], }, ], }, }) ); document.body.removeChild(element); }); it("should handle hiddenWrapper switch", () => { const element = document.createElement( "next-builder.builder-container" ) as BuilderContainerElement; document.body.appendChild(element); const wrapper = shallow(spyOnRender.mock.calls[0][0] as any); const onSwitchHiddenWrapper = jest.fn(); element.addEventListener("wrapper.hidden.switch", onSwitchHiddenWrapper); wrapper.find(BuilderContainer).invoke("onSwitchHiddenWrapper")(true); expect(onSwitchHiddenWrapper).toBeCalledWith( expect.objectContaining({ detail: true, }) ); document.body.removeChild(element); }); });
import java.util.EmptyStackException; public class Stack { private stackNode top; private int length; public class stackNode { private int data; private stackNode next; public stackNode(int data) { this.data = data; } } public Stack() { top = null; length = 0; } public int length() { return length; } public boolean isEmpty() { return length == 0; } public void push(int data) { stackNode temp = new stackNode(data); temp.next = top; top = temp; length++; } public int pop() { if (isEmpty()) { throw new EmptyStackException(); } int res = top.data; top = top.next; length--; return res; } public int peek() { if (isEmpty()) { throw new EmptyStackException(); } return top.data; } public static void main(String[] args) { Stack stack = new Stack(); stack.push(10); stack.push(15); stack.push(20); System.out.println(stack.peek()); stack.pop(); System.out.println(stack.peek()); stack.pop(); System.out.println(stack.peek()); } }
import atexit from sqlalchemy import Column, String, Integer, Text, DateTime, create_engine, func from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base PG_DSN = 'postgresql://app:1234@127.0.0.1:5431/ultimate' engine = create_engine(PG_DSN) Base = declarative_base() Session = sessionmaker(bind=engine) atexit.register(engine.dispose) class Announcement(Base): __tablename__ = 'app_announcement' id = Column(Integer, primary_key=True, autoincrement=True) header = Column(String, nullable=False) description = Column(Text, nullable=False) creation_time = Column(DateTime, server_default=func.now()) username = Column(String, nullable=False, unique=True, index=True) Base.metadata.create_all(bind=engine)
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore // ObjectMarshaler allows user-defined types to efficiently add themselves to the // logging context, and to selectively omit information which shouldn't be // included in logs (e.g., passwords). type ObjectMarshaler interface { MarshalLogObject(ObjectEncoder) error } // ObjectMarshalerFunc is a type adapter that turns a function into an // ObjectMarshaler. type ObjectMarshalerFunc func(ObjectEncoder) error // MarshalLogObject calls the underlying function. func (f ObjectMarshalerFunc) MarshalLogObject(enc ObjectEncoder) error { return f(enc) } // ArrayMarshaler allows user-defined types to efficiently add themselves to the // logging context, and to selectively omit information which shouldn't be // included in logs (e.g., passwords). type ArrayMarshaler interface { MarshalLogArray(ArrayEncoder) error } // ArrayMarshalerFunc is a type adapter that turns a function into an // ArrayMarshaler. type ArrayMarshalerFunc func(ArrayEncoder) error // MarshalLogArray calls the underlying function. func (f ArrayMarshalerFunc) MarshalLogArray(enc ArrayEncoder) error { return f(enc) }