text
stringlengths
184
4.48M
package com.ortega.tshombo.feature.myStore.domain.useCase import com.ortega.tshombo.core.utils.PreferencesManager import com.ortega.tshombo.feature.myStore.domain.entity.StoreEntity import com.ortega.tshombo.feature.myStore.domain.repository.IMyStoreRepository import retrofit2.HttpException import java.io.IOException import javax.inject.Inject class GetStore @Inject constructor( private val iMyStoreRepository: IMyStoreRepository, private val preferencesManager: PreferencesManager ) { suspend operator fun invoke( onSuccess: (StoreEntity) -> Unit, onError: (String) -> Unit ) { try { val userId = preferencesManager.getData("userId", "") if (userId != "") { val response = iMyStoreRepository.getStoreByUserId(userId.toInt()) if (response.code() == 200) { if (response.body() != null) { onSuccess(response.body()!!.data) } } else { onError("Fetching error") } } else { onError("Not have a store") } } catch (e: HttpException) { onError(e.localizedMessage ?: "An unexpected error occurred") } catch (e: IOException) { onError(e.localizedMessage ?: "Couldn't reach server. Check your internet connection.") } } }
import React, { useState, useEffect } from "react"; import axios from "axios"; import { User } from "../../../models/user"; import "./ViewUsersGeneral.css"; import { useNavigate } from "react-router-dom"; const apiUrl = "http://localhost:3000"; //const apiUrl='//api.bankitos.duckdns.org'; function ViewUsersGeneral({ _id, token }: { _id: string; token: string }) { const [users, setUsers] = useState<User[]>([]); const [searchText, setSearchText] = useState<string>(""); const navigate = useNavigate(); useEffect(() => { const fetchUsers = async () => { try { const headers = { "x-access-token": token, }; const response = await axios.get(apiUrl + "/users", { headers, }); setUsers(response.data); } catch (error) { console.error("Error fetching users:", error); // Handle error if necessary } }; fetchUsers(); }, [_id, token]); const handleUsersClick = (userId: string) => { // Redirect to the user details page when a user button is clicked navigate(`/user/${userId}`); }; const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => { setSearchText(event.target.value); }; const filteredUsers = users.filter((user) => `${user.first_name} ${user.middle_name ? user.middle_name + " " : ""} ${user.last_name}` .toLowerCase() .includes(searchText.toLowerCase()), ); const renderStars = (rating: string) => { const ratingNumber = parseInt(rating); let stars = []; for (let i = 0; i < ratingNumber; i++) { stars.push(<span key={i}>★</span>); } return stars; }; return ( <div className="containerViewUsersGeneral"> <div className="searchContainer"> <div className="searchInput"> <input type="text" placeholder="Search users..." value={searchText} onChange={handleSearchChange} className="searchInput" /> </div> </div> <div className="buttonContainerViewUsersGeneral"> {filteredUsers.length === 0 ? ( <p>No users with this name</p> ) : ( // Render buttons for each user filteredUsers.map((user) => ( <button key={user._id} onClick={() => handleUsersClick(user._id || "")} className="buttonViewUsersGeneral" > {user.first_name + " "}{" "} {user.middle_name ? user.middle_name + " " : ""}{" "} {" " + user.last_name} <br /> {user.description ? "Description: " + user.description : null} <br /> {renderStars(user.user_rating ? user.user_rating + " " : "")} </button> )) )} </div> </div> ); } export default ViewUsersGeneral;
--- title: "Unlock Windows 10 Booting Secrets: Learn the Easy Way to Clone Your Drive and Supercharge Your PC Performance!" ShowToc: true date: "2023-06-25" author: "Carol Brown" --- ***** # Unlock Windows 10 Booting Secrets: Learn the Easy Way to Clone Your Drive and Supercharge Your PC Performance! Windows 10 is one of the most popular operating systems in the world, with more than 1 billion active users. It's packed with new features and improvements, but sometimes, users still find themselves dealing with slow boot times and sluggish performance. Luckily, there are ways to unlock the secrets of Windows 10 booting and supercharge your PC's performance. One of the most effective methods of improving your PC's performance is by cloning your existing drive. Cloning a drive is a process of creating an exact copy of your current hard drive on a new drive. Cloning your hard drive is highly recommended if you want to upgrade your hardware or if your current hard drive is slowing down your PC. Here are the steps to clone your hard drive and improve your PC's performance: Step 1: Identify your hard drive The first step in the process of cloning your hard drive is to identify which drive you're currently using. In Windows 10, open the File Explorer and navigate to This PC. You should be able to see all the drives connected to your system. Step 2: Choose the new drive The next step is to choose the new drive where you want to clone your existing drive. Ensure that the new drive is larger in capacity than your current drive. You can purchase a new hard drive from any computer store or online. Step 3: Clone your hard drive There are several software tools available that can clone your hard drive. One of the most popular tools is EaseUS Todo Backup. It's free to download, and it's an easy-to-use tool that can clone your hard drive in just a few clicks. Once you've downloaded and installed the software, follow these steps: - Launch EaseUS Todo Backup and click on Clone. - Choose your existing drive as the source and the new drive as the destination. - Click on Proceed to clone your hard drive. Depending on the size of your drive, the process of cloning can take several hours. You can leave your system running during the process, or you can schedule the cloning process overnight. Step 4: Point to the new drive Once the cloning process is complete, you need to tell your PC to boot from the new drive instead of the old one. Restart your computer and press the key to enter the BIOS settings. In the BIOS settings, navigate to the Boot Options, and choose the new drive as the boot device. Save the changes and exit the BIOS settings. Congratulations! You've successfully cloned your hard drive and supercharged your PC's performance. Cloning your hard drive is a simple and effective way to improve your PC's performance. By unlocking the secrets of Windows 10 booting, you can also ensure that your PC is running at top speed. By following these easy steps, you can enjoy a faster and more responsive PC. {{< youtube AAC0Jb4YRc0 >}} Cloning your Windows 10 boot drive to a new hard drive is not as easy as it might seem. While it’s trivial to copy the majority of your files from one drive to another, copying every single file to a bootable disk will require a separate program. And because the source hard drive can’t be active while it’s being copied, you’ll need to use a cloning program that runs outside of Windows. Clonezilla Live runs from a separate boot medium like a CD, DVD, or USB drive, allowing you to copy your boot disk. The process is not difficult, but Clonezilla’s lack of a GUI can make it challenging to navigate confidently. Note: the following method will do a clone of the target hard drive, regardless of the OS it is running. Therefore, it will work for Windows (any version), Linux or even MacOS. ## Create Clonezilla Live Disk 1. Download Clonezilla. Get the version called “stable” with a string of numbers after it. 2. In the next screen, change the file type from “.zip” to “.iso.” Unless you know you need a 32-bit version of the software, you can leave CPU architecture as “amd64.” Leave the repository set to “auto.” Then, click “Download.” 3. Insert a blank CD or DVD into your disk drive. 4. Navigate to the downloaded ISO file in Windows Explorer. Right-click on the file and choose “Burn disc image” from the context menu. 5. Confirm the correct disk drive is selected, and click “Burn” to burn a bootable version of the ISO to disk. ## Boot into Clonezilla Live 1. Make sure both your source and destination hard disks are connected to your computer. 2. Reboot your computer. 3. After you hear the single beep to indicate that POST was completed successfully, you will see your BIOS splash screen. At this point, press either the F12 or DEL key (depending on your BIOS) to choose a boot disk. If you’re not sure what to press, look for an on-screen option that says something like “Boot Menu.” 4. Select your DVD drive from the resulting menu. ## Initialize Clonezilla Live 1. Once Clonezilla Live starts, you’ll see a splash screen. Leave the default and press “Enter” on your keyboard. 2. You’ll see some white text go by indicating that Clonezilla is booting. When it’s done, choose the appropriate language. 3. Leave the default selection (“Don’t touch keymap”), and press Enter on your keyboard to select. 4. Some more white text will go by. When you again see a blue and grey screen, press Enter to choose “Start Clonezilla.” ## Set Up Disk Cloning Now that we’ve initialized everything, we’re ready to clone our disks. 1. On the next screen use the down arrow on your keyboard to select “device-device.” This allows you to clone from one physical hard disk to another physical hard disk. 2. Press the Enter key to choose “Beginner Mode” which is the default. 3. On the next screen leave the default selection of “disk_to_local_disk” and press Enter. This setting allows you to clone one physically-connected disk to another physically-connected disk. The other options allow you to clone to network-connected disks or work with partitions. 4. Select the source disk and press Enter. I’m using a virtual machine to capture screenshots, so you might see more disks. Your menu will also show different names and capacities. Since any names you’ve applied in Windows won’t typically be visible here, pay close attention to disk capacity and mount point. 5. Select the destination disk and press Enter. Again, you might see more hard drives here. 6. Leave the default option to skip checking or repairing the source file system and press Enter. 7. Press Enter again to actually begin the cloning process. ## Run Cloning Process 1. Clonezilla will ask you to confirm that you want to clone the disks, erasing the destination disk in the process. Make sure everything looks correct before typing “y” and pressing Enter. 2. Clonezilla really wants you to be sure. Confirm your choices again, then type “y” and press Enter. 3. You’ll see Clonezilla create the partition table on the destination disk. 4. When prompted, type “y” and press Enter to confirm that you want to clone the bootloader to the destination drive. The bootloader is what allows the computer to start from a disk; without the bootloader, the drive will not be bootable. 5. Finally, the cloning process actually begins! Keep an eye on the progress bars to see how long it will take. 6. When done, Clonezilla will run some self-checks on the cloned drive. Press Enter to continue when prompted. 7. In the next menu press Enter to shut down the machine. 8. After a five-second countdown, Clonezilla will halt itself, and the machine should turn off. If your computer doesn’t shut itself down, you can manually switch it off after you see the line that says [info] Will now halt. You’re done! ## Conclusion After the cloning process is complete, restart your computer and select your newly-cloned disk as your boot drive. Alexander Fox is a tech and science writer based in Philadelphia, PA with one cat, three Macs and more USB cables than he could ever use. Our latest tutorials delivered straight to your inbox
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Image = void 0; var _react = _interopRequireWildcard(require("react")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } const Image = StyledImage => /*#__PURE__*/(0, _react.forwardRef)((_ref, ref) => { let { ...props } = _ref; // Assuming props is an object with a 'source' property let source = props.source; if (typeof source === 'number') { // Handle case where source is a number } else if (!props.source.uri) { // Check if source.uri is not defined or falsy source = { uri: props.source.default ? props.source.default.src : props.source // If so, set source to an object with a 'uri' property // Use a ternary operator to check if props.source.default exists, // and if so, use its 'src' property, otherwise, use the original source }; } const { alt, ...resolvedProps } = props; if (typeof alt !== 'string') { console.warn('Please pass alt prop to Image component'); } return /*#__PURE__*/_react.default.createElement(StyledImage, _extends({}, resolvedProps, { source: source, accessibilityLabel: (props === null || props === void 0 ? void 0 : props.accessibilityLabel) || alt, accessibilityRole: (props === null || props === void 0 ? void 0 : props.accessibilityRole) || 'image', alt: alt, ref: ref })); }); exports.Image = Image; //# sourceMappingURL=Image.js.map
extends ../layouts/default.pug block config //- Global Page Configuration - var pageTitle = 'Multipurpose' append css link(rel='stylesheet', href='https://unpkg.com/aos@next/dist/aos.css') block content //- * * * * * * * * //- * * Navbar * * //- * * * * * * * * include mixins/navbar.pug +navbar({ navbarBg: 'bg-transparent', navbarStyle: 'navbar-dark', navbarBrandColor: 'text-white', navbarBtnColor: 'btn-teal', navbarContainer: 'container', navbarPosition: 'fixed-top' }) //- * * * * * * * * * * //- * * Page Header * * //- * * * * * * * * * * include mixins/header.pug +header({ pageHeaderBg: 'bg-gradient-primary-to-secondary', pageHeaderStyle: 'page-header-dark', svgBorderAngled: false, svgBorderRounded: true, svgBorderWaves: false, svgBorderFill: 'text-white' }) .page-header-content.pt-10 .container .row.align-items-center .col-lg-6(data-aos='fade-up') h1.page-header-title Build your next project faster with SB UI Kit Pro p.page-header-text.mb-5 Welcome to SB UI Kit Pro, a toolkit for building beautiful web interfaces, created by the development team at Start Bootstrap a.btn.btn-teal.font-weight-500.mr-2(href='index.html') | View Pages i.ml-2(data-feather='arrow-right') a.btn.btn-link(href='https://docs.startbootstrap.com/sb-ui-kit-pro/quickstart') | Documentation .col-lg-6.d-none.d-lg-block(data-aos='fade-up', data-aos-delay='100') img.img-fluid(src='assets/img/illustrations/windows.svg') //- img.img-fluid(src='assets/img/drawkit/color/drawkit-content-man-color.svg') //- * * * * * * * * * * * //- * * Features Grid * * //- * * * * * * * * * * * include mixins/section.pug +section({ sectionBg: 'bg-white', sectionPadding: 'py-10', svgBorderAngled: false, svgBorderRounded: true, svgBorderWaves: false, svgBorderFill: 'text-light' }) .container .row.text-center .col-lg-4.mb-5.mb-lg-0 .icon-stack.icon-stack-xl.bg-gradient-primary-to-secondary.text-white.mb-4 i(data-feather='layers') h3 Built for developers p.mb-0 | Our customizable, block-based build system makes creating your next project fast and easy! .col-lg-4.mb-5.mb-lg-0 .icon-stack.icon-stack-xl.bg-gradient-primary-to-secondary.text-white.mb-4 i(data-feather='smartphone') h3 Modern responsive design p.mb-0 | Featuring carefully crafted, mobile-first components, your end product will function beautifully on any device! .col-lg-4 .icon-stack.icon-stack-xl.bg-gradient-primary-to-secondary.text-white.mb-4 i(data-feather='code') h3 Complete documentation p.mb-0 | All of the layouts, page sections, components, and utilities are fully covered in this products docs. //- * * * * * * * * * * * * * //- * * Features Detailed * * //- * * * * * * * * * * * * * include mixins/section.pug +section({ sectionBg: 'bg-light', sectionPadding: 'py-10', svgBorderAngled: false, svgBorderRounded: false, svgBorderWaves: false, svgBorderFill: '' }) .container .row.align-items-center.justify-content-center .col-md-9.col-lg-6.order-1.order-lg-0(data-aos='fade-right') .content-skewed.content-skewed-right img.content-skewed-item.img-fluid.shadow-lg.rounded-lg(src='assets/img/demo/screenshots/landing-portfolio.png', alt='...') .col-lg-6.order-0.order-lg-1.mb-5.mb-lg-0(data-aos='fade-left') .mb-5 h2 Here's What You Get p.lead | When you purchase this UI Kit, you get access to a robust suite of powerful tools and components to help you build your next landing page quickly and easily. .row .col-md-6.mb-4 h6 Landing Pages p.mb-2.small We've crafted landing page examples for many popular business and product types. a.small.text-arrow-icon(href="#!") | Learn More i(data-feather="arrow-right") .col-md-6.mb-4 h6 Page Examples p.mb-2.small.mb-0 Use our pre-built page examples to quickly create inner pages to your website. a.small.text-arrow-icon(href="#!") | Learn More i(data-feather="arrow-right") .row .col-md-6.mb-4 h6 Layouts p.mb-2.small.mb-0 Our flex box based layout options make your site beautifully responsive and adaptable to any device. a.small.text-arrow-icon(href="#!") | Learn More i(data-feather="arrow-right") .col-md-6.mb-4 h6 Modular Sections p.small.mb-0 All of the sections on each page are modular, so you can drop them into an existing page, or start with a new one! a.small.text-arrow-icon(href="#!") | Learn More i(data-feather="arrow-right") hr.m-0 //- * * * * * * * * * * * * //- * * Pricing Section * * //- * * * * * * * * * * * * include mixins/section.pug +section({ sectionBg: 'bg-light', sectionPadding: 'pt-10', svgBorderAngled: false, svgBorderRounded: true, svgBorderWaves: false, svgBorderFill: 'text-dark' }) .container .text-center.mb-5 h2 Pricing Table p.lead Here's an example of a pricing table. .row.z-1 .col-lg-4.mb-5.mb-lg-n10(data-aos='fade-up', data-aos-delay='100') .card.pricing.h-100 .card-body.p-5 .text-center .badge.badge-light.badge-pill.badge-marketing.badge-sm Free .pricing-price sup $ | 0 span.pricing-price-period /mo ul.fa-ul.pricing-list li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark 1 user li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Community support li.pricing-list-item span.fa-li i.far.fa-circle.text-gray-200 | Style customizer li.pricing-list-item span.fa-li i.far.fa-circle.text-gray-200 | Custom components li.pricing-list-item span.fa-li i.far.fa-circle.text-gray-200 | Expanded utilities li.pricing-list-item span.fa-li i.far.fa-circle.text-gray-200 | Third-party integration li.pricing-list-item span.fa-li i.far.fa-circle.text-gray-200 | Layout options .col-lg-4.mb-5.mb-lg-n10(data-aos='fade-up') .card.pricing.h-100 .card-body.p-5 .text-center .badge.badge-primary-soft.badge-pill.badge-marketing.badge-sm.text-primary Standard .pricing-price sup $ | 19 span.pricing-price-period /mo ul.fa-ul.pricing-list li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Up to 15 users li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Email and live chat support li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Style customizer li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Custom components li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Expanded utilities li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Third-party integration li.pricing-list-item span.fa-li i.far.fa-check-circle.text-teal span.text-dark Layout options .col-lg-4.mb-lg-n10(data-aos='fade-up', data-aos-delay='100') .card.pricing.h-100 .card-body.p-5 .text-center .badge.badge-light.badge-pill.badge-marketing.badge-sm Enterprise p.card-text.py-10 This is an example of the pricing table element that is included with this UI kit! //- * * * * * * * * * * //- * * FAQ Section * * //- * * * * * * * * * * include mixins/section.pug +section({ sectionBg: 'bg-dark', sectionPadding: 'py-10', svgBorderAngled: false, svgBorderRounded: true, svgBorderWaves: false, svgBorderFill: 'text-white' }) .container .row.my-10 .col-lg-6.mb-5 .d-flex.h-100 .icon-stack.flex-shrink-0.bg-teal.text-white i.fas.fa-question .ml-4 h5.text-white What is SB UI Kit Pro? p.text-white-50 SB UI Kit Pro is a fully coded, responsive, Bootstrap based UI toolkit for developers. .col-lg-6.mb-5 .d-flex.h-100 .icon-stack.flex-shrink-0.bg-teal.text-white i.fas.fa-question .ml-4 h5.text-white What can I build with SB UI Kit Pro? p.text-white-50 Build anything you want to using this UI kit! It is flexible, multipurpose, and full of tools for you to use during development. .col-lg-6.mb-5.mb-lg-0 .d-flex.h-100 .icon-stack.flex-shrink-0.bg-teal.text-white i.fas.fa-question .ml-4 h5.text-white Do I get free updates? p.text-white-50 All of Start Bootstrap's premium products will come with updates for feature additions, bugfixes, and other small updates. .col-lg-6 .d-flex.h-100 .icon-stack.flex-shrink-0.bg-teal.text-white i.fas.fa-question .ml-4 h5.text-white What frameworks does it integrate with? p.text-white-50 Our HTML based pro products are build with framework integration in mind. The compiled code is HTML and CSS, which is able to integrate with any framework. .row.justify-content-center.text-center .col-lg-8 .badge.badge-transparent-light.badge-pill.badge-marketing.mb-4 Get Started h2.text-white Save time with SB UI Kit Pro p.lead.text-white-50.mb-5 Start Bootstrap's premium UI Kit beautifully and intuitively extends the Bootstrap framework making it easy to build your next project! a.btn.btn-teal.font-weight-500(href='#!') Buy Now! //- * * * * * * * * * * * //- * * Testimonials * * //- * * * * * * * * * * * include mixins/section.pug +section({ sectionBg: 'bg-white', sectionPadding: 'pt-10', svgBorderAngled: false, svgBorderRounded: true, svgBorderWaves: false, svgBorderFill: 'text-light' }) .container .row.mb-10 .col-lg-6.mb-5.mb-lg-0.divider-right(data-aos='fade') .testimonial.p-lg-5 .testimonial-brand.text-gray-400 include /assets/img/demo/brand-logos/google.svg p.testimonial-quote.text-primary | "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ut error vel omnis adipisci. Ad nam officiis sapiente dicta incidunt harum." .testimonial-name | Adam Hall .testimonial-position | Head of Engineering .col-lg-6(data-aos='fade', data-aos-delay='100') .testimonial.p-lg-5 .testimonial-brand.text-gray-400 include /assets/img/demo/brand-logos/instagram.svg p.testimonial-quote.text-primary | "Adipisci mollitia nemo magnam iure, temporibus molestiae odit, sit harum dolores neque maiores quo eligendi nam corrupti." .testimonial-name | Lia Peterson .testimonial-position | Technical Project Manager .row .col-lg-6.mb-lg-n10.mb-5.mb-lg-0.z-1 a.card.text-decoration-none.h-100.lift(href='#!') .card-body.py-5 .d-flex.align-items-center .icon-stack.icon-stack-xl.bg-primary.text-white.flex-shrink-0 i(data-feather='activity') .ml-4 h5.text-primary Work smarter, not harder p.card-text.text-gray-600 Learn more about how our product can save you time and effort in the long run! .col-lg-6.mb-lg-n10.z-1 a.card.text-decoration-none.h-100.lift(href='#!') .card-body.py-5 .d-flex.align-items-center .icon-stack.icon-stack-xl.bg-secondary.text-white.flex-shrink-0 i(data-feather='code') .ml-4 h5.text-secondary Built for developers p.card-text.text-gray-600 Our components, utilities, and layouts are built with developers in mind. //- * * * * * * * * * * * * //- * * Company Section * * //- * * * * * * * * * * * * include mixins/section.pug +section({ sectionBg: 'bg-light', sectionPadding: 'py-10', svgBorderAngled: false, svgBorderRounded: false, svgBorderWaves: false, svgBorderFill: '' }) .container.mt-5 .row.align-items-center .col-lg-6 h4 Ready to get started? p.lead.mb-5.mb-lg-0.text-gray-500 Get in touch or create an account. .col-lg-6.text-lg-right a.btn.btn-primary.font-weight-500.mr-3.my-2(href='#!') Contact Sales a.btn.btn-white.font-weight-500.my-2.shadow(href='#!') Create Account hr.m-0 block footer include mixins/footer.pug +footer({ footerBg: 'bg-light', footerStyle: 'footer-light' }) append scripts script(src='https://unpkg.com/aos@next/dist/aos.js') script. AOS.init({ disable: 'mobile', duration: 600, once: true });
<template> <button class = 'drawer-item' @mousedown.left = 'addRipple' @mouseup.left = 'ripples = []' > <transition-group class = 'drawer-item__ripples' name = 'drawer-item__ripple-grow' tag = 'div' > <div v-for = 'ripple in ripples' :key = 'ripple.id' :style = '{ top: ripple.top, left: ripple.left, width: ripple.width, height: ripple.height }' class = 'drawer-item__ripple' /> </transition-group> <span class = 'drawer-item__wrapper-icon'> <slot /> </span> <span class = 'drawer-item__wrapper-text' v-text = 'title' /> </button> </template> <script> import { ref } from 'vue'; export default { name: 'DrawerItem', props: { title: { type: String, default: '' } }, setup() { const ripples = ref([]); const addRipple = ({ clientX, clientY, target }) => { const { top, left } = target.getBoundingClientRect(); const rippleSize = Math.max(target.offsetWidth, target.offsetHeight); ripples.value.push({ id: Date.now(), top: `${clientY - top - rippleSize / 2}px`, left: `${clientX - left - rippleSize / 2}px`, width: `${rippleSize}px`, height: `${rippleSize}px` }); }; return { ripples, addRipple }; } }; </script> <style scoped> .drawer-item { position: relative; display: flex; align-items: center; width: 100%; height: 4rem; padding: 0 .8rem; overflow: hidden; font-weight: 500; font-size: 1.3rem; line-height: 1rem; font-family: 'Roboto', sans-serif; color: #2c3e50; text-decoration: none; background-color: transparent; border: none; border-radius: .2rem; outline: none; cursor: pointer; user-select: none; will-change: box-shadow; } .drawer-item:not(:last-child) { margin-bottom: .4rem; } .drawer-item::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: currentColor; border-radius: inherit; opacity: 0; transition: opacity .3s cubic-bezier(.25, .8, .5, 1); pointer-events: none; will-change: opacity; } .drawer-item:hover:enabled::before { opacity: .05; } .drawer-item:focus:enabled::before { opacity: .1; } .drawer-item__wrapper-icon { height: 2.4rem; margin-right: 3.2rem; pointer-events: none; fill: #757575; } .drawer-item__wrapper-icon > :first-child { height: 100%; } .drawer-item__wrapper-text { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; pointer-events: none; } .drawer-item__ripples { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; } .drawer-item__ripple { position: absolute; background-color: rgba(255, 255, 255, .3); background-color: currentColor; border-radius: 50%; transform: scale(0); opacity: .3; will-change: opacity, transform; } .drawer-item__ripple-grow-enter-active { transition: transform 1.5s ease-out; } .drawer-item__ripple-grow-leave-active { transition: .7s ease-out; transition-property: opacity, transform; } .drawer-item__ripple-grow-enter-from { transform: scale(0); } .drawer-item__ripple-grow-enter-to { transform: scale(4); } .drawer-item__ripple-grow-leave-from { transform: scale(4); opacity: .3; } .drawer-item__ripple-grow-leave-to { transform: scale(4); opacity: 0; } </style>
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * 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/>. */ package org.kuali.kra.award; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.award.home.Award; import org.kuali.kra.award.home.approvedsubawards.AwardApprovedSubaward; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.coeus.sys.api.model.ScaleTwoDecimal; import org.kuali.rice.krad.util.AuditCluster; import org.kuali.rice.krad.util.AuditError; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.document.Document; import org.kuali.rice.krad.rules.rule.DocumentAuditRule; import java.util.ArrayList; import java.util.List; public class AwardSubawardAuditRule implements DocumentAuditRule { private static final String SUBAWARD_AUDIT_ERRORS = "subawardAuditErrors"; private static final String SUBAWARD_AUDIT_WARNINGS = "subawardAuditWarnings"; List<AwardApprovedSubaward> awardApprovedSubawards; private List<AuditError> auditErrors; private List<AuditError> auditWarnings; @Override public boolean processRunAuditBusinessRules(Document document) { boolean valid = true; AwardDocument awardDocument = (AwardDocument) document; auditErrors = new ArrayList<AuditError>(); auditWarnings = new ArrayList<AuditError>(); Award award = awardDocument.getAward(); this.awardApprovedSubawards = award.getAwardApprovedSubawards(); if(!validateApprovedSubawardDuplicateOrganization(awardApprovedSubawards)){ valid = false; auditErrors.add(new AuditError(Constants.SUBAWARD_AUDIT_RULES_ERROR_KEY, KeyConstants.ERROR_DUPLICATE_ORGANIZATION_NAME, Constants.MAPPING_AWARD_HOME_PAGE + "." + Constants.SUBAWARD_PANEL_ANCHOR, new String[]{"Organization"})); } for (int i = 0; i < awardApprovedSubawards.size(); i++) { AwardApprovedSubaward subAward = awardApprovedSubawards.get(i); ScaleTwoDecimal amount = subAward.getAmount(); if (amount == null) { valid = false; // a "required field" error is already reported by the framework, so don't call reportError } else if(!amount.isGreaterThan(new ScaleTwoDecimal(0.00))) { valid = false; auditWarnings.add(new AuditError("document.awardList[0].awardApprovedSubawards[" + i + "].amount", KeyConstants.ERROR_AMOUNT_IS_ZERO, Constants.MAPPING_AWARD_HOME_PAGE + "." + Constants.SUBAWARD_PANEL_ANCHOR, null)); } } reportAndCreateAuditCluster(); return valid; } /** * This method creates and adds the AuditCluster to the Global AuditErrorMap. */ @SuppressWarnings("unchecked") protected void reportAndCreateAuditCluster() { if (auditErrors.size() > 0) { GlobalVariables.getAuditErrorMap().put(SUBAWARD_AUDIT_ERRORS, new AuditCluster(Constants.SUBAWARD_PANEL_NAME, auditErrors, Constants.AUDIT_ERRORS)); } if (auditWarnings.size() > 0) { GlobalVariables.getAuditErrorMap().put(SUBAWARD_AUDIT_WARNINGS, new AuditCluster(Constants.SUBAWARD_PANEL_NAME, auditWarnings, Constants.AUDIT_WARNINGS)); } } /** * * Test Approved Subawards for duplicate organizations * @return Boolean */ protected boolean validateApprovedSubawardDuplicateOrganization(List<AwardApprovedSubaward> awardApprovedSubawards){ boolean valid = true; int index = 0; test: for (AwardApprovedSubaward loopAwardApprovedSubaward : awardApprovedSubawards) { int innerIndex = 0; for(AwardApprovedSubaward testAwardApprovedSubaward : awardApprovedSubawards) { if (innerIndex != index) { if(testAwardApprovedSubaward.getOrganizationName().equals(loopAwardApprovedSubaward.getOrganizationName())){ valid = false; break test; } innerIndex++; } } index++; } return valid; } }
<template> <h2 :style="{ color: color }">COLOR CHANGING</h2> </template> <script> import { ref, computed } from "vue"; import { useTransition, TransitionPresets } from "@vueuse/core"; export default { setup() { // 色值/位置 const source = ref([255, 255, 255]); const output = useTransition(source, { duration: 3000, transition: TransitionPresets.easeOutExpo, }); const color = computed(() => { const [r, g, b] = output.value; return `rgb(${r}, ${g}, ${b})`; }); source.value = [0, 0, 0]; return { color, }; }, }; </script>
from typing import Optional from sqlalchemy.orm.session import Session from domain.api_key.entities import ApiKey, UserApiKey from domain.api_key.repositories import IUserApiKeyRepository from .data_mappers import ApiKeyDataMapper, UserApiKeyDataMapper from .models import ApiKeyModel, UserApiKeyModel class ApiKeyRepository: session: Session def __init__(self, session: Session): self.session = session def add(self, api_key: ApiKey): api_key_model = ApiKeyDataMapper.entity_to_model(api_key) self.session.add(api_key_model) self.session.commit() def get_by_key_id(self, key_id: str) -> Optional[ApiKey]: api_key_model = self.session.query(ApiKeyModel).filter_by(key_id=key_id).one_or_none() if api_key_model: return ApiKeyDataMapper.model_to_entity(api_key_model) return None def delete(self, key_id: str) -> Optional[ApiKey]: api_key_model = self.session.query(ApiKeyModel).filter_by(key_id=key_id).one_or_none() if not api_key_model: return None api_key = ApiKeyDataMapper.model_to_entity(api_key_model) self.session.delete(api_key_model) self.session.commit() return api_key def next_api_key_id(self) -> str: api_key_id = None while not api_key_id or self.session.query(ApiKeyModel).filter_by(key_id=api_key_id).one_or_none() is not None: api_key_id = ApiKey.next_id() return api_key_id class UserApiKeyRepository(IUserApiKeyRepository): session: Session def __init__(self, session: Session): self.session = session self.api_key_repository = ApiKeyRepository(session) def add(self, user_api_key: UserApiKey) -> UserApiKey: self.api_key_repository.add(user_api_key.api_key) user_api_key_model = UserApiKeyDataMapper.entity_to_model(user_api_key) self.session.add(user_api_key_model) self.session.commit() return user_api_key def get_user_api_keys(self, user_id: int) -> list[UserApiKey]: user_api_key_models = self.session.query(UserApiKeyModel).filter_by(user_id=user_id).all() result = [] for user_api_key_model in user_api_key_models: api_key = self.api_key_repository.get_by_key_id(user_api_key_model.key_id) result.append(UserApiKeyDataMapper.model_to_entity(user_api_key_model, api_key)) return result def get_by_key_id(self, key_id: str) -> Optional[UserApiKey]: user_api_key_model = self.session.query(UserApiKeyModel).filter_by(key_id=key_id).one_or_none() if not user_api_key_model: return None api_key = self.api_key_repository.get_by_key_id(key_id) return UserApiKeyDataMapper.model_to_entity(user_api_key_model, api_key) def delete(self, key_id: str) -> Optional[UserApiKey]: user_api_key_model = self.session.query(UserApiKeyModel).filter_by(key_id=key_id).one_or_none() if not user_api_key_model: return None self.session.delete(user_api_key_model) self.session.commit() api_key = self.api_key_repository.delete(key_id) user_api_key = UserApiKeyDataMapper.model_to_entity(user_api_key_model, api_key) return user_api_key def next_api_key_id(self) -> str: return self.api_key_repository.next_api_key_id()
import dotenv from "dotenv"; import path from "path"; import { createProduct, deleteProductById, getProductBy, getProducts, updateProduct } from "./"; import { createCategory, deleteCategoryById } from "../category"; import { ProductReturnType, ProductFullInterface } from "../../interfaces/Product"; import { CategoryCreatedReturnType } from "../../interfaces/Category"; // to resolve "Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string" dotenv.config({ path: `${path.join(__dirname, `../../../../.env.test`)}`, }); describe("Product Model", () => { let categoryId: number; let product: ProductFullInterface = { id: "", name: "Product 1", price: 999, categoryId: 0, }; beforeAll(async function () { const result: CategoryCreatedReturnType = await createCategory("New Category"); categoryId = result.id; product.categoryId = result.id; }); afterAll(async function () { await deleteCategoryById(categoryId); }); it("should have a createProduct method", () => { expect(createProduct).toBeDefined(); }); it("should have a getProducts method", () => { expect(getProducts).toBeDefined(); }); it("should have a getProductBy method", () => { expect(getProductBy).toBeDefined(); }); it("should have a deleteProductById method", () => { expect(deleteProductById).toBeDefined(); }); it("should have a updateProduct method", () => { expect(updateProduct).toBeDefined(); }); it("should create a product normally using createProduct method", async () => { const result: ProductReturnType = await createProduct(product); product = result; expect(result.id).toBeDefined(); expect(result.name).toBeDefined(); expect(result.name).toEqual(product.name); }); it("should get a product by id normally using getProductBy method", async () => { const result: ProductReturnType = await getProductBy("id", product.id); expect(result.id).toBeDefined(); expect(result.name).toBeDefined(); expect(result.id).toEqual(product.id); }); it("should update a product by id normally using updateProduct method", async () => { const newPrice = 1100; const result: ProductReturnType = await updateProduct({ ...product, price: newPrice }); product = result; expect(result.id).toBeDefined(); expect(result.name).toBeDefined(); expect(Number(result.price)).toEqual(newPrice); }); it("should get all products using getProducts method", async () => { const result: ProductReturnType[] = await getProducts(); expect(result.length).toBeGreaterThanOrEqual(1); expect(result).toContain(product); }); it("should delete product by id using deleteProductById method", async () => { const result: ProductReturnType = await deleteProductById(product.id); expect(result.id).toBeDefined(); expect(result.id).toEqual(product.id); }); });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Wishlist</title> <link href="/admin/favicon/favicon.ico" rel="icon"> <style> .gradient-custom { /* fallback for old browsers */ background: #151317; /* Chrome 10-25, Safari 5.1-6 */ background: -webkit-linear-gradient(to right, rgb(82, 10, 10), rgb(19, 66, 154)); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ background: linear-gradient(to right, rgb(29, 16, 16), rgb(34, 1, 11)) } </style> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark fixed-top" style="background-color: #0000004a;"> <div class="container px-4 px-lg-5"> <a class="navbar-brand text-warning fw-bold fs-2" href="/">Comic World</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0 ms-lg-4"> <li class="nav-item"><a class="nav-link active" aria-current="page" href="/">Home</a></li> <li class="nav-item"><a class="nav-link" href="/Comic">Comics</a></li> <li class="nav-item"><a class="nav-link " href="/collectables">Collectables</a></li> </ul> <form class="d-flex text-center"> <a href="/Cart" class="btn text-light btn-sm me-3" type="submit"> <i class="bi-cart-fill me-2"></i><span>Cart</span> </a> <a href="/Wishlist" class="btn text-light btn-sm me-3" type="submit"> <i class="bi bi-bag-heart-fill me-2"></i><span>Wishlist</span> {{!-- <span class="badge bg-dark text-white ms-1 rounded-pill">0</span> --}} </a> {{#if Log}} {{!-- <a href="/Profile" class="btn btn-sm text-light" type="submit"> <i class="bi bi-person-circle me-2"></i>{{Log.name}}</i> </a> --}} <div class="dropdown"> <button class="btn text-light dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> <i class="bi bi-person-circle me-2"></i> {{Log.name}} </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="/UserProfile">Profile</a></li> <li><a class="dropdown-item" href="/UserLogout">Logout</a></li> </ul> </div> {{else}} <a href="/Login" class="btn btn-sm btn-outline-warning" type="submit"> <i class="bi bi-door-open"></i></i> Login </a>{{/if}} </form> </div> </div> </nav> <section class=" gradient-custom" style="height:100vh;"> <div class="container py-5"> <div class="row d-flex justify-content-center my-4"> <div class="col-md-8"> <div class="card mb-4"> <div class="card-header py-3"> <h5 class="mb-0">Wishlist</h5> </div> {{#each products}} <div class="card-body"> <!-- Single item --> {{!-- {{#each Cart}} --}} <div class="row"> <div class="col-lg-3 col-md-12 mb-4 mb-lg-0"> <!-- Image --> <div class="bg-image hover-overlay hover-zoom ripple rounded" data-mdb-ripple-color="light"> <img src="/admin/images/{{this.image.[0].filename}}" class="w-50 h-75" alt="Blue Jeans Jacket" /> <a href="#!"> <div class="mask" style="background-color: rgba(251, 251, 251, 0.2)"></div> </a> </div> <!-- Image --> </div> <div class="col-lg-5 col-md-6 mb-4 mb-lg-0"> <!-- Data --> <h3>{{this.name}}</h3> <p>{{this.category}} > {{this.subCategory}}</p> <a class="btn btn-primary btn-sm me-1 mb-2" href="/DeleteWish/{{this._id}}" data-mdb-toggle="tooltip" title="Remove item"> <i class="fas fa-trash"></i> </a> <a class="btn btn-success btn-sm me-1 mb-2" href="/MoveCart/{{this._id}}" data-mdb-toggle="tooltip" title="Move to Cart"> <i class="bi bi-cart-fill"></i> </a> <!-- Data --> </div> <div class="col-lg-4 col-md-6 mb-4 mb-lg-0"> <!-- Price --> <p class="text-start text-md-center"> <strong><i class="bi bi-currency-rupee"></i>{{this.price}}</strong> </p> <!-- Price --> </div> </div> <!-- Single item --> <hr class="my-4" /> </div> {{/each}} </div> </div> </div> </section> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> </body> </html>
<template> <div class="credential-list"> <b-container class="credential-list__header mb-2 p-0" fluid> <b-row no-gutters> <b-col cols="7" sm="9" class=" pl-2 pr-3">Name</b-col> <b-col cols="4" sm="2">Updated</b-col> <b-col cols="1" class="text-center"> <font-awesome-icon :icon="['fas', 'angle-left']" /> </b-col> </b-row> </b-container> <CredentialListItem v-for="(credential, index) in localCredentials" :key="index" :credential="credential" @onClickCredential="() => toggleCred(index)" /> </div> </template> <script> import Vue from 'vue' import { cloneDeep } from 'lodash' import { BContainer, BRow, BCol } from 'bootstrap-vue' import CredentialListItem from '@/components/CredentialListItem.vue' export default Vue.extend({ components: { CredentialListItem, BContainer, BRow, BCol }, props: { credentials: { type: Array, required: true } }, data() { return { localCredentials: [] } }, watch: { credentials(newValue) { newValue && this.buildLocalCredentials() } }, created() { this.buildLocalCredentials() }, methods: { buildLocalCredentials() { const newCredentials = cloneDeep(this.credentials) this.localCredentials = newCredentials.map((cred) => ({ ...cred, open: false })) }, toggleCred(index) { const newCredentials = cloneDeep(this.localCredentials) this.localCredentials = newCredentials.map((cred, indx) => { if (index === indx) { cred.open = !cred.open } return cred }) } } }) </script> <style lang="scss"> .credential-list { &__header { font-size: 14px; } } </style>
<template> <v-table> <tr> <th class="py-2 text-left">Elève</th> <th> <div class="bg-blue-lighten-1 rounded py-1 px-1">Moyenne</div> </th> <th v-for="tr in props.travaux" :key="tr.Id"> <div class="bg-blue-lighten-4 rounded mx-2 my-1 py-1 text-subtitle-1"> {{ props.sheets.get(tr.IdSheet)!.Sheet.Title }} </div> </th> </tr> <tr v-for="(student, index) in data?.Students" :key="index" :class="{ 'bg-grey-lighten-2': index % 2 == 0 }" > <td class="px-2 text-left">{{ student.Label }}</td> <td class="pa-1 text-center font-weight-bold"> {{ getMoyenne(student) }} </td> <td class="text-center" v-for="tr in props.travaux" :key="tr.Id"> <MarksTableCell :data="getMark(tr, student)"></MarksTableCell> </td> </tr> </v-table> </template> <script setup lang="ts"> import type { HomeworkMarksOut, SheetExt, StudentHeader, Travail, StudentTravailMark } from "@/controller/api_gen"; import MarksTableCell from "./MarksTableCell.vue"; interface Props { data: HomeworkMarksOut; travaux: Travail[]; sheets: Map<number, SheetExt>; } const props = defineProps<Props>(); function getMark(tr: Travail, student: StudentHeader) { const sheetMarks = (props.data?.Marks || {})[tr.Id]; const mark: StudentTravailMark = (sheetMarks.Marks || {})[student.Id] || { Mark: 0, Dispensed: false, NbTries: 0 }; return mark; } function getMoyenne(student: StudentHeader) { let total = 0; let nbTravaux = 0; props.travaux.forEach(tr => { const m = getMark(tr, student); if (m.Dispensed) { return; } total += m.Mark; nbTravaux += 1; }); if (nbTravaux == 0) return "-"; return (total / nbTravaux).toFixed(2); } </script>
package com.eztech.fitrans.service; import com.eztech.fitrans.constants.PositionTypeEnum; import com.eztech.fitrans.model.Department; import com.eztech.fitrans.model.Role; import com.eztech.fitrans.model.UserEntity; import com.eztech.fitrans.repo.DepartmentRepository; import com.eztech.fitrans.repo.RoleRepository; import com.eztech.fitrans.repo.UserRepository; import com.eztech.fitrans.util.DataUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Slf4j @CacheConfig(cacheNames = { "UserDetailsServiceImpl" }, cacheManager = "localCacheManager") public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository repo; @Autowired private RoleRepository roleRepository; @Autowired private DepartmentRepository departmentRepo; public Boolean isLdap; public Boolean isAdmin; public void setIsLdap(Boolean isLdap) { this.isLdap = isLdap; } public Boolean getIsLdap() { return this.isLdap; } public void setIsAdmin(Boolean isAdmin) { this.isAdmin = isAdmin; } public Boolean getIsAdmin() { return this.isAdmin; } @Override @Cacheable(key = "#username", cacheManager = "localCacheManager") public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity user = repo.findByUsername(username); // if(isLdap) { if (user != null) { if (!"ACTIVE".equalsIgnoreCase(user.getStatus())) { throw new UsernameNotFoundException("User exist but not active - User not found with username: " + username); } List<String> role = new ArrayList<>(); List<Long> listRole = new ArrayList<>(); List<Role> roles = roleRepository.getRole(user.getId()); if (DataUtils.notNullOrEmpty(roles)) { listRole = roles.stream() .map(Role::getId) .collect(Collectors.toList()); role = repo.getRoleDetail(listRole); } return new User(user.getUsername(), user.getPassword(), buildSimpleGrantedAuthorities(roles, role)); } else { throw new UsernameNotFoundException("User not found: " + username); } // else { // if (isLdap) { // log.warn("User login ldap ok but not found with username in db {} ---> Create in db", username); // user = new UserEntity(); // user.setEmail(username + "@bidv.com.vn"); // user.setFullName(username); // user.setUsername(username); // user.setStatus("ACTIVE"); // user.setPassword("$2a$10$xgMeNxDvGTeI2u/MwPqKV.oIq8O1OeDEhcy8k19V.dTvLpWe88xRS"); // // user.setPosition(PositionTypeEnum.UNKNOWN.getName()); // // user. // repo.save(user); // return new User(user.getUsername(), user.getPassword(), // buildSimpleGrantedAuthorities(new ArrayList<>(), new ArrayList<>())); // } else { // // add lần đầu // if (isAdmin) { // user = new UserEntity(); // user.setEmail(username + "@bidv.com.vn"); // user.setFullName(username); // user.setUsername(username); // user.setStatus("ACTIVE"); // user.setPassword("$2a$10$xgMeNxDvGTeI2u/MwPqKV.oIq8O1OeDEhcy8k19V.dTvLpWe88xRS"); // // user.setPosition(PositionTypeEnum.UNKNOWN.getName()); // repo.save(user); // return new User(user.getUsername(), user.getPassword(), // buildSimpleGrantedAuthorities(new ArrayList<>(), new ArrayList<>())); // } else { // throw new UsernameNotFoundException("User not login LDAP - User not found with username: " + username); // } // } // } } private static List<SimpleGrantedAuthority> buildSimpleGrantedAuthorities(final List<Role> roles, List<String> roleList) { List<SimpleGrantedAuthority> authorities = new ArrayList<>(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } if (DataUtils.notNullOrEmpty(roleList)) { for (String role : roleList) { authorities.add(new SimpleGrantedAuthority(role)); } } return authorities; } public String getDepartmentCodeByUsername(String username) { // UserEntity user = repo.findByUsername(username); String code = repo.findCodeByUsername(username); if (code == null) { log.warn("User login ldap ok but not found deparment with username in db:", username); // throw new UsernameNotFoundException("Username not found department: " + username); code = "UNKNOWN"; } return code; } public String getRoleByUsername(String username) { String role = repo.findRoleByUsername(username); if (DataUtils.isNullOrEmpty(role)) { log.warn("User login ldap ok but not found role with username in db:" + username); // throw new UsernameNotFoundException("Username not found role: " + username); role = Role.ROLE_USER; } return role; } public Map<String, Object> getPositionByUsername(String username) { UserEntity user = repo.findByUsername(username); Map<String, Object> mapper = new HashMap<String, Object>(); String position = null; String fullname = null; Long departmentId = null; if (DataUtils.isNullOrEmpty(user)) { log.warn("User login ldap ok but not found with username in db:" + username); // throw new UsernameNotFoundException("Username not found position: " + username); mapper.put("position", "UNKNOWN"); mapper.put("fullname", "UNKNOWN"); mapper.put("departmentId", "UNKNOWN"); } else { // Integer priorityCard = repo.getPriorityCardByDepartmentId(user.getDepartmentId()); position = !DataUtils.isNullOrEmpty(user.getPosition()) ? user.getPosition() : "UNKNOWN"; fullname = !DataUtils.isNullOrEmpty(user.getFullName()) ? user.getFullName() : "UNKNOWN"; departmentId = !DataUtils.isNullOrEmpty(user.getDepartmentId()) ? user.getDepartmentId() : null; mapper.put("position", position); mapper.put("fullname", fullname); mapper.put("departmentId", departmentId); } return mapper; } }
DDL (Data Definition Language 데이터 정의) 테이터의 스키마 객체를 생성 변경 제거 하거나 권한의 부여나 박탈 주석 자료버림등을 수행 데이터베이스 구조를 정의하고 관리 객체를 생성, 수정, 삭제하는데 사용한다. 대표적인 명령문 CREATE(생성), ALTER(수정), DROP(삭제), COMMENT(주석), GRANT, REVOKE (권한부여), TRUNCATE(자료버림) CREATE(생성) : CREATE TABLE : 새로운 테이블 생성 CREATE VIEW : 가상 테이블을 생성해서 데이터 베이스 일부 데이터에 대한 뷰를 정의 CREATE DATABASE : 새로운 데이터베이스를 생성 CREATE INDEX : 새로운 인덱스를 생성하여 데이터 검색속도 향상 ALTER TABLE 테이블이름 MODIFY(변경하고자하는 열의 이름 문자열유형(수정값 BYTE)); 예제코드 : ALTER TABLE EMPLOYEE MODIFY(JOB VARCHAR2(20 BYTE)); 코드 설명 : 'EMPLOYEE' 테이블에서 'JOB'열에 입력된 값이 열의 최대 길이를 초과하여 문제가 발생했을 경우 ALTER와 MODIFY를 작성하여 JOB 열의 크기를 20BYTE로 변경할 수 있다. ALTER(수정) : ALTER TABLE : 이미 존재하는 테이블의 구조 변경, 열을 추가하고 수정, 삭제, 제약 조건등을 변경할 수 있음 ALTER INDEX : 이미 존재하는 인덱스의 구조 변경 ALTER SESSION SET "_ORACLE_SCRIPT" = TRUE; Oracle DataBase에서 "ORACLE_SCRIPT" 모드 활성 -> 12C 이상 버전에서 사용할 수 있는 특별한 모드 DROP : 데이터베이스에서 객체(테이블, 뷰, 인덱스, 사용자 등)를 삭제하는데 사용되는 sql 명령어 / 영구삭제 DROP TABLE 테이블이름; DROP VIEW 뷰이름; DROP INDEX 인덱스 이름; DROP USER 사용자이름; CASCADE : 해당 명령이 연결된 객체 또는 데이터 영향 주는 방식 지정 주로 삭제 명령으로 사용 삭제 명령이 관련된 모든 객체나 데이터를 삭제 DROP TABLE 부모테이블 CASCADE CONSTRAINTS; GRANT(권한부여) : 권한을 부여하는 키워드 SELECT INSERT UPDATE DELECT CREATE TABLE등을 수행하는 권한을 지정할 수 있다. GRANT 사용 예제 : GRANT 권한 TO 역할 또는 사용자[WITH GRANT OPTION]; CREATE SESSION 권한 부여 : 사용자가 데이터베이스에 로그인하고 세션을 생성하는데필요한 권한. 이 권한을 부여하면 부여된 사용자는 데이터베이스에 로그인 할 수 있는 권한을 가지게 됨 CREATE ANY TABLE 권한 부여 : 사용자가 데이터베이스 내에서 어떤 스키마나 테이블을 생성할 수 있는 권한을 부여 권한이 부여된 사용자는 어떤 스키마에서든 테이블을 생성할 수 있다. CONNECT : 사용자가 데이터베이스에 연결하는데 필요한 권한 RESOURCE : 사용자가 테이블, 시퀀스 등의 리소스를 생성할 수 있는 권한 부여 DBA : 데이터베이스 관리자 권한을 가짐 사용자에게 거의 모든 데이터베이스 작업을 수행할 수 있는 권한을 부여 이 권한은 보안상 주의해서 부여 SESSION (세션) : 컴퓨터 네트워크 분야에서 사용되는 용어 사용자 또는 클라이언트 서버 간의 연결을 나타냄 데이터베이스는 사용자 또는 응용프로그램이 데이터베이스 서버에 연결하고 상호 작용하는 동안 작업의 단위 의미 각 세션은 독립적인 환경을 가지며, 데이터베이스 서버와 통신을 담당. SET (설정) : 설정 또는 조정하는데 사용 변수 설정 : 변수값을 설정하거나 변경하는데 사용 SET Salary = 5000; 변수를 5000으로 설정하는것을 의미 DML (Data Manipulation Language 데이터 조작 언어) 데이터를 생성 수정 삭제하거나 조회하는데 사용되는 언어 INSERT (데이터 삽입) : 데이터베이스 테이블에 새로운 레코드(행) 삽입 SELECT (데이터 조회) : 데이터베이스 테이블에서 데이터를 조회하고 검색 UPDATE (데이터 수정) : 이미 존재하는 데이터를 업데이트 하고 수정 DELETE (데이터 삭제) : 데이터베이스 테이블에서 행 삭제 예제 코드 : INSERT : INSERT INTO 테이블이름 (열1, 열2, 열3, ...) VALUES(값1, 값2, 값3, ...); SELECT : SELECT 열1, 열2, ... (만약 열을 지정하지 않고 모두 보고자 할 경우 * 입력) FROM 테이블이름 WHERE 조건; UPDATE : UPDATE 테이블이름 SET 열1 = 값1, 열2 = 값2, ... WHERE 조건; DELETE : DELETE FROM 테이블이름 WHERE 조건
--- title: "Weather App" date: 2020-11-15 lesson: 35 --- <!-- Setting the html code --> {% set html %} <div id="app" class="weatherApp l-stack">Checking the weather near you...</div> {% endset %} <!-- Setting the js code --> {% set js %} <script> // Variables let locationAPI = 'https://ipapi.co/json' let city; let weatherAPI = ' https://api.weatherbit.io/v2.0/current' let weatherKey = '5503cec5734c4b79a0f908a36937391e' let app = document.querySelector('#app'); // Methods function renderWeather(prop) { app.innerHTML = ` <p>{% include "icons/map-pin.svg" %} ${city}</p> <div class="weatherGrid"> <img src="https://www.weatherbit.io/static/img/icons/${prop.weather.icon}.png" alt="${prop.weather.description}"></img> <div> <p class="temperature"><strong>${prop.app_temp}º C</strong></span> <p class="description">${prop.weather.description}</p> <div> </div>` } function getWeather () { fetch(locationAPI).then(function (response) { if (response.ok) { return response.json(); } else { return Promise.reject(response); } }).then(function (locationData) { city = locationData.city; let lat = locationData.latitude; let lon = locationData.longitude; let locationParameters = `&lat=${lat}&lon=${lon}`; return fetch(`${weatherAPI}?${locationParameters}&key=${weatherKey}`); }).then(function (response) { if (response.ok) { return response.json(); } else { return Promise.reject(response); } }).then(function (weatherData) { let userWeather = weatherData.data[0]; renderWeather(userWeather); }).catch(function (error) { console.warn(error); }); } // Inits and listeners getWeather(); </script> {% endset %} <!-- Rendering the html --> <div class="htmlBox"> {{ html | safe }} </div> <!-- Rendering the html and js as syntax highlight --> {% highlight "html" %} {{ html | safe }} {{ js | safe }} {% endhighlight %} <!-- Inserting the js as a script --> {{ js | safe }}
import React, { useState } from 'react'; import AddPhotoAlternateIcon from '@mui/icons-material/AddPhotoAlternate'; import { useNavigate } from 'react-router-dom'; import Alert from '@mui/material/Alert'; import { makeStyles } from '@mui/styles'; import Footer from '../../shared/components/Footer.jsx'; import NavLogin from '../../shared/components/NavLogin.jsx'; const useStyles = makeStyles({ customAlert: { width: '100%', margin: '16px 0 -16px 0', borderRadius: '8px', }, errorInput: { border: '1px solid red', }, }); function UploadImage() { const [selectedFile, setSelectedFile] = useState(null); const [preview, setPreview] = useState(null); const [error, setError] = useState(''); const navigate = useNavigate(); const classes = useStyles(); const handleFileChange = (event) => { const file = event.target.files[0]; setSelectedFile(file); const reader = new FileReader(); reader.onloadend = () => { setPreview(reader.result); }; reader.readAsDataURL(file); }; const handleUpload = async () => { if (!selectedFile) { setError('Please select a file first!'); return; } try { const formData = new FormData(); formData.append('image', selectedFile); const response = await fetch(`${import.meta.env.VITE_API_URL}/upload`, { method: 'POST', body: formData, }); if (!response.ok) { console.error('Failed to upload image to Cloudinary'); setError('Failed to upload image'); return; } const data = await response.json(); const imageUrl = data.imageUrl; const updateUserResponse = await fetch(`${import.meta.env.VITE_API_URL}/users/${localStorage.userId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ imageLink: imageUrl }), }); if (updateUserResponse.ok) { console.log('Image uploaded successfully'); navigate('/step-overview-2-homeowner'); } else { console.error('Failed to update user with image link'); setError('Failed to upload image'); } } catch (error) { console.error('Error uploading image:', error); setError('Error uploading image'); } }; const handleButtonClick = () => { document.getElementById('fileInput').click(); }; return ( <div className="page__container"> <NavLogin /> <div className="content"> <div className="center-container"> <div className="upload__image__page"> <div className="homeowner__register__header"> <h1 className="photo__h1">Give us a photo of yourself</h1> <h2>Upload your profile picture</h2> </div> <div className="center"> {preview ? ( <img src={preview} alt="Preview" style={{ width: '160px', height: '160px', padding: '16px', border: '1px solid #A3B9EA', borderRadius: '8px', margin: '32px 0 0 0', }} /> ) : ( <AddPhotoAlternateIcon style={{ width: '160px', height: '160px', padding: '16px', border: '1px solid #A3B9EA', borderRadius: '8px', color: '#A3B9EA', margin: '32px 0 0 0', }} className="AddPhotoAlternateIcon" onClick={handleButtonClick} /> )} <h2>A photo of you</h2> <p>Please make sure the photo clearly shows your face</p> <input type="file" accept="image/*" onChange={handleFileChange} style={{ display: 'none' }} id="fileInput" /> <button className="white__button medium" type="button" onClick={handleButtonClick}> Upload photo </button> </div> {error && ( <Alert severity="error" className={classes.customAlert}> {error} </Alert> )} <div className="next__help"> <button className="blue__button medium" type="button" onClick={handleUpload}> Next step </button> <span className="help">I need help</span> </div> </div> </div> </div> <Footer /> </div> ); } export default UploadImage;
from __future__ import absolute_import, division, print_function import copy from lib2to3.pytree import Base from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import rospy from drone_env.envs.base_env import BaseEnv from drone_env.envs.common.action import Action from drone_env.envs.common.utils import extract_nparray_from_dict from gym.spaces import Box import copy Observation = Union[np.ndarray, float] class MultiTaskEnv(BaseEnv): @classmethod def default_config(cls) -> dict: config = super().default_config() config["simulation"].update( { "simulation_time_step": 0.004, # 0.001 or 0.005 for 5x speed } ) config["observation"].update( { "type": "Kinematics", "noise_stdv": 0.02, "scale_obs": True, "include_raw_state": True, "bnd_constraint": True, } ) config["action"].update( { "type": "ContinuousVirtualAction", "act_noise_stdv": 0.05, "thrust_range": [-1, 1], } ) config["target"].update( { "type": "RandomGoal", "target_name_space": "goal_", } ) config.update( { "duration": 1500, # [steps] "simulation_frequency": 50, # [hz] "policy_frequency": 25, # [hz] "position_success_threshhold": 0.5, # [meters] "attitude_success_threshhold": 0.02, # [rad] "tasks": { "tracking": { "ori_diff": np.array([1.0, 1.0, 1.0, 1.0]), "ang_diff": np.array([1.0, 1.0, 1.0]), "angvel_diff": np.array([1.0, 1.0, 1.0]), "pos_diff": np.array([1.0, 1.0, 1.0]), "vel_diff": np.array([1.0, 1.0, 1.0]), "vel_norm_diff": np.array([1.0]), }, "constraint": { "survive": np.array([1.0]), "action_cost": np.array([0.1, 0.1]), "pos_ubnd_cost": np.array([0.1, 0.1, 0.1]), # x,y,z "pos_lbnd_cost": np.array([0.1, 0.1, 0.1]), # x,y,z }, "success": { "att": np.array([10.0, 10.0, 10.0]), "pos": np.array([10.0, 10.0, 10.0]), "fail": np.array([10.0]), }, # x,y,z }, "angle_reset": True, # reset env if roll and pitch too large } ) return config def __init__(self, config: Optional[Dict[Any, Any]] = None) -> None: super().__init__(config) self.angle_reset = self.config.get("angle_reset", True) self.max_episode_steps = self.config["duration"] self.tasks = self.config["tasks"] self.w = self.get_tasks_weights() self.feature_len = self.w.shape[0] self.tracking_feature_len = np.concatenate( extract_nparray_from_dict(self.tasks["tracking"]) ).shape[0] self.feature_space = Box( low=-np.inf, high=np.inf, shape=(len(self.w),), dtype=np.float32 ) self.obs, self.obs_info = None, None if self.observation_type.constraint is not None: self.env_constraint = self.observation_type.constraint self.pos_ubnd = self.env_constraint["pos_ubnd"] self.pos_lbnd = self.env_constraint["pos_lbnd"] self.success_timer = 0 def one_step( self, action: Action, ) -> Tuple[Observation, float, bool, dict]: """[perform a step action and observe result] Args: action (Action): action from the agent [-1,1] with size (4,) Returns: Tuple[Observation, float, bool, dict]: obs: np.array [-1,1] with size (9,), reward: scalar, terminal: bool, info: dictionary of all the step info, """ self._simulate(action) obs, obs_info = self.observation_type.observe() self.obs, self.obs_info = obs, obs_info reward, reward_info = self._reward(obs.copy(), action, obs_info) terminal, terminal_info = self._is_terminal(obs_info) info = { "step": self.steps, "obs": obs, "obs_info": obs_info, "act": action, "tasks": self.tasks, "reward": reward, "features": reward_info["features"], "reward_info": reward_info, "terminal": terminal, "terminal_info": terminal_info, } self._update_goal_and_env(obs_info) self._step_info(info) return obs, reward, terminal, info def _reward( self, obs: np.array, act: np.array, obs_info: dict, ) -> Tuple[float, dict]: """calculate reward Args: obs (np.array): act (np.array): agent action [-1,1] with size (4,) obs_info (dict): contain all information of a step Returns: Tuple[float, dict]: [reward scalar and a detailed reward info] """ features = self.calc_features(obs, obs_info) reward = np.dot(self.w, features) reward_info = { "reward": reward, "features": features, "tasks": self.tasks, } return float(reward), reward_info def reset(self) -> Observation: self.reset_params() self._reset() self._sample_new_goal() obs, obs_info = self.observation_type.observe() self.obs, self.obs_info = obs, obs_info obs_info["features"] = self.calc_features(obs, obs_info) return obs, obs_info def reset_params(self): self.steps = 0 self.done = False self.succecss_timer = 0 def update_tasks(self, task: dict): self.tasks = task self.w = self.get_tasks_weights() def get_tasks_weights(self): tasks = self.tasks feature_weights = np.concatenate(extract_nparray_from_dict(tasks["tracking"])) constr_weights = np.concatenate(extract_nparray_from_dict(tasks["constraint"])) success_weights = np.concatenate(extract_nparray_from_dict(tasks["success"])) return np.concatenate([feature_weights, constr_weights, success_weights]) def calc_features(self, obs, obs_info): tracking_features = self.calc_track_features(obs) constraint_features = self.calc_constr_features(obs_info) success_features = self.calc_success_features(obs_info) return np.concatenate( [tracking_features, constraint_features, success_features] ) def calc_track_features(self, obs: np.array) -> np.array: return -np.abs(obs[0 : self.tracking_feature_len]) def calc_constr_features(self, obs_info: dict) -> np.array: pos = obs_info["obs_dict"]["position"] constr_dict = obs_info["constr_dict"] done, _ = self._is_terminal(obs_info) survive = np.array([done]).astype(np.float32) act = np.array( [self.action_type.action_rew(), self.action_type.action_cont_rew()] ) pos_bnd = self.calc_dist_to_pos_bnd(pos, constr_dict) return np.concatenate([survive, act, pos_bnd]) def calc_dist_to_pos_bnd( self, pos: np.array, constr_dict: dict, range=(-10, 1) ) -> np.array: """closer to the bnd the higher the cost""" ubnd_pos = constr_dict["upper_boundary_position"] lbnd_pos = constr_dict["lower_boundary_position"] ubnd_cost = -np.exp(pos - ubnd_pos) lbnd_cost = -np.exp(-(pos - lbnd_pos)) return np.clip(np.concatenate([ubnd_cost, lbnd_cost]), *range) def calc_success_features(self, obs_info: dict) -> np.array: pos, goal_pos = ( obs_info["obs_dict"]["position"], obs_info["goal_dict"]["position"], ) pos_success = self.position_task_successs(pos, goal_pos) ang, goal_ang = ( obs_info["obs_dict"]["angle"], obs_info["goal_dict"]["angle"], ) att_success = self.attitude_task_successs(ang, goal_ang) _, ter_info = self._is_terminal(obs_info) fail = -np.array([ter_info["fail"]]).astype(float) return np.concatenate([att_success, pos_success, fail]) def attitude_task_successs(self, ang: np.array, goal_ang: np.array) -> np.array: """task success if distance to goal is less than sucess_threshhold Args: pos ([np.array]): [position of machine] goal_pos ([np.array]): [position of goal] Returns: [np.array]: [1.0 if success, otherwise 0.0] """ ref_ang = np.abs(ang[0:3] - goal_ang[0:3]) return np.array(ref_ang <= self.config["attitude_success_threshhold"]).astype( float ) def position_task_successs(self, pos: np.array, goal_pos: np.array) -> np.array: """task success if distance to goal is less than sucess_threshhold Args: pos ([np.array]): [position of machine] goal_pos ([np.array]): [position of goal] Returns: [np.array]: [1.0 if success, otherwise 0.0] """ ref_pos = np.abs(pos[0:3] - goal_pos[0:3]) return np.array(ref_pos <= self.config["position_success_threshhold"]).astype( float ) def _is_terminal(self, obs_info: dict) -> bool: """if episode terminate - time: episode duration finished Returns: bool: [episode terminal or not] """ time = False if self.config["duration"] is not None: time = self.steps >= int(self.config["duration"]) - 1 success = False success = self.check_success(obs_info) fail = False if self.env_constraint is not None: if (obs_info["obs_dict"]["position"] <= self.pos_lbnd).any(): fail = True if (obs_info["obs_dict"]["position"] >= self.pos_ubnd).any(): fail = True if self.angle_reset: roll = obs_info["obs_dict"]["angle"][0] if (roll > np.pi - 1) or (roll < -np.pi + 1): fail = True pitch = obs_info["obs_dict"]["angle"][1] if (pitch > np.pi - 1) or (pitch < -np.pi + 1): fail = True return time or success or fail, {"time": time, "success": success, "fail": fail} def check_success(self, obs_info, success_region=0.1): w_pos_diff = np.array(self.tasks["tracking"]["pos_diff"]) w_vel_diff = np.array(self.tasks["tracking"]["vel_diff"]) w_ang_diff = np.array(self.tasks["tracking"]["ang_diff"]) success_bnd = np.array([0.0, 0.0, 0.0]) if (w_pos_diff > 0).any(): value = obs_info["proc_dict"]["pos_diff"] diff = w_pos_diff elif (w_vel_diff > 0).any(): value = obs_info["proc_dict"]["vel_diff"] diff = w_vel_diff elif (w_ang_diff > 0).any(): value = obs_info["proc_dict"]["ang_diff"] diff = w_ang_diff else: return False success_bnd = success_region * np.array([diff[0] > 0, diff[1] > 0, diff[2] > 0]) success_bnd[success_bnd == 0.0] += 1 success = self.time_in_success_region(value, -success_bnd, success_bnd) return success def time_in_success_region(self, val, val_lbnd, val_ubnd, time=3): if (val > val_lbnd).all() and (val < val_ubnd).all(): self.success_timer += 1 else: self.succecss_timer = 0 if self.succecss_timer > time * self.config["policy_frequency"]: return True return False def _sample_new_goal(self): if self.config["target"]["type"] == "MultiGoal" and self.config["target"].get( "enable_random_goal", True ): n_waypoints = np.random.randint(4, 8) self.target_type.sample_new_wplist(n_waypoints=n_waypoints) elif self.config["target"]["type"] == "RandomGoal": pos = self.config["simulation"]["position"] self.target_type.sample_new_goal(origin=np.array([pos[1], pos[0], -pos[2]])) elif self.config["target"]["type"] == "FixedGoal": self.target_type.sample_new_goal() if __name__ == "__main__": import copy from drone_env.envs.common.gazebo_connection import GazeboConnection from drone_env.envs.script import close_simulation # pip install snakeviz # python -m cProfile -o out.profile drone_env/drone_env/envs/multitask_env.py -s time # snakeviz multitask_env.profile auto_start_simulation = False if auto_start_simulation: close_simulation() ENV = MultiTaskEnv # MultiTaskEnv, MultiTaskPIDEnv env_kwargs = { "DBG": True, "simulation": { "gui": True, "enable_meshes": True, "auto_start_simulation": auto_start_simulation, "position": (0, 0, 0.05), # initial spawned position }, "observation": { "DBG_ROS": False, "DBG_OBS": False, "noise_stdv": 0.0, }, "action": { "DBG_ACT": True, "act_noise_stdv": 0.0, "thrust_range": [-1, 1], }, "target": { "DBG_ROS": False, }, } def env_step(): env = ENV(env_kwargs) env.reset() action = env.action_space.sample() action = np.zeros_like(action) for _ in range(100000): action += 0.02 * np.ones_like(action) obs, reward, terminal, info = env.step(action) GazeboConnection().unpause_sim() env_step()
# Premise Contains all software and notebooks to reproduce the figures for a yet to be published study on the interrelation between wearable-derived physiology and self-assessed wellbeing. Unfortunately, the input data is not yet publicly available but will hopefully be publised together with the paper. Package structure is based on an earlier version of my personal [data science template](https://github.com/marcwie/datascience-template). # Purpose Parse wearable sensors (e.g, Apple Watch, Fitbit, Garmin) data and survey responses collected within the Corona Data Donation project (*Corona Datenspende*, click [here](https://corona-datenspende.github.io/en/) for more information). The Corona Data Donation Project is one of the largest citizen science initiatives worldwide. From 2020 to 2022, more than 120,000 German residents donated continuous daily measurements of resting heart rate, physical activity and sleep timing for the advancement of public health research. These data streams were collected passively through a dedicated smartphone app, seamlessly connecting with participants’ fitness trackers and smartwatches. Additionally, participants actively engaged in regular surveys, sharing insights into their health and well-being during the COVID-19 pandemic. This package analyzes the interrelation between objectively measured physiology from wearable devices, i.e., resting heart rate, step count and sleep timing, and self-assessed well-being according to the [WHO-5 Well-Being Index](https://www.corc.uk.net/outcome-experience-measures/the-world-health-organisation-five-well-being-index-who-5/) # Installation The package requires [poetry](https://python-poetry.org/). Make sure to have it installed and run `make install` after cloning this repository to install all dependencies. # Repository structure ``` . ├── Makefile # setup, download data and run analysis ├── README.md # README file as displayed on github ├── config # config files to be parsed by hydra │   └── main.yaml # ├── notebooks # notebooks for analysis │   ├── 0.01-compare_old_and_new_data_after_refactoring.ipynb # │   ├── 1.01-plot_raw_survey_data.ipynb # │   ├── 1.02-analyze_vitals_vs_survey.ipynb # │   ├── 1.03-individual-interrelations-and-correlations.ipynb # │   ├── 2.01-figures_for_paper.ipynb # │   └── X.0X-template.ipynb # a template notebooks with some defaults and presets ├── poetry.lock # poetry configurations ├── pyproject.toml # ├── scripts # bash scrits │   └── execute_notebooks.sh # run all jupyter notebooks from the command line └── src # package source code to be used in notebooks ├── __init__.py # ├── analyze.py # compute results ├── download.py # load data from database ├── merge.py # merge input data into single file for later use ├── preprocess.py # data cleaning and preprocessing └── utils # ├── __init__.py # ├── colors.py # some custom colors └── styling.py # custom styling for figures ``` # Setup After gaining data access you will receive instructions for setting up a VPN. You can then interact with the database by creating a file named `.env` in the root of the repository using the following template and filling in your credentials. Do not add this file to your git repository. ``` HOST = PORT = DBNAME = DBUSER = PASSWORD = ``` # Analysis In your command line type: ``` $ make activate $ jupyter notebook ``` The first command activates the virtual environment for the project (see `Makefile` for details). You can then run all notebooks from the ``notebooks`` folder. Alternatively you can run the entire analysis pipeline by simply typing ``` $ make pipeline ``` This downloads the raw data, performs necessary pre-processing steps, computes the final data set and runs the relevant jupyter notebooks. All output files are stored in a folder under ``output`` that is named according to the current time to prevent overwriting of previous outputs.
const jwt = require("jsonwebtoken"); const bcrypt = require("bcrypt"); const dotenv = require("dotenv"); const userRepository = require("../repositories/userRepository"); const secretKey = "phan-thanh-luc-2003"; const EmailCode = require("../email/successBookingEmail"); dotenv.config(); class UserController { async register(req, res) { try { const { full_name, email, phone, password } = req.body; const hashPassword = await bcrypt.hash(password, 10); const user = await userRepository.register({ full_name, email, phone, password: hashPassword, }); res.status(201).json({ status: 201, message: "Register successfully" }); } catch (error) { res.status(501).json(error); } } async userLogin(req, res) { try { const { email, password } = req.body; const user = await userRepository.getUserByEmail(email); if (!user) { res.status(401).json({ error: "Invalid credentials" }); } const isPasswordVal = await bcrypt.compare(password, user.password); if (!isPasswordVal) { res.status(401).json({ error: "Invalid credentials" }); } const token = jwt.sign( { _id: user._id, name: user.full_name, email }, secretKey, { expiresIn: "1h" } ); res.cookie("token", token, { httpOnly: true }); return res.json({ token,role:user.role }); } catch (error) { return res.status(501).json(error); } } async authUser(req, res) { try { const token = req.headers.authorization.split(" "); jwt.verify(token[1], secretKey, (err, decoded) => { if (err) { // Handle invalid token return res.status(401).json({ message: "Invalid token" }); } res.json(decoded); }); } catch (error) { res.status(501).json("User undefine"); } } //not yet done async confirmAccountUser(req, res) { const { email } = req.body; try { const already = await userRepository.getUserByEmail(email); if (!already) { return res.status(404).json({ status: 404 }); } const code= await EmailCode.codeConfirm(email); res.cookie("code",code,{httpOnly:true}) // // document.cookie="code="+code // localStorage.setItem("code",JSON.stringify(code)) return res.status(201).json({ status: 201}); } catch (error) { return res.status(501).json("Invalid email"); } } //not yet done async token(req,res){ try { const code = document.cookie if (code) { res.json(code); } else { res.status(404).json({ error: 'Code cookie not found' }); } } catch (error) { console.error(error); res.status(500).json({ error: 'Internal server error' }); } } async logout(req,res){ try { res.clearCookie("token",{httpOnly:true}) res.status(201).json({status:201,message:"Logout successfully"}) } catch (error) { res.status(501).json("Log out fail") } } async allUserChat(req,res){ const id=req.params.id try { const allUser=await userRepository.getUserChat(id) res.status(201).json(allUser) } catch (error) { res.status(501).json(error) } } async allUser(req,res){ const {id}=req.params try { const allUser=await userRepository.getAllUser(id) res.status(201).json(allUser) } catch (error) { res.status(501).json(error) } } } module.exports = new UserController();
<% view_only_html ||=false %> <style> .html_editor_container { height: 550px; } .html_editor { border: 1px solid red; text-align: left; } .html_text { background-color: whitesmoke; min-height: 400px; text-align: left; padding: 10px; } .html_results { <% if !view_only_html %> border:1px solid black; <% end %> text-align: left; padding: 10px; } .html_editor_section_title { margin:10px; } .height100 { height: 100%; } #code { margin:0; padding:10px; white-space: pre-wrap; max-width: 800px; } </style> <!-- todo: prettify code: https://github.com/googlearchive/code-prettify --> <script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script> <div class='html_editor_container zfullscreen'> <% if !view_only_html %> <!-- <h1> html editor </h1> --> <% end %> <div class='display_flex_wrap' style='zheight: 100%'> <% if !view_only_html %> <div class='flex1'> <!-- <div class='html_editor_section_title'> Code </div> --> <pre id=code class='html_text prettyprint height100' onkeyup='updateCode({announce: true})' contenteditable=""><%=cast[:website_html]%></pre> </div> <% end %> <div class='flex1'> <!-- <div class='html_editor_section_title'> Results </div> --> <div class='flex1 html_results height100'> <%=CGI.unescapeHTML(cast[:website_html].to_s)%> </div> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.11.0/beautify.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.11.0/beautify-css.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.11.0/beautify-html.js"></script> <script> beautifyOpts = { "indent_size": "2", "indent_char": " ", "max_preserve_newlines": "5", "preserve_newlines": true, "keep_array_indentation": false, "break_chained_methods": false, "indent_scripts": "normal", "brace_style": "collapse", "space_before_conditional": true, "unescape_strings": false, "jslint_happy": false, "end_with_newline": false, "wrap_line_length": "80", "indent_inner_html": false, "comma_first": false, "e4x": false, "indent_empty_lines": false }; // var lastHtml = ''; // function setCodeUpdateTimer() { // var html = $.trim($('.html_text').text()); // lastHtml = html; // updateCastHTML(html); // } // } // function updateCastHTML(html) { // html = // $('.html_text').text(html); // updateCode(); // } function prettyPrintCode() { $('.html_text').removeClass('prettyprinted'); PR.prettyPrint(); } var lastHtml = ''; function updateCode(opts = {}) { if (opts.html) $('.html_text').text(opts.html); html = $.trim($('.html_text').text()); if (html!=lastHtml) { html = html_beautify(html, beautifyOpts); $('.html_results').html(html) lastHtml = html; if (opts.announce) { if (window.sendChat) sendChat({type: 'newHTML', html:html, user_id: "<%=cuid%>"}); $.post('/casts/edit/<%=cast_id%>', {website_html: html}); clearTimeout(window.codeUpdater); window.codeUpdater = setTimeout(()=> {prettyPrintCode()}, 3000); } if (opts.prettyPrint) { PR.prettyPrint(); } } } </script>
#ifndef EVENT_HPP_ #define EVENT_HPP_ #include <sstream> #include <vector> #include <map> #include <set> #include <string> using namespace std; #include <assert.h> #include <stdint.h> enum EventType { INVALID_EVENT, ROI_START, ROI_FINISH, /** Tracking the Parsec region-of-interest */ THREAD_START, /** When a new thread starts running, so we can setup its resources */ THREAD_FINISH, /** When a thread exits, so we can teardown its resources */ THREAD_BLOCKED, /** When a thread is about to block inside the kernel, e.g. when doing a join */ THREAD_UNBLOCKED, /** When a thread returns from blocking inside the kernel, e.g. after having joined */ MEMORY_READ, MEMORY_WRITE, MEMORY_ALLOCATION, MEMORY_FREE, BASIC_BLOCK, /** Insn counting */ HAPPENS_BEFORE_SOURCE, HAPPENS_BEFORE_SINK /** All sync ops are mapped down to HB edges */ }; class Event { #ifdef SIMULATOR_FRONTEND private: /** Which thread last accessed each sync object. Used to provide source * information on HB-sink events. */ static map<ADDRINT, THREADID> s_WhoLastAccessed; /** Lock for s_WhoLastAccessed */ static PinLock sl_LastAccessed; #endif public: EventType m_type; uint16_t m_tid; // MEMORY_READ, MEMORY_WRITE, MEMORY_ALLOCATION, MEMORY_FREE uint64_t m_addr; uint8_t m_memOpSize; bool m_stackRef; // HAPPENS_BEFORE_SOURCE, HAPPENS_BEFORE_SINK uint64_t m_syncObject; uint64_t m_logicalTime; /** filled in by the simulator */ bool m_isLifeLock; /** The thread that was the source of this HB-sink event. INVALID_THREADID if there is no such thread, e.g. the very first time this lock is acquired. */ uint16_t m_hbSourceThread; // HAPPENS_BEFORE_SINK uint8_t m_insnCount; // BASIC_BLOCK #ifdef SIMULATOR_FRONTEND static Event MemoryEvent( unsigned tid, EventType typ, uint64_t addr, unsigned memOpSize, bool stackRef ) { assert( MEMORY_READ == typ || MEMORY_WRITE == typ ); Event e = Event( tid, typ ); e.m_addr = addr; e.m_memOpSize = memOpSize; e.m_stackRef = stackRef; return e; } static Event AllocationEvent( unsigned tid, EventType typ, uint64_t startAddr, uint64_t extent=0) { assert( MEMORY_ALLOCATION == typ || MEMORY_FREE == typ ); if ( 0 == extent ) { assert( MEMORY_FREE == typ ); } Event e = Event( tid, typ ); e.m_addr = startAddr; e.m_memOpSize = extent; return e; } static Event SyncSourceEvent( unsigned tid, EventType typ, uint64_t syncObject, bool lifelock ) { assert( HAPPENS_BEFORE_SOURCE == typ ); Event e = Event( tid, typ ); e.m_syncObject = syncObject; e.m_isLifeLock = lifelock; sl_LastAccessed.lock(); s_WhoLastAccessed[syncObject] = tid; sl_LastAccessed.unlock(); return e; } static Event SyncSinkEvent( unsigned tid, EventType typ, uint64_t syncObject, bool lifelock ) { assert( HAPPENS_BEFORE_SINK == typ ); Event e = Event( tid, typ ); e.m_syncObject = syncObject; e.m_isLifeLock = lifelock; THREADID lastAccessor = INVALID_THREADID; sl_LastAccessed.lock(); if ( s_WhoLastAccessed.count(syncObject) > 0 ) { lastAccessor = s_WhoLastAccessed.at( syncObject ); } sl_LastAccessed.unlock(); e.m_hbSourceThread = lastAccessor; return e; } static Event BasicBlockEvent( unsigned tid, EventType typ, unsigned insnCount ) { assert( BASIC_BLOCK == typ ); Event e = Event( tid, typ ); e.m_insnCount = insnCount; return e; } static Event ThreadEvent( unsigned tid, EventType typ ) { assert( ROI_START == typ || ROI_FINISH == typ || THREAD_START == typ || THREAD_FINISH == typ || THREAD_BLOCKED == typ || THREAD_UNBLOCKED == typ ); return Event( tid, typ ); } #endif /** This no-arg ctor is needed only for the lockfree ringbuffer. */ Event() { clear(); } /** reset this Event */ void clear() { m_type = INVALID_EVENT; m_tid = -1; m_addr = 0; m_memOpSize = 0; m_stackRef = false; m_syncObject = 0; m_hbSourceThread = -1; m_insnCount = 0; m_logicalTime = 0; m_isLifeLock = false; } string toString() { string name; stringstream ss; switch ( m_type ) { case INVALID_EVENT: ss << "INVALID event"; ss << " tid=" << m_tid; ss << " addr=" << m_addr; ss << " size=" << m_memOpSize; ss << " stack=" << m_stackRef; ss << " syncObj=" << m_syncObject; ss << " sourceTid=" << m_hbSourceThread; ss << " icount=" << m_insnCount; break; case ROI_START: name = "ROI_start"; goto PrintThreadEvent; case ROI_FINISH: name = "ROI_finish"; goto PrintThreadEvent; case THREAD_BLOCKED: name = "thread_blocked"; goto PrintThreadEvent; case THREAD_UNBLOCKED: name = "thread_unblocked"; goto PrintThreadEvent; case THREAD_START: name = "thread_start"; goto PrintThreadEvent; case THREAD_FINISH: name = "thread_finish"; PrintThreadEvent: ss << name << ", tid=" << m_tid; break; case MEMORY_READ: name = "read"; goto PrintMemEvent; case MEMORY_WRITE: name = "write"; PrintMemEvent: ss << name << ", tid=" << m_tid << ", size=" << m_memOpSize << ", stack=" << m_stackRef; break; case MEMORY_ALLOCATION: name = "alloc"; goto PrintAllocEvent; case MEMORY_FREE: name = "free"; PrintAllocEvent: ss << name << ", tid=" << m_tid << ", addr=0x" << hex << m_addr << dec << ", size=" << m_memOpSize ; break; case BASIC_BLOCK: ss << "basicblock" << ", tid=" << m_tid << ", insnCount=" << m_insnCount; break; case HAPPENS_BEFORE_SOURCE: name = "HB_source"; goto PrintSyncEvent; case HAPPENS_BEFORE_SINK: name = "HB_sink"; PrintSyncEvent: ss << name << ", tid=" << m_tid << ", syncObject=0x" << hex << m_syncObject << dec; if ( m_hbSourceThread != INVALID_THREADID ) { ss << ", hbSourceTid=" << m_hbSourceThread; } break; default: assert(false); } return ss.str(); } private: /** Private ctor */ Event( unsigned tid, EventType typ ) { clear(); m_tid = tid; m_type = typ; } }; #endif /* EVENT_HPP_ */
"use client"; import Link from "next/link"; import { useState } from "react"; import Rating from "@mui/material/Rating"; // LOCAL CUSTOM COMPONENTS import ProductPrice from "./components/product-price"; import FavoriteButton from "./components/favorite-button"; // GLOBAL CUSTOM COMPONENTS import HoverBox from "components/HoverBox"; import { H6 } from "components/Typography"; import LazyImage from "components/LazyImage"; import { FlexBetween } from "components/flex-box"; interface Props { off?: number; slug: string; title: string; price: number; imgUrl: string; rating: number; hideReview?: boolean; hideFavoriteIcon?: boolean; } export default function ProductCard2({ slug, title, price, imgUrl, rating, off = 20, hideReview, hideFavoriteIcon }: Props) { const [favorite, setFavorite] = useState(false); return ( <div> <Link href={`/products/${slug}`}> <HoverBox overflow="hidden" borderRadius={2}> <LazyImage width={270} height={270} alt={title} src={imgUrl} /> </HoverBox> </Link> <FlexBetween mt={2}> <div> <H6 mb={0.5} title={title} ellipsis> {title} </H6> {!hideReview ? <Rating size="small" value={rating} color="warn" readOnly /> : null} <ProductPrice price={price} off={off} /> </div> {!hideFavoriteIcon ? ( <FavoriteButton isFavorite={favorite} handleClick={() => setFavorite((state) => !state)} /> ) : null} </FlexBetween> </div> ); }
import { FunctionComponent, Suspense } from "react"; import { QueryClient, QueryClientProvider } from "react-query"; import { ReactQueryDevtools } from "react-query/devtools"; import Body from "./Body"; export const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, // useErrorBoundary: true, /** * suspense 옵션을 넣게 되면 react suspense 클래스로 loading,fetching을 위임하게 된다. */ suspense: true, retry: false, }, }, }); const App: FunctionComponent = () => { return ( <QueryClientProvider client={queryClient}> <Suspense fallback={<h1>LOADING... SUSPENSE</h1>}> <Body /> </Suspense> <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider> ); }; export default App;
#pragma once #include <QString> #include "qf4cplus_global.h" #include <QObject> #include "QState.h" #include "Interfaces/IQHsm.h" #include "QFEvent.h" #include "QSignal.h" #include "QSignals.h" #include "TransitionChain.h" #include "TransitionChain.h" #define Q_STATE_DECL(state_) \ Q_INVOKABLE QString state_(shared_ptr<IQFEvent> qEvent);\ const QString m_##state_ = #state_;\ namespace QtQf4CPlus { class QF4CPLUS_EXPORT QHsm :public QObject,public IQHsm { Q_OBJECT #pragma region private class private: class TransitionChainRecorder { public: TransitionChainRecorder() { } private: TransitionChain m_transitionSteps; public: void Record(QString stateMethod, shared_ptr<QSignal> signal) { m_transitionSteps.append(TransitionStep(stateMethod, signal)); } /// <summary> /// Returns the recorded transition steps in form of a <see cref="TransitionChain"/> instance. /// </summary> /// <returns></returns> shared_ptr<TransitionChain> GetRecordedTransitionChain() { // We turn the ArrayList into a strongly typed array return make_shared<TransitionChain>(m_transitionSteps); } bool operator==(std::nullptr_t) { return this == nullptr; } bool operator!=(std::nullptr_t) { return this != nullptr; } int length() { return m_transitionSteps.length(); } }; #pragma endregion public: QHsm(); ~QHsm(); void Init(); QString getCurrentStateName(); void Dispatch(shared_ptr<IQFEvent> qEvent); private: QString m_myStateMethod; QString m_mySourceStateMethod; QString m_targetStateName; static QString _sTopState; QHash<QString, QMetaMethod> hash; //static QString Top(shared_ptr<IQFEvent> qEvent) //{ // QString empty("Top"); // return empty; //} QString GetSuperStateMethod(QString stateMethod); QString TriggerByReflect(QString stateMethod, shared_ptr<IQFEvent> qEvent); QString Trigger(QString stateMethod, shared_ptr<QSignal> qSignal); QString Trigger(QString receiverStateMethod, shared_ptr<QSignal> qSignal, shared_ptr<TransitionChainRecorder> recorder); void ExitUpToSourceState(); void TransitionFromSourceToTarget(QString targetStateMethod, shared_ptr<TransitionChainRecorder> recorder); int ExitUpToLca(QString targetStateMethod, QList<QString>& statesTargetToLca, shared_ptr<TransitionChainRecorder> recorder); void TransitionDownToTargetState(QString targetStateMethod, QList<QString>& statesTargetToLca, int indexFirstStateToEnter, shared_ptr<TransitionChainRecorder> recorder); void EnsureLastTransistionStepIsEntryIntoTargetState(QString targetStateMethod, shared_ptr<TransitionChainRecorder> recorder); void TransitionToSynchronized(QString targetState, shared_ptr<TransitionChain> transitionChain); void ExecuteTransitionChain(shared_ptr<TransitionChain> transitionChain); protected: void InitializeState(QString state); bool IsInState(QString inquiredState); void DispatchSynchronized(shared_ptr<IQFEvent> qEvent); QString TopState; void TransitionTo(QString targetState); void StateTrace(QString state, shared_ptr<QSignal> signal); void TransitionTo(QString targetState, shared_ptr<TransitionChain> transitionChain); }; };
import React from "react"; export function pickFromSyntheticEvent<T extends HTMLElement>() { return <K extends keyof T>(key: K) => <E extends (t: T[K]) => void>(fn: E) => (event: React.SyntheticEvent<T>) => fn(event.currentTarget[key]); } // Для получения данных из любого события // // Применение export const getValue = pickFromSyntheticEvent<HTMLInputElement>()("value"); export const getChecked = pickFromSyntheticEvent<HTMLInputElement>()("checked"); // function Input({onChange, value}: {onChange: (value: string) => void, value: string}) { // return ( // <input value={value} onChange={getValue(onChange)} /> // ) // } function Checkbox({ onChange, value, }: { onChange: (value: boolean) => void; value: boolean; }) { return ( <input type="checkbox" checked={value} onChange={getChecked(onChange)} /> ); } // Для совмешения утилит // interface IInputProps { // onChange: (value: string) => void; // value: string; // } // function Input({ value, onChange }: IInputProps) { // return ( // <input // value={value} // onChange={preventDefault(stopPropagation(getValue(onChange)))} // /> // ); // }
<?php /** * @file * Contains \Drupal\language\Form\NegotiationUrlForm. */ namespace Drupal\language\Form; use Drupal\system\SystemConfigFormBase; /** * Configure the URL language negotiation method for this site. */ class NegotiationUrlForm extends SystemConfigFormBase { /** * Implements \Drupal\Core\Form\FormInterface::getFormID(). */ public function getFormID() { return 'language_negotiation_configure_url_form'; } /** * Implements \Drupal\Core\Form\FormInterface::buildForm(). */ public function buildForm(array $form, array &$form_state) { global $base_url; $config = $this->configFactory->get('language.negotiation'); language_negotiation_include(); $form['language_negotiation_url_part'] = array( '#title' => t('Part of the URL that determines language'), '#type' => 'radios', '#options' => array( LANGUAGE_NEGOTIATION_URL_PREFIX => t('Path prefix'), LANGUAGE_NEGOTIATION_URL_DOMAIN => t('Domain'), ), '#default_value' => $config->get('url.source'), ); $form['prefix'] = array( '#type' => 'details', '#tree' => TRUE, '#title' => t('Path prefix configuration'), '#description' => t('Language codes or other custom text to use as a path prefix for URL language detection. For the default language, this value may be left blank. <strong>Modifying this value may break existing URLs. Use with caution in a production environment.</strong> Example: Specifying "deutsch" as the path prefix code for German results in URLs like "example.com/deutsch/contact".'), '#states' => array( 'visible' => array( ':input[name="language_negotiation_url_part"]' => array( 'value' => (string) LANGUAGE_NEGOTIATION_URL_PREFIX, ), ), ), ); $form['domain'] = array( '#type' => 'details', '#tree' => TRUE, '#title' => t('Domain configuration'), '#description' => t('The domain names to use for these languages. Leave blank for the default language. Use with caution in a production environment.<strong>Modifying this value may break existing URLs. Use with caution in a production environment.</strong> Example: Specifying "de.example.com" as language domain for German will result in an URL like "http://de.example.com/contact".'), '#states' => array( 'visible' => array( ':input[name="language_negotiation_url_part"]' => array( 'value' => (string) LANGUAGE_NEGOTIATION_URL_DOMAIN, ), ), ), ); $languages = language_list(); $prefixes = language_negotiation_url_prefixes(); $domains = language_negotiation_url_domains(); foreach ($languages as $langcode => $language) { $t_args = array('%language' => $language->name, '%langcode' => $language->langcode); $form['prefix'][$langcode] = array( '#type' => 'textfield', '#title' => $language->default ? t('%language (%langcode) path prefix (Default language)', $t_args) : t('%language (%langcode) path prefix', $t_args), '#maxlength' => 64, '#default_value' => isset($prefixes[$langcode]) ? $prefixes[$langcode] : '', '#field_prefix' => $base_url . '/', ); $form['domain'][$langcode] = array( '#type' => 'textfield', '#title' => t('%language (%langcode) domain', array('%language' => $language->name, '%langcode' => $language->langcode)), '#maxlength' => 128, '#default_value' => isset($domains[$langcode]) ? $domains[$langcode] : '', ); } $form_state['redirect'] = 'admin/config/regional/language/detection'; return parent::buildForm($form, $form_state); } /** * Implements \Drupal\Core\Form\FormInterface::validateForm(). */ public function validateForm(array &$form, array &$form_state) { $languages = language_list(); // Count repeated values for uniqueness check. $count = array_count_values($form_state['values']['prefix']); foreach ($languages as $langcode => $language) { $value = $form_state['values']['prefix'][$langcode]; if ($value === '') { if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LANGUAGE_NEGOTIATION_URL_PREFIX) { // Throw a form error if the prefix is blank for a non-default language, // although it is required for selected negotiation type. form_error($form['prefix'][$langcode], t('The prefix may only be left blank for the default language.')); } } elseif (strpos($value, '/') !== FALSE) { // Throw a form error if the string contains a slash, // which would not work. form_error($form['prefix'][$langcode], t('The prefix may not contain a slash.')); } elseif (isset($count[$value]) && $count[$value] > 1) { // Throw a form error if there are two languages with the same // domain/prefix. form_error($form['prefix'][$langcode], t('The prefix for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value))); } } // Count repeated values for uniqueness check. $count = array_count_values($form_state['values']['domain']); foreach ($languages as $langcode => $language) { $value = $form_state['values']['domain'][$langcode]; if ($value === '') { if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LANGUAGE_NEGOTIATION_URL_DOMAIN) { // Throw a form error if the domain is blank for a non-default language, // although it is required for selected negotiation type. form_error($form['domain'][$langcode], t('The domain may only be left blank for the default language.')); } } elseif (isset($count[$value]) && $count[$value] > 1) { // Throw a form error if there are two languages with the same // domain/domain. form_error($form['domain'][$langcode], t('The domain for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value))); } } // Domain names should not contain protocol and/or ports. foreach ($languages as $langcode => $name) { $value = $form_state['values']['domain'][$langcode]; if (!empty($value)) { // Ensure we have exactly one protocol when checking the hostname. $host = 'http://' . str_replace(array('http://', 'https://'), '', $value); if (parse_url($host, PHP_URL_HOST) != $value) { form_error($form['domain'][$langcode], t('The domain for %language may only contain the domain name, not a protocol and/or port.', array('%language' => $name))); } } } parent::validateForm($form, $form_state); } /** * Implements \Drupal\Core\Form\FormInterface::submitForm(). */ public function submitForm(array &$form, array &$form_state) { // Save selected format (prefix or domain). $this->configFactory->get('language.negotiation') ->set('url.source', $form_state['values']['language_negotiation_url_part']) ->save(); // Save new domain and prefix values. language_negotiation_url_prefixes_save($form_state['values']['prefix']); language_negotiation_url_domains_save($form_state['values']['domain']); parent::submitForm($form, $form_state); } }
import translationIT from "../../public/locales/it/it.json"; import translationEN from "../../public/locales/en/en.json"; import translationFR from "../../public/locales/fr/fr.json"; import HeroWorks from "@/components/heros/heroWorks"; import SezioneIntro from "@/components/worksItem/sezioneIntro"; import Image from "next/image"; import Typography from "@/components/worksItem/typography"; import ColorBrand from "@/components/worksItem/colorBrand"; import Illustrazioni from "@/components/worksItem/illustrazioni"; import Label from "@/components/worksItem/label"; import Social from "@/components/worksItem/social"; import Head from "next/head"; import Link from "next/link"; import React from "react"; import { useState, useEffect } from "react"; import { Icon } from "@iconify/react"; const Works = ({ works, previousWork, nextWork }) => { const [isScrolling, setIsScrolling] = useState(false); useEffect(() => { const handleScroll = () => { if (window.scrollY > 400) { setIsScrolling(true); } else { setIsScrolling(false); } }; window.addEventListener("scroll", handleScroll); return () => { window.removeEventListener("scroll", handleScroll); }; }, []); return ( <> <Head> <title>{`Miao - ${works?.name}`}</title> <meta name="description" content={works?.descrizione} /> <meta name="keywords" content={works?.keywords} /> <meta name="author" content="Elisa Avantey" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" ></meta> <meta property="og:url" content="https://www.miaographics.it/" /> <meta property="og:type" content="website" /> <meta property="og:title" content={`Miao - ${works?.name}`} /> <meta property="og:image" content="https://www.miaographics.it/assets/cover_web.png" /> <meta property="og:description" content="Esplora il nostro blog e scopri il mondo del design attraverso gli occhi di un esperto. Approfondimenti, tendenze e ispirazione per il tuo prossimo progetto creativo. Entra nel nostro mondo di idee e creatività!" /> <meta name="twitter:card" content="summary_large_image" /> <meta property="twitter:domain" content="miaographics.it" /> <meta property="twitter:url" content="https://www.miaographics.it/" /> <meta name="twitter:title" content={`Miao - ${works?.name}`} /> <meta name="twitter:image" content="https://www.miaographics.it/assets/cover_web.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/site.webmanifest" /> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" /> <meta name="msapplication-TileColor" content="#ffffff" /> <meta name="theme-color" content="#ffffff"></meta> </Head> <div className="w-full min-h-[calc(50vh_-_60px)] md:h-[calc(60vh_-_100px)] lg:h-[calc(100vh_-_70px)] 2xl:h-[calc(100vh_-_100px)] fxl:h-[calc(100vh_-_150px)] 4xl:h-[calc(100vh_-_250px)] flex flex-col lg:flex-row items-center justify-center 2xl:justify-center relative"> <HeroWorks img={works.img} name={works.name} descrizione={works?.descrizione} location={works?.location} button={works?.button} /> </div> <section className="flex flex-col gap-6 min-h-[40vh] w-[90%] mx-auto pt-6"> <SezioneIntro translation={works} /> </section> <section className="w-[90%] mx-auto min-h-[40vh] lg:h-[90vh] relative"> <Image src={works?.logoImg} fill alt="logo brand" className="object-contain" priority /> </section> <section className="flex flex-col gap-6 w-[90%] mx-auto pt-6"> <Typography translation={works?.typo} /> </section> <section className="flex flex-col gap-6 w-[90%] mx-auto pt-6"> <ColorBrand translation={works?.color} /> </section> {works?.illustrazioni ? ( <section className="flex flex-col gap-6 w-[90%] mx-auto pt-6"> <Illustrazioni translation={works?.illustrazioni} /> </section> ) : ( "" )} {works?.label ? ( <section className="flex flex-col gap-6 w-[90%] mx-auto pt-6"> <Label translation={works?.label} /> </section> ) : ( "" )} {works?.social ? ( <section className="flex flex-col gap-6 w-[90%] mx-auto pt-10"> <Social translation={works?.social} /> </section> ) : ( "" )} <div className={`pagination-buttons ${isScrolling ? "show" : ""} ${ previousWork ? "show-reverse" : "" }`} > {previousWork && ( <Link href={`/works/${previousWork}`} className="pagination-button"> <Icon icon="raphael:arrowleft" /> </Link> )} {nextWork && ( <Link href={`/works/${nextWork}`} className="pagination-button ml-auto" > <Icon icon="raphael:arrowright" /> </Link> )} </div> </> ); }; export default Works; export async function getStaticProps(context) { const { params, locale } = context; let obj; switch (locale) { case "it": obj = translationIT; break; case "en": obj = translationEN; break; case "fr": obj = translationFR; break; default: obj = translationIT; break; } let targetObj = obj?.portfolio?.singleWorks?.[params?.title]; const arr = Object.keys(obj?.portfolio?.singleWorks); const currentIndex = arr.findIndex((el) => el === params.title); const previousWork = currentIndex > 0 ? arr[currentIndex - 1] : null; const nextWork = currentIndex < arr.length - 1 ? arr[currentIndex + 1] : null; const filteredOthers = arr .filter((el) => el !== params?.title) // Exclude the current service .map((el) => { return { name: obj?.portfolio?.singleWorks?.[el]?.name, img: obj?.portfolio?.singleWorks?.[el]?.img, descrizione: obj?.portfolio?.singleWorks?.[el]?.descrizione, button: obj?.portfolio?.singleWorks?.[el]?.button, link: el, }; }); return { props: { works: targetObj, others: filteredOthers, previousWork, nextWork, }, }; } export async function getStaticPaths({ locale }) { let obj; switch (locale) { case "it": obj = translationIT; break; case "en": obj = translationEN; break; case "fr": obj = translationFR; break; default: obj = translationIT; break; } const works = Object.keys(obj?.portfolio?.singleWorks); const pathEn = works?.map((el) => { return { params: { title: el, }, locale: "en", }; }); const pathFr = works?.map((el) => { return { params: { title: el, }, locale: "fr", }; }); const pathIt = works?.map((el) => { return { params: { title: el, }, locale: "it", }; }); const paths = pathIt.concat(pathEn).concat(pathFr); return { paths, fallback: false, }; }
import numpy as np import george from george import kernels import matplotlib.pyplot as plt import scipy.optimize as op def initialize_state_covariance(initial_state, initial_state_estimate): state_covariance = np.outer(initial_state - initial_state_estimate, initial_state - initial_state_estimate) return state_covariance def gp_regression(training_data_X, training_data_Y, test_point, kernel): gp = george.GP(kernel) gp.compute(training_data_X.flatten()) mean, variance = gp.predict(training_data_Y.flatten(), test_point.flatten()) return mean[0], variance[0] # def compute_jacobian(previous_state_estimate, process_noise_covariance): # jacobian = np.eye(len(previous_state_estimate)) # return jacobian def compute_jacobian(previous_position_estimate, process_noise_covariance): jacobian = np.array([[1.0]]) # Since the state is 1-dimensional (position) return jacobian def update_covariance_matrix(predicted_covariance, process_noise_covariance, jacobian): covariance_matrix = predicted_covariance - np.dot(np.dot(np.dot(predicted_covariance, jacobian.T), np.linalg.inv(np.dot(np.dot(jacobian, predicted_covariance), jacobian.T) + process_noise_covariance)), np.dot(np.dot(predicted_covariance, jacobian.T), np.linalg.inv(np.dot(np.dot(jacobian, predicted_covariance), jacobian.T) + process_noise_covariance))) return covariance_matrix def gp_regression_measurement_update(previous_state_estimate): return np.array([previous_state_estimate]), np.array([[1.0]]) # mean and variance of the measurement def compute_jacobian_measurement_update(previous_state_estimate): jacobian_measurement = np.array([[1.0]]) return jacobian_measurement def measurement_update(previous_state_estimate, covariance_matrix, measurement, measurement_noise_covariance): predicted_measurement, predicted_measurement_covariance = gp_regression_measurement_update(previous_state_estimate) jacobian_measurement = compute_jacobian_measurement_update(previous_state_estimate) kalman_gain = np.dot(np.dot(covariance_matrix, jacobian_measurement.T), np.linalg.inv(np.dot(np.dot(jacobian_measurement, covariance_matrix), jacobian_measurement.T) + measurement_noise_covariance)) updated_state_estimate = previous_state_estimate + np.dot(kalman_gain, (measurement - predicted_measurement)) updated_covariance = np.dot(np.eye(len(updated_state_estimate)) - np.dot(kalman_gain, jacobian_measurement), covariance_matrix) return updated_state_estimate, updated_covariance # Sample time series data np.random.seed(42) time_steps = 100 true_positions = np.cumsum(np.random.normal(size=time_steps)) measurements = true_positions + np.random.normal(scale=0.5, size=time_steps) # Initialization initial_position = 0.0 initial_position_estimate = 0.0 initial_state_covariance = initialize_state_covariance(np.array([initial_position]), np.array([initial_position_estimate])) process_noise_covariance = np.eye(1) measurement_noise_covariance = np.eye(1) # Initialize the GP model with one data point kernel = 1.0 * kernels.ExpSquaredKernel(1.0) gp = george.GP(kernel) # Main loop estimated_positions = np.zeros(time_steps) predicted_positions = np.zeros(time_steps) current_position_estimate = initial_position_estimate current_covariance = initial_state_covariance for t in range(1, time_steps): # Prediction Step predicted_position, predicted_covariance = gp_regression(np.array([[current_position_estimate]]), np.array([[measurements[t-1]]]), np.array([[true_positions[t]]]), kernel) jacobian_process_model = compute_jacobian(np.array([current_position_estimate]), process_noise_covariance) current_covariance = update_covariance_matrix(predicted_covariance, process_noise_covariance, jacobian_process_model) # Measurement Update Step current_position_estimate, current_covariance = measurement_update(np.array([predicted_position]), current_covariance, measurements[t], measurement_noise_covariance) # # Update the GP model with the new data point # gp.compute(np.array([[true_positions[t]]])) # #gp.optimize(messages=True) # Optional: Optimize hyperparameters # Update the GP model with the new data point gp.compute(np.array([[true_positions[t]]])) gp.kernel.pars = np.log([1.0, 1.0]) # Manually set the initial hyperparameters result = op.minimize(gp.nll, gp.kernel.pars, args=(np.array([measurements[t]]),)) gp.kernel.pars = result.x # Store the current state estimate estimated_positions[t] = current_position_estimate predicted_positions[t] = predicted_position # Plotting plt.figure(figsize=(12, 6)) plt.plot(true_positions, label='True Positions', marker='o', linestyle='-', color='blue') plt.plot(measurements, label='Measurements', marker='x', linestyle='None', color='green') plt.plot(predicted_positions, label='Predicted Positions (Before Update)', marker='o', linestyle='--', color='orange') plt.plot(estimated_positions, label='Estimated Positions (After Update)', marker='o', linestyle='-', color='red') plt.title('True Positions, Measurements, and Estimated Positions') plt.xlabel('Time Step') plt.ylabel('Position') plt.legend() plt.tight_layout() plt.show()
import {Controller, SubmitErrorHandler, SubmitHandler, useForm} from "react-hook-form"; type AddForm = { name: string; age: number; cardNumber: number; } const normalizeCardNumber = (value: string) => { return value.replace(/\s/g, "").match(/.{1,4}/g)?.join(" ").substr(0, 19) || ""; } const AddTechnicForm = () => { const { register, handleSubmit, watch, reset, setValue, control, // Интеграция с библиотеками clearErrors, formState: { errors, isValid } } = useForm<AddForm>({ defaultValues: { age: 18 }, mode: "onBlur" }); const submit: SubmitHandler<AddForm> = data => { alert(JSON.stringify(data)); reset(); // Очистка формы } const error: SubmitErrorHandler<AddForm> = data => { console.log(data); } return ( <> <form onSubmit={handleSubmit(submit, error)}> <label> Имя <input type="text" {...register('name', { required: 'Поле обязательно', minLength: { value: 5, message: 'Длина должна быть больше 5 символов' } })} aria-invalid={!!errors.name}/> </label> <div>{errors?.name && <p>{errors?.name?.message || 'Ошибка'}</p>}</div> <Controller render={({ field }) => <input {...field} />} name='age' control={control} /> <input type="number" {...register('age')}/> <input placeholder='0000 0000 0000 0000' type='tel' inputMode='numeric' autoComplete='cc-number' {...register('cardNumber')} onChange={(event) => { const {value} = event.target; event.target.value = normalizeCardNumber(value); }} /> <button disabled={!isValid}>Отправить</button> <button type='button' onClick={() => reset({ name: '', age: 0 })}>Очистить форму</button> <button type='button' onClick={() => clearErrors()}>Очистить ошибки</button> <button type='button' onClick={() => setValue('name', 'Вася')}>Установить имя</button> </form> {watch('age')} </> ); }; export default AddTechnicForm;
from django.db import models from cores import models as core_models class EasyFood(core_models.TimeStampedModel): class Meta: verbose_name = "간편식" verbose_name_plural = "간편식" name = models.CharField(max_length=140, null=True, verbose_name="간편식", unique=True) description = models.TextField(null=True, verbose_name="간편식설명", blank=True) ingredients = models.ManyToManyField( "ingredients.Ingredient", related_name="easyfood", blank=True, verbose_name="재료", ) photo = models.ImageField(blank=True, upload_to="easyfood_photos") def __str__(self): return self.name
import { getFirestore, collection, query, getDocs } from "firebase/firestore"; import app from "@/shared/FirebaseConfig"; import React, { useEffect, useState } from "react"; import PostItem from "@/components/Home/PostItem"; import { Ghost, TrashIcon } from "lucide-react"; import Toast from "../../components/Home/Toast"; import { useRouter } from "next/navigation"; import { removeRecordsFromDB } from "@/utils/utils"; import { useAuthContext } from "@/context/AuthUserContext"; import Loading from "@/components/Loading"; function Profile() { const db = getFirestore(app); const { user } = useAuthContext(); const router = useRouter(); const [ownedPosts, setOwnedPosts] = useState([]); const [showToast, setShowToast] = useState(false); const [isLoading, setIsLoading] = useState(true); useEffect(() => { if (user === null) router.push("/"); }, [user]); //load session user posts useEffect(() => { getUserOwnedPosts(); }, [user]); //function to get current users posts for display const getUserOwnedPosts = async () => { if (user?.email) { const q = query(collection(db, "Posts", user.email, "PostsOwned")); const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { setOwnedPosts((ownedPosts) => [...ownedPosts, doc.data()]); }); setIsLoading(false); } }; //delete from db functions const onDeletePost = async (title) => { setIsLoading(true); const postId = title.split("").reverse().join(""); await removeRecordsFromDB(postId, user.email); setIsLoading(false); presentToast(); }; //fire toast, delay 3 seconds, then redirect to dashboard const presentToast = () => { setShowToast(true); router.push("/dashboard"); // setTimeout(() => { // setShowToast(false); // router.push("/dashboard"); // }, 1000); }; return ( <> {isLoading && <Loading />} <div className=""> {showToast ? ( <div className="absolute top-10 right-10"> <Toast msg={"Post Deleted Successfully"} closeToast={() => setShowToast(false)} /> </div> ) : null} {!isLoading && ( <div className="lg:max-w-[1126px] mx-auto py-6"> <h2 className="px-6 text-center lg:text-start text-[3rem] font-extrabold text-[#0356fc]"> Profile{" "} <span className="text-gray-900 text-[0.8rem] font-semibold"></span> </h2> <p className="text-[1rem] font-medium text-gray-900 px-6 text-center lg:text-start"> Manage your posts </p> <div className="text-center lg:text-center text-[2rem] font-bold text-[#0356fc] border-b-slate-100 border-b-2 px-6 mt-12 py-2"> My Posts </div> <div className="max-w-[120rem] mx-auto flex flex-wrap justify-center items-start gap-4 sm:gap-6"> {ownedPosts.length > 0 ? ( ownedPosts.map((item, indx) => ( <div key={indx} className="relative p-3"> <PostItem post={item} /> <button className="p-2 w-fit text-sm text-white font-semibold rounded-md absolute top-5 right-5"> <TrashIcon stroke="#fff" fill="#db2525" size={24} className="hover:scale-110" onClick={() => onDeletePost(item.title)} /> </button> </div> )) ) : ( <> <div className="p-6 w-full h-[50%] flex flex-col items-center justify-center gap-3"> <Ghost stroke="#000" size={42} /> <p className="text-lg font-semibold"> Nothing to see here... </p> </div> </> )} </div> </div> )} </div> </> ); } export default Profile;
package Tuan3; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class ResultEx5 { /* * Complete the 'pairs' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER k * 2. INTEGER_ARRAY arr */ public static int pairs(int k, List<Integer> arr) { Collections.sort(arr); int count = 0; int i=1; int j=0; while (i<arr.size()){ if(arr.get(i)-arr.get(j)>k){ j++; } if(arr.get(i)-arr.get(j)==k) { count++; j++; } if(arr.get(i)-arr.get(j)<k){ i++; } } // Write your code here return count; } } public class Ex5 { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); int n = Integer.parseInt(firstMultipleInput[0]); int k = Integer.parseInt(firstMultipleInput[1]); List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()); int result = ResultEx5.pairs(k, arr); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
// Copyright 2020 Redpanda Data, Inc. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.md // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0 #include "cluster/persisted_stm.h" #include "bytes/iostream.h" #include "cluster/cluster_utils.h" #include "cluster/logger.h" #include "raft/consensus.h" #include "raft/errc.h" #include "raft/offset_monitor.h" #include "raft/state_machine_base.h" #include "raft/types.h" #include "ssx/sformat.h" #include "storage/kvstore.h" #include "storage/record_batch_builder.h" #include "storage/snapshot.h" #include <seastar/core/abort_source.hh> #include <seastar/core/coroutine.hh> #include <seastar/core/future.hh> #include <filesystem> namespace { std::optional<cluster::stm_snapshot_header> read_snapshot_header( iobuf_parser& parser, const model::ntp& ntp, const ss::sstring& name) { auto version = reflection::adl<int8_t>{}.from(parser); vassert( version == cluster::stm_snapshot_version || version == cluster::stm_snapshot_version_v0, "[{} ({})] Unsupported persisted_stm snapshot_version {}", ntp, name, version); if (version == cluster::stm_snapshot_version_v0) { return std::nullopt; } cluster::stm_snapshot_header header; header.offset = model::offset(reflection::adl<int64_t>{}.from(parser)); header.version = reflection::adl<int8_t>{}.from(parser); header.snapshot_size = reflection::adl<int32_t>{}.from(parser); return header; } } // namespace namespace cluster { template<supported_stm_snapshot T> template<typename... Args> persisted_stm<T>::persisted_stm( ss::sstring snapshot_mgr_name, ss::logger& logger, raft::consensus* c, Args&&... args) : _raft(c) , _log(logger, ssx::sformat("[{} ({})]", _raft->ntp(), snapshot_mgr_name)) , _snapshot_backend(snapshot_mgr_name, _log, c, std::forward<Args>(args)...) { } template<supported_stm_snapshot T> ss::future<std::optional<stm_snapshot>> persisted_stm<T>::load_local_snapshot() { return _snapshot_backend.load_snapshot(); } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::stop() { co_await raft::state_machine_base::stop(); co_await _gate.close(); } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::remove_persistent_state() { return _snapshot_backend.remove_persistent_state(); } file_backed_stm_snapshot::file_backed_stm_snapshot( ss::sstring snapshot_name, prefix_logger& log, raft::consensus* c) : _ntp(c->ntp()) , _log(log) , _snapshot_mgr( std::filesystem::path(c->log_config().work_directory()), std::move(snapshot_name), ss::default_priority_class()) {} ss::future<> file_backed_stm_snapshot::remove_persistent_state() { _snapshot_size = 0; co_await _snapshot_mgr.remove_snapshot(); co_await _snapshot_mgr.remove_partial_snapshots(); } ss::future<std::optional<stm_snapshot>> file_backed_stm_snapshot::load_snapshot() { auto maybe_reader = co_await _snapshot_mgr.open_snapshot(); if (!maybe_reader) { co_return std::nullopt; } storage::snapshot_reader& reader = *maybe_reader; iobuf meta_buf = co_await reader.read_metadata(); iobuf_parser meta_parser(std::move(meta_buf)); auto header = read_snapshot_header(meta_parser, _ntp, name()); if (!header) { vlog(_log.warn, "Skipping snapshot {} due to old format", store_path()); // can't load old format of the snapshot, since snapshot is missing // it will be reconstructed by replaying the log co_await reader.close(); co_return std::nullopt; } stm_snapshot snapshot; snapshot.header = *header; snapshot.data = co_await read_iobuf_exactly( reader.input(), snapshot.header.snapshot_size); _snapshot_size = co_await reader.get_snapshot_size(); co_await reader.close(); co_await _snapshot_mgr.remove_partial_snapshots(); co_return snapshot; } ss::future<> file_backed_stm_snapshot::persist_local_snapshot( storage::simple_snapshot_manager& snapshot_mgr, stm_snapshot&& snapshot) { iobuf data_size_buf; int8_t version = stm_snapshot_version; int64_t offset = snapshot.header.offset(); int8_t data_version = snapshot.header.version; int32_t data_size = snapshot.header.snapshot_size; reflection::serialize( data_size_buf, version, offset, data_version, data_size); return snapshot_mgr.start_snapshot().then( [&snapshot_mgr, snapshot = std::move(snapshot), data_size_buf = std::move(data_size_buf)]( storage::file_snapshot_writer writer) mutable { return ss::do_with( std::move(writer), [&snapshot_mgr, snapshot = std::move(snapshot), data_size_buf = std::move(data_size_buf)]( storage::file_snapshot_writer& writer) mutable { return writer.write_metadata(std::move(data_size_buf)) .then([&writer, snapshot = std::move(snapshot)]() mutable { return write_iobuf_to_output_stream( std::move(snapshot.data), writer.output()); }) .finally([&writer] { return writer.close(); }) .then([&snapshot_mgr, &writer] { return snapshot_mgr.finish_snapshot(writer); }); }); }); } ss::future<> file_backed_stm_snapshot::persist_local_snapshot(stm_snapshot&& snapshot) { return persist_local_snapshot(_snapshot_mgr, std::move(snapshot)) .then([this] { return _snapshot_mgr.get_snapshot_size().then( [this](uint64_t size) { _snapshot_size = size; }); }); } const ss::sstring& file_backed_stm_snapshot::name() { return _snapshot_mgr.name(); } ss::sstring file_backed_stm_snapshot::store_path() const { return _snapshot_mgr.snapshot_path().string(); } size_t file_backed_stm_snapshot::get_snapshot_size() const { return _snapshot_size; } kvstore_backed_stm_snapshot::kvstore_backed_stm_snapshot( ss::sstring snapshot_name, prefix_logger& log, raft::consensus* c, storage::kvstore& kvstore) : _ntp(c->ntp()) , _name(snapshot_name) , _snapshot_key(detail::stm_snapshot_key(snapshot_name, c->ntp())) , _log(log) , _kvstore(kvstore) {} kvstore_backed_stm_snapshot::kvstore_backed_stm_snapshot( ss::sstring snapshot_name, prefix_logger& log, model::ntp ntp, storage::kvstore& kvstore) : _ntp(ntp) , _name(snapshot_name) , _snapshot_key(detail::stm_snapshot_key(snapshot_name, ntp)) , _log(log) , _kvstore(kvstore) {} bytes kvstore_backed_stm_snapshot::snapshot_key() const { bytes k; k.append( reinterpret_cast<const uint8_t*>(_snapshot_key.begin()), _snapshot_key.size()); return k; } const ss::sstring& kvstore_backed_stm_snapshot::name() { return _name; } ss::sstring kvstore_backed_stm_snapshot::store_path() const { return _snapshot_key; } /// Serialized format of snapshots for newer format used by /// kvstore_backed_stm_snapshot, once deserialized struct will be decomposed /// into a normal stm_snapshot to keep the interface the same across impls struct stm_thin_snapshot : serde:: envelope<stm_thin_snapshot, serde::version<0>, serde::compat_version<0>> { model::offset offset; iobuf data; auto serde_fields() { return std::tie(offset, data); } }; ss::future<std::optional<stm_snapshot>> kvstore_backed_stm_snapshot::load_snapshot() { auto snapshot_blob = _kvstore.get( storage::kvstore::key_space::stms, snapshot_key()); if (!snapshot_blob) { co_return std::nullopt; } auto thin_snapshot = serde::from_iobuf<stm_thin_snapshot>( std::move(*snapshot_blob)); stm_snapshot snapshot; snapshot.header = stm_snapshot_header{ .version = stm_snapshot_version, .snapshot_size = static_cast<int32_t>(thin_snapshot.data.size_bytes()), .offset = thin_snapshot.offset}; snapshot.data = std::move(thin_snapshot.data); co_return snapshot; } ss::future<> kvstore_backed_stm_snapshot::persist_local_snapshot(stm_snapshot&& snapshot) { stm_thin_snapshot thin_snapshot{ .offset = snapshot.header.offset, .data = std::move(snapshot.data)}; auto serialized_snapshot = serde::to_iobuf(std::move(thin_snapshot)); co_await _kvstore.put( storage::kvstore::key_space::stms, snapshot_key(), std::move(serialized_snapshot)); } ss::future<> kvstore_backed_stm_snapshot::remove_persistent_state() { co_await _kvstore.remove(storage::kvstore::key_space::stms, snapshot_key()); } size_t kvstore_backed_stm_snapshot::get_snapshot_size() const { /// get_snapshot_size() is used to account for total size of files across /// the disk, kvstore has its own accounting method so return 0 here to not /// skew the existing metrics. return 0; } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::wait_for_snapshot_hydrated() { return _on_snapshot_hydrated.wait([this] { return _snapshot_hydrated; }); } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::do_write_local_snapshot() { auto snapshot = co_await take_local_snapshot(); auto offset = snapshot.header.offset; co_await _snapshot_backend.persist_local_snapshot(std::move(snapshot)); _last_snapshot_offset = std::max(_last_snapshot_offset, offset); } template<supported_stm_snapshot T> void persisted_stm<T>::write_local_snapshot_in_background() { ssx::spawn_with_gate(_gate, [this] { return write_local_snapshot(); }); } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::write_local_snapshot() { return _op_lock.with([this]() { return wait_for_snapshot_hydrated().then( [this] { return do_write_local_snapshot(); }); }); } template<supported_stm_snapshot T> uint64_t persisted_stm<T>::get_local_snapshot_size() const { return _snapshot_backend.get_snapshot_size(); } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::ensure_local_snapshot_exists(model::offset target_offset) { vlog( _log.debug, "ensure snapshot_exists with target offset: {}", target_offset); return _op_lock.with([this, target_offset]() { return wait_for_snapshot_hydrated().then([this, target_offset] { if (target_offset <= _last_snapshot_offset) { return ss::now(); } return wait(target_offset, model::no_timeout) .then([this, target_offset]() { vassert( target_offset < next(), "[{} ({})] after we waited for target_offset ({}) " "next ({}) must be greater", _raft->ntp(), name(), target_offset, next()); return do_write_local_snapshot(); }); }); }); } template<supported_stm_snapshot T> model::offset persisted_stm<T>::max_collectible_offset() { return model::offset::max(); } template<supported_stm_snapshot T> ss::future<fragmented_vector<model::tx_range>> persisted_stm<T>::aborted_tx_ranges(model::offset, model::offset) { return ss::make_ready_future<fragmented_vector<model::tx_range>>(); } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::wait_offset_committed( model::timeout_clock::duration timeout, model::offset offset, model::term_id term) { auto stop_cond = [this, offset, term] { return _raft->committed_offset() >= offset || _raft->term() > term; }; return _raft->commit_index_updated().wait(timeout, stop_cond); } template<supported_stm_snapshot T> ss::future<bool> persisted_stm<T>::do_sync( model::timeout_clock::duration timeout, model::offset offset, model::term_id term) { const auto committed = _raft->committed_offset(); const auto ntp = _raft->ntp(); _raft->events().notify_commit_index(); if (offset > committed) { try { co_await wait_offset_committed(timeout, offset, term); } catch (const ss::broken_condition_variable&) { co_return false; } catch (const ss::gate_closed_exception&) { co_return false; } catch (const ss::abort_requested_exception&) { co_return false; } catch (const ss::condition_variable_timed_out&) { co_return false; } catch (...) { vlog( _log.error, "sync error: wait_offset_committed failed with {}; " "offsets: dirty={}, committed={}", std::current_exception(), offset, committed); co_return false; } } else { offset = committed; } if (_raft->term() == term) { try { co_await wait(offset, model::timeout_clock::now() + timeout); } catch (const ss::broken_condition_variable&) { co_return false; } catch (const ss::gate_closed_exception&) { co_return false; } catch (const ss::abort_requested_exception&) { co_return false; } catch (const ss::condition_variable_timed_out&) { co_return false; } catch (const ss::timed_out_error&) { vlog( _log.warn, "sync timeout: waiting for offset={}; committed " "offset={}", offset, committed); co_return false; } catch (...) { vlog( _log.error, "sync error: waiting for offset={} failed with {}; committed " "offset={};", offset, std::current_exception(), committed); co_return false; } if (_raft->term() == term) { _insync_term = term; co_return true; } // we lost leadership during waiting } co_return false; } template<supported_stm_snapshot T> ss::future<bool> persisted_stm<T>::sync(model::timeout_clock::duration timeout) { auto term = _raft->term(); if (!_raft->is_leader()) { co_return false; } if (_insync_term == term) { co_return true; } if (_is_catching_up) { auto deadline = model::timeout_clock::now() + timeout; auto sync_waiter = ss::make_lw_shared<expiring_promise<bool>>(); _sync_waiters.push_back(sync_waiter); co_return co_await sync_waiter->get_future_with_timeout( deadline, [] { return false; }); } _is_catching_up = true; // To guarantee that we have caught up with all records written by previous // leaders, we choose the last offset before the start of the current term // as the sync offset. Because the leader replicates the configuration batch // at the start of the term, this offset is guaranteed to be less than // committed index, so we won't need any additional flushes even if the // client produces with acks=1. model::offset sync_offset; auto log_offsets = _raft->log()->offsets(); if (log_offsets.dirty_offset_term == term) { auto last_term_start_offset = _raft->log()->find_last_term_start_offset(); if (last_term_start_offset > model::offset{0}) { sync_offset = last_term_start_offset - model::offset{1}; } else { sync_offset = model::offset{}; } } else { // We haven't been able to append the configuration batch at the start // of the term yet. sync_offset = log_offsets.dirty_offset; } auto is_synced = co_await do_sync(timeout, sync_offset, term); _is_catching_up = false; for (auto& sync_waiter : _sync_waiters) { sync_waiter->set_value(is_synced); } _sync_waiters.clear(); co_return is_synced; } template<supported_stm_snapshot T> ss::future<bool> persisted_stm<T>::wait_no_throw( model::offset offset, model::timeout_clock::time_point deadline, std::optional<std::reference_wrapper<ss::abort_source>> as) noexcept { return wait(offset, deadline, as) .then([] { return true; }) .handle_exception_type([](const ss::abort_requested_exception&) { // Shutting down return false; }) .handle_exception_type( [this, offset, ntp = _raft->ntp()](const ss::timed_out_error&) { vlog(_log.warn, "timed out while waiting for offset: {}", offset); return false; }) .handle_exception( [this, offset, ntp = _raft->ntp()](std::exception_ptr e) { vlog( _log.error, "An error {} happened during waiting for offset: {}", e, offset); return false; }); } template<supported_stm_snapshot T> ss::future<> persisted_stm<T>::start() { std::optional<stm_snapshot> maybe_snapshot; try { maybe_snapshot = co_await load_local_snapshot(); } catch (...) { vassert( false, "[[{}] ({})]Can't load snapshot from '{}'. Got error: {}", _raft->ntp(), name(), _snapshot_backend.store_path(), std::current_exception()); } if (maybe_snapshot) { stm_snapshot& snapshot = *maybe_snapshot; auto next_offset = model::next_offset(snapshot.header.offset); if (next_offset >= _raft->start_offset()) { vlog( _log.debug, "start with applied snapshot, set_next {}", next_offset); co_await apply_local_snapshot( snapshot.header, std::move(snapshot.data)); set_next(next_offset); _last_snapshot_offset = snapshot.header.offset; } else { // This can happen on an out-of-date replica that re-joins the group // after other replicas have already evicted logs to some offset // greater than snapshot.header.offset. We print a warning and // continue. The stm will later detect this situation and deal with // it in the apply fiber by calling handle_eviction. vlog( _log.warn, "Skipping snapshot {} since it's out of sync with the log", _snapshot_backend.store_path()); vlog( _log.debug, "start with non-applied snapshot, set_next {}", next_offset); set_next(next_offset); } } else { auto offset = _raft->start_offset(); vlog(_log.debug, "start without snapshot, maybe set_next {}", offset); if (offset >= model::offset(0)) { set_next(offset); } } _snapshot_hydrated = true; _on_snapshot_hydrated.broadcast(); } template class persisted_stm<file_backed_stm_snapshot>; template class persisted_stm<kvstore_backed_stm_snapshot>; template persisted_stm<file_backed_stm_snapshot>::persisted_stm( ss::sstring, seastar::logger&, raft::consensus*); template persisted_stm<kvstore_backed_stm_snapshot>::persisted_stm( ss::sstring, seastar::logger&, raft::consensus*, storage::kvstore&); } // namespace cluster
'use client'; import { useEffect, useState } from 'react'; import { Controller } from 'react-hook-form'; import { useForm } from 'react-hook-form'; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form'; import * as z from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; const FormSchema = z.object({ url: z.string().min(1, 'URL is required').max(100), title: z.string().min(1, 'Title is required').max(100), description: z.string().min(1, 'Description is required'), ageCategoryIds: z.array(z.number()), themeCategoryIds: z.array(z.number()), }); interface Category { id: number; name: string; type: 'age' | 'theme'; } const UploadVideo = () => { const form = useForm<z.infer<typeof FormSchema>>({ resolver: zodResolver(FormSchema), defaultValues: { url: '', title: '', description: '', ageCategoryIds: [], themeCategoryIds: [], }, }); const [ageCategories, setAgeCategories] = useState<Category[]>([]); const [themeCategories, setThemeCategories] = useState<Category[]>([]); const [feedbackMessage, setFeedbackMessage] = useState<string>(''); const [isError, setIsError] = useState<boolean>(false); useEffect (() => { const fetchCategories = async () => { const res = await fetch('/api/categories'); const data = await res.json(); setAgeCategories(data.ageCategories); setThemeCategories(data.themeCategories); }; fetchCategories().catch(console.error); }, []); // Function to transform YouTube URL from watch format to embed format // and extract video ID function transformYouTubeUrlAndExtractId(url: string): { transformedUrl: string, videoId: string | null } { let videoId: string | null = null; try { const parsedUrl = new URL(url); videoId = parsedUrl.searchParams.get('v') ?? parsedUrl.pathname.replace('/', ''); if (parsedUrl.hostname === 'www.youtube.com' && videoId) { return { transformedUrl: `https://www.youtube.com/embed/${videoId}`, videoId }; } else if (parsedUrl.hostname === 'youtu.be') { return { transformedUrl: `https://www.youtube.com/embed/${videoId}`, videoId }; } } catch (error) { console.error('Error parsing URL:', error); } return { transformedUrl: url, videoId }; } const onSubmit = async (values: z.infer<typeof FormSchema>) => { console.log(values); // Transform YouTube URL and extract video ID const {transformedUrl, videoId} = transformYouTubeUrlAndExtractId(values.url); const thumbnailUrl = videoId ? `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg` : ''; // Destructure ageCategoryIds and themeCategoryIds from values and capture the rest under otherData const { ageCategoryIds, themeCategoryIds, ...otherData } = values; // Merge ageCategoryIds and themeCategoryIds const categoryIds = [...ageCategoryIds, ...themeCategoryIds]; // Construct the final data object to be sent, including the merged categoryIds const submitData = { ...otherData, // This contains url, title, description url: transformedUrl, thumbnailUrl, categoryIds, // The merged array of category IDs }; try { const response = await fetch ('/api/admin', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(submitData), }); if (!response.ok) { throw new Error('Failed to upload the video'); } const data = await response.json(); setFeedbackMessage('Video uploaded successfully'); console.log('Video uploaded successfully', data); } catch (error) { setIsError(true); setFeedbackMessage('Failed to upload video'); console.error('Failed to upload video', error); } }; // I have to add a function to change the normal youtube url to an embed url // so in stead of https://www.youtube.com/watch?v=OVKRBGzH8aM // it would be https://www.youtube.com/embed/OVKRBGzH8aM // same with the thumbnail image, I need to add the option to upload a special url that changes the youtube url to the thumbnail image //https://img.youtube.com/vi/[youtube video ID]/maxresdefault.jpg return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className='w-full'> <div className='space-y-2'> <FormField control={form.control} name='url' render={({ field }) => ( <FormItem> <FormLabel>Video URL</FormLabel> <FormControl> <Input placeholder='Paste the video URL' {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name='title' render={({ field }) => ( <FormItem> <FormLabel>Title</FormLabel> <FormControl> <Input placeholder='Type in the video title' {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name='description' render={({ field }) => ( <FormItem> <FormLabel>Description</FormLabel> <FormControl> <Input placeholder='Type in a video description' {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Controller name="ageCategoryIds" control={form.control} render={({ field: {onChange, value, ref} }) => ( <FormControl> <> <FormLabel>Age groups</FormLabel> <select ref={ref} multiple value={value.map(String)} onChange={(e) => { const selectedOptions = Array.from(e.target.selectedOptions, option => parseInt(option.value, 10)); onChange(selectedOptions); }} aria-label="Age Categories" className='form-multiselect' > {ageCategories.map((category) => ( <option key={category.id} value={category.id}> {category.name} </option> ))} </select> </> </FormControl> )} /> <Controller name="themeCategoryIds" control={form.control} render={({ field: { onChange, value, ref } }) => ( <FormControl> <> <FormLabel>Theme select</FormLabel> <select ref={ref} multiple value={value.map(String)} onChange={(e) => { const val = Array.from(e.target.selectedOptions, option => parseInt(option.value, 10)); onChange(val); }} aria-label="Theme Categories" className='form-multiselect'> {themeCategories.map((category) => ( <option key={category.id} value={category.id}> {category.name} </option> ))} </select> </> </FormControl> )} /> </div> <Button className='w-full mt-6' type='submit'> Upload video </Button> {feedbackMessage && ( <div className={isError ? 'text-red-500' : 'text-green-500'}> {feedbackMessage} </div> )} </form> </Form> ); }; export default UploadVideo;
package splunk import "context" // A sink serves as the last stage of a processing pipeline. All sinks are implemented as blocking calls which don't start any new goroutines. // Drain receives all values from the provided channel and returns them in a slice. // Drain blocks the caller until the input channel is closed or the provided context is cancelled. // An error is returned if and only if the provided context was cancelled before the input channel was closed. func Drain[T any](ctx context.Context, in <-chan T) ([]T, error) { var result []T for { select { case <-ctx.Done(): return result, ctx.Err() case repo, ok := <-in: if !ok { return result, nil } result = append(result, repo) } } } // Chan converts a slice to a channel. The channel returned is a closed, buffered channel containing exactly the same // values. func Chan[T any](in []T) <-chan T { result := make(chan T, len(in)) defer close(result) // non-empty buffered channels can be drained even when closed. for _, t := range in { result <- t } return result }
<%= render "shared/header" %> <div class='wrapper'> <div class='side-ber'> <div class="side-ber__header"> <h3 class='side-ber__title'>参加メンバー</h3> </div> <div class="side-ber__footer"> <% @users.each do |user| %> <div class="room-user__list"> <%= link_to user.full_user, user_path(user), class: "user-list" %> </div> <% end %> </div> </div> <div class="main-chat"> <div class="chat-header"> <div class="chat-title">〜<%= @room.name %>〜</div> <div class='chat-button'> <% if @room.creator == current_user %> <div class="chat-destroy"> <%= link_to "削除", room_path(@room.id), method: :delete, class: "destroy-name", data: { confirm: '本当に削除しますか?' } %> </div> <div class="chat-edit" style="float: left;"> <%= link_to "編集", edit_room_path(@room.id), class: "edit-name"%> </div> <% end %> <div class="chat-event" style="float: right;"> <%= link_to "イベント", room_events_path(@room.id), class: "event-name" %> </div> </div> </div> <div class='chat-messages'> <% current_date = nil %> <% @messages.each do |message| %> <% if message.created_at.in_time_zone.strftime('%m/%d') != current_date %> <% current_date = message.created_at.in_time_zone.strftime('%m/%d') %> <span class="message-date"><%= "#{current_date} (#{I18n.t('date.abbr_day_names')[message.created_at.in_time_zone.wday]})" %> </span> <% end %> <div class="message"> <div class="upper-message"> <% unless message.user == current_user %> <div class="<%= message.user == current_user ? 'my-message__image' : 'your-message__image' %>"> <%= image_tag message.user.image.url, class: (message.user == current_user ? 'my-image' : 'your-image') %> </div> <div class="<%= message.user == current_user ? 'my-message__user' : 'your-message__user' %>"> <span class="<%= message.user == current_user ? 'my-full__name' : 'your-full__name' %>"><%= message.user.full_name %></span> </div> <% end %> </div> <div class="<%= message.user == current_user ? 'my-lower__message' : 'your-lower__message' %>"> <% if message.user == current_user %> <div class="my-message__content"> <% if message.content.present? %> <span class="my-content__text"><%= message.content %></span> <% end %> <% if message.image.present? %> <div class="my-message__image"> <%= image_tag message.image.url, class: "my-content__image" %> </div> <% end %> <span class="my-content__date"><%= message.created_at.in_time_zone.strftime('%H:%M') %></span> </div> <% else %> <div class="your-message__content"> <% if message.content.present? %> <span class="your-content__text"><%= message.content %></span> <% end %> <% if message.image.present? %> <div class="your-message__image"> <%= image_tag message.image.url, class: "your-content__image" %> </div> <% end %> <span class="your-content__date"><%= message.created_at.in_time_zone.strftime('%H:%M') %></span> </div> <% end %> </div> </div> <% end %> </div> <div class='chat-form'> <%= form_with model: [@room, @message], class: 'form-message', local: true, multipart: true do |f| %> <%= f.text_field :content, class: 'chat-message', placeholder: 'メッセージを入力' %> <label class='chat-image__form'> <%= f.file_field :image, class: 'chat-image', id: 'chat-image-file' %> <input type="file" class="hidden" style="display:none"> <label for="chat-image-file" class="choose-file">画像</label> </label> <%= f.submit '送信', class: 'form-submit' %> <% end %> </div> </div> </div>
package ${package}.${moduleName}.controller; import java.util.Arrays; import java.util.Map; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import AbstractController; import ${package}.${moduleName}.entity.${className}Entity; import ${package}.${moduleName}.service.${className}Service; import ${mainPath}.common.utils.PageUtils; import ${mainPath}.common.utils.Result; /** * ${comments} * * @author ${author} * @email ${email} * @date ${datetime} */ @RestController @RequestMapping("${moduleName}/${pathName}") public class ${className}Controller extends AbstractController{ @Autowired private ${className}Service ${classname}Service; /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("${moduleName}:${pathName}:list") public Result list(@RequestParam Map<String, Object> params){ PageUtils page = ${classname}Service.queryPage(params); return Result.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{${pk.attrname}}") @RequiresPermissions("${moduleName}:${pathName}:info") public Result info(@PathVariable("${pk.attrname}") ${pk.attrType} ${pk.attrname}){ ${className}Entity ${classname} = ${classname}Service.selectById(${pk.attrname}); return Result.ok().put("${classname}", ${classname}); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("${moduleName}:${pathName}:save") public Result save(@RequestBody ${className}Entity ${classname}){ //you should set the ${className}Entity's 'id' value ${classname}Service.insert(${classname}); return Result.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("${moduleName}:${pathName}:update") public Result update(@RequestBody ${className}Entity ${classname}){ ${classname}Service.updateById(${classname}); return Result.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("${moduleName}:${pathName}:delete") public Result delete(@RequestBody ${pk.attrType}[] ${pk.attrname}s){ ${classname}Service.deleteBatchIds(Arrays.asList(${pk.attrname}s)); return Result.ok(); } }
import React, { useEffect, useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import auth from "../services/authService"; import axiosInstance from "../services/axiosInstance"; const SignUp = () => { const navigate = useNavigate(); const [error, setError] = useState(null); const [user, setUser] = useState({ name: "", email: "", number: "", password: "", }); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axiosInstance.post("auth/customer/signup", user); console.log(response.status); // if (response.status === 400) { // setError(response.data.message); // } else { // const { access_token } = response.data; // auth.setAuthToken(access_token); // navigate("/"); // window.location = "/"; // } } catch (error) { // setError(error.response.data.message); console.log(error); } }; return ( <div className="container mx-auto my-5 items-center justify-center flex"> <form className="form-control" onSubmit={handleSubmit}> <div className=" "> <h1 className="text-center text-xl font-bold text-orange-500 uppercase"> Sign up </h1> {error && ( <div className="alert alert-error rounded-sm container mx-auto my-5"> <svg xmlns="http://www.w3.org/2000/svg" className="stroke-current shrink-0 h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> <span className="text-white">{error}</span> </div> )} <label className="label " htmlFor="name"> <span className="label-text text-md font-bold">Name</span> </label> <input onChange={(e) => setUser({ ...user, name: e.target.value })} value={user.name} type="name" id="name" required placeholder="Enter your name" className="input input-bordered text-sm w-96" /> <label className="label " htmlFor="email"> <span className="label-text text-md font-bold">Email</span> </label> <input onChange={(e) => setUser({ ...user, email: e.target.value })} value={user.email} type="email" id="email" required placeholder="Enter your email" className="input input-bordered text-sm w-96" /> <label className="label " htmlFor="number"> <span className="label-text text-md font-bold">Phone Number</span> </label> <input onChange={(e) => setUser({ ...user, number: e.target.value })} value={user.number} type="number" id="number" required placeholder="Enter your number" className="input input-bordered text-sm w-96" /> <label className="label" htmlFor="password"> <span className="label-text text-md font-bold">Password</span> </label> <input onChange={(e) => setUser({ ...user, password: e.target.value })} value={user.password} type="password" id="password" required placeholder="Enter your password" className="input input-bordered text-sm w-96" /> </div> <button className={`btn bg-gray-900 mt-3 px-5 hover:bg-gray-800 text-white font-bold ${ user.email && user.password ? "btn-active" : "btn-disabled" }`} type="submit" > Sign Up </button> <div className="flex dark:text-white flex-col text-center text-sm mt-3 text-gray-950"> <div className="mt-1"> <span>Already have account? </span> <Link className="hover:underline" to="/signin"> Sign In </Link> </div> </div> </form> </div> ); }; export default SignUp;
const router = require('express').Router(); const { Dealership, Car } = require('../../models'); // Retrieve all Cars router.get('/', async (req, res) => { try { const carData = await Car.findAll(); res.status(200).json(carData); } catch (err) { res.status(500).json(err); } }); // Retrieve One Car by ID router.get('/vehical/:id', async (req, res) => { try { const carData = await Car.findByPk(req.params.id); if (!carData) { res.status(404).json({ message: 'No Car found with that id!' }); return; } res.status(200).json(carData); } catch (err) { res.status(500).json(err); } }); // Retrieve all Cars and included associated Dealership data router.get('/dealer-location', async (req, res) => { try { const carData = await Car.findAll({ include:[ {model: Dealership}] }); res.status(200).json(carData); } catch (err) { res.status(500).json(err); } }); // Create a Car router.post('/', async (req, res) => { try { const carData = await Car.create(req.body); res.status(200).json(carData); } catch (err) { res.status(400).json(err); } }); // Update a Car by ID router.put('/update/:id', (req, res) => { Car.update( { make: req.body.make, model: req.body.model, year: req.body.year, color: req.body.color, dealership_id: req.body.dealership_id, }, { where: { id: req.params.id, }, } ) .then((updatedCar) => { res.json(updatedCar); }) .catch((err) => { console.log(err); res.json(err); }); }); // Delete a Car by ID router.delete('/delete/:id', async (req, res) => { try { const carData = await Car.destroy({ where: { id: req.params.id, }, }); if (!carData) { res.status(404).json({ message: 'No Car found with that id!' }); return; } res.status(200).json(carData); } catch (err) { res.status(500).json(err); } }); module.exports = router;
''' case: Write a Class that can summarize the given data - Named the class with `Data` - Initialize the object with no input - `Data` has several attributes: - `data` --> return the input data - `size` --> return the size of the input data - `Data` has several methods: - `read_data(data)` --> to read the input data - `find_total()` --> return the total sum of the input data - `find_average()` --> return the average of the input data ''' class Data: ''' class of given data parameters ---------- data = given data size = length of data method ---------- read_data = input given data to class find_total = calculate total sum of data find_average = calculate average of data ''' def read_data(self, data): #define read_data method self.data = data self.size = len(data) def find_total(self): #define find_total method total = sum(self.data) return total def find_average(self): #define find_average method average = sum(self.data)/self.size return average pass 'Example' data = [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5] try: data_obj = Data() data_obj.read_data(data) print(data_obj.data) print(data_obj.size) print(data_obj.find_total()) print(data_obj.find_average()) except Exception as e: print('There is something wrong')
import { delay, lastValueFrom, map, of } from "rxjs"; import { ObjectValidator } from "./object-validator"; interface UserFormOutput { name: string; email: string; hobbies: string[]; age: number; } describe('ObjectValidator', () => { const mockData: UserFormOutput = { name: 'John', email: 'email@gmail.com', age: 20, hobbies: ['hobby1'] } it('should create an instance', () => { expect(new ObjectValidator()).toBeTruthy(); }); describe('Synchronous validations', () => { it('should validate to true correctly', () => { const validator = new ObjectValidator<UserFormOutput>() .addValidationRule('name', value => value.includes('John')) .addValidationRule('hobbies', value => value.length > 0) .addValidationRule('age', value => value > 18) .addValidationRule('email', value => value.includes('@')) expect(validator.validate(mockData)).toBeTrue(); validator.removeValidationRule('age'); validator.addValidationRule('age', value => value < 18); expect(validator.validate(mockData)).toBeFalse(); }); }) describe('Asynchronous validations', () => { it('should validate data', async () => { const asynchronousValidationNonValid = of(mockData) .pipe( map(data => data.age > 20), delay(100) ); const asynchronousValidationValid = of(mockData) .pipe( map(data => data.age <= 20), delay(100) ); const validator = new ObjectValidator<UserFormOutput>() .addValidationRule('name', value => value.includes('John')) .addValidationRule('hobbies', value => value.length > 0) .addAsyncValidationRule('age', () => lastValueFrom(asynchronousValidationNonValid)) expect(await validator.validateAsync(mockData)).toBeFalse(); validator.removeValidationRule('age'); expect(await validator.validateAsync(mockData)).toBeTrue(); validator.addAsyncValidationRule('age', () => lastValueFrom(asynchronousValidationValid)); expect(await validator.validateAsync(mockData)).toBeTrue(); }); it('should not validate asynchronous validations if synchronous validations do not pass', async () => { const validator = new ObjectValidator<UserFormOutput>() .addValidationRule('name', value => value.includes('fakeName')) .addValidationRule('hobbies', value => value.length > 0) .addAsyncValidationRule('age', () => lastValueFrom(of(true).pipe(delay(100)))); expect(await validator.validateAsync(mockData)).toBeFalse(); }); }); describe('Clone', () => { it('should correctly clone', () => { const asyncronousValidation = of(mockData) .pipe( map(data => data.hobbies.length >= 0), delay(10) ) const normalValidator = new ObjectValidator<UserFormOutput>() .addValidationRule('name', value => value.includes('John')) .addValidationRule('email', value => value.length > 0) .addAsyncValidationRule('age', () => lastValueFrom(asyncronousValidation)); const clonedValidator = normalValidator.clone() .addValidationRule('age', value => value > 20); expect(normalValidator.validate(mockData)).toBeTrue(); expect(clonedValidator.validate(mockData)).toBeFalse(); }); }); describe('Validation removals', () => { it('should remove a validation', () => { const mockData: UserFormOutput = { name: 'John', email: 'John@gmail.com', age: 15, hobbies: [] } const failedValidator = new ObjectValidator<UserFormOutput>() .addValidationRule('name', value => value.includes('John')) .addValidationRule('age', value => value > 18); expect(failedValidator.validate(mockData)).toBeFalse(); const successValidator = failedValidator.removeValidationRule('age'); expect(successValidator.validate(mockData)).toBeTrue(); }); }); });
@use 'sass:math'; @import 'base/mixins'; //&display=swap - добавить при подключении через плагин // Подключить если есть локальные файлы шрифтов @import 'fonts/fonts'; // Подключить если есть файл иконочного шрифта //@import "fonts/icons"; $fontFamily: 'Circe'; $fontSize: rem(18); // Основные цвета $white: #ffffff; $whiteBold: #f4f8fb; $accent: linear-gradient(144.39deg, #e9277c 0%, #f03482 0.01%, #ff783e 100%); $pink: #f13780; $accentHover: #ffd600; $yellow: #ffb50d; $black: #19193c; $blackLight: #1b1b1b; $red: #eb5757; $grey: #e4e4e4; $greyLight: #4f4f4f; $greyThin: #9c9c9c; // Минимальная ширина страницы $minWidth: 320; // Ширина полотна (макета) $maxWidth: 1920; // Ширина ограничивающего контейнера (0 = нет ограничения) $maxWidthContainer: 1200; // Общий отступ у контейнера // (30 = по 15px слева и справа, 0 = нет отступа) $containerPadding: 40; // Тип адаптива: // 1 = отзывчивость (у контейнера нет брейкпоинтов), // 2 = по брейк-поинтам (контейнер меняет свою ширину по брейк-поинтам) $responsiveType: 1; // Ширина страбатывания первого брейкпоинта $containerWidth: $maxWidthContainer + $containerPadding; // Брейк-поинты $pc: em($containerWidth); // ПК, ноутбуки, некоторые планшеты в горизонтальном положении $tablet: em(991.98); // Планшеты, некоторые телефоны в горизонтальном положении $mobile: em(767.98); // Телефоны L $mobileSmall: em(479.98); // Телефоны S @import 'base/null'; body { // Скролл заблокирован .lock & { overflow: hidden; touch-action: none; } .menu-open & { .header__nav { transform: translateX(0); } } // Сайт загружен .loaded & { } } .wrapper { min-height: 100%; display: flex; flex-direction: column; overflow: hidden; // Прижимаем footer > main { flex: 1 1 auto; } // Фикс для слайдеров > * { min-width: 0; } } .sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; border: 0; padding: 0; white-space: nowrap; clip-path: inset(100%); clip: rect(0 0 0 0); overflow: hidden; } /* (i) Стили будут применяться ко всем классам содержащим *__container Например header__container, main__container и т.д. Снипет (HTML): cnt */ @if ($responsiveType==1) { // Отзывчивая [class*='__container'] { @if ($maxWidthContainer>0) { max-width: rem($maxWidthContainer); box-sizing: content-box; margin: 0 auto; } @if ($containerPadding>0) { padding: 0 rem(math.div($containerPadding, 2)); } @media (max-width: em(1280)) { max-width: rem(945); } } } @else { // По брейк-поинтам [class*='__container'] { margin: 0 auto; @if ($maxWidthContainer>0) { max-width: rem($maxWidthContainer); box-sizing: content-box; } @else { @if ($containerPadding>0) { padding: 0 rem(math.div($containerPadding, 2)); } } @media (max-width: $pc) { max-width: rem(970); } @media (max-width: $tablet) { max-width: rem(750); } @media (max-width: $mobile) { max-width: none; @if ($containerPadding>0 and $maxWidthContainer>0) { padding: 0 rem(math.div($containerPadding, 2)); } } } } // Подключение базовых стилей, шаблонов (заготовок) и вспомагательных классов // Для подключения/отключения конкретных стилей смотри base.scss @import '~js-datepicker/dist/datepicker.min.css'; @import 'base'; // Подключение стилей общих элементов проекта @import 'common'; @import 'components/pagination'; @import 'components/product'; @import 'components/review'; @import 'components/tags'; @import 'components/menu'; @import 'components/socials'; @import 'components/payment'; @import 'components/field'; @import 'components/breadcrumbs'; @import 'components/card'; @import 'components/guide'; @import 'components/chars'; @import 'components/stock'; @import 'components/pricelist'; @import 'components/calendar'; @import 'components/timing'; @import 'components/runline'; @import 'components/event'; // @import 'sections/promo'; @import 'sections/form'; @import 'sections/section'; @import 'sections/news'; @import 'sections/guides'; @import 'sections/slider'; @import 'sections/faq'; @import 'sections/info'; @import 'sections/gallery'; @import 'sections/excursion'; @import 'sections/testimonials'; @import 'sections/placement'; @import 'sections/stocks'; @import 'sections/find'; @import 'sections/timeline'; @import 'sections/work'; @import 'sections/partners'; @import 'sections/album'; @import 'sections/sources'; @import 'sections/relative'; @import 'sections/desire'; @import 'sections/process'; @import 'sections/price'; @import 'sections/offer'; @import 'sections/booking'; @import 'sections/gift'; @import 'sections/schedule'; @import 'sections/classic'; @import 'sections/school'; @import 'sections/training'; @import 'sections/banner'; @import 'sections/announce'; @import 'sections/events'; // Подключение стилей отдельных блоков @import 'header'; @import 'footer'; // Подключение стилей отдельных страниц @import 'home';
import './App.css'; import Navbar from './components/Navbar'; import TextForm from './components/TextForm'; // import About from './components/about'; import React, { useState } from 'react'; import Alert from './components/Alert'; // import { // BrowserRouter as Router, // Routes, // Route // } from "react-router-dom"; function App() { const [mode, setMode] = useState('light'); // Whether dark mode is enabled or not const [alert, setAlert] = useState(null); const showAlert = (message, type) => { setAlert({ msg: message, type: type }) setTimeout(() => { setAlert(null); }, 1500); } const toggleMode = () => { if (mode === 'light') { setMode('dark'); document.body.style.backgroundColor = '#333333'; document.body.style.color = 'white'; showAlert('Dark mode has been enabled', 'success'); } else { setMode('light'); document.body.style.backgroundColor = 'white'; document.body.style.color = 'black'; showAlert('Light mode has been enabled', 'success'); } } return ( <> {/* <Router> */} <Navbar title="TextUtils" mode={mode} toggleMode={toggleMode} /> <Alert alert={alert} /> <div className="container my-3"> {/* <Routes> <Route exact path="/about" element={<About />} /> <Route exact path="/" element={<TextForm heading="Enter your Text to analyze below:" mode={mode} showAlert={showAlert} />} /> </Routes> */} <TextForm heading="Enter your Text to analyze below:" mode={mode} showAlert={showAlert} /> </div> {/* </Router> */} </> ); } export default App;
<script lang="ts"> import { AnimeTopics, type Settings } from './settings'; import { RangeSlider } from '@skeletonlabs/skeleton'; import { forceUpdateBackground } from '$actions/dynamic-background'; import NumberInput from '$shared-components/number-input.svelte'; import * as m from '$i18n/messages'; import FilterSelector from '$shared-components/filter-selector.svelte'; import SettingsBase from '$backgrounds/common-image/settings-base.svelte'; export let settings: Settings; const { topic, blur, filter } = settings; const topicNames: [AnimeTopics, string][] = [ [AnimeTopics.Any, m.Backgrounds_AnimeImage_Settings_Topic_Any()], [AnimeTopics.AI, 'AI Drawing'], [AnimeTopics.ACG, 'ACG'], [AnimeTopics.MOE, 'MOE'], [AnimeTopics.OriginalGod, 'Original God'], [AnimeTopics.PCTransverse, 'PC Transverse'], [AnimeTopics.Landscape, 'Landscape'], [AnimeTopics.Genshin, 'Genshin'], ]; let updateInterval = settings.updateInterval.value / 60; $: { settings.updateInterval.value = Math.max(updateInterval, 1) * 60; } </script> <label class="label mb-2"> <span>{m.Backgrounds_AnimeImage_Settings_Topic()}</span> <select class="select" bind:value={$topic}> {#each topicNames as [topic, name]} <option value={topic}>{name}</option> {/each} </select> </label> <!-- svelte-ignore a11y-label-has-associated-control --> <label class="label"> <span>{m.Backgrounds_AnimeImage_Settings_UpdateInterval()}</span> <div> <NumberInput bind:value={updateInterval} min={1} /> </div> </label> <SettingsBase {settings} provider={{ href: 'https://t.mwm.moe/us/', name: 't.mwm.moe' }} /> <button class="btn variant-soft" on:click={forceUpdateBackground}> {m.Backgrounds_AnimeImage_Settings_Refresh()} </button>
package com.appsmith.server.helpers; import com.appsmith.server.domains.Application; import com.appsmith.server.domains.GitArtifactMetadata; import com.appsmith.server.exceptions.AppsmithError; import com.appsmith.server.exceptions.AppsmithException; import com.appsmith.util.WebClientUtils; import net.minidev.json.JSONObject; import org.eclipse.jgit.util.StringUtils; import reactor.core.publisher.Mono; import reactor.netty.http.client.HttpClientRequest; import java.io.IOException; import java.time.Duration; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GitUtils { public static final Duration RETRY_DELAY = Duration.ofSeconds(1); public static final Integer MAX_RETRIES = 20; /** * Sample repo urls : * git@example.com:user/repoName.git * ssh://git@example.org/<workspace_ID>/<repo_name>.git * https://example.com/user/repoName * * @param sshUrl ssh url of repo * @return https url supported by curl command extracted from ssh repo url */ public static String convertSshUrlToBrowserSupportedUrl(String sshUrl) { if (StringUtils.isEmptyOrNull(sshUrl)) { throw new AppsmithException(AppsmithError.INVALID_PARAMETER, "ssh url"); } return sshUrl.replaceFirst(".*git@", "https://") .replaceFirst("(\\.[a-zA-Z0-9]*):", "$1/") .replaceFirst("\\.git$", ""); } /** * Sample repo urls : * git@example.com:username/reponame.git * ssh://git@example.org/<workspace_ID>/<repo_name>.git * * @param remoteUrl ssh url of repo * @return repo name extracted from repo url */ public static String getRepoName(String remoteUrl) { // Pattern to match git SSH URL final Matcher matcher = Pattern.compile( "((git|ssh)|([\\w\\-\\.]+@[\\w\\-\\.]+))(:(\\/\\/)?)([\\w.@:\\/\\-~\\(\\)\\%]+)(\\.git|)(\\/)?") .matcher(remoteUrl); if (matcher.find()) { // To trim the postfix and prefix return matcher.group(6).replaceFirst("\\.git$", "").replaceFirst("^(.*[\\\\\\/])", ""); } throw new AppsmithException( AppsmithError.INVALID_GIT_CONFIGURATION, "Remote URL is incorrect, " + "please add a URL in standard format. Example: git@example.com:username/reponame.git"); } /** * This method checks if the provided git-repo is public or private by checking the response from the get request * if we get 200 or 202 then repo is public otherwise it's private * * @param remoteHttpsUrl remote url in https format * @return if the repo is public * @throws IOException exception thrown during openConnection */ public static Mono<Boolean> isRepoPrivate(String remoteHttpsUrl) { return WebClientUtils.create(remoteHttpsUrl) .get() .httpRequest(httpRequest -> { HttpClientRequest reactorRequest = httpRequest.getNativeRequest(); reactorRequest.responseTimeout(Duration.ofSeconds(2)); }) .exchange() .flatMap(response -> { if (response.statusCode().is2xxSuccessful()) { return Mono.just(Boolean.FALSE); } else { return Mono.just(Boolean.TRUE); } }) .onErrorResume(throwable -> Mono.just(Boolean.TRUE)); } /** * Sample repo urls : * git@gitPlatform.com:user/repoName.git * gitPlatform * * @param sshUrl ssh url of repo * @return git hosting provider */ public static String getGitProviderName(String sshUrl) { if (StringUtils.isEmptyOrNull(sshUrl)) { return ""; } return sshUrl.split("\\.")[0].replaceFirst("git@", ""); } public static String getDefaultBranchName(GitArtifactMetadata gitArtifactMetadata) { return StringUtils.isEmptyOrNull(gitArtifactMetadata.getDefaultBranchName()) ? gitArtifactMetadata.getBranchName() : gitArtifactMetadata.getDefaultBranchName(); } /** * This method checks if the application is connected to git and is the default branched. * * @param application application to be checked * @return true if the application is default branched, false otherwise */ public static boolean isDefaultBranchedApplication(Application application) { GitArtifactMetadata metadata = application.getGitApplicationMetadata(); return isApplicationConnectedToGit(application) && !StringUtils.isEmptyOrNull(metadata.getBranchName()) && metadata.getBranchName().equals(metadata.getDefaultBranchName()); } /** * This method checks if the application is connected to Git or not. * @param application application to be checked * @return true if the application is connected to Git, false otherwise */ public static boolean isApplicationConnectedToGit(Application application) { GitArtifactMetadata metadata = application.getGitApplicationMetadata(); return metadata != null && !StringUtils.isEmptyOrNull(metadata.getDefaultApplicationId()) && !StringUtils.isEmptyOrNull(metadata.getRemoteUrl()); } public static boolean isMigrationRequired(JSONObject layoutDsl, Integer latestDslVersion) { boolean isMigrationRequired = true; String versionKey = "version"; if (layoutDsl.containsKey(versionKey)) { int currentDslVersion = layoutDsl.getAsNumber(versionKey).intValue(); if (currentDslVersion >= latestDslVersion) { isMigrationRequired = false; } } return isMigrationRequired; } public static boolean isAutoCommitEnabled(GitArtifactMetadata gitArtifactMetadata) { return gitArtifactMetadata.getAutoCommitConfig() == null || gitArtifactMetadata.getAutoCommitConfig().getEnabled(); } }
part of 'login_bloc.dart'; abstract class LoginEvent extends Equatable { const LoginEvent(); @override List<Object> get props => []; } class CallbackEvent extends LoginEvent { const CallbackEvent(); } class EmailLoginEvent extends LoginEvent { final String email; final String password; const EmailLoginEvent({required this.email, required this.password}); } class EmailRegisterEvent extends LoginEvent { final String email; final String password; const EmailRegisterEvent({required this.email, required this.password}); } class DiscordLogin extends LoginEvent { const DiscordLogin(); } class GoogleLogin extends LoginEvent { const GoogleLogin(); } class AppleLogin extends LoginEvent { const AppleLogin(); } class SpotifyEvent extends LoginEvent { const SpotifyEvent(); } class CreateUserProfile extends LoginEvent { const CreateUserProfile(); } class GoBack extends LoginEvent { final String path; const GoBack({ required this.path, }); }
# Code4Recovery Spec Composer Package This package contains a class that makes the most up-to-date meeting types available to your application. Updates are released anytime new meeting types are added. ## Installation ```shell composer require code4recovery/spec ``` ## Instantiation ```php use Code4Recovery\Spec; $spec = new Spec(); ``` ## Get all available languages Returns an array of all available languages for type translation. The array is keyed by language code and has the expanded language name as the value. ```php $spec->getLanguages(); ``` Example returned value ```php [ 'en' => 'English', 'es' => 'Español', 'fr' => 'Français', 'ja' => '日本語', 'sv' => 'Svenska', ]; ``` ## Get all types Returns an object containing every current meeeting type stored in the type repository with each language translation. ```php $spec->getAllTypes(); ``` Example returned value (truncated) ```php { "11": { "en": "11th Step Meditation", "es": "Meditación del Paso 11", "fr": "Méditation sur la 11e Étape", "ja": "ステップ11 黙想", "sv": "11th Stegs Meditation" }, "12x12": { "en": "12 Steps & 12 Traditions", "es": "12 Pasos y 12 Tradiciones", "fr": "12 Étapes et 12 Traditions", "ja": "12のステップと12の伝統", "sv": "12 Steg & 12 Traditioner" }, ... }; ``` ## Get types by language Returns an array of types translated into the specified language. ```php $spec->getTypesByLanguage('en'); ``` Example returned value ```php [ 11 => "11th Step Meditation" "12x12" => "12 Steps & 12 Traditions" "A" => "Secular" "ABSI" => "As Bill Sees It" "AL" => "Concurrent with Alateen" "AL-AN" => "Concurrent with Al-Anon" "AM" => "Amharic" "ASL" => "American Sign Language" "B" => "Big Book" "BA" => "Babysitting Available" "BE" => "Newcomer" "BI" => "Bisexual" "BRK" => "Breakfast" "C" => "Closed" "CAN" => "Candlelight" "CF" => "Child-Friendly" "D" => "Discussion" "DA" => "Danish" "DB" => "Digital Basket" "DD" => "Dual Diagnosis" "DE" => "German" "DR" => "Daily Reflections" "EL" => "Greek" "EN" => "English" "FA" => "Persian" "FF" => "Fragrance Free" "FR" => "French" "G" => "Gay" "GR" => "Grapevine" "H" => "Birthday" "HE" => "Hebrew" "HI" => "Hindi" "HR" => "Croatian" "HU" => "Hungarian" "ITA" => "Italian" "JA" => "Japanese" "KOR" => "Korean" "L" => "Lesbian" "LGBTQ" => "LGBTQ" "LIT" => "Literature" "LS" => "Living Sober" "LT" => "Lithuanian" "M" => "Men" "MED" => "Meditation" "ML" => "Malayalam" "N" => "Native American" "NDG" => "Indigenous" "NO" => "Norwegian" "O" => "Open" "OUT" => "Outdoor" "P" => "Professionals" "POC" => "People of Color" "POL" => "Polish" "POR" => "Portuguese" "PUN" => "Punjabi" "RUS" => "Russian" "S" => "Spanish" "SEN" => "Seniors" "SK" => "Slovak" "SM" => "Smoking Permitted" "SP" => "Speaker" "ST" => "Step Study" "SV" => "Swedish" "T" => "Transgender" "TC" => "Location Temporarily Closed" "TH" => "Thai" "TL" => "Tagalog" "TR" => "Tradition Study" "UK" => "Ukrainian" "W" => "Women" "X" => "Wheelchair Access" "XB" => "Wheelchair-Accessible Bathroom" "XT" => "Cross Talk Permitted" "Y" => "Young People" ]; ``` ## License Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.
<h2>Employee List</h2> <div class="card"> <p-table [value]="employees" styleClass="p-datatable-striped" responsiveLayout="scroll" [scrollable]="true" scrollHeight="700px"> <ng-template pTemplate="header"> <tr> <th style="text-align:center">First Name</th> <th style="text-align:center">Last Name</th> <th style="text-align:center">Age</th> <th style="text-align:center">Job Description</th> <th style="text-align:center">Actions</th> </tr> </ng-template> <ng-template pTemplate="body" let-employee> <tr> <td style="text-align:center">{{employee.name}}</td> <td style="text-align:center">{{employee.surname}}</td> <td style="text-align:center">{{employee.age}}</td> <td style="text-align:center">{{employee.jobDescription}}</td> <td> <button p-Button (click)="updateEmployee(employee.id)" class="p-button p-button-outlined1 p-button-success p-button-raised p-button-rounded">Update</button> <button p-Button (click)="deleteEmployee(employee.id)" class="p-button p-button-outlined2 p-button-danger p-button-raised p-button-rounded" style="margin-left: 10px">Delete</button> <button p-Button (click)="employeeDetails(employee.id)" class="p-button p-button-outlined p-button-info p-button-raised p-button-rounded" style="margin-left: 10px">View</button> </td> </tr> </ng-template> </p-table> </div> <!-- <table class="table table-striped"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Job Description</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let employee of employees"> <td>{{employee.name}}</td> <td>{{employee.surname}}</td> <td>{{employee.age}}</td> <td>{{employee.jobDescription}}</td> <td> <button (click)="updateEmployee(employee.id)" class="btn btn-info">Update</button> <button (click)="deleteEmployee(employee.id)" class="btn btn-danger" style="margin-left: 10px">Delete</button> <button (click)="employeeDetails(employee.id)" class="btn btn-info" style="margin-left: 10px">View</button> </td> </tr> </tbody> </table> -->
class Man { field int x, y; // screen location of the man's top-left corner field int totalHeight; field int nooseX; field int nooseLength; field int postX; field int platformWidth; field int headRadius; field int bodyHeight; field int bodyStartY; field int bodyEndY; field int limbLength; field int armsY; /** Constructs a new man starting at the given location */ constructor Man new(int Ax, int Ay) { let x = Ax; let y = Ay; let headRadius = 20; let totalHeight = 160; let nooseLength = 20; let nooseX = 120; let platformWidth = 60; let postX = platformWidth / 2; let bodyHeight = 50; let bodyStartY = y + nooseLength + (headRadius * 2); let bodyEndY = bodyStartY + bodyHeight; let limbLength = 15; let armsY = bodyStartY + 15; return this; } /** Disposes this man */ method void dispose() { do Memory.deAlloc(this); return; } /** Erases the square from the screen. */ method void erase() { do Screen.setColor(false); // do Screen.drawRectangle(x, y, x + size, y + size); do Screen.setColor(true); return; } /** Draws the square on the screen */ method void drawHead() { do Screen.drawCircle(x + nooseX, y + nooseLength + headRadius, headRadius); return; } method void drawNoose() { do Screen.drawLine(x + nooseX, y, x + nooseX, y + headRadius); return; } method void drawPlatform() { do Screen.drawLine(x, y + totalHeight, x + platformWidth, y + totalHeight); return; } method void drawTopBeam() { do Screen.drawLine(x + postX, y, x + nooseX, y); return; } method void drawPost() { do Screen.drawLine(x + postX, y, x + postX, y + totalHeight); return; } method void drawBody() { var int bodyStartY; var int bodyEndY; let bodyStartY = y + nooseLength + (headRadius * 2); let bodyEndY = bodyStartY + bodyHeight; do Screen.drawLine(x + nooseX, bodyStartY, x + nooseX, bodyEndY); return; } method void drawArmLeft() { do Screen.drawLine(x + nooseX, armsY, x + nooseX - limbLength, armsY); return; } method void drawArmRight() { do Screen.drawLine(x + nooseX, armsY, x + nooseX + limbLength, armsY); return; } method void drawLegLeft() { do Screen.drawLine(x + nooseX, bodyEndY, x + nooseX - limbLength, bodyEndY + 10); return; } method void drawLegRight() { do Screen.drawLine(x + nooseX, bodyEndY, x + nooseX + limbLength, bodyEndY + 10); return; } }
const express = require('express'); const socket = require('socket.io'); const cors = require('cors'); const path = require('path'); const mongoose = require('mongoose'); const helmet = require('helmet'); const app = express(); app.use((req, res, next) => { req.io = io; next(); }); app.use(helmet()); const testimonialsRoutes = require('./routes/testimonials.routes'); const concertsRoutes = require('./routes/concerts.routes'); const seatsRoutes = require('./routes/seats.routes'); app.use(cors()); app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use('/api', testimonialsRoutes); app.use('/api', concertsRoutes); app.use('/api', seatsRoutes); app.use(express.static(path.join(__dirname, '/client/build'))); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '/client/build/index.html')); }); app.use((req, res) => { res.status(404).json({ message: 'Not found...' }); }) const server = app.listen(process.env.PORT || 8000, () => { console.log('Server is running on port: 8000'); }); const io = socket(server); io.on('connection', (socket) => { console.log('New socket!' + socket.id); }); const NODE_ENV = process.env.NODE_ENV; let dbUri = ''; if(NODE_ENV === 'production') dbUri = 'mongodb+srv://' + process.env.MONGODB_USERNAME + ':' + process.env.MONGODB_PASSWORD + '@' + process.env.MONGODB_URL + '/' + process.env.MONGODB_DATABASE + '?retryWrites=true&w=majority'; else if(NODE_ENV === 'test') dbUri = 'mongodb://localhost:27017/NewWaveDBtest'; else dbUri = 'mongodb://localhost:27017/NewWaveDB'; mongoose.connect(dbUri, { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.once('open', () => { console.log('Connected to the database'); }); db.on('error', err => console.log('Error ' + err)); module.exports = server;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <title>SFC Guest Book</title> <meta property="og:title" content="일요미식회 방명록" /> <meta property="og:description" content="다음엔 어떤 맛있는 걸 먹을까?" /> <meta property="og:image" content="https://i.pinimg.com/564x/ca/4d/76/ca4d76a9f837feeaa7f6cee32603cd19.jpg" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Nanum+Gothic+Coding:wght@400;700&display=swap" rel="stylesheet"> <style> * { font-family: 'Nanum Gothic Coding', monospace; } .mypic { width: 100%; height: 300px; background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://i.pinimg.com/564x/e9/fc/3f/e9fc3fc8d9a4c870cfeb4cd516ec9da6.jpg"); background-position: center 30%; background-size: cover; color: white; display: flex; flex-direction: column; align-items: center; justify-content: center; } .mypic h1{font-family: "Noto Serif KR", serif; font-weight: bold; letter-spacing: -3px;} .mypost { width: 95%; max-width: 500px; margin: 20px auto 20px auto; box-shadow: 0px 0px 3px 0px black; padding: 20px; } .mypost>button { margin-top: 15px; } .mycards { width: 95%; max-width: 500px; margin: auto; } .mycards>.card { margin-top: 10px; margin-bottom: 10px; } </style> <script> $(document).ready(function () { set_temp(); show_comment(); }); function set_temp() { fetch("http://spartacodingclub.shop/sparta_api/weather/busan").then((res) => res.json()).then((data) => { let temp = data['temp'] $('#temp').text(temp) }); } function save_comment() { let name = $('#name').val() let comment = $('#comment').val() let formData = new FormData(); formData.append("name_give", name); formData.append("comment_give", comment); fetch('/guestbook', { method: "POST", body: formData, }).then((res) => res.json()).then((data) => { alert(data["msg"]); window.location.reload(); }); } function show_comment() { fetch('/guestbook').then((res) => res.json()).then((data) => { let rows = data['result'] $('#comment-list').empty() rows.forEach((a)=>{ let name = a['name'] let comment = a['comment'] let temp_html = `<div class="card"> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>${comment}</p> <footer class="blockquote-footer">${name}</footer> </blockquote> </div> </div>` $('#comment-list').append(temp_html) }) }) } </script> </head> <body> <div class="mypic"> <h1>Sunday Foodie Club</h1> <h3>먹킷리스트</h3> <p>부산 현재 기온: <span id="temp">36</span>도</p> </div> <div class="mypost"> <div class="form-floating mb-3"> <input type="text" class="form-control" id="name" placeholder="url" /> <label for="floatingInput">닉네임</label> </div> <div class="form-floating"> <textarea class="form-control" placeholder="Leave a comment here" id="comment" style="height: 100px"></textarea> <label for="floatingTextarea2">지역 / 상호명</label> </div> <button onclick="save_comment()" type="button" class="btn btn-dark"> 글 남기기 </button> </div> <div class="mycards" id="comment-list"> <div class="card"> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>내용</p> <footer class="blockquote-footer">글쓴이</footer> </blockquote> </div> </div> <div class="card"> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>내용</p> <footer class="blockquote-footer">글쓴이</footer> </blockquote> </div> </div> </div> </body> </html>
/* Copyright © 2021 Carl Caum <carl@carlcaum.com> 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 cmd import ( "fmt" "os" "github.com/spf13/cobra" "sumologic.com/sumo-cli/sumoapp" ) var ( outputFile string ) // buildCmd represents the build command var buildCmd = &cobra.Command{ Use: "build", Short: "Compile a single application JSON artifact", Long: `Compiles all the application overlays into a single JSON file that can be imported into Sumo Logic's Continuous Intelligence Platform`, Run: func(cmd *cobra.Command, args []string) { var path string switch len(args) { case 0: path = appPath case 1: path = args[0] default: fmt.Fprintf(os.Stderr, "Error: too many arguments. Expects none or one. Use --help to learn more") os.Exit(1) } app := sumoapp.NewApplicationWithPath(path) if err := app.LoadAppOverlays(); err != nil { fmt.Fprintf(os.Stderr, "Error: %s", err) os.Exit(1) } jsonString, err := app.ToJSON() if err != nil { fmt.Fprintf(os.Stderr, "Error: %s", err) os.Exit(1) } if outputFile == "" { fmt.Println(string(jsonString)) } else { err := os.WriteFile(outputFile, jsonString, 0644) if err != nil { fmt.Fprintf(os.Stderr, "Error: Unable to write to file %s. %w", outputFile, err) os.Exit(1) } } }, } func init() { appCmd.AddCommand(buildCmd) buildCmd.PersistentFlags().StringVarP(&outputFile, "output-file", "o", "", "Output file containing the compiled JSON") }
import Component from 'components/component'; import bind from 'decorators/bind'; import cx from 'classnames'; import {placeCaretAtEnd} from 'helpers/utils'; import React from 'react'; import PropTypes from 'prop-types'; import styles from './index.less'; export default class EditableTitle extends Component { static propTypes = { value: PropTypes.string.isRequired, sub: PropTypes.bool, onSubmit: PropTypes.func.isRequired, big: PropTypes.bool, className: PropTypes.string, textClassName: PropTypes.string, noProgress: PropTypes.bool }; getInitState () { return { editing: false }; } componentWillReceiveProps (nextProps) { if (this.state.editing && nextProps.value !== this.props.value) { this.setState({ editing: false }); } } componentDidUpdate (prevProps, prevState) { if (!prevState.editing && this.state.editing) { const input = this.refs.input; if (input) { placeCaretAtEnd(input); } } } @bind onClick () { this.setState({ editing: true, editValue: this.props.value }); } @bind onChange () { this.setState({ editValue: this.refs.input.innerText }); } @bind cancel (event) { event.preventDefault(); this.setState({ editing: false, editValue: '' }); } @bind onSubmit (event) { event.preventDefault(); const {noProgress} = this.props; if (noProgress) { if (this.state.editValue === '') { this.setState({ editing: false, editValue: '' }); return; } this.props.onSubmit(this.state.editValue); this.setState({ editing: false }); } else { this.props .onSubmit(this.state.editValue) .then(() => { this.setState({ editing: false }); }); } } @bind keyPress (event) { if (event.charCode === 13) { this.onSubmit(event); } } render () { const {sub, big} = this.props; return ( <div className={cx(sub && styles.sub, big && styles.big)}> {this.renderContent()} </div> ); } renderContent () { const {editing} = this.state; const {value, className, textClassName} = this.props; let result; if (!editing) { result = ( <button className={cx(styles.root, styles.editButton, className)} onClick={this.onClick} > <div className={cx(styles.title, textClassName || styles.titleStyle)}>{value}</div> <i className='nc-icon-outline ui-1_edit-74' /> </button> ); } else { result = ( <form onSubmit={this.onSubmit} className={cx(styles.root, className)} > <div onInput={this.onChange} className={cx(styles.title, textClassName || styles.titleStyle)} contentEditable dangerouslySetInnerHTML={{__html: this.state.editValue}} onKeyPress={this.keyPress} ref='input' /> <button className={cx(styles.formButton, styles.confirmButton)}>Ok</button> <button className={cx(styles.formButton, styles.cancelButton)} onClick={this.cancel}>Cancel</button> </form> ); } return result; } }
import React, { useState, useEffect } from 'react'; import "./header.css"; import NetflixLogo from "../../assets/images/pngwing.com.png"; import SearchIcon from '@mui/icons-material/Search'; import NotificationsNoneIcon from '@mui/icons-material/NotificationsNone'; import AccountBoxIcon from '@mui/icons-material/AccountBox'; import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown'; const Header = () => { const [scrolling, setScrolling] = useState(false); useEffect(() => { const handleScroll = () => { if (window.scrollY > 0) { setScrolling(true); } else { setScrolling(false); } }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); return ( <div className={`header_outer_container ${scrolling ? 'nav__black' : ''}`}> <div className='header_container'> <div className='header_left'> <ul> <li><img src={NetflixLogo} alt="Netflix Logo" width="100" /></li> <li>Home</li> <li>TVShows</li> <li>Movies</li> <li>Latest</li> <li>MyList</li> <li>Browse by Languages</li> </ul> </div> <div className='header_right'> <ul> <li><SearchIcon /></li> <li><NotificationsNoneIcon /></li> <li><AccountBoxIcon /></li> <li><ArrowDropDownIcon /></li> </ul> </div> </div> </div> ) } export default Header;
import {BehaviorSubject} from "rxjs"; import {rendezvous} from "../typescript/async/rendezvous"; import onPromiseCompletion from "../typescript/async/onPromiseCompletion"; /** * A promise of the completion of a behaviour subject. * * @param subject * The subject to monitor for completion. * @return * A promise of the final value of the subject. */ export default async function behaviourSubjectCompletionPromise<T>( subject: BehaviorSubject<T> ): Promise<T> { // Create a rendezvous promise to receive the value const [promise, resolve, reject] = rendezvous<T>(); // Subscribe the observer const subscription = subject.subscribe({ error: (err) => { reject(err) }, complete: () => resolve(subject.getValue()) }); // Once the promise resolves, the subscription is no longer required onPromiseCompletion( promise, () => subscription.unsubscribe() ); return promise; }
import { useState } from "react"; import { Link } from "react-router-dom"; import { projectAuth } from "../../Database/firebase/config"; import { useLogin } from "../../Database/Hooks/useLogin"; import "./SL.css"; export default function Login() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isPending, setIsPending] = useState(false); const [error, setError] = useState(null); const onSubmit = async (e) => { e.preventDefault(); setIsPending(true); await projectAuth.signInWithEmailAndPassword(email, password).catch(error => { setError("Email and password do not match."); }); setIsPending(false); }; return ( <div className="SLFormContainer"> <form onSubmit={onSubmit} className="SLform"> <h2>Login to an existing account</h2> <p className={`errorMSG ${error ? "displayError" : ""}`}>Error: {error}</p> <label> <span>Email:</span> <input type="email" required onChange={(e) => setEmail(e.target.value)} value={email} /> </label> <label> <span>Password:</span> <input type="password" required onChange={(e) => setPassword(e.target.value)} value={password} /> </label> {!isPending && <button className="submitButton">Login</button>} {isPending && ( <button className="submitButton" disabled> loading... </button> )} <Link to="/Signup">I don't have an account</Link> </form> </div> ); }
/* { "description" : "Search for values in an array."} */ interface Search { /* { "@description" : "Search an array for cells matching a template, returning all matching cells.", "list" : "The array to search.", "field" : "The field to search against.", "template" : "An instance of the same type as the data held in list, in which the field to match against is set to the value being searched for." "@return" : "An array of cells matching the search term.", "@deprecated" : true } */ Data[] search(Data list[], TypeField field, Data template) /* { "@description" : "Search an array for cells matching a template, returning all matching cells.", "list" : "The array to search.", "field" : "The field to search against.", "template" : "An instance of the same type as the data held in list, in which the field to match against is set to the value being searched for." "@return" : "An array of cells matching the search term." } */ Data[] find(Data list[], TypeField field, Data template) /* { "@description" : "Search an array for a cell matching a template, returning the first matching cell.", "list" : "The array to search.", "field" : "The field to search against.", "template" : "An instance of the same type as the data held in list, in which the field to match against is set to the value being searched for." "@return" : "An array of cells matching the search term." } */ Data findFirst(Data list[], TypeField field, Data template) }
// // ViewController.swift // SwitchTuistFinalTest // // Created by Muzlive_Player on 2023/08/09. // import UIKit import SnapKit import RxSwift import RxCocoa import AssetsPickerViewController import Photos import DateToolsSwift class ViewController: UIViewController { private let logoImageView = UIImageView() private let assetsViewControllerButton = UIButton() private let dateLabel = UILabel() private let ealierResultLabel = UILabel() private let presentingObjcVCButton = UIButton() lazy var disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .purple setupView() setupLayout() setupAttribute() setupBinding() } } extension ViewController { private func setupView(){ [ logoImageView, assetsViewControllerButton, dateLabel, ealierResultLabel, presentingObjcVCButton ].forEach { view.addSubview($0) } } private func setupLayout() { assetsViewControllerButton.snp.makeConstraints { $0.height.width.equalTo(150) $0.centerX.centerY.equalToSuperview() } logoImageView.snp.makeConstraints { $0.bottom.equalTo(assetsViewControllerButton.snp.top) .offset(-24) $0.width.height.equalTo(120) $0.centerX.equalToSuperview() } dateLabel.snp.makeConstraints { $0.top.equalTo(assetsViewControllerButton.snp.bottom) .offset(16) $0.centerX.equalToSuperview() } ealierResultLabel.snp.makeConstraints { $0.top.equalTo(dateLabel.snp.bottom) .offset(16) $0.centerX.equalToSuperview() } presentingObjcVCButton.snp.makeConstraints { $0.top.equalTo(ealierResultLabel.snp.bottom) .offset(16) $0.width.equalTo(150) $0.height.equalTo(52) $0.centerX.equalToSuperview() } } private func setupAttribute(){ assetsViewControllerButton.backgroundColor = .red assetsViewControllerButton.setTitle("assetsVCButton", for: .normal) logoImageView.image = UIImage(named: "logo") let now = Date() dateLabel.text = "\(now)" ealierResultLabel.text = "\(now.isEarlier(than: now))" presentingObjcVCButton.setTitle("move To objcVC", for: .normal) presentingObjcVCButton.backgroundColor = .blue } private func setupBinding(){ assetsViewControllerButton.rx.tap .asDriver() .drive(onNext: { [weak self] _ in guard let self = self else { return } let nextVC = self.setupAssetsPickerView() nextVC.modalPresentationStyle = .overFullScreen self.present(nextVC, animated: false) }) .disposed(by: disposeBag) presentingObjcVCButton.rx.tap .asDriver() .drive(onNext: { [weak self] _ in guard let self = self else { return } let nextVC = ObjcTestViewController() // nextVC.modalPresentationStyle = .overFullScreen self.present(nextVC, animated: false) }) .disposed(by: disposeBag) } } extension ViewController { private func setupAssestConfig() -> AssetsPickerConfig { let predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) let options = PHFetchOptions() options.predicate = predicate let config = AssetsPickerConfig() config.albumIsShowEmptyAlbum = false config.assetFetchOptions = [.smartAlbum: options] config.assetsMaximumSelectionCount = 1 return config } private func setupAssetsPickerView() -> AssetsPickerViewController { let picker = AssetsPickerViewController() picker.pickerConfig = setupAssestConfig() return picker } }
import React from 'react' import Paper from '@mui/material/Paper' import Table from '@mui/material/Table' import TableRow from '@mui/material/TableRow' import TableHead from '@mui/material/TableHead' import TableBody from '@mui/material/TableBody' import TableCell from '@mui/material/TableCell' import TableContainer from '@mui/material/TableContainer' import TextField from '@mui/material/TextField' import Button from '@mui/material/Button' const TableClosing = ({ data, setTableData }) => { const handleInputChange = (e, id, field) => { const newTableData = data.map(item => { if (item._id === id) { return { ...item, [field]: e.target.value } } return item }) setTableData(newTableData) } const handleRemove = id => { const newTableData = data.filter(item => item._id !== id) setTableData(newTableData) } if (!data || !Array.isArray(data) || data.length === 0) { return <p>Add Products</p> } return ( <TableContainer component={Paper}> <Table sx={{ minWidth: 650 }} aria-label='simple table'> <TableHead> <TableRow> <TableCell>Product ID</TableCell> <TableCell>Product Name</TableCell> <TableCell>End of the Day Qty</TableCell> <TableCell>Start of the Day Qty</TableCell> <TableCell>Usage</TableCell> <TableCell>Remove</TableCell> </TableRow> </TableHead> <TableBody> {data.map(row => ( <TableRow key={row._id}> <TableCell component='th' scope='row'> {row._id} </TableCell> <TableCell>{row.name}</TableCell> <TableCell> <TextField value={row.endOfDayQty} onChange={e => handleInputChange(e, row._id, 'endOfDayQty')} variant='outlined' size='small' type='number' /> </TableCell> <TableCell> <TextField value={row.startOfDayQty} onChange={e => handleInputChange(e, row._id, 'startOfDayQty')} variant='outlined' size='small' type='number' /> </TableCell> <TableCell>{row.startOfDayQty - row.endOfDayQty}</TableCell> <TableCell> <Button variant='outlined' color='error' onClick={() => handleRemove(row._id)}> Remove </Button> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ) } export default TableClosing
import React, { useState, useContext } from 'react'; import Axios from 'axios'; import server from '../../config/service'; import AuthContext from '../../context/AuthProvider'; import { useNavigate } from 'react-router-dom'; import './RegisterStyles.css'; const Register = () => { const [zipcode, setZipcode] = useState(""); const [firstname, setFirstname] = useState(""); const [lastname, setLastname] = useState(""); const [email, setEmail] = useState(""); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [loginState, setLoginState] = useState(false); const [systemMsg, setSystemMsg] = useState(""); const { setAuth } = useContext(AuthContext); const navigate = useNavigate(); const requestHandler = async(e) => { e.preventDefault(); Axios.post(`${server.host}/v1/account/register`, { zipCode: zipcode, firstName: firstname, lastName: lastname, email: email, username: username, password: password }).then((res) => { let result = res.status === 200 ? true : false; setAuth({ id: res.data.id, username: res.data.username, token: res.data.token }); setLoginState(result); }).catch((err) => { setSystemMsg("username or email is already in use"); }); } return ( <> { loginState ? navigate("/dashboard") : ( <div class="register-box"> <h2>Create an Account</h2> <form> <div class="user-box"> <input type="number" name="" required="" onChange={(e) => { setZipcode(e.target.value); }}/> <label>Zip Code</label> </div> <div class="user-box"> <input type="firstName" name="" required="" onChange={(e) => { setFirstname(e.target.value); }}/> <label>First Name</label> </div> <div class="user-box"> <input type="lastName" name="" required="" onChange={(e) => { setLastname(e.target.value); }}/> <label>Last Name</label> </div> <div class="user-box"> <input type="userEmail" name="" required="" onChange={(e) => { setEmail(e.target.value); }}/> <label>E-Mail</label> </div> <div class="user-box"> <input type="username" name="" required="" onChange={(e) => { setUsername(e.target.value); }}/> <label>Username</label> </div> <div class="user-box"> <input type="password" name="" required="" onChange={(e) => { setPassword(e.target.value); }}/> <label>Password</label> </div> <div class="user-box"> <button onClick={requestHandler}> <span></span> <span></span> <span></span> <span></span> <a href="/dashboard" > Register </a> </button> <p className={systemMsg ? "system" : "offscreen"} aria-live="assertive">{systemMsg}</p> </div> </form> </div> ) } </> ) } export default Register
""" Pow(x, n): https://leetcode.com/problems/powx-n/ Problem: Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Constraints: - Power can be negative. Ex: 2^-2 = 1/2^2 = 1/4 = 0.25 Input: x = 2.00000, n = 10 Output: 1024.00000 Input: x = 2.10000, n = 3 Output: 9.26100 Input: x = 2.00000, n = -2 Output: 0.25000 """ def brute_force(x: float, n: int) -> float: """ Time complexity: O(n) Space complexity: O(1) """ result = 1 for _ in range(abs(n)): result *= x return result if n >= 0 else 1 / result def optimized_solution(x: float, n: int) -> float: """ Time complexity: O(log n) Space complexity: O(1) """ result = 1.0 if n == 0: return result elif n < 0: x = 1 / x n = -n while n > 0: if n % 2 == 1: result *= x x *= x n //= 2 return result def myPow(x: float, n: int) -> float: def helper(x, n): if n == 0: return 1 if x == 0: return 0 result = helper(x, n // 2) result = result * result return x * result if n % 2 else result result = helper(x, abs(n)) return result if n >= 0 else 1 / result
use crate::schema::{messages, users}; use async_graphql::SimpleObject; use diesel::{deserialize::Queryable, AsChangeset, Insertable, Selectable}; #[derive(Debug, SimpleObject, Clone, Selectable, Queryable)] #[diesel(table_name = users)] pub struct User { pub id: i32, pub username: Option<String>, pub email: String, pub password: String, } #[derive(AsChangeset, SimpleObject, Insertable)] #[diesel(table_name = users)] pub struct NewUser { pub username: Option<String>, pub email: String, pub password: String, } #[derive(Debug, SimpleObject, Clone, Selectable, Queryable)] #[diesel(table_name = messages)] pub struct Message { pub id: i32, pub sender: i32, pub receiver: i32, pub text: String, } #[derive(AsChangeset, SimpleObject, Insertable)] #[diesel(table_name = messages)] pub struct NewMessage { pub sender: i32, pub receiver: i32, pub text: String, }
--- title: 005: Kotlin의 함수: 값 정의, 호출 및 반환 description: published: true date: 2023-02-16T02:32:23.662Z tags: editor: markdown dateCreated: 2023-02-16T02:32:22.067Z --- > 이 문서는 **Google Cloud Translation API를 사용해 자동 번역**되었습니다. 어떤 문서는 원문을 읽는게 나을 수도 있습니다.{.is-info} - [005: Functions in Kotlin: Defining, Calling, and Returning Values***English** document is available*](/en/Knowledge-base/Kotlin/Learning/005-functions-in-kotlin-defining-calling-and-returning-values) {.links-list} # Kotlin의 함수: 값 정의, 호출 및 반환 기능은 특정 작업을 수행하는 코드 집합입니다. Kotlin에서는 나중에 해당 작업을 수행해야 할 때마다 호출할 자체 함수를 정의할 수 있습니다. 이 게시물에서는 함수를 정의하고 호출하고 값을 반환하는 방법을 배웁니다. ## 함수 정의 Kotlin에서는 ```fun``` 키워드를 사용하여 함수를 정의합니다. 예를 들어 인사말을 출력하는 함수를 정의하고 싶다고 합시다. 다음과 같이 할 수 있습니다. ```kotlin fun printGreeting() { println("Hello, world!") } ``` 인수를 받는 함수를 정의할 수도 있습니다. 예를 들어 이름이 있는 인사말 메시지를 인쇄하는 함수를 정의하고 싶다고 가정해 보겠습니다. 다음과 같이 할 수 있습니다. ```kotlin fun printGreeting(name: String) { println("Hello, $name!") } ``` 값을 반환하는 함수를 정의할 수도 있습니다. 예를 들어 두 숫자의 합을 계산하는 함수를 정의하고 싶다고 가정해 보겠습니다. 다음과 같이 할 수 있습니다. ```kotlin fun sum(a: Int, b: Int): Int { return a + b } ``` ## 함수 호출 함수 이름 뒤에 괄호 ```()```를 사용하여 함수를 호출합니다. 예를 들어 앞에서 정의한 ```printGreeting()``` 함수를 다음과 같이 호출할 수 있습니다. ```kotlin printGreeting() // prints "Hello, world!" ``` 인수를 받는 함수를 정의한 경우 괄호 ```()``` 안에 인수를 전달해야 합니다. 예를 들어 앞에서 정의한 ```printGreeting(name: String)``` 함수를 다음과 같이 호출할 수 있습니다. ```kotlin printGreeting("John") // prints "Hello, John!" ``` 값을 반환하는 함수를 정의한 경우 반환 값을 변수에 저장해야 합니다. 예를 들어 앞에서 정의한 ```sum(a: Int, b: Int): Int``` 함수를 다음과 같이 호출할 수 있습니다. ```kotlin val result = sum(1, 2) // result is 3 ``` ## 반환 값 이전 섹션에서 본 것처럼 값을 반환하는 함수를 정의할 수 있습니다. Kotlin에서는 ```return``` 키워드를 사용하여 함수에서 값을 반환합니다. 예를 들어 두 숫자의 합을 계산하고 결과를 반환하는 함수를 정의하고 싶다고 가정해 보겠습니다. 다음과 같이 할 수 있습니다. ```kotlin fun sum(a: Int, b: Int): Int { return a + b } ``` ```kotlin fun sum(a: Int, b: Int): Int = a + b ```코틀린 재미있는 합(a: Int, b: Int): Int = a + b ``` 후자의 예에서는 간단히 함수 이름 ```sum```에 할당하여 ```a + b``` 값을 반환합니다. 이번 포스팅은 여기까지! 요약하면 함수를 정의하고 호출하고 값을 반환하는 방법을 배웠습니다.
package lesson13.practice; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import pageObjects.baseObjects.BaseTest; import pageFactory.saucedemo.LoginPage; import pageFactory.saucedemo.ProductPage; public class ProductPageFactoryTest extends BaseTest { @BeforeTest public void precondition(){ get(LoginPage.class) .open() .enterUsername() .enterPassword() .clickLogin(); } @Test(dataProvider = "index", priority = 1) public void addProductCartTest(Integer index){ get(ProductPage.class).waitUntilPageLoaded().clickAddToCard(index); } @DataProvider(name = "index") public Object[][] getData(){ return new Object[][]{ {1}, {2}, {3}, {4} }; } }
Nome do Componente Curricular: Laboratório de Sistemas Computacionais: Engenharia de Sistemas Pré-requisitos: Laboratório de Sistemas Computacionais: Arquitetura e Organização de Computadores Carga Horária Total: 36h Carga Horária Prática: 28h Carga Horária Teórica: 08h Objetivos Gerais: Esta unidade curricular faz parte das unidades curriculares integradas definidas no Projeto Pedagógico do Curso, as quais são utilizadas para que o aluno possa, de fato, desenvolver um sistema computacional completo durante o seu processo de aprendizagem, envolvendo a integração entre hardware e software. O sistema completo compreende o desenvolvimento da arquitetura do processador, a definição de uma linguagem de programação, o projeto de um compilador, a definição de um sistema operacional e um processo de comunicação em rede entre dois ou mais sistemas. Dentro deste contexto, ao término desta unidade curricular, o aluno deverá ter elaborado a especificação do projeto de um sistema computacional completo, tanto do ponto de vista do software como do hardware. Sendo assim, o objetivo geral dessa unidade curricular é capacitar o aluno a conceber e especificar, em termos sistêmicos, seus projetos de engenharia, tanto no nível de produtos como serviços e negócios. Específicos:  Oferecer ao aluno a fundamentação sobre sistemas e a ciência de sistemas;  Capacitar o aluno a realizar projetos de engenharia baseando-se em conceitos de gerenciamento de projetos;  Capacitar o aluno a conceber, especificar e desenvolver artefatos de engenharia a partir de uma visão integrada de sistemas;  Oferecer ao aluno uma visão geral dos principais padrões de Engenharia de Sistemas;  Capacitar o aluno a aplicar os conceitos de Engenharia de Sistemas no desenvolvimento de produtos, processos e serviços;  Capacitar o aluno a desenvolver apresentações orais e redação de textos. Ementa: Introdução e histórico da Engenharia de Sistemas. Fundamentos e tipos de sistemas. Modelos de ciclo de vida. Concepção de sistemas. Gerenciamento de sistemas, produtos e serviços. Aplicações da Engenharia de Sistemas. Equipes e indivíduos no contexto da Engenharia de sistemas. Conteúdo Programático: Perspectiva histórica e visão geral da Engenharia de Sistemas. Valor econômico da Engenharia de Sistemas. Desafios da Engenharia de Sistemas. Relacionamento da Engenharia de Sistemas com outras disciplinas. Corpo de conhecimento da Engenharia de Sistemas (SEBoK – Systems Engineering Body of Knowledge): estrutura e escopo. Sistemas: fundamentos e ciência dos sistemas. Utilização de modelos para representação de sistemas. Gerenciamento de Engenharia de Sistemas: planejamento, avaliação, gerenciamento de riscos, medição, gerenciamento de decisão. Padrões em Engenharia de Sistemas. Aplicações: engenharia de sistemas de produtos, engenharia de sistemas de serviços, engenharia de sistemas de empresas, sistemas de sistemas. Influência da Engenharia de Sistemas nos negócios, empresas, equipes e indivíduos. Metodologia de Ensino Utilizada: Esta unidade curricular será baseada em análise de estudos de casos e desenvolvimento de projetos. Os projetos serão realizados tanto em sala de aula como extra-classe, utilizando-se de ferramentas de modelagem e simulação de sistemas. Essa unidade curricular também levará o aluno a elaborar apresentações orais, construir estruturas de trabalhos técnicos e científicos, na forma de relatórios, além da redação de textos. Recursos Instrucionais Necessários: Quadro branco, projetor multimídia, computadores com software de modelagem e simulação de sistemas, e sistema de apoio à condução da unidade curricular (Moodle). Critérios de Avaliação: O sistema de avaliação será definido pelo docente responsável pela unidade curricular no início das atividades letivas devendo ser aprovado pela Comissão de Curso e divulgado aos alunos. O sistema adotado deve contemplar o processo de ensino e aprendizagem estabelecido neste Projeto Pedagógico, com o objetivo de favorecer o progresso do aluno ao longo do semestre. A promoção do aluno na unidade curricular obedecerá aos critérios estabelecidos pela Pró-Reitoria de Graduação, tal como discutido no Projeto Pedagógico do Curso. Bibliografia Básica: 1. Kossiakoff, A.; Sweet, W. N.; Seymour, S. And Biener, S. M. Systems Engineering Principles and Practice. Wiley Series in Systems Engineering and Management, 2011. 2. Blanchard, B. S. and Fabrychy, W. J. Systems Engineering and Analysis. Prentice Hall International series in Industrial & Systems Engineering, 5th Edition, 2010. 3. Weilkiens, T. Systems Engineering with SysML/UML: Modeling, Analysis, Design. The MK/OMG Press, 2008. Complementar: 1. INCOSE. 2012. Systems Engineering Handbook: A Guide for System Life Cycle Processes and Activities, version 3.2.2. San Diego, CA, USA: International Council on Systems Engineering (INCOSE), INCOSE-TP-2003-002-03.2.2. 2. Meadows, D. H. Thinking in Systems: A Primer. Chelsea Green Publishing Company. 2008. 3. Martin, J. N. Systems Engineering Guidebook: A Process for Developing Systems and Products. CRC Press, 1996. 4. Sommerville, I. Engenharia de Software. Editora Pearson, 8a edição. 2007. 5. Pressman, R. Software Engineering: a practitioner’s approach. McGraw-Hill, 6th edition, 2005. 6. Como Fazer Apresentações em Eventos Acadêmicos e Empresariais – Linguagem Verbal, Comunicação Corporal e Recursos Audivisuais. Maria Helena da Nobrega. Editora Atlas. ISBN: 8522456380, 2010. 7. Metodologia de Pesquisa para Ciência da Computação. Raul Sidnei Wazlawick. ISBN: 9788535235227, 2009.
package main import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" "github.com/deniskhan22bd/Golang/ProjectGolang/pkg/models" "github.com/deniskhan22bd/Golang/ProjectGolang/pkg/validator" "github.com/gorilla/mux" ) // Define an envelope type. type envelope map[string]interface{} func (app *application) GetToken(w http.ResponseWriter, r *http.Request) (string, error) { // Add the "Vary: Authorization" header to the response. This indicates to any // caches that the response may vary based on the value of the Authorization // header in the request. w.Header().Add("Vary", "Authorization") // Retrieve the value of the Authorization header from the request. This will // return the empty string "" if there is no such header found. authorizationHeader := r.Header.Get("Authorization") // If there is no Authorization header found, use the contextSetUser() helper // that we just made to add the AnonymousUser to the request context. Then we // call the next handler in the chain and return without executing any of the // code below. if authorizationHeader == "" { r = app.contextSetUser(r, models.AnonymousUser) app.invalidAuthenticationTokenResponse(w, r) return "", errors.New("Empty token") } // Otherwise, we expect the value of the Authorization header to be in the format // "Bearer <token>". We try to split this into its constituent parts, and if the // header isn't in the expected format we return a 401 Unauthorized response // using the invalidAuthenticationTokenResponse() helper (which we will create // in a moment). headerParts := strings.Split(authorizationHeader, " ") if len(headerParts) != 2 || headerParts[0] != "Bearer" { app.invalidAuthenticationTokenResponse(w, r) return "", errors.New("Invalid token format") } // Extract the actual authentication token from the header parts. token := headerParts[1] v := validator.New() // If the token isn't valid, use the invalidAuthenticationTokenResponse() // helper to send a response, rather than the failedValidationResponse() helper // that we'd normally use. if models.ValidateTokenPlaintext(v, token); !v.Valid() { app.invalidAuthenticationTokenResponse(w, r) return "", errors.New("Invalid token") } return token, nil } // readIDParam reads interpolated "id" from request URL and returns it and nil. If there is an error // it returns and 0 and an error. func (app *application) readIDParam(r *http.Request) (int, error) { vars := mux.Vars(r) param := vars["id"] id, err := strconv.Atoi(param) if err != nil || id < 1 { return 0, errors.New("invalid id parameter") } return id, nil } // writeJSON marshals data structure to encoded JSON response. It returns an error if there are // any issues, else error is nil. func (app *application) writeJSON(w http.ResponseWriter, status int, data envelope, headers http.Header) error { // Use the json.MarshalIndent() function so that whitespace is added to the encoded JSON. Use // no line prefix and tab indents for each element. js, err := json.MarshalIndent(data, "", "\t") if err != nil { return err } // Append a newline to make it easier to view in terminal applications. js = append(js, '\n') // At this point, we know that we won't encounter any more errors before writing the response, // so it's safe to add any headers that we want to include. We loop through the header map // and add each header to the http.ResponseWriter header map. Note that it's OK if the // provided header map is nil. Go doesn't through an error if you try to range over ( // or generally, read from) a nil map for key, value := range headers { w.Header()[key] = value } // Add the "Content-Type: application/json" header, then write the status code and JSON response. w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) if _, err := w.Write(js); err != nil { app.logger.PrintError(err, nil) return err } return nil } // readJSON decodes request Body into corresponding Go type. It triages for any potential errors // and returns corresponding appropriate errors. func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst interface{}) error { // Use http.MaxBytesReader() to limit the size of the request body to 1MB to prevent // any potential nefarious DoS attacks. maxBytes := 1_048_576 r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes)) // Initialize the json.Decoder, and call the DisallowUnknownFields() method on it // before decoding. So, if the JSON from the client includes any field which // cannot be mapped to the target destination, the decoder will return an error // instead of just ignoring the field. dec := json.NewDecoder(r.Body) dec.DisallowUnknownFields() // Decode the request body to the destination. err := dec.Decode(dst) if err != nil { // If there is an error during decoding, start the error triage... var syntaxError *json.SyntaxError var unmarshalTypeError *json.UnmarshalTypeError var invalidUnmarshalError *json.InvalidUnmarshalError switch { // Use the error.As() function to check whether the error has the type *json.SyntaxError. // If it does, then return a plain-english error message which includes the location // of the problem. case errors.As(err, &syntaxError): return fmt.Errorf("body contains badly-formed JSON at (charcter %d)", syntaxError.Offset) // In some circumstances Decode() may also return an io.ErrUnexpectedEOF error // for syntax error in the JSON. So, we check for this using errors.Is() and return // a generic error message. There is an open issue regarding this at // https://github.com/golang/go/issues/25956 case errors.Is(err, io.ErrUnexpectedEOF): return errors.New("body contains badly-formed JSON") // Likewise, catch any *json.UnmarshalTypeError errors. // These occur when the JSON value is the wrong type for the target destination. // If the error relates to a specific field, then we include that in our error message // to make it easier for the client to debug. case errors.As(err, &unmarshalTypeError): if unmarshalTypeError.Field != "" { return fmt.Errorf("body contains incorrect JSON type for field %q", unmarshalTypeError.Field) } return fmt.Errorf("body contains incorrect JSON type (at character %d)", unmarshalTypeError.Offset) // An io.EOF error will be returned by Decode() if the request body is empty. We check // for this with errors.Is() and return a plain-english error message instead. case errors.Is(err, io.EOF): return errors.New("body must not be empty") // If the JSON contains a field which cannot be mapped to the target destination // then Decode() will now return an error message in the format "json: unknown // field "<name>"". We check for this, extract the field name from the error, // and interpolate it into our custom error message. // Note, that there's an open issue at https://github.com/golang/go/issues/29035 // regarding turning this into a distinct error type in the future. case strings.HasPrefix(err.Error(), "json: unknown field "): fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ") return fmt.Errorf("body contains unknown key %s", fieldName) // If the request body exceeds 1MB in size then decode will now fail with the // error "http: request body too large". There is an open issue about turning // this into a distinct error type at https://github.com/golang/go/issues/30715. case err.Error() == "http: request body too large": return fmt.Errorf("body must not be larger than %d bytes", maxBytes) // A json.InvalidUnmarshalError error will be returned if we pass a non-nil // pointer to Decode(). We catch this and panic, rather than returning an error // to our handler. At the end of this chapter we'll talk about panicking // versus returning, and discuss why it's an appropriate thing to do in this specific // situation. case errors.As(err, &invalidUnmarshalError): panic(err) // For anything else, return the error message as-is. default: return err } } // Call Decode() again, using a pointer to an empty anonymous struct as the // destination. If the request body only contained a single JSON value then this will // return an io.EOF error. So if we get anything else, we know that there is // additional data in the request body, and we return our own custom error message. err = dec.Decode(&struct{}{}) if err != io.EOF { return errors.New("body must only contain a single JSON value") } return nil } func (app *application) readString(qs url.Values, key string, defaultValue string) string { // Extract the value for a given key from the query string. If no key exists this // will return the empty string "". s := qs.Get(key) // If no key exists (or the value is empty) then return the default value. if s == "" { return defaultValue } // Otherwise return the string. return s } // The readCSV() helper reads a string value from the query string and then splits it // into a slice on the comma character. If no matching key could be found, it returns // the provided default value. func (app *application) readCSV(qs url.Values, key string, defaultValue []string) []string { // Extract the value from the query string. csv := qs.Get(key) // If no key exists (or the value is empty) then return the default value. if csv == "" { return defaultValue } // Otherwise parse the value into a []string slice and return it. return strings.Split(csv, ",") } // The readInt() helper reads a string value from the query string and converts it to an // integer before returning. If no matching key could be found it returns the provided // default value. If the value couldn't be converted to an integer, then we record an // error message in the provided Validator instance. func (app *application) readInt(qs url.Values, key string, defaultValue int, v *validator.Validator) int { // Extract the value from the query string. s := qs.Get(key) // If no key exists (or the value is empty) then return the default value. if s == "" { return defaultValue } // Try to convert the value to an int. If this fails, add an error message to the // validator instance and return the default value. i, err := strconv.Atoi(s) if err != nil { v.AddError(key, "must be an integer value") return defaultValue } // Otherwise, return the converted integer value. return i }
# ▣ 입력설명 # 첫 번째 줄은 보석 종류의 개수와 가방에 담을 수 있는 무게의 한계값이 주어진다. 두 번째 줄부터 각 보석의 무게와 가치가 주어진다. # 가방의 저장무게는 1000kg을 넘지 않는다. 보석의 개수는 30개 이내이다. # # ▣ 출력설명 # 첫 번째 줄에 가방에 담을 수 있는 보석의 최대가치를 출력한다. # # ▣ 입력예제 1 # 4 11 # 5 12 # 3 8 # 6 14 # 4 8 # # ▣ 출력예제 1 # 28 if __name__ == "__main__": n, m = map(int, input().split()) dy = [0] * (m + 1) for i in range(n): w, v = map(int, input().split()) for j in range(w, m + 1): dy[j] = max(dy[j], dy[j - w] + v) # 기존값과 비교 print(dy[m])
/** * */ package com.ppx.terminal.common.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; import com.ppx.terminal.common.page.Page; /** * * @author mark * @date 2019年7月16日 */ public class ControllerReturn { private static final String CODE_TITLE = "code"; private static final String MSG_TITLE = "msg"; private static Map<String, Object> SUCCESS = new LinkedHashMap<String, Object>(2); static { SUCCESS.put(CODE_TITLE, 0); SUCCESS.put(MSG_TITLE, "SUCCESS"); } private static Map<String, Object> ERROR = new LinkedHashMap<String, Object>(2); static { ERROR.put(CODE_TITLE, 50000); ERROR.put(MSG_TITLE, "ERROR"); } public static Map<String, Object> of() { return SUCCESS; } public static Map<String, Object> error() { return ERROR; } public static Map<String, Object> exists(int result, String msg) { if (result == 0) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(2); returnMap.put(CODE_TITLE, "40000"); returnMap.put(MSG_TITLE, msg); return returnMap; } else { return SUCCESS; } } public static Map<String, Object> page(Page page, List<?> list) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(4); returnMap.putAll(SUCCESS); returnMap.put("page", page); returnMap.put("list", list); return returnMap; } public static Map<String, Object> page(Page page, List<Object> list, String key, Object value) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(5); returnMap.putAll(SUCCESS); returnMap.put("page", page); returnMap.put("list", list); returnMap.put(key, value); return returnMap; } // 业务自定义:40000~40099 public static Map<String, Object> of(int code, String msg) { if (code >= 40000 && code <= 40099) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(2); returnMap.put(CODE_TITLE, code); returnMap.put(MSG_TITLE, msg); return returnMap; } else { throw new RuntimeException("code must be from 40000-40099, code:" + code); } } // 业务自定义:50050~50099 public static Map<String, Object> error(int code, String msg) { if (code >= 50050 && code <= 50099) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(2); returnMap.put(CODE_TITLE, code); returnMap.put(MSG_TITLE, msg); return returnMap; } else { throw new RuntimeException("code must be from 50050-50099, code:" + code); } } public static Map<String, Object> of(Map<String, Object> map) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(); returnMap.putAll(SUCCESS); returnMap.putAll(map); return returnMap; } public static Map<String, Object> of(String key, Object value) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(3); returnMap.putAll(SUCCESS); returnMap.put(key, value); return returnMap; } public static Map<String, Object> of(String k1, Object v1, String k2, Object v2) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(4); returnMap.putAll(SUCCESS); returnMap.put(k1, v1); returnMap.put(k2, v2); return returnMap; } public static Map<String, Object> of(String k1, Object v1, String k2, Object v2, String k3, Object v3) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(5); returnMap.putAll(SUCCESS); returnMap.put(k1, v1); returnMap.put(k2, v2); returnMap.put(k3, v3); return returnMap; } public static Map<String, Object> of(String k1, Object v1, String k2, Object v2, String k3, Object v3, String k4, Object v4) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(6); returnMap.putAll(SUCCESS); returnMap.put(k1, v1); returnMap.put(k2, v2); returnMap.put(k3, v3); returnMap.put(k4, v4); return returnMap; } public static Map<String, Object> of(String k1, Object v1, String k2, Object v2, String k3, Object v3, String k4, Object v4, String k5, Object v5) { Map<String, Object> returnMap = new LinkedHashMap<String, Object>(8); returnMap.putAll(SUCCESS); returnMap.put(k1, v1); returnMap.put(k2, v2); returnMap.put(k3, v3); returnMap.put(k4, v4); returnMap.put(k5, v5); return returnMap; } /** * 返回错误(JSON格式) * * @param response * @param errorCode * @param errorInfo */ public static boolean errorJson(HttpServletResponse response, int code, String msg) { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); Map<String, Object> map = error(code, msg); try (PrintWriter printWriter = response.getWriter()) { String returnJson = new ObjectMapper().writeValueAsString(map); printWriter.write(returnJson); } catch (IOException e) { e.printStackTrace(); } return false; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Queue | Front | Rear | isEmpty</title> <script> let queue = []; let currentSize = queue.length; let maxSize = 5; /* Enqueue is a function to add element to the front/start of Array @param newVal */ // function enqueue(newVal) { // if (currentSize >= maxSize) { // alert("Queue is already full"); // } else { // queue[currentSize] = newVal; // currentSize++; // } // } function enqueueWithBtn() { let newVal = parseInt(document.getElementById("newVal").value); if (currentSize >= maxSize) { alert("Queue is already full"); } else { queue[currentSize] = newVal; currentSize++; document.getElementById("newVal").value = ""; } } /* display is a function to display all the elements inside queue */ function display() { console.warn(queue); } /* dequeue is a function to Remove item from Front/Start Of Array */ function dequeue() { for (let i = 0; i < queue.length - 1; i++) { queue[i] = queue[i + 1]; } pop(); // console.warn(queue); } /* pop is a function to Remove item from from End/Rear of the Array */ function pop() { if (!isEmpty()) { currentSize--; queue.length = currentSize; } else { alert("Queue is already empty"); } } /* front is a function which will return front element of an array */ function front() { let front; if (!isEmpty()) { front = queue[0]; console.warn(front, "First Element"); return front; } else { alert("Queue is already empty"); } } /* rear is a function which will return last element of an array */ function rear() { let last; if (!isEmpty()) { last = queue[currentSize - 1]; console.warn(last, "Last Element"); return last; } else { alert("Queue is already empty"); } } /* isEmpty is a function which will tell whether a given is empty or not */ function isEmpty() { if (currentSize <= 0) { return true; } return false; } // enqueue(10); // enqueue(20); // enqueue(30); // enqueue(40); // enqueue(50); // display(); // console.warn(front(), "First Element"); // console.warn(rear(), "Last Element"); // dequeue(); // display(); // console.warn(front(), "First Element"); // console.warn(rear(), "Last Element"); // display(); </script> </head> <body> <h1>Front, Rear & isEmpty in Queue</h1> <h1>Queue with Input in Javascript</h1> <input type="text" id="newVal" /> <button onclick="enqueueWithBtn()">Add Element</button> <button onclick="dequeue()">Remove Element</button> <button onclick="display()">Display Element</button> <button onclick="front()">Display Front Element</button> <button onclick="rear()">Display Rear Element</button> </body> </html>
#!/usr/bin/env node /* NOTICE This (software/technical data) was produced for the U. S. Government under Contract Number HHSM-500-2012-00008I, and is subject to Federal Acquisition Regulation Clause 52.227-14, Rights in Data-General. No other use other than that granted to the U. S. Government, or to those acting on behalf of the U. S. Government under that Clause is authorized without the express written permission of The MITRE Corporation. For further information, please contact The MITRE Corporation, Contracts Management Office, 7515 Colshire Drive, McLean, VA 22102-7539, (703) 983-6000. ©2018 The MITRE Corporation. */ /** * Module dependencies. */ // const debug = require('debug')('init:server'); const https = require('https'); // const http = require('http'); const fs = require('fs'); const nconf = require('nconf'); let io = require('socket.io'); const log4js = require('log4js'); const winston = require('winston'); const logger = require('../utils/logger') const error = winston.loggers.get('error'); const info = winston.loggers.get('info'); const debug = winston.loggers.get('debug'); // Get the name of the config file from the command line (optional) nconf.argv().env(); const cfile = 'configs/acequill.json'; // Validate the incoming JSON config file try { const content = fs.readFileSync(cfile, 'utf8'); const myjson = JSON.parse(content); if (myjson) { info.info('Valid JSON config file'); } } catch (ex) { info.error(`Error in ${cfile}`); info.error('Exiting...'); info.error(ex); process.exit(1); } nconf.file({ file: cfile, }); // log4js.loadAppender('file'); log4js.configure({ appenders: { admin: { type: 'dateFile', category: 'admin', filename: 'logs/admin.log', pattern: '-yyyy-MM-dd', alwaysIncludePattern: false, maxLogSize: 20480, backups: 10, }, caller: { type: 'dateFile', category: 'caller', filename: 'logs/caller.log', pattern: '-yyyy-MM-dd', alwaysIncludePattern: false, maxLogSize: 20480, backups: 10, }, asterisk: { type: 'dateFile', category: 'asterisk', filename: 'logs/asterisk.log', pattern: '-yyyy-MM-dd', alwaysIncludePattern: false, maxLogSize: 20480, backups: 10, } }, categories: { default: { appenders: [ 'admin' ], level: 'info' }, } }); /** * Get port from environment and store in Express. */ const decode = require('../utils/decode'); const app = require('../app'); const port = decode(nconf.get('port')); app.set('port', port); /** * Create HTTP server. * */ info.info('Listening for HTTPS connections'); const credentials = { key: fs.readFileSync(decode(nconf.get('ssl:key'))), cert: fs.readFileSync(decode(nconf.get('ssl:cert'))), }; const server = https.createServer(credentials, app); /* console.log("Listening for HTTP connections"); var server = http.createServer(app); */ io = require('socket.io')(server); require('../sockets/admin')(io.of('/admin'), nconf); require('../asterisk'); if (decode(nconf.get('sttService')) === 'enabled') { process.env.GOOGLE_APPLICATION_CREDENTIALS = `${process.cwd()}/configs/google/google.json`; debug.debug(process.env.GOOGLE_APPLICATION_CREDENTIALS); } else { info.info(`STT Service is currently DISABLED. This allows the ACE Quill web server to be run without including the STT node_modules.`); } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': info.error(`${bind} requires elevated privileges`); process.exit(1); break; case 'EADDRINUSE': info.error(`${bind} is already in use`); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ /** * Listen on provided port, on all network interfaces. */ function onListening() { const addr = server.address(); const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`; info.info(`Listening on port: ${bind}`); } /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening);
<?php /* * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com> * * 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. */ namespace JMS\DiExtraBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Alias; use JMS\DiExtraBundle\Exception\RuntimeException; use JMS\DiExtraBundle\Config\ServiceFilesResource; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\DependencyInjection\DefinitionDecorator; use Symfony\Component\DependencyInjection\Definition; use JMS\DiExtraBundle\Finder\PatternFinder; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class AnnotationConfigurationPass implements CompilerPassInterface { private $kernel; private $finder; public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; $this->finder = new PatternFinder('JMS\DiExtraBundle\Annotation'); } public function process(ContainerBuilder $container) { $reader = $container->get('annotation_reader'); $factory = $container->get('jms_di_extra.metadata.metadata_factory'); $converter = $container->get('jms_di_extra.metadata.converter'); $directories = $this->getScanDirectories($container); if (!$directories) { $container->getCompiler()->addLogMessage('No directories configured for AnnotationConfigurationPass.'); return; } $files = $this->finder->findFiles($directories); $container->addResource(new ServiceFilesResource($files, $directories)); foreach ($files as $file) { $container->addResource(new FileResource($file)); require_once $file; $className = $this->getClassName($file); if (null === $metadata = $factory->getMetadataForClass($className)) { continue; } if (null === $metadata->getOutsideClassMetadata()->id) { continue; } foreach ($converter->convert($metadata) as $id => $definition) { $container->setDefinition($id, $definition); } } } private function getScanDirectories(ContainerBuilder $c) { $bundles = $this->kernel->getBundles(); $scanBundles = $c->getParameter('jms_di_extra.bundles'); $scanAllBundles = $c->getParameter('jms_di_extra.all_bundles'); $directories = $c->getParameter('jms_di_extra.directories'); foreach ($bundles as $name => $bundle) { if (!$scanAllBundles && !in_array($name, $scanBundles, true)) { continue; } if ('JMSDiExtraBundle' === $name) { continue; } $directories[] = $bundle->getPath(); } return $directories; } /** * Only supports one namespaced class per file * * @throws \RuntimeException if the class name cannot be extracted * @param string $filename * @return string the fully qualified class name */ private function getClassName($filename) { $src = file_get_contents($filename); if (!preg_match('/\bnamespace\s+([^;]+);/s', $src, $match)) { throw new RuntimeException(sprintf('Namespace could not be determined for file "%s".', $filename)); } $namespace = $match[1]; if (!preg_match('/\bclass\s+([^\s]+)\s+(?:extends|implements|{)/s', $src, $match)) { throw new RuntimeException(sprintf('Could not extract class name from file "%s".', $filename)); } return $namespace.'\\'.$match[1]; } }
package jehc.zxmodules.dao.impl; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import jehc.xtmodules.xtcore.base.impl.BaseDaoImpl; import jehc.zxmodules.dao.ZxJudgeApplyDao; import jehc.zxmodules.model.ZxJudgeApply; /** * 供应商验厂申请单 * 2017-09-25 09:27:09 g */ @Repository("zxJudgeApplyDao") public class ZxJudgeApplyDaoImpl extends BaseDaoImpl implements ZxJudgeApplyDao{ /** * 分页 * @param condition * @return */ @SuppressWarnings("unchecked") public List<ZxJudgeApply> getZxJudgeApplyListByCondition(Map<String,Object> condition){ return (List<ZxJudgeApply>)this.getList("getZxJudgeApplyListByCondition",condition); } /** * 查询对象 * @param id * @return */ public ZxJudgeApply getZxJudgeApplyById(String id){ return (ZxJudgeApply)this.get("getZxJudgeApplyById", id); } /** * 添加 * @param zx_judge_apply * @return */ public int addZxJudgeApply(ZxJudgeApply zxJudgeApply){ return this.add("addZxJudgeApply", zxJudgeApply); } /** * 修改 * @param zx_judge_apply * @return */ public int updateZxJudgeApply(ZxJudgeApply zxJudgeApply){ return this.update("updateZxJudgeApply", zxJudgeApply); } /** * 修改(根据动态条件) * @param zx_judge_apply * @return */ public int updateZxJudgeApplyBySelective(ZxJudgeApply zxJudgeApply){ return this.update("updateZxJudgeApplyBySelective", zxJudgeApply); } /** * 删除 * @param condition * @return */ public int delZxJudgeApply(Map<String,Object> condition){ return this.del("delZxJudgeApply", condition); } /** * 批量添加 * @param zx_judge_applyList * @return */ public int addBatchZxJudgeApply(List<ZxJudgeApply> zxJudgeApplyList){ return this.add("addBatchZxJudgeApply", zxJudgeApplyList); } /** * 批量修改 * @param zx_judge_applyList * @return */ public int updateBatchZxJudgeApply(List<ZxJudgeApply> zxJudgeApplyList){ return this.update("updateBatchZxJudgeApply", zxJudgeApplyList); } /** * 批量修改(根据动态条件) * @param zx_judge_applyList * @return */ public int updateBatchZxJudgeApplyBySelective(List<ZxJudgeApply> zxJudgeApplyList){ return this.update("updateBatchZxJudgeApplyBySelective", zxJudgeApplyList); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\categories; use App\Models\cities; use App\Models\lawyers; use App\Models\lawyerreviews; use App\Models\adminnotifications; use App\Models\blogs; use App\Models\nominations; use App\Models\sitesettings; use App\Models\unapprovedlawyers; use Auth; use DB; use App\Models\User; //use Mail; use Validator; use Illuminate\Validation\Rule; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Mail; class AdminController extends Controller { public function __construct() { $this->middleware('auth'); } public function slugify($text) { $text = preg_replace('~[^\pL\d]+~u', '-', $text); $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); $text = preg_replace('~[^-\w]+~', '', $text); $text = trim($text, '-'); $text = preg_replace('~-+~', '-', $text); $text = strtolower($text); if (empty($text)) { return 'n-a'; } return $text; } public function adminnotification($url , $notification , $type) { $notifye = new adminnotifications; $notifye->url = $url; $notifye->notification = $notification; $notifye->readstatus = 1; $notifye->type = $type; $notifye->save(); } public function addcategory() { return view('admin.categories.add'); } public function allcategory() { $data = categories::where('status', 1)->get(); return view('admin.categories.all')->with(array('data'=>$data)); } public function createcategory(Request $request) { $thumbnail = $request->file('thumbnailimage'); $thumbnailimage = rand().'.'.$thumbnail->getClientOriginalExtension(); $thumbnail->move(public_path('images'), $thumbnailimage); $tittle = $request->tittle; $shortdescription = $request->description; $category = new categories; $category->url = $this->slugify($request->tittle); $category->tittle = $tittle; $category->description = $shortdescription; $category->thumbnail = $thumbnailimage; $category->mettatittle = $tittle; $category->metadescription = $shortdescription; $category->og_image = $thumbnailimage; $category->status = 1; $category->save(); return redirect()->back()->with('message', 'Category Successfully Inserted'); } public function editcategory($id) { $data = DB::table('categories')->where('id' , $id)->get()->first(); return view('admin.categories.edit')->with(array('data'=>$data)); } public function updatecategory(Request $request) { $tittle = $request->tittle; $description = $request->description; $id = $request->id; $data = array('mettatittle'=>$tittle,'metadescription'=>$description,'tittle'=>$tittle,'description'=>$description); categories::where('id', $id)->update($data); return redirect()->back()->with('message', 'Category Content Updated Successfully'); } public function updatecategorythumbnail(Request $request) { $thumbnail = $request->file('thumbnailimage'); $thumbnailimage = rand().'.'.$thumbnail->getClientOriginalExtension(); $thumbnail->move(public_path('images'), $thumbnailimage); $id = $request->id; $data = array('thumbnail'=>$thumbnailimage,'og_image'=>$thumbnailimage); categories::where('id', $id)->update($data); return redirect()->back()->with('message', 'Thumbnail Image Updated Successfully'); } public function deletecategory($id) { $data = DB::table('lawyers')->where('categoryid' , $id)->get(); if (!empty($data)) { foreach ($data as $r ) { $changestatuslawyers = array('status'=>0); lawyers::where('id', $r->id)->update($changestatuslawyers); } } $data2 = DB::table('cities')->where('serviceid' , $id)->get(); if (!empty($data2)) { foreach ($data2 as $r ) { $changestatuscities = array('status'=>0); cities::where('id', $r->id)->update($changestatuscities); } } $changestatuscategory = array('status'=>0); categories::where('id', $id)->update($changestatuscategory); return redirect()->back()->with('message', 'Delete Category Successfully'); } public function addcity() { return view('admin.cities.add'); } public function allcities() { $data = cities::where('status', 1)->get(); return view('admin.cities.all')->with(array('data'=>$data)); } public function createcity(Request $request) { $data = DB::table('categories')->where('id' , $request->serviceid)->get()->first(); // $thumbnail = $request->file('thumbnailimage'); // $thumbnailimage = rand().'.'.$thumbnail->getClientOriginalExtension(); // $thumbnail->move(public_path('images'), $thumbnailimage); $tittle = $request->tittle; $shortdescription = $request->description; $category = new cities; $category->url = $this->slugify($request->tittle); $category->tittle = $tittle; $category->serviceid = $request->serviceid; $category->description = $shortdescription; // $category->thumbnail = $thumbnailimage; $category->mettatittle = "Best ".$data->tittle." Lawyers In " .$tittle; $category->metadescription = $shortdescription; // $category->og_image = $thumbnailimage; $category->status = 1; $category->save(); return redirect()->back()->with('message', 'City Successfully Inserted'); } public function editcity($id) { $data = DB::table('cities')->where('id' , $id)->get()->first(); return view('admin.cities.edit')->with(array('data'=>$data)); } public function updatecity(Request $request) { $tittle = $request->tittle; $description = $request->description; $id = $request->id; $data = array('mettatittle'=>$tittle,'metadescription'=>$description,'tittle'=>$tittle,'description'=>$description); cities::where('id', $id)->update($data); return redirect()->back()->with('message', 'Category Content Updated Successfully'); } public function updatecitythumbnail(Request $request) { $thumbnail = $request->file('thumbnailimage'); $thumbnailimage = rand().'.'.$thumbnail->getClientOriginalExtension(); $thumbnail->move(public_path('images'), $thumbnailimage); $id = $request->id; $data = array('thumbnail'=>$thumbnailimage,'og_image'=>$thumbnailimage); cities::where('id', $id)->update($data); return redirect()->back()->with('message', 'Thumbnail Image Updated Successfully'); } public function deletecity($id) { $data = DB::table('lawyers')->where('citiyid' , $id)->get(); $data2 = DB::table('lawyers')->where('citiyid' , $id)->get(); if (empty($data)) { $data = array('status'=>0); cities::where('id', $id)->update($data); return redirect()->back()->with('message', 'Delete City Successfully'); }else{ foreach ($data2 as $r) { $data2 = array('status'=>0); lawyers::where('id', $r->id)->update($data2); } $data3 = array('status'=>0); cities::where('id', $id)->update($data3); return redirect()->back()->with('message', 'Delete City Successfully'); } } public function addlawyer() { return view('admin.lawyers.add'); } public function alllawyers() { $data = lawyers::where('status', 1)->orderby('id' , 'DESC')->get(); return view('admin.lawyers.all')->with(array('data'=>$data)); } function uniqueUsername($name){ $url=$this->slugify($name); $countNames=lawyers::where('name',$name)->count(); //$uniqueurl=''; // $index=1; $url=$url.'-'.++$countNames; return $url; } public function createlawyer(Request $request) { if(!empty($request->file('image'))){ $image = $request->file('image'); $lawyerimage = rand().'.'.$image->getClientOriginalExtension(); $image->move(public_path('images'), $lawyerimage); }else{ $lawyerimage = 'imagplaceholder.jpg'; } $url=$this->uniqueUsername($request->name); $lawyer = new lawyers; $lawyer->name = $request->name; $lawyer->url = $url; $lawyer->categoryid = $request->serviceid; $lawyer->citiyid = $request->cityid; $lawyer->bio = $request->bio; $lawyer->image = $lawyerimage; $lawyer->officeaddress = $request->officeaddress; $lawyer->phonenumber = $request->phoneno; $lawyer->emailaddress = $request->email; $lawyer->website = $request->websitelink; $lawyer->facebook = $request->facebook; $lawyer->twitter = $request->twitter; $lawyer->fax = $request->fax; $lawyer->featured = 0; $lawyer->linkdlin = $request->linkdlin; $lawyer->r_experience = $request->ratting_experience; $lawyer->r_personal = $request->ratting_assesments; $lawyer->r_online_reviews = $request->ratting_reviews; $lawyer->r_online_profiles = $request->ratting_profiles; $lawyer->education = $request->education; $lawyer->tagline = $request->tagline; if($request->featuredortop == 1) { $lawyer->featured = 1; }else{ $lawyer->toplawyers = 1; } $lawyer->field1 = $request->field1; $lawyer->field2 = $request->field2; $lawyer->field3 = $request->field3; $lawyer->field4 = $request->field4; $lawyer->link1 = $request->link1; $lawyer->link2 = $request->link2; $lawyer->link3 = $request->link3; $lawyer->link4 = $request->link4; $lawyer->status = 1; $lawyer->mettatittle = $request->name; $lawyer->metadescription = $request->bio; $lawyer->og_image = $lawyerimage; $lawyer->save(); return redirect()->back()->with('message', 'Lawyer Successfully Inserted'); } public function editlawyer($id,$unapproved=null) { if($unapproved=='true'){ $data =unapprovedlawyers::where('id',$id)->get()->first(); if($data->lawyerApprovedid==null) $data->lawyerApprovedid=-1; else $original_data=lawyers::where('id',$data->lawyerApprovedid)->first(); } else $data = DB::table('lawyers')->where('id' , $id)->get()->first(); return view('admin.lawyers.edit')->with(array('data'=>$data,'od'=>isset($original_data)?$original_data:'')); // dd($data); } public function updatelawyer(Request $request) { $name = $request->name; $bio = $request->bio; $officeaddress = $request->officeaddress; $phonenumber = $request->phoneno; $emailaddress = $request->email; $website = $request->websitelink; $facebook = $request->facebook; $twitter = $request->twitter; $fax = $request->fax; $linkdlin = $request->linkdlin; $r_experience = $request->ratting_experience; $r_personal = $request->ratting_assesments; $r_online_reviews = $request->ratting_reviews; $r_online_profiles = $request->ratting_profiles; $tagline = $request->tagline; $education = $request->education; $serviceid = $request->serviceid; $cityid = $request->cityid; $field1 = $request->field1; $field2 = $request->field2; $field3 = $request->field3; $field4 = $request->field5; $link1 = $request->link1; $link2 = $request->link2; $link3 = $request->link3; $link4 = $request->link4; $id = $request->id; $data = array('field1'=>$field1,'approve_profile' => '1','email_verified' =>'true','status' => 1,'field2'=>$field2,'field3'=>$field3,'field4'=>$field4,'link1'=>$link1,'link2'=>$link2,'link3'=>$link3,'link4'=>$link4,'mettatittle'=>$name,'metadescription'=>$bio,'categoryid'=>$serviceid,'citiyid'=>$cityid,'name'=>$name,'bio'=>$bio,'officeaddress'=>$officeaddress,'phonenumber'=>$phonenumber,'emailaddress'=>$emailaddress,'website'=>$website,'facebook'=>$facebook,'twitter'=>$twitter,'fax'=>$fax,'linkdlin'=>$linkdlin,'r_experience'=>$r_experience,'r_personal'=>$r_personal,'r_online_reviews'=>$r_online_reviews,'r_online_profiles'=>$r_online_profiles,'education'=>$education,'tagline'=>$tagline); lawyers::where('id', $id)->update($data); unapprovedlawyers::where('lawyerApprovedid', $id)->update($data); return redirect()->back()->with('message', 'Lawyer Data Updated Successfully'); } public function updatelawyerimage(Request $request) { $thumbnail = ''; if($request->has('image')) { $thumbnail = $request->file('image'); $thumbnailimage = rand().'.'.$thumbnail->getClientOriginalExtension(); $thumbnail->move(public_path('images'), $thumbnailimage); $id = $request->id; $data = array('image'=>$thumbnailimage,'og_image'=>$thumbnailimage); lawyers::where('id', $id)->update($data); } return redirect()->back()->with('message', 'Thumbnail Image Updated Successfully'); } public function deletelawyer($id) { $data = array('status'=>0); lawyers::where('id', $id)->update($data); return redirect()->back()->with('message', 'Delete Lawyer Successfully'); } public function allreviews() { $data = lawyerreviews::all(); return view('admin.reviews.index')->with(array('data'=>$data)); } public function editreview($id) { $reviews = DB::table('lawyerreviews')->where('id', $id)->first(); $name = $reviews->name; $email = $reviews->email; $review = $reviews->review; $rattings = $reviews->rattings; $status = $reviews->status; $lawyers_id = $reviews->lawyers_id; $id = $reviews->id; return response()->json(['name' => $name,'email' => $email,'review' => $review,'rattings' => $rattings,'status' => $status,'lawyers_id' => $lawyers_id,'id' => $id]); } public function updatereview(Request $request) { $lawyerid = $request->lawyerid; $rattings = $request->rattings; $status = $request->status; $review = $request->review; $name = $request->name; $email = $request->email; $id = $request->id; $data = array('name'=>$name,'email'=>$email,'review'=>$review,'rattings'=>$rattings,'status'=>$status,'lawyers_id'=>$lawyerid); lawyerreviews::where('id', $id)->update($data); return redirect()->back()->with('message', 'Review Updated Successfully'); } public function deletereview($id) { DB::table('lawyerreviews')->delete($id); return redirect()->back()->with('message', 'Delete Review Successfully'); } public function addblog() { return view('admin.blogs.add'); } public function allblogs() { $data = blogs::all(); return view('admin.blogs.all')->with(array('data'=>$data)); } public function createblog(Request $request) { $url = $this->slugify($request->tittle); $image = $request->file('image'); $blogimage = rand() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('images'), $blogimage); $saveblog = new blogs; $saveblog->image = $blogimage; $saveblog->url = $url; $saveblog->status = 1; $saveblog->tittle = $request->tittle; $saveblog->blogdate = $request->blogdate; $saveblog->description = $request->blog; $saveblog->shortdescription = $request->blogshortdescription; $saveblog->mettatittle = $request->tittle; $saveblog->metadescription = $request->blogshortdescription; $saveblog->og_image = $blogimage; $saveblog->save(); return redirect()->back()->with('message', 'Blog Successfully Inserted'); } public function updateblog(Request $request) { $url = $this->slugify($request->tittle); $tittle = $request->tittle; $blogdate = $request->blogdate; $blog = $request->blog; $id = $request->id; $blogshortdescription = $request->blogshortdescription; $data = array('mettatittle'=>$tittle,'metadescription'=>$blogshortdescription,'shortdescription'=>$blogshortdescription,'url'=>$url,"tittle"=>$tittle,"blogdate"=>$blogdate,"description"=>$blog); blogs::where('id', $id)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updateblogimage(Request $request) { $id = $request->id; $image = $request->file('image'); $blogimage = rand() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('images'), $blogimage); $data = array('image'=>$blogimage,'og_image'=>$blogimage); blogs::where('id', $id)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function editblog($id) { $data = DB::table('blogs')->where('id' , $id)->get()->first(); return view('admin.blogs.edit')->with(array('data'=>$data)); } public function deleteblog($id) { DB::table('blogs')->delete($id); return redirect()->back()->with('message', 'Delete Blog Successfully'); } public function getcities($id) { $data = DB::table('cities')->where('status' , 1)->where('serviceid' , $id)->get(); foreach ($data as $r) { echo "<option value='".$r->id."'>".$r->tittle."</option>"; } } public function changetofeatured($second , $id) { $data = DB::table('lawyers')->where('id' , $second)->get()->first(); $checktoplawyers = $data->toplawyers; if($checktoplawyers == 0){ if($id == 1) { $data = array('featured'=>0); }else{ $data = array('featured'=>1); } lawyers::where('id', $second)->update($data); }else{ echo "error"; } } public function toplawyers($second , $id) { $data = DB::table('lawyers')->where('id' , $second)->get()->first(); $checktoplawyers = $data->featured; if($checktoplawyers == 0){ if($id == 1) { $data = array('toplawyers'=>0); }else{ $data = array('toplawyers'=>1); } lawyers::where('id', $second)->update($data); }else{ echo "error"; } } public function nominations() { $data = DB::table('nominations')->where('status' , 0)->get(); return view('admin.nominations.all')->with(array('data'=>$data)); } public function approvednomination() { $data = DB::table('nominations')->where('status' , 1)->get(); return view('admin.nominations.all')->with(array('data'=>$data)); } public function editnomination($id) { $data = DB::table('nominations')->where('id' , $id)->get()->first(); return view('admin.nominations.edit')->with(array('data'=>$data)); } public function changenominationstatus($one , $two) { if($two == 1) { $data = array('status'=>0); }else{ $data = array('status'=>1); } nominations::where('id', $one)->update($data); } public function updatenominationimage(Request $request) { $id = $request->id; $image = $request->file('image'); $blogimage = rand() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('images'), $blogimage); $data = array('image'=>$blogimage); nominations::where('id', $id)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updatenomination(Request $request) { $id = $request->id; $r_experience = $request->ratting_experience; $r_personal = $request->ratting_assesments; $r_online_reviews = $request->ratting_reviews; $r_online_profiles = $request->ratting_profiles; $data = array('r_experience'=>$r_experience,'r_personal'=>$r_personal,'r_online_reviews'=>$r_online_reviews,'r_online_profiles'=>$r_online_profiles,'name'=>$request->name , 'bio'=>$request->bio ,'phonenumber'=>$request->phonenumber ,'emailaddress'=>$request->emailaddress ,'website'=>$request->website ,'votes'=>$request->votes); nominations::where('id', $id)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function deletenomination($id) { DB::table('nominations')->delete($id); return redirect()->back()->with('message', 'Delete Nomination Successfully'); } public function sitesettings() { $data = DB::table('sitesettings')->get()->first(); return view('admin.settings.index')->with(array('data'=>$data)); } public function updatewebsitetittle(Request $request) { $id = 1; $data = array('websitetittle'=>$request->websitetittle); sitesettings::where('id', $id)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updatecontactdetails(Request $request) { $phonenumber = $request->phonenumber; $email = $request->email; $address = $request->address; $latitude = $request->latitude; $longitue = $request->longitue; $data = array('address'=>$address,"phoneno"=>$phonenumber,"email"=>$email,"longitue"=>$longitue,"latitude"=>$latitude); sitesettings::where('id', 1)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updatesocialmedialinks(Request $request) { $facebook = $request->facebook; $twitter = $request->twitter; $instagram = $request->instagram; $linkdlin = $request->linkdlin; $data = array('facebook'=>$facebook,"twitter"=>$twitter,"instagram"=>$instagram,"linkdlin"=>$linkdlin); sitesettings::where('id', 1)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updatefootertext(Request $request) { $english = $request->english; $data = array('footertext'=>$english); sitesettings::where('id', 1)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updatewebsitelogo(Request $request) { $validatedData = $request->validate([ 'image' => "dimensions:max_width=165,max_height=45|required", ]); $thumbnail = $request->file('image'); $thumbnailimage = rand().'.'.$thumbnail->getClientOriginalExtension(); $thumbnail->move(public_path('images'), $thumbnailimage); $data = array('logo'=>$thumbnailimage); sitesettings::where('id', 1)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updateenable(Request $request) { $data = array('logoenable'=>$request->enabale); sitesettings::where('id', 1)->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function contactmessage() { return view('admin.requests.contactrequests'); } public function viewcontactrequests() { $data = DB::table('contacts')->get()->first(); return view('admin.requests.viewcontactrequest')->with(array('data'=>$data)); } public function profile() { return view('admin.profile.index'); } public function updateprofile(Request $request) { $name = $request->name; $email = $request->email; $country = $request->country; $phone = $request->phone; $id = Auth::user()->id; $data = array('name'=>$name,"email"=>$email,"country"=>$country,"phonenumber"=>$phone); user::where('id', $id) ->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } public function updatepassword(Request $request) { $password = $request->password; $password = Hash::make($request->password); $id = Auth::user()->id; $data = array('password'=>$password); user::where('id', $id) ->update($data); return redirect()->back()->with('message', 'Updated Successfully'); } function requestLawyers(){ $data = unapprovedlawyers::where('registeredBy','lawyer')->whereNull('lawyerApprovedid')->orderby('id' , 'DESC')->get(); return view('admin.lawyers.all')->with(array('data'=>$data)); // dd($data); } function editrequestLawyers(){ $data = unapprovedlawyers::where('registeredBy','lawyer')->whereNotNull('lawyerApprovedid')->orderby('id' , 'DESC')->get(); return view('admin.lawyers.all')->with(array('data'=>$data)); // dd($data); } function approveLawyers($id,$val){ $request=unapprovedlawyers::where('id',$id)->first(); //dd($request); if($val=='0'){ unapprovedlawyers::where('id',$id)->update(['status'=>$val,'registeredBy'=>'lawyer']); lawyers::where('id',$request->lawyerApprovedid)->update(['status'=>$val,'registeredBy'=>'lawyer']); } if($val=='1'){ $url=$this->uniqueUsername($request->name); // $request=unapprovedlawyers::where('id',$id)->first(); unapprovedlawyers::where('id',$id)->update(['status'=>$val,'registeredBy'=>'admin']); $lawyer = lawyers::find($request->lawyerApprovedid) ?? new lawyers; $lawyer->name = $request->name ?? ''; $lawyer->url = $url; $lawyer->categoryid = $request->categoryid; $lawyer->citiyid = $request->citiyid; $lawyer->bio = $request->bio ?? ''; $lawyer->image = $request->image ?? ''; $lawyer->officeaddress = $request->officeaddress ?? ''; $lawyer->phonenumber = $request->phonenumber ?? ''; $lawyer->emailaddress = $request->emailaddress ?? ''; $lawyer->website = $request->website ?? ''; $lawyer->facebook = $request->facebook ?? ''; $lawyer->twitter = $request->twitter ?? ''; $lawyer->fax = $request->fax ?? ''; $lawyer->featured = 0 ?? ''; $lawyer->linkdlin = $request->linkdlin ?? ''; $lawyer->r_experience = $request->r_experience ?? ''; $lawyer->r_personal = $request->r_personal ?? ''; $lawyer->r_online_reviews = $request->r_online_reviews ?? ''; $lawyer->r_online_profiles = $request->r_online_profiles ?? ''; $lawyer->education = $request->education ?? ''; $lawyer->tagline = $request->tagline ?? ''; // if($request->featuredortop == 1) // { // $lawyer->featured = 1; // }else{ $lawyer->toplawyers = 1; // } $lawyer->field1 = $request->field1 ?? ''; $lawyer->field2 = $request->field2 ?? ''; $lawyer->field3 = $request->field3 ?? ''; $lawyer->field4 = $request->field4 ?? ''; $lawyer->link1 = $request->link1 ?? ''; $lawyer->link2 = $request->link2 ?? ''; $lawyer->link3 = $request->link3 ?? ''; $lawyer->link4 = $request->link4 ?? ''; $lawyer->status = 1; $lawyer->password=$request->password; $lawyer->mettatittle = $request->mettatittle ?? ''; $lawyer->metadescription = $request->metadescription ?? ''; $lawyer->og_image = $request->og_image ?? ''; $lawyer->registeredBy='admin'; $lawyer->updated_at=date('d-m-Y H:i:s'); // AdminController::createOrUpdate(array('id'=>$request->lawyerApprovedid ?? ''),$lawyer); $lawyer->save(); //return redirect()->back()->with('message', 'Lawyer Successfully Inserted'); // ]); if($request->lawyerApprovedid==''){ $redirects=$request->lawyerApprovedid; $ids=lawyers::latest('id')->first()->id; unapprovedlawyers::where('id',$id)->update(['lawyerApprovedid'=>$ids]); } else unapprovedlawyers::where('id',$id)->update(['lawyerApprovedid'=>$request->lawyerApprovedid]); } // return redirect('admin/editlawyer/'. unapprovedlawyers::where('id',$id)->pluck('lawyerApprovedid')->first()); return redirect()->back(); } //----------------------------------------------------emails------------------------------- public function emails($email=null){ $emails=lawyers::get(['emailaddress']); if($email!=null){ if (file_exists(resource_path( 'views/admin/savedemails/'.$email.'.html'))) { $fp= file_get_contents( resource_path( 'views/admin/savedemails/'.$email.'.html' ), 'r' ); $filename=$email; return view('admin.emails.emails',compact('fp','filename','emails')); } else return redirect('admin/emails'); } else //$data=['name'=>'haris','data'=>'asdasd']; // $user['to']='haris1192317043@gmail.com'; // Mail::send('admin.emails.emails',$data,function($message) use ($user){ // $message->to($user['to']); // $message->subject('hello'); // }); return view('admin.emails.emails',compact('emails')); } public function save_email_templates(Request $r){ // dd($r->email); if (file_exists(resource_path( 'views/admin/savedemails/'.$r->oldfilename.'.html'))) { rename(resource_path( 'views/admin/savedemails/'.$r->oldfilename.'.html'), resource_path( 'views/admin/savedemails/'.$this->slugify($r->filename).'.html' )); $fp= fopen( resource_path( 'views/admin/savedemails/'.$r->filename.'.html' ), 'w' ); fwrite($fp, $r->email); fclose($fp); } else{ $fp= fopen( resource_path( 'views/admin/savedemails/'.$this->slugify($r->filename).'.html' ), 'w' ); fwrite($fp, $r->email); fclose($fp); } } public function get_saved_email_templates(){ $html=[]; $url=url()->current(); $emailurl=trim($url,"admin/get-saved-email-templates"); $fileList = glob(resource_path( 'views/admin/savedemails/*.html')); foreach($fileList as $filename){ if(is_file($filename)){ $file=explode('/',$filename); $extensionless=explode('.',end($file)); $html[]= array('filename'=> $extensionless[0],'path'=> $emailurl.'/resources/views/admin/savedemails/'.end($file)); } } return $html; } public function send_emails(Request $r){ // dd($r->to); if (file_exists(resource_path( 'views/admin/savedemails/'.$r->email.'.html'))){ $emails = $r->to; $data=['name'=>'haris','data'=>'asdasd']; try{ Mail::send('admin.savedemails.'.$r->email, $data, function($message) use ($emails) { $message->bcc($emails)->subject('Top at Law'); }); } catch(\Swift_RfcComplianceException $e){ return response()->json('some email address does not exists on internet e.g. ('.$e->getMessage().')'); } return response()->json('email sent'); } else return response()->json('something went wrong'); } function delete_emails(Request $r){ $name=$r->name; if(file_exists(resource_path( 'views/admin/savedemails/'.$name.'.html'))){ unlink(resource_path( 'views/admin/savedemails/'.$name.'.html')); } } //---------------------------------------------------end emails---------------------------- function profile_claims(){ $getProfiles=DB::table('claim_profile')->get(); return view('admin.lawyers.claim_profile',compact('getProfiles')); } function profile_claims_delete($id){ DB::table('claim_profile')->where('id',$id)->delete(); return redirect()->back(); } function profile_claimed_approve($email,$id,$cid){ lawyers::where('id',$id)->update(['emailaddress'=>$email]); DB::table('claim_profile')->where('id',$cid)->delete(); return redirect()->back(); } public function addplan() { return view('admin.bootplan.addplan'); } public function createplan(Request $request) { DB::table('boostplan') ->insert([ 'plan_title' => $request->tittle, 'plan_price' =>$request->price, 'plan_type' =>$request->plan_days, 'plan_detail' => $request->description, 'planfeature' => $request->plan_feature, 'planfeature_1' => $request->planfeature_1, 'planfeature_2' => $request->planfeature_2, 'planfeature_3' => $request->planfeature_3, ]); return redirect()->back()->with('message', 'Plan Successfully Inserted'); } public function allplan() { $data = DB::table('boostplan')->get(); return view('admin.bootplan.allplan')->with(array('data'=>$data)); } public function editplan($id) { $data = DB::table('boostplan')->where('id',$id)->first(); return view('admin.bootplan.editplan')->with(array('data'=>$data)); } public function updateplan(Request $request) { DB::table('boostplan') ->where('id',$request->id) ->update([ 'plan_title' => $request->tittle, 'plan_price' =>$request->price, 'plan_type' =>$request->plan_days, 'plan_detail' => $request->description, 'planfeature' => $request->plan_feature, 'planfeature_1' => $request->planfeature_1, 'planfeature_2' => $request->planfeature_2, 'planfeature_3' => $request->planfeature_3, ]); return redirect()->back()->with('message', 'Boost Plan Updated Successfully'); } }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; protected $table = "products"; protected $fillable = ["name", "stock", "price", "category_id", "shop_id", "created_at", "updated_at"]; public function carts() { return $this->hasMany(Cart::class); } public function category() { return $this->belongsTo(Category::class); } public function shop() { return $this->belongsTo(Shop::class); } }
import unittest from macrotrends_data_scrapper.utils.manage_driver import DriverManager class TestManageDriver(unittest.TestCase): """Class to be used to test ManageDriver class and its methods. Methods ------- setUp(): setUp reused variables/objects test_set_up_driver(): test set_up_driver method, check if driver gets url or not test_kill_driver(): test kill_driver method, check if driver is shutdown """ def setUp(self): """Set up reused variables/objects.""" self.driver_manager = DriverManager() def test_set_up_driver(self): """Check if the driver gets the url.""" url = "https://www.macrotrends.net/stocks/stock-screener" self.driver_manager.set_up_driver(url) self.assertTrue(self.driver_manager.driver.current_url == url) def test_kill_driver(self): """Check if the driver is shut down.""" self.driver_manager.kill_driver() self.assertFalse(self.driver_manager.driver.service.is_connectable()) if __name__ == "__main__": unittest.main()
# ComponentGroup This is a helper object that allows nesting of components into groups. Users never instantiate it directly in an input file, but indirectly via input file syntax like so: ``` [Components] [./compA] [../] [./group] [./comp1] [../] [./comp2] [../] [../] [] ``` This input file will build 3 components: `compA`, `group/comp1`, `group/comp2`. No matter the location in the input file, components are always referred to with their full name, i.e. in our example above, one cannot refer to `comp1` with name `comp1` inside the group `group` - it must be referred to as `group/comp1`. !syntax parameters /Components/ComponentGroup !syntax inputs /Components/ComponentGroup !syntax children /Components/ComponentGroup
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <!--use the head in frag to replace current head part in this html--> <head th:replace="_frags :: head(~{::title})"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>归档</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css"> <link rel="stylesheet" href="../static/css/style.css"> </head> <body> <!-- navigation part--> <nav th:replace="_frags :: menu(4)" class="ui inverted attached segment interval-tb-reduce"> <div class="ui container"> <div class="ui inverted stackable menu"> <h2 class="ui teal header item">My Blog</h2> <a href="#" class="m-item item my-mobile-hide"><i class="home icon"></i>首页</a> <a href="#" class="m-item item my-mobile-hide"><i class="idea icon"></i>分类</a> <a href="#" class="m-item item my-mobile-hide"><i class="tags icon"></i>标签</a> <!-- search box part--> <div class="m-item item my-mobile-hide" style="width: 50%;height: 0"></div> <div class="m-item right item my-mobile-hide"> <div class="ui icon input search-bar"> <input type="search" placeholder="Search..." > <i class="search link icon"></i> </div> </div> <div class="ui container right item my-mobile-hide"> <img src="../static/images/profile.PNG" alt="My Profile" class="round_icon" th:src="@{/images/profile.PNG}"> <a href="#" class="item"><i class="address card outline icon"></i>Me</a> </div> </div> </div> <a href="#" class="ui menu toggle black icon button my-ps-topright my-mobile-show"> <i class="sidebar icon"></i> </a> </nav> <!--<div class="ui transparent bottom attached segment"></div>--> <!--content--> <div class="interval-tb-middle"> <div class="ui container"> <div class="ui top attached middle aligned segment"> <!-- two column blog menu--> <div class="ui middle aligned two column grid"> <div class="column"> <h3 class="ui blue header">Blogs</h3> </div> <div class="right aligned column"> 共 <h2 class="ui red header my-text-interval-small" style="display: inline-block" th:text="${countBlog}">14</h2> 篇 </div> <!-- two column menu ended--> </div> </div> <!-- order by years--> <th:block th:each="oneyear : ${archiveMap}"> <br> <br> <h3 class="ui header center aligned" th:text="${oneyear.key}">2021</h3> <div class="ui fluid vertical center aligned middle aligned menu"> <a href="#" th:href="@{/blog/{id}(id=${blog.id})}" target="_blank" class="middle aligned item" th:each="blog : ${oneyear.value}"> <span style="display: inline-list-item; font-size: 18px"> <i class="ui teal circle icon"></i><span th:text="${blog.title}">title</span> <div class="ui blue basic left pointing label" style="font-size: 8px"> <span th:text="${#dates.format(blog.createTime,'MM-dd')}">10-2</span> </div> </span> <div class="ui teal label" th:text="${blog.flag}">原创</div> </a> </div> <br> </th:block> </div> </div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <!--bottom elements--> <footer th:replace="_frags :: foot" class="ui inverted vertical segment interval-tb-add"> <div class="ui center aligned container"> <div class="ui inverted divided stackable grid"> <div class="three wide column"> <img src="../static/images/profile.PNG" alt="My Profile" class="round_icon" style="width: 100px;height: 100px" th:src="@{/images/profile.PNG}"> </div> <div class="three wide column"> <h4 class="ui inverted header">最新博客</h4> <div class="ui inverted link list"> <a href="#" class="item">1</a> <a href="#" class="item">2</a> <a href="#" class="item">3</a> </div> </div> <div class="three wide column"> <div class="ui inverted link list"> <h4 class="ui inverted header">代办事项</h4> <a href="#" class="item">1</a> <a href="#" class="item">2</a> <a href="#" class="item">3</a> </div> </div> <div class="seven wide column"></div> </div> <div class="ui inverted section divider"></div> <p class="my-text-interval-small my-alpha">Copyright©2021 Blog of XI BI</p> </div> </footer> <!--/*/<th:block th:replace="_frags :: scripts">/*/--> <script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> <!--/*/</th:block>/*/--> <script> $('.menu.toggle').click(function (){ $('.m-item').toggleClass('my-mobile-hide'); }); </script> </body> </html>
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:lab10/presentation/pages/sign_up_page.dart'; import 'package:lab10/presentation/widgets/form_container_widget.dart'; import 'package:lab10/global/common/toast.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:google_sign_in/google_sign_in.dart'; import '../../firebase_auth_implementation/firebase_auth_services.dart'; class LoginPage extends StatefulWidget { const LoginPage({super.key}); get auth => false; @override State<LoginPage> createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { bool _isSigning = false; final FirebaseAuthService _auth = FirebaseAuthService(); final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; TextEditingController _emailController = TextEditingController(); TextEditingController _passwordController = TextEditingController(); TextEditingController get emailController => _emailController; TextEditingController get passwordController => _passwordController; @override void dispose() { _emailController.dispose(); _passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text("Login"), ), body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Login", style: TextStyle(fontSize: 27, fontWeight: FontWeight.bold), ), SizedBox( height: 30, ), FormContainerWidget( controller: _emailController, hintText: "Email", isPasswordField: false, ), SizedBox( height: 10, ), FormContainerWidget( controller: _passwordController, hintText: "Password", isPasswordField: true, ), SizedBox( height: 30, ), GestureDetector( onTap: () { _signIn(); }, child: Container( width: double.infinity, height: 45, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(10), ), child: Center( child: _isSigning ? CircularProgressIndicator( color: Colors.white,) : Text( "Login", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), ), ), ), SizedBox(height: 10,), GestureDetector( onTap: () { _signInWithGoogle(); }, child: Container( width: double.infinity, height: 45, decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(10), ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(FontAwesomeIcons.google, color: Colors.white,), SizedBox(width: 5,), Text( "Sign in with Google", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), ], ), ), ), ), SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Don't have an account?"), SizedBox( width: 5, ), GestureDetector( onTap: () { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => SignUpPage()), (route) => false, ); }, child: Text( "Sign Up", style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold, ), ), ), ], ), ], ), ), ), ); } void _signIn() async { setState(() { _isSigning = true; }); String email = _emailController.text; String password = _passwordController.text; User? user = await _auth.signInWithEmailAndPassword(email, password); setState(() { _isSigning = false; }); if (user != null) { showToast(message: "User is successfully signed in"); Navigator.pushNamed(context, "/home"); } else { showToast(message: "some error occured"); } } _signInWithGoogle()async{ final GoogleSignIn _googleSignIn = GoogleSignIn(); try { final GoogleSignInAccount? googleSignInAccount = await _googleSignIn.signIn(); if(googleSignInAccount != null ){ final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential credential = GoogleAuthProvider.credential( idToken: googleSignInAuthentication.idToken, accessToken: googleSignInAuthentication.accessToken, ); await _firebaseAuth.signInWithCredential(credential); Navigator.pushNamed(context, "/home"); } }catch(e) { print("some error occured $e"); } } }
import { useState } from "react"; import { useDispatch } from "react-redux"; import { addToCart } from "../redux/cartSlice"; const ModalBody = ({ productDetail, img }) => { const dispatch = useDispatch(); const [quantity, setQuantity] = useState(1); const decrement = () => { if (quantity > 1) { setQuantity(quantity - 1); } }; const increment = () => { setQuantity(quantity + 1); }; const addBasket = () => { dispatch( addToCart({ id: productDetail?.code, title: productDetail?.name, img: productDetail?.articlesList[0]?.galleryDetails[0]?.baseUrl, price: productDetail?.whitePrice?.price, quantity: quantity, }) ); }; console.log(productDetail) return ( <div className="rounded overflow-hidden shadow-lg hover:shadow-xl grid md:flex"> <div className="flex items-center justify-center "> <img className="md:w-[600px] w-[300px] md:h-[600px] h-[300px] rounded-lg" src={img} alt="Property Image" /> </div> <div className="flex flex-col align-center justify-between gap-4 my-5"> <div className="px-6 py-4 flex-row-3"> <div className="mb-2"> <p className="text-md md:text-xl font-semi text-gray-900 mb-2"> {productDetail?.description} </p> </div> <div className="flex justify-between mt-2"> <div className="flex items-center"> <img src="../pictures/dress.webp" className="w-12" /> <p className="ml-2 text-lg font-medium text-gray-700"> {productDetail?.articlesList[0]?.genericDescription ? productDetail?.articlesList[0]?.genericDescription : "*"} </p> </div> <div className="flex items-center"> <img src="../pictures/beden.png" className="w-12" /> <p className="ml-2 text-lg font-medium text-gray-700 "> {productDetail?.fits[0]} </p> </div> <div className="flex items-center"> <img src="../pictures/type.png" className="w-12" /> <p className="ml-2 text-sm font-medium text-gray-700"> {productDetail?.mainCategory?.name} </p> </div> </div> </div> <div className="px-6 py-4 flex justify-between items-center "> <div className="flex items-center gap-3"> <img src="../pictures/country.png" className="w-12" /> <div className="items-center"> <p className="text-sm font-medium text-gray-800"> {productDetail?.productCountryOfProduction ? productDetail?.productCountryOfProduction : "Global"} </p> <p className="text-xs text-gray-600 max-w-80 letter-wrap"> {productDetail?.manufacturedBy} </p> </div> </div> <div className="flex items-center"> <img src="../pictures/category.png" className="w-12" /> <p className="ml-2 text-lg font-medium text-gray-700"> {productDetail?.customerGroup} </p> </div> <div className="flex items-center "> <img src="../pictures/coton.png" className="w-12" /> <p className="ml-2 text-sm font-medium text-gray-700"> {productDetail?.articlesList[0]?.materialDetails[0].name ? productDetail?.articlesList[0]?.materialDetails[0].name : productDetail.keyFibreTypes[0]} </p> </div> </div> <div className="flex items-center justify-between px-6 mb-4"> <div className="flex items-center mt-2 "> <div className="mr-2 rounded-full py-6 px-6 text-xs font-medium text-white" style={{ backgroundColor: productDetail?.color.rgbColor }} > {" "} </div> <p className="text-xl">{productDetail?.articlesList[0]?.colourDescription}</p> </div> <div className="flex items-center "> <img src="../pictures/year.png" className="w-12 rounded-full" /> <p className="ml-2 text-xl font-medium text-gray-700"> {productDetail?.yearOfProduction} </p> </div> <div className="flex items-center "> <img src="../pictures/marka.png" className="w-12 rounded-full" /> <p className="ml-2 text-xl font-medium text-gray-700"> {productDetail?.articlesList[0]?.brandName} </p> </div> </div> <div className="flex items-center justify-end px-6 mb-4"> <div className="flex items-center justify-end gap-4 mt-5"> <p className="text-2xl md-text-3xl font-extrabold text-blue-800"> $ {(productDetail?.whitePrice.price * quantity).toFixed(2)} </p> <div onClick={decrement} className="bg-red-400 px-2 rounded-lg text-xl"> -</div> <input className="w-5 outline-none border-none text-black text-center text-2xl" type="text" value={quantity} /> <div onClick={increment} className="bg-green-400 px-2 rounded-lg text-xl"> +</div> <button onClick={addBasket} className="bg-red-400 px-4 py-2 rounded-md hover:bg-red-600 hover:text-white">Sepete ekle</button> </div> </div> </div> </div> ); }; export default ModalBody;
/* Criador: uZeus_#6777 */ const hastebin = require('hastebin'); const Event = require('../../structures/Event') const { MessageEmbed, MessageActionRow, MessageButton, Message } = require('discord.js') const { Collection } = require('@discordjs/collection'); const { config } = require('dotenv'); const actionRow = new MessageActionRow() .addComponents( [ new MessageButton() .setStyle('SUCCESS') .setLabel('📋 Inscrição') .setCustomId('inscricao'), new MessageButton() .setStyle('DANGER') .setLabel('☎️ Suporte') .setCustomId('suporte'), new MessageButton() .setStyle('PRIMARY') .setLabel('🤝 Partner') .setCustomId('partner'), ] ) const row = new MessageActionRow() .addComponents( [ new MessageButton() .setStyle('DANGER') .setLabel('❌ Finalizar Ticket') .setCustomId('deletar') ] ) module.exports = class extends Event { constructor(client) { super(client, { name: 'ready' }) } run = async (client, interaction) => { console.log(`Bot ${this.client.user.username} logado com sucesso!`) this.client.registryCommands() let canal = client.channels.cache.get(client.config.id_ticket) const embed = new MessageEmbed() .setColor(client.config.corembed) .setDescription(`Abra um ticket de **acordo** com a categoria. **1° Botão** - Para realizar a **INSCRIÇÃO** de equipe(s). **2° Botão** - Duvidas, denuncias e **suporte**. **2° Botão** - Assuntos relacionados a **Projetos/Partner**.`) embed.setFooter({ text: client.config.rodape }) .setTimestamp() embed.setAuthor({ name: "Liga Brasileira de FiveM | Ticket" }); var msg = await canal.send({ embeds: [embed], components: [actionRow] }) const collector = msg.createMessageComponentCollector() collector.on('collect', (i) => { const inscricao = new MessageEmbed() .setColor(client.config.corembed) .setDescription(`Bem vindo(a) <@${i.user.id}> a LBF. Quantas equipes deseja colocar em nosso campeonato? `) inscricao.setFooter({ text: client.config.rodape }) .setTimestamp() inscricao.setAuthor({ name: "Liga Brasileira de FiveM | Ticket" }); const suporte = new MessageEmbed() .setColor(client.config.corembed) .setDescription(`Bem vindo(a) <@${i.user.id}> a LBF. Em o que podemos ajudar?`) suporte.setFooter({ text: client.config.rodape }) .setTimestamp() suporte.setAuthor({ name: "Liga Brasileira de FiveM | Ticket" }); const partner = new MessageEmbed() .setColor(client.config.corembed) .setDescription(`Bem vindo(a) <@${i.user.id}> a LBF. Qual tipo de parceria que deseja fazer conosco?`) partner.setFooter({ text: client.config.rodape }) .setTimestamp() partner.setAuthor({ name: "Liga Brasileira de FiveM | Ticket" }); switch (i.customId) { case 'inscricao': let criador = i.user.id if (client.guilds.cache.get(i.guildId).channels.cache.find(c => c.topic === `<:lbf1:912551506547474454> | Usuario: <@${i.user.id}>\n<:lbf1:912551506547474454> | Id do usuario: ${i.user.id}\n<:lbf1:912551506547474454> | Ticket: Inscrição`)) { return i.reply({ content: 'Você já criou um ticket para esta categoria!', ephemeral: true }); } i.guild.channels.create(`ticket-${i.user.username}`, { parent: client.config.id_inscricao, topic: `<:lbf1:912551506547474454> | Usuario: <@${i.user.id}>\n<:lbf1:912551506547474454> | Id do usuario: ${i.user.id}\n<:lbf1:912551506547474454> | Ticket: Inscrição`, permissionOverwrites: [{ id: i.user.id, allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'], }, { id: client.config.cargo, allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'], }, { id: i.guild.roles.everyone, deny: ['VIEW_CHANNEL'], }, ], type: 'text', }).then(async c => { i.reply({ content: `Ticket criado com sucesso! <#${c.id}>`, ephemeral: true }) var msg = await c.send({ embeds: [inscricao], components: [row] }) const collector = msg.createMessageComponentCollector() collector.on('collect', (i) => { switch (i.customId) { case 'deletar': i.reply({ content: 'Salvando mensagens e gerando logs...' }); const guild = client.guilds.cache.get(i.guildId); const chan = guild.channels.cache.get(i.channelId); chan.messages.fetch().then(async (messages) => { let a = messages.filter(m => m.author.bot !== true).map(m => `${new Date(m.createdTimestamp).toLocaleString('pt-BR')} - ${m.author.username}#${m.author.discriminator}: ${m.attachments.size > 0 ? m.attachments.first().proxyURL : m.content}` ).reverse().join('\n'); if (a.length < 1) a = "Infelizmente não tinha nenhuma mensagem no ticket." hastebin.createPaste(a, { contentType: 'text/plain', server: 'https://hastebin.com' }, {}) .then(function (urlToPaste) { var canal1 = client.guilds.cache.get(i.guildId).channels.cache.find(c => c.topic === `logs`) const embedii = new MessageEmbed() embedii.setAuthor({ name: `LBF | Liga Brasileira de FiveM` }) .setColor(client.config.corembed) .setDescription(`<:lbf1:912551506547474454> | Ticket aberto por: <@${criador}>\n<:lbf1:912551506547474454> | Ticket finalizado por: <@${i.user.id}>\n<:lbf1:912551506547474454> | Categoria: Inscrição\n<:lbf1:912551506547474454> | Logs: [**Clique aqui**](${urlToPaste})`) .setFooter({ text: client.config.rodape }) canal1.send({ embeds: [embedii] }) setTimeout(() => { chan.delete(); }, 5000); }); }); //a } }) }) break; case 'suporte': let criador1 = i.user.id if (client.guilds.cache.get(i.guildId).channels.cache.find(c => c.topic === `<:lbf1:912551506547474454> | Usuario: <@${i.user.id}>\n<:lbf1:912551506547474454> | Id do usuario: ${i.user.id}\n<:lbf1:912551506547474454> | Ticket: Suporte`)) { return i.reply({ content: 'Você já criou um ticket para esta categoria!', ephemeral: true }); } i.guild.channels.create(`ticket-${i.user.username}`, { parent: client.config.id_suporte, topic: `<:lbf1:912551506547474454> | Usuario: <@${i.user.id}>\n<:lbf1:912551506547474454> | Id do usuario: ${i.user.id}\n<:lbf1:912551506547474454> | Ticket: Suporte`, permissionOverwrites: [{ id: i.user.id, allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'], }, { id: client.config.cargo, allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'], }, { id: i.guild.roles.everyone, deny: ['VIEW_CHANNEL'], }, ], type: 'text', }).then(async c => { i.reply({ content: `Ticket criado com sucesso! <#${c.id}>`, ephemeral: true }) var msg = await c.send({ embeds: [inscricao], components: [row] }) const collector = msg.createMessageComponentCollector() collector.on('collect', (i) => { switch (i.customId) { case 'deletar': i.reply({ content: 'Salvando mensagens e gerando logs...' }); const guild = client.guilds.cache.get(i.guildId); const chan = guild.channels.cache.get(i.channelId); chan.messages.fetch().then(async (messages) => { let a = messages.filter(m => m.author.bot !== true).map(m => `${new Date(m.createdTimestamp).toLocaleString('pt-BR')} - ${m.author.username}#${m.author.discriminator}: ${m.attachments.size > 0 ? m.attachments.first().proxyURL : m.content}` ).reverse().join('\n'); if (a.length < 1) a = "Infelizmente não tinha nenhuma mensagem no ticket." hastebin.createPaste(a, { contentType: 'text/plain', server: 'https://hastebin.com' }, {}) .then(function (urlToPaste) { var canal1 = client.guilds.cache.get(i.guildId).channels.cache.find(c => c.topic === `logs`) const embedii = new MessageEmbed() embedii.setAuthor({ name: `LBF | Liga Brasileira de FiveM` }) .setColor(client.config.corembed) .setDescription(`<:lbf1:912551506547474454> | Ticket aberto por: <@${criador1}>\n<:lbf1:912551506547474454> | Ticket finalizado por: <@${i.user.id}>\n<:lbf1:912551506547474454> | Categoria: Inscrição\n<:lbf1:912551506547474454> | Logs: [**Clique aqui**](${urlToPaste})`) .setFooter({ text: client.config.rodape }) canal1.send({ embeds: [embedii] }) setTimeout(() => { chan.delete(); }, 5000); }); }); //a } }) }) break; case 'partner': let criador2 = i.user.id if (client.guilds.cache.get(i.guildId).channels.cache.find(c => c.topic === `<:lbf1:912551506547474454> | Usuario: <@${i.user.id}>\n<:lbf1:912551506547474454> | Id do usuario: ${i.user.id}\n<:lbf1:912551506547474454> | Ticket: Partner`)) { return i.reply({ content: 'Você já criou um ticket para esta categoria!', ephemeral: true }); } i.guild.channels.create(`ticket-${i.user.username}`, { parent: client.config.id_partner, topic: `<:lbf1:912551506547474454> | Usuario: <@${i.user.id}>\n<:lbf1:912551506547474454> | Id do usuario: ${i.user.id}\n<:lbf1:912551506547474454> | Ticket: Partner`, permissionOverwrites: [{ id: i.user.id, allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'], }, { id: client.config.cargo, allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'], }, { id: i.guild.roles.everyone, deny: ['VIEW_CHANNEL'], }, ], type: 'text', }).then(async c => { i.reply({ content: `Ticket criado com sucesso! <#${c.id}>`, ephemeral: true }) var msg = await c.send({ embeds: [inscricao], components: [row] }) const collector = msg.createMessageComponentCollector() collector.on('collect', (i) => { switch (i.customId) { case 'deletar': i.reply({ content: 'Salvando mensagens e gerando logs...' }); const guild = client.guilds.cache.get(i.guildId); const chan = guild.channels.cache.get(i.channelId); chan.messages.fetch().then(async (messages) => { let a = messages.filter(m => m.author.bot !== true).map(m => `${new Date(m.createdTimestamp).toLocaleString('pt-BR')} - ${m.author.username}#${m.author.discriminator}: ${m.attachments.size > 0 ? m.attachments.first().proxyURL : m.content}` ).reverse().join('\n'); if (a.length < 1) a = "Infelizmente não tinha nenhuma mensagem no ticket." hastebin.createPaste(a, { contentType: 'text/plain', server: 'https://hastebin.com' }, {}) .then(function (urlToPaste) { var canal1 = client.guilds.cache.get(i.guildId).channels.cache.find(c => c.topic === `logs`) const embedii = new MessageEmbed() embedii.setAuthor({ name: `LBF | Liga Brasileira de FiveM` }) .setColor(client.config.corembed) .setDescription(`<:lbf1:912551506547474454> | Ticket aberto por: <@${criador2}>\n<:lbf1:912551506547474454> | Ticket finalizado por: <@${i.user.id}>\n<:lbf1:912551506547474454> | Categoria: Inscrição\n<:lbf1:912551506547474454> | Logs: [**Clique aqui**](${urlToPaste})`) .setFooter({ text: client.config.rodape }) canal1.send({ embeds: [embedii] }) setTimeout(() => { chan.delete(); }, 5000); }); }); //a } }) }) break; } }) } }
#include <stdio.h> // printf(), perror() #include <stdlib.h> // exit() #include <string.h> // strcpy() #include <unistd.h> // read(), write(), close() #include <sys/un.h> // struct sockaddr_un #include <sys/socket.h> // connect() int main() { int my_socket; socklen_t socket_addr_len; struct sockaddr_un socket_address; int retval; char ch = 'A'; // creat a socket for the client my_socket = socket(AF_UNIX, SOCK_STREAM, 0); // name the socket, as given in the server socket_address.sun_family = AF_UNIX; strcpy(socket_address.sun_path, "my_unix_domain_socket"); socket_addr_len = sizeof(socket_address); // connect to the server socket retval = connect(my_socket, (struct sockaddr *)&socket_address, socket_addr_len); // check for error if( retval == -1 ) { perror("Client Error"); exit(EXIT_FAILURE); } // if connected to the server without any error, we can read and write on the socket write(my_socket, &ch, 1); read(my_socket, &ch, 1); printf("Received from Server: %c\n", ch); // close connection close(my_socket); // all done return 0; }
--- title: "01_regression" author: "Brenna Kelly" date: "2024-02-09" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## setup ```{r} library(sp) library(sf) library(tmap) library(INLA) library(spdep) library(dplyr) library(moments) library(ggplot2) library(stringr) library(regclass) ``` ## data ```{r} # acs <- acs_merge acs <- read.csv("data/7020_data_count.csv") acs$geoid <- str_pad(acs$geoid, width = 12, pad = "0", side = "left") head(acs) # acs_geom <- st_read("data/7020_geom.shp") # # # merge by geoid # acs <- merge(acs_geom, acs, by = "geoid") # drop empty geometries # acs <- acs[which(st_is_empty(acs) == FALSE), ] # # # drop areas with no population # empty_areas <- acs[which(is.na(acs$hisp_p)), ] # acs <- acs[which(!acs$geoid %in% empty_areas$geoid), ] # fix poverty (some have 0) acs$pov_p <- ifelse(is.na(acs$pov_p), 0 , acs$pov_p) # scale 0-100 acs <- acs |> mutate(hisp_perc = ifelse(is.na(hisp_p), 0, hisp_p*100)) |> mutate(black_perc = ifelse(is.na(black_p), 0, black_p*100)) |> mutate(aian_perc = ifelse(is.na(aian_p), 0, aian_p*100)) |> mutate(asian_perc = ifelse(is.na(asian_p), 0, asian_p*100)) |> mutate(nhpi_perc = ifelse(is.na(nhpi_p), 0, nhpi_p*100)) |> mutate(other_perc = ifelse(is.na(other_p), 0, other_p*100)) |> mutate(tom_perc = ifelse(is.na(tom_p), 0, tom_p*100)) |> mutate(pov_perc = ifelse(is.na(pov_p), 0, pov_p*100)) acs <- acs |> mutate(hisp_p_log = log(hisp_perc + min(acs$hisp_perc[which(acs$hisp_perc > 0)]))) |> mutate(black_p_log = log(black_perc + min(acs$black_perc[which(acs$black_perc > 0)]))) |> mutate(aian_p_log = log(aian_perc + min(acs$aian_perc[which(acs$aian_perc > 0)]))) |> mutate(asian_p_log = log(asian_perc + min(acs$asian_perc[which(acs$asian_perc > 0)]))) |> mutate(nhpi_p_log = log(nhpi_perc + min(acs$nhpi_perc[which(acs$nhpi_perc > 0)]))) |> mutate(other_p_log = log(other_perc + min(acs$other_perc[which(acs$other_perc > 0)]))) |> mutate(tom_p_log = log(tom_perc + min(acs$tom_perc[which(acs$tom_perc > 0)]))) |> mutate(pov_p_log = log(pov_perc + min(acs$pov_perc[which(acs$pov_perc > 0)]))) |> mutate(total_1k = total / 1000) |> mutate(total_1k_log = log(total_1k + min(acs$total_1k[which(acs$total_1k > 0)]))) acs$state <- str_sub(acs$geoid, start = 0, end = 2) acs$total_centered <- acs$total_1k - mean(acs$total_1k) # acs$total_1k_log <- log(acs$total_1k) skewness(acs$total_1k) # write.csv(acs, "acs_inla.csv", row.names = FALSE) ``` ```{r} #sources <- read.csv("/Users/brenna/Downloads/Air Quality System (AIRS AQS).csv") # icis_minor <- read.csv("/Users/brenna/Downloads/Integrated Compliance Information System-Air (ICIS-Air).csv") icis <- read.csv("/Users/brenna/Downloads/ICIS-AIR_downloads/ICIS-AIR_FACILITIES.csv") addresses <- icis[, c("REGISTRY_ID", "STREET_ADDRESS", "CITY", "STATE", "ZIP_CODE")] addresses$file <- rep(c(1:(28*2)), length = nrow(addresses)) table(addresses$file) addr_files <- split(addresses, addresses$file) for(i in 1:length(addr_files)) { name <- paste0("address_file_", i, ".csv") write.table(addr_files[i], file = name, col.names = FALSE, row.names = FALSE, sep = ",") } write.csv() fac <- read.csv("/Users/brenna/Downloads/national_combined/NATIONAL_FACILITY_FILE.CSV") facilities <- fac[, c("REGISTRY_ID", "CENSUS_BLOCK_CODE", "LATITUDE83", "LONGITUDE83")] head(fac) table(is.na(facilities$CENSUS_BLOCK_CODE)) test <- merge(facilities, icis, by = "REGISTRY_ID") test <- test |> filter(!is.na(LATITUDE83) & !is.na(LONGITUDE83) & !is.na(CENSUS_BLOCK_CODE)) test$CENSUS_BLOCK_CODE <- str_pad(test$CENSUS_BLOCK_CODE, width = 15, side = "left", pad = "0") test$census_block_group <- str_sub(test$CENSUS_BLOCK_CODE, start = 1, end = 12) n_sources <- test |> count(census_block_group) # merge with acs test_acs <- merge(acs, n_sources, by.x = "geoid", by.y = "census_block_group", all.x = TRUE) prop.table(table(test_acs$n == 0)) test_acs$n <- ifelse(is.na(test_acs$n), 0, test_acs$n) test_acs$n_test <- test_acs$n + 1 test_acs$n_test_log <- log(test_acs$n + 1) test_acs$n_test <- ifelse(test_acs$n > 500, 1, test_acs$n) skewness(test_acs$n / (test_acs$total_1k + 1)) ``` ```{r} summary(test_acs) test <- inla(n_lower_o3 ~ offset(total_1k),# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = test_acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) summary(test) 1.77e+218 round(exp(test$summary.fixed), 2) 1 - exp(-27/1621*10) ``` ### scaling, transformations ```{r} # skewness(log(acs$hisp_p + min(acs$hisp_p[which(acs$hisp_p > 0)])), na.rm = TRUE) # # skewness(acs$hisp_p) # summary(acs) # skewness(log(acs$pov_p + min(acs$pov_p[which(acs$pov_p > 0)])), na.rm = TRUE) ``` ## pre-analysis exploration ```{r} aggregate(acs$black_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$black_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$aian_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$aian_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$hisp_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$hisp_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$pov_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$pov_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$asian_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$asian_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$tom_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$tom_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$other_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$other_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$total, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$total, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) aggregate(acs$coll_p, by = list(acs$o3_measured_u), FUN = mean, na.rm = TRUE) aggregate(acs$coll_p, by = list(acs$o3_measured_l), FUN = mean, na.rm = TRUE) ``` ## spatial structure ```{r} # area id for each observation # acs$idarea <- 1:nrow(acs) # # ## building the spatial weight matrix # # # centroids # acs.geom <- st_geometry(acs) # acs.coords <- st_centroid(acs.geom) # # # plot(acs.geom, reset = FALSE) # # plot(acs.coords, pch = 16, col = 2, add = TRUE) # # # queen's case boundaries # acs_nb <- poly2nb(acs) # # summary(acs_nb) # acs_nb # # acs_nb <- acs_nb[-c(3928, 3929, 15237, 20928, 33392, 36909, 48512, # # 53416, 53423, 53472, 96818, 97230, 97256, 97605, # # 102598, 107669, 109842, 110179, 110183, 137369, # # 141538, 153359, 155904, 160601, 167742, 172373, # # 191215, 230418, 231154, 231156, 231362, 232786, # # 234668, 235531)] # acs_nb # # no_neighbors <- c(3928, 3929, 15237, 20928, 33392, 36909, 48512, # 53416, 53423, 53472, 96818, 97230, 97256, 97605, # 102598, 107669, 109842, 110179, 110183, 137369, # 141538, 153359, 155904, 160601, 167742, 172373, # 191215, 230418, 231154, 231156, 231362, 232786, # 234668, 235531) # # no_neighbors <- acs[c(3928, 3929, 15237, 20928, 33392, 36909, 48512, # 53416, 53423, 53472, 96818, 97230, 97256, 97605, # 102598, 107669, 109842, 110179, 110183, 137369, # 141538, 153359, 155904, 160601, 167742, 172373, # 191215, 230418, 231154, 231156, 231362, 232786, # 234668, 235531), ]# |> # #st_drop_geometry() # no_neighbors # no_neighbors[1] # # acs <- acs[-c(no_neighbors), ] # # acs[c(no_neighbors), ] # # acs_nb <- poly2nb(acs) # summary(acs_nb) # # nb_contiguity <- st_contiguity(acs) # nb_k1 <- st_knn(st_centroid(acs), 1) # nb_mixed <- nb_union(nb_contiguity, nb_k1) # wt <- st_weights(nb_mixed) # # test <- st_weights(nb_k1) # # # acs_nb[ c(3928, 3929, 15237, 20928, 33392, 36909, 48512, # 53416, 53423, 53472, 96818, 97230, 97256, 97605, # 102598, 107669, 109842, 110179, 110183, 137369, # 141538, 153359, 155904, 160601, 167742, 172373, # 191215, 230418, 231154, 231156, 231362, 232786, # 234668, 235531)] # # test <- knn2nb(knearneigh(acs.coords, k = 1)) # summary(test) # # no_neighbors[1] # # acs[] # # acs_nb[[3928]] # # acs_nb[[230418]] # # acs[no_neighbors[1], ] # # acs_nb[[1]] # # st_nearest_feature(acs[no_neighbors[1], ], acs) # # # Syr2 <- as_Spatial(acs) # coords <- coordinates(Syr2) # Sy2_nb <- edit.nb(acs_nb, coords, polys = Syr2) # # edit(acs_nb, coords) # #Sy2_nb <- edit.nb(acs_nb, acs.coords, polys = acs) # # # c(no_neighbors[1] - 1, no_neighbors[1] + 1) # # str(no_neighbors[1]) # geoid <- no_neighbors[1, "geoid"] |> # st_drop_geometry() # acs_nb[14665] # st_nearest_feature(no_neighbors[1, ], acs) # # no_neighbors[i, ] # # find the closest region, in terms of fips # for(i in 1:length(no_neighbors)) { # # index <- no_neighbors[i] # # acs_nb[[index]] <- c(no_neighbors[1] - 1, no_neighbors[1] + 1) # #index - 1 #st_nearest_feature(acs[no_neighbors[i], ], acs) # # } # # # st_nearest_feature(acs[no_neighbors[235530], ], acs) # str(acs_nb) # # # # delauney triangulation # # Sy3_nb <- tri2nb(Syracuse.coords) # # # # # binary spatial weights (more neighbors not downweighted; i.e., style != 'W') # # Sy1_lw_B <- nb2listw(Sy1_nb, style = 'B') # # inverse distance weighting # dists <- nbdists(acs_nb, acs.coords) # # inverse_distance <- function(x) {1/(x/1000)} # # idw <- lapply(dists, inverse_distance) # # acs_lw_idwB <- nb2listw(acs_nb, glist = idw, style = "B", zero.policy = TRUE) ``` ### global Moran's I test for autocorrelation ```{r} # # moran.test(acs$pm_measured_l, # listw = acs_lw_idwB, # alternative = "two.sided", # randomisation = TRUE, zero.policy = TRUE) # # monte carlo method # moran.mc(boston$logCMEDV, # listw = acs_lw_idwB, # nsim = 999, # alternative = 'greater') ``` ### local Moran's I; spatial pattern of autocorrelation ```{r} # lm1 = localmoran(acs$, # listw = acs_lw_idwB, # alternative = "two.sided") # # acs$pval.bin <- as.factor(ifelse(acs$pval < 0.05, "Significant", "Not-significant")) # # tm_shape(boston) + # tm_fill("pval.bin") + # tm_borders() + # tm_layout(main.title = "Local Moran's I (z-scores)", # main.title.size = 1, # legend.position = c("left", "bottom")) ``` ### spatial weight matrix ```{r} # acs_knn <- knn2nb(knearneigh(acs.coords, k = 2)) # ?knearneigh # # ?edit.nb # # acs_w <- nb2mat(nb_k1, zero.policy = TRUE) # # acs.listw <- nb2listw(acs_knn, zero.policy = TRUE) # neighbors # # acs_w <- nb2mat(acs.listw) # INLA # ``` ### inla graph ```{r} # map # map <- as_Spatial(acs$geometry) #codes <- rgdal::make_EPSG() #codes[which(codes$code == "4326"), ] # map <- spTransform(map, # CRS("+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +ellps=GRS80 +datum=NAD83")) # # sapply(slot(map, "polygons"), function(x){slot(x, "ID")}) # # # map@data$geoid <- acs$geoid # rownames(map@data) <- acs$geoid # # rownames(acs) <- 1:nrow(acs) # # SpatialPolygonsDataFrame(map, acs), match.ID = TRUE) # # # nb <- poly2nb(map) nb <- poly2nb(acs) nb2INLA("map.adj", nb) g <- inla.read.graph(filename = "map.adj") acs$idarea <- 1:nrow(acs) acs$idarea_2 <- 1:nrow(acs) ``` ## regression with INLA not looping because... ugh ```{r} ## running 12 inla models (one for each pollutant-scale) and saving them into a list; the saving the list to an rds file inla_results_pois <- list() inla_results_pois saveRDS(inla_results_pois, file = "data/inla_results_pois.rds") test <- readRDS("data/inla_results_pois.rds") inla_results_pois[["inla_co_l"]] <- inla(n_lower_co ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_co_u"]] <- inla(n_upper_co ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_no2_l"]] <- inla(n_lower_no2 ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_no2_u"]] <- inla(n_upper_no2 ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_pm_l"]] <- inla(n_lower_pm ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_pm_u"]] <- inla(n_upper_pm ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_pb_l"]] <- inla(n_lower_pb ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k_log,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_pb_u"]] <- inla(n_upper_pb ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_so2_l"]] <- inla(n_lower_so2 ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_so2_u"]] <- inla(n_upper_so2 ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k,# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_o3_l"]] <- inla(n_lower_o3 ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k_log,# + offset(total_1k),# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) inla_results_pois[["inla_o3_u"]] <- inla(n_upper_o3 ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k_log,# + offset(total_1k),# + #f(idarea, model = "besag", graph = g_id, scale.model = TRUE) + #f(idarea_2, model = "iid"), data = acs, family = "poisson", control.inla= list(int.strategy = "eb"), control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) VIF(glm(n_upper_o3 ~ hisp_p_log + black_p_log + aian_p_log + asian_p_log + nhpi_p_log + other_p_log + tom_p_log + total_1k_log, data = acs, family = "poisson")) # VIF is very low ``` ```{r} res_lower <- inla_results_pois$inla_o3_l$summary.fixed res_upper <- inla_results_pois$inla_o3_u$summary.fixed res_lower$label <- "lower" res_upper$label <- "upper" res <- rbind(res_lower, res_upper) # res <- o3_res #summary(fit_intx)$coefs.SE.CI res <- tibble::rownames_to_column(res, "variable") res$variable <- ifelse(res$variable == "total_1k", "pop", res$variable) res$variable <- ifelse(res$variable == "total_1k1", "pop1", res$variable) res$label <- case_when(grepl("hisp", res$variable) == TRUE ~ "Hispanic or Latinx", grepl("black", res$variable) == TRUE ~ "Black or African American", grepl("aian", res$variable) == TRUE ~ "American Indian or Alaska Native", grepl("asian", res$variable) == TRUE ~ "Asian", grepl("nhpi", res$variable) == TRUE ~ "Native Hawaiian or Other Pacific Islander", grepl("other", res$variable) == TRUE ~ "Some Other Race", grepl("tom", res$variable) == TRUE ~ "Two or More Races", grepl("pop", res$variable) == TRUE ~ "Population, 1K") res$label <- ifelse(grepl("1", res$variable) == TRUE, paste0(res$label, ", upper"), paste0(res$label, ", lower")) res$scale <- ifelse(grepl("1", res$variable) == TRUE, "upper", "lower") res$mean <- round(exp(res$mean), 3) res$`0.025quant` <- round(exp(res$`0.025quant`), 3) res$`0.975quant` <- round(exp(res$`0.975quant`), 3) res <- res[, c("variable", "mean", "0.025quant", "0.975quant", "scale", "label")] res$sig <- ifelse(res$`0.025quant` < 1 & res$`0.025quant` < 1, "neg", NA) res$sig <- ifelse(res$`0.975quant` > 1 & res$`0.975quant` > 1, "pos", res$sig) # figure res |> filter(!variable %in% c("(Intercept)", "(Intercept)1")) |> ggplot(aes(y = label, color = scale, group = scale)) + theme_classic() + geom_point(aes(x = mean), size = 1) + #scale_size_manual(values = c(1, 3)) + scale_color_manual(values = c("#ff2908","#f78e75")) + geom_linerange(aes(xmin = `0.025quant`, xmax = `0.975quant`)) + labs(x = "Odds of having O3 monitor (log scale)") + coord_cartesian(xlim = c(0.8, 1.1)) + geom_vline(xintercept = 1, linetype = "solid") + geom_vline(xintercept = c(0.8, 0.9, 1.1, 1.2), alpha = 0.5, linetype="dotted") + scale_x_continuous(trans = 'log10') + theme(axis.line.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank()) + geom_text(aes(x = (`0.975quant` + 0.02), y=label, label = round(mean, 2)), hjust = 0, fontface = "bold") +#, size = 4) + geom_text(aes(x = 0.8, y = label, label = stringr::str_wrap(label, 30), hjust=0), fontface = "plain", size = 4) ``` ```{r pm} res_lower <- inla_results_pois$inla_pm_l$summary.fixed res_upper <- inla_results_pois$inla_pm_u$summary.fixed res_lower$label <- "lower" res_upper$label <- "upper" res <- rbind(res_lower, res_upper) # res <- o3_res #summary(fit_intx)$coefs.SE.CI res <- tibble::rownames_to_column(res, "variable") res$variable <- ifelse(res$variable == "total_1k", "pop", res$variable) res$variable <- ifelse(res$variable == "total_1k1", "pop1", res$variable) res$label <- case_when(grepl("hisp", res$variable) == TRUE ~ "Hispanic or Latinx", grepl("black", res$variable) == TRUE ~ "Black or African American", grepl("aian", res$variable) == TRUE ~ "American Indian or Alaska Native", grepl("asian", res$variable) == TRUE ~ "Asian", grepl("nhpi", res$variable) == TRUE ~ "Native Hawaiian or Other Pacific Islander", grepl("other", res$variable) == TRUE ~ "Some Other Race", grepl("tom", res$variable) == TRUE ~ "Two or More Races", grepl("pop", res$variable) == TRUE ~ "Population, 1K") res$label <- ifelse(grepl("1", res$variable) == TRUE, paste0(res$label, ", upper"), paste0(res$label, ", lower")) res$scale <- ifelse(grepl("1", res$variable) == TRUE, "upper", "lower") res$mean <- round(exp(res$mean), 3) res$`0.025quant` <- round(exp(res$`0.025quant`), 3) res$`0.975quant` <- round(exp(res$`0.975quant`), 3) res <- res[, c("variable", "mean", "0.025quant", "0.975quant", "scale", "label")] res$sig <- ifelse(res$`0.025quant` < 1 & res$`0.025quant` < 1, "neg", NA) res$sig <- ifelse(res$`0.975quant` > 1 & res$`0.975quant` > 1, "pos", res$sig) # figure res |> filter(!variable %in% c("(Intercept)", "(Intercept)1")) |> ggplot(aes(y = label, color = scale, group = scale)) + theme_classic() + geom_point(aes(x = mean), size = 1) + #scale_size_manual(values = c(1, 3)) + scale_color_manual(values = c("#22b573", "#90d9b8")) + geom_linerange(aes(xmin = `0.025quant`, xmax = `0.975quant`)) + labs(x = "Odds of having O3 monitor (log scale)") + coord_cartesian(xlim = c(0.8, 1.1)) + geom_vline(xintercept = 1, linetype = "solid") + geom_vline(xintercept = c(0.8, 0.9, 1.1, 1.2), alpha = 0.5, linetype="dotted") + scale_x_continuous(trans = 'log10') + theme(axis.line.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank()) + geom_text(aes(x = (`0.975quant` + 0.02), y=label, label = round(mean, 2)), hjust = 0, fontface = "bold") +#, size = 4) + geom_text(aes(x = 0.8, y = label, label = stringr::str_wrap(label, 30), hjust=0), fontface = "plain", size = 4) ``` ```{r no2} res_lower <- inla_results_pois$inla_no2_l$summary.fixed res_upper <- inla_results_pois$inla_no2_u$summary.fixed res_lower$label <- "lower" res_upper$label <- "upper" res <- rbind(res_lower, res_upper) # res <- o3_res #summary(fit_intx)$coefs.SE.CI res <- tibble::rownames_to_column(res, "variable") res$variable <- ifelse(res$variable == "total_1k", "pop", res$variable) res$variable <- ifelse(res$variable == "total_1k1", "pop1", res$variable) res$label <- case_when(grepl("hisp", res$variable) == TRUE ~ "Hispanic or Latinx", grepl("black", res$variable) == TRUE ~ "Black or African American", grepl("aian", res$variable) == TRUE ~ "American Indian or Alaska Native", grepl("asian", res$variable) == TRUE ~ "Asian", grepl("nhpi", res$variable) == TRUE ~ "Native Hawaiian or Other Pacific Islander", grepl("other", res$variable) == TRUE ~ "Some Other Race", grepl("tom", res$variable) == TRUE ~ "Two or More Races", grepl("pop", res$variable) == TRUE ~ "Population, 1K") res$label <- ifelse(grepl("1", res$variable) == TRUE, paste0(res$label, ", upper"), paste0(res$label, ", lower")) res$scale <- ifelse(grepl("1", res$variable) == TRUE, "upper", "lower") res$mean <- round(exp(res$mean), 3) res$`0.025quant` <- round(exp(res$`0.025quant`), 3) res$`0.975quant` <- round(exp(res$`0.975quant`), 3) res <- res[, c("variable", "mean", "0.025quant", "0.975quant", "scale", "label")] res$sig <- ifelse(res$`0.025quant` < 1 & res$`0.025quant` < 1, "neg", NA) res$sig <- ifelse(res$`0.975quant` > 1 & res$`0.975quant` > 1, "pos", res$sig) # figure res |> filter(!variable %in% c("(Intercept)", "(Intercept)1")) |> ggplot(aes(y = label, color = scale, group = scale)) + theme_classic() + geom_point(aes(x = mean), size = 1) + #scale_size_manual(values = c(1, 3)) + scale_color_manual(values = c("#9e005d", "#ce7fad")) + geom_linerange(aes(xmin = `0.025quant`, xmax = `0.975quant`)) + labs(x = "Odds of having O3 monitor (log scale)") + coord_cartesian(xlim = c(0.8, 1.1)) + geom_vline(xintercept = 1, linetype = "solid") + geom_vline(xintercept = c(0.8, 0.9, 1.1, 1.2), alpha = 0.5, linetype="dotted") + scale_x_continuous(trans = 'log10') + theme(axis.line.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank()) + geom_text(aes(x = (`0.975quant` + 0.02), y=label, label = round(mean, 2)), hjust = 0, fontface = "bold") +#, size = 4) + geom_text(aes(x = 0.8, y = label, label = stringr::str_wrap(label, 30), hjust=0), fontface = "plain", size = 4) ``` ```{r so2} res_lower <- inla_results_pois$inla_so2_l$summary.fixed res_upper <- inla_results_pois$inla_so2_u$summary.fixed res_lower$label <- "lower" res_upper$label <- "upper" res <- rbind(res_lower, res_upper) # res <- o3_res #summary(fit_intx)$coefs.SE.CI res <- tibble::rownames_to_column(res, "variable") res$variable <- ifelse(res$variable == "total_1k", "pop", res$variable) res$variable <- ifelse(res$variable == "total_1k1", "pop1", res$variable) res$label <- case_when(grepl("hisp", res$variable) == TRUE ~ "Hispanic or Latinx", grepl("black", res$variable) == TRUE ~ "Black or African American", grepl("aian", res$variable) == TRUE ~ "American Indian or Alaska Native", grepl("asian", res$variable) == TRUE ~ "Asian", grepl("nhpi", res$variable) == TRUE ~ "Native Hawaiian or Other Pacific Islander", grepl("other", res$variable) == TRUE ~ "Some Other Race", grepl("tom", res$variable) == TRUE ~ "Two or More Races", grepl("pop", res$variable) == TRUE ~ "Population, 1K") res$label <- ifelse(grepl("1", res$variable) == TRUE, paste0(res$label, ", upper"), paste0(res$label, ", lower")) res$scale <- ifelse(grepl("1", res$variable) == TRUE, "upper", "lower") res$mean <- round(exp(res$mean), 3) res$`0.025quant` <- round(exp(res$`0.025quant`), 3) res$`0.975quant` <- round(exp(res$`0.975quant`), 3) res <- res[, c("variable", "mean", "0.025quant", "0.975quant", "scale", "label")] res$sig <- ifelse(res$`0.025quant` < 1 & res$`0.025quant` < 1, "neg", NA) res$sig <- ifelse(res$`0.975quant` > 1 & res$`0.975quant` > 1, "pos", res$sig) # figure res |> filter(!variable %in% c("(Intercept)", "(Intercept)1")) |> ggplot(aes(y = label, color = scale, group = scale)) + theme_classic() + geom_point(aes(x = mean), size = 1) + #scale_size_manual(values = c(1, 3)) + scale_color_manual(values = c("#0071bc", "#7fb7dd")) + geom_linerange(aes(xmin = `0.025quant`, xmax = `0.975quant`)) + labs(x = "Odds of having O3 monitor (log scale)") + coord_cartesian(xlim = c(0.8, 1.1)) + geom_vline(xintercept = 1, linetype = "solid") + geom_vline(xintercept = c(0.8, 0.9, 1.1, 1.2), alpha = 0.5, linetype="dotted") + scale_x_continuous(trans = 'log10') + theme(axis.line.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank()) + geom_text(aes(x = (`0.975quant` + 0.02), y=label, label = round(mean, 2)), hjust = 0, fontface = "bold") +#, size = 4) + geom_text(aes(x = 0.8, y = label, label = stringr::str_wrap(label, 30), hjust=0), fontface = "plain", size = 4) ``` ```{r pb} res_lower <- inla_results_pois$inla_pb_l$summary.fixed res_upper <- inla_results_pois$inla_pb_u$summary.fixed res_lower$label <- "lower" res_upper$label <- "upper" res <- rbind(res_lower, res_upper) # res <- o3_res #summary(fit_intx)$coefs.SE.CI res <- tibble::rownames_to_column(res, "variable") res$variable <- ifelse(res$variable == "total_1k", "pop", res$variable) res$variable <- ifelse(res$variable == "total_1k1", "pop1", res$variable) res$label <- case_when(grepl("hisp", res$variable) == TRUE ~ "Hispanic or Latinx", grepl("black", res$variable) == TRUE ~ "Black or African American", grepl("aian", res$variable) == TRUE ~ "American Indian or Alaska Native", grepl("asian", res$variable) == TRUE ~ "Asian", grepl("nhpi", res$variable) == TRUE ~ "Native Hawaiian or Other Pacific Islander", grepl("other", res$variable) == TRUE ~ "Some Other Race", grepl("tom", res$variable) == TRUE ~ "Two or More Races", grepl("pop", res$variable) == TRUE ~ "Population, 1K") res$label <- ifelse(grepl("1", res$variable) == TRUE, paste0(res$label, ", upper"), paste0(res$label, ", lower")) res$scale <- ifelse(grepl("1", res$variable) == TRUE, "upper", "lower") res$mean <- round(exp(res$mean), 3) res$`0.025quant` <- round(exp(res$`0.025quant`), 3) res$`0.975quant` <- round(exp(res$`0.975quant`), 3) res <- res[, c("variable", "mean", "0.025quant", "0.975quant", "scale", "label")] res$sig <- ifelse(res$`0.025quant` < 1 & res$`0.025quant` < 1, "neg", NA) res$sig <- ifelse(res$`0.975quant` > 1 & res$`0.975quant` > 1, "pos", res$sig) # figure res |> filter(!variable %in% c("(Intercept)", "(Intercept)1")) |> ggplot(aes(y = label, color = scale, group = scale)) + theme_classic() + geom_point(aes(x = mean), size = 1) + #scale_size_manual(values = c(1, 3)) + scale_color_manual(values = c("#c1272d", "#df9295")) + geom_linerange(aes(xmin = `0.025quant`, xmax = `0.975quant`)) + labs(x = "Odds of having O3 monitor (log scale)") + coord_cartesian(xlim = c(0.7, 1.4)) + geom_vline(xintercept = 1, linetype = "solid") + geom_vline(xintercept = c(0.8, 0.9, 1.1, 1.2), alpha = 0.5, linetype="dotted") + scale_x_continuous(trans = 'log10') + theme(axis.line.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank()) + geom_text(aes(x = (`0.975quant` + 0.02), y=label, label = round(mean, 2)), hjust = 0, fontface = "bold") +#, size = 4) + geom_text(aes(x = 0.7, y = label, label = stringr::str_wrap(label, 30), hjust=0), fontface = "plain", size = 4) ``` ```{r co} res_lower <- inla_results_pois$inla_co_l$summary.fixed res_upper <- inla_results_pois$inla_co_u$summary.fixed res_lower$label <- "lower" res_upper$label <- "upper" res <- rbind(res_lower, res_upper) # res <- o3_res #summary(fit_intx)$coefs.SE.CI res <- tibble::rownames_to_column(res, "variable") res$variable <- ifelse(res$variable == "total_1k", "pop", res$variable) res$variable <- ifelse(res$variable == "total_1k1", "pop1", res$variable) res$label <- case_when(grepl("hisp", res$variable) == TRUE ~ "Hispanic or Latinx", grepl("black", res$variable) == TRUE ~ "Black or African American", grepl("aian", res$variable) == TRUE ~ "American Indian or Alaska Native", grepl("asian", res$variable) == TRUE ~ "Asian", grepl("nhpi", res$variable) == TRUE ~ "Native Hawaiian or Other Pacific Islander", grepl("other", res$variable) == TRUE ~ "Some Other Race", grepl("tom", res$variable) == TRUE ~ "Two or More Races", grepl("pop", res$variable) == TRUE ~ "Population, 1K") res$label <- ifelse(grepl("1", res$variable) == TRUE, paste0(res$label, ", upper"), paste0(res$label, ", lower")) res$scale <- ifelse(grepl("1", res$variable) == TRUE, "upper", "lower") res$mean <- round(exp(res$mean), 3) res$`0.025quant` <- round(exp(res$`0.025quant`), 3) res$`0.975quant` <- round(exp(res$`0.975quant`), 3) res <- res[, c("variable", "mean", "0.025quant", "0.975quant", "scale", "label")] res$sig <- ifelse(res$`0.025quant` < 1 & res$`0.025quant` < 1, "neg", NA) res$sig <- ifelse(res$`0.975quant` > 1 & res$`0.975quant` > 1, "pos", res$sig) # figure res |> filter(!variable %in% c("(Intercept)", "(Intercept)1")) |> ggplot(aes(y = label, color = scale, group = scale)) + theme_classic() + geom_point(aes(x = mean), size = 1) + #scale_size_manual(values = c(1, 3)) + scale_color_manual(values = c("#00a99d", "#7fd3cd")) + geom_linerange(aes(xmin = `0.025quant`, xmax = `0.975quant`)) + labs(x = "Odds of having O3 monitor (log scale)") + coord_cartesian(xlim = c(0.8, 1.1)) + geom_vline(xintercept = 1, linetype = "solid") + geom_vline(xintercept = c(0.8, 0.9, 1.1, 1.2), alpha = 0.5, linetype="dotted") + scale_x_continuous(trans = 'log10') + theme(axis.line.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank()) + geom_text(aes(x = (`0.975quant` + 0.02), y=label, label = round(mean, 2)), hjust = 0, fontface = "bold") +#, size = 4) + geom_text(aes(x = 0.8, y = label, label = stringr::str_wrap(label, 30), hjust=0), fontface = "plain", size = 4) ```
""" Leetcode 934. Shortest Bridge (medium) 2023-05-21 You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one island. Return the smallest number of 0's you must flip to connect the two islands. Example 1: Input: grid = [[0,1],[1,0]] Output: 1 Example 2: Input: grid = [[0,1,0],[0,0,0],[0,0,1]] Output: 2 Example 3: Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1 """ from typing import List class Solution: """ leetcode solution 1: DFS + BFS Runtime: 391 ms, faster than 71.21% of Python3 online submissions for Shortest Bridge. Memory Usage: 19.4 MB, less than 39.27% of Python3 online submissions for Shortest Bridge. """ def shortestBridge(self, grid: List[List[int]]) -> int: n = len(grid) first_x, first_y = -1, -1 # Find any land cell, treat it as a cell of island A for i in range(n): for j in range(n): if grid[i][j] == 1: first_x, first_y = i, j break moves = ((-1, 0), (1, 0), (0, -1), (0, 1)) # Recursively check the neighboring land cell of current cell grid[x][y] # and add all land cells of island A to bfs_q def dfs(x, y): grid[x][y] = 2 bfs_q.append((x, y)) for dx, dy in moves: cur_x, cur_y = x + dx, y + dy if 0 <= cur_x < n and 0 <= cur_y < n and grid[cur_x][cur_y] == 1: dfs(cur_x, cur_y) # Add all land cells of island A to bfs_q bfs_q = [] dfs(first_x, first_y) distance = 0 while bfs_q: new_bfs_q = [] for x, y in bfs_q: for dx, dy in moves: cur_x, cur_y = x + dx, y + dy if 0 <= cur_x < n and 0 <= cur_y < n: if grid[cur_x][cur_y] == 1: return distance elif grid[cur_x][cur_y] == 0: new_bfs_q.append((cur_x, cur_y)) grid[cur_x][cur_y] = -1 # Once we finish one round without finding land cells of island B, # we will start the next round on all water cells that are 1 cell # further away from island A and increment the distance by 1 bfs_q = new_bfs_q distance += 1 s = Solution() tests = [ ([[0, 1], [1, 0]], 1), ([[0, 1, 0], [0, 0, 0], [0, 0, 1]], 2), ([[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]], 1), ] for inp, exp in tests: res = s.shortestBridge(inp) if res != exp: print('input: ', inp) print('expect: ', exp) print('output: ', res) print() print('Completed testing')
import java.io.File; import java.io.IOException; import java.util.*; public class AudioContentStore { private static ArrayList<AudioContent> contents; private static Map<String, Integer> titleSearch; private static Map<String, ArrayList<Integer>> artistSearch; private static Map<String, ArrayList<Integer>> genreSearch; public AudioContentStore() { audioContentStore(); makeTitleSearchMap(); makeArtistSearchMap(); makeGenreSearchMap(); } // makes map with string title as key and integer index as value public void makeTitleSearchMap() { titleSearch = new HashMap<>(); for (int i = 0; i < contents.size(); i++) { int index = i + 1; titleSearch.put(contents.get(i).getTitle().toLowerCase(), index); } } // makes map with string title as key and arraylist of integer indexes as value public void makeArtistSearchMap() { artistSearch = new HashMap(); int index = 1; for (AudioContent c : contents) { if (c.getType().equals(Song.TYPENAME)) { Song temp = (Song) c; // initializes arraylist if first encounter of author or else creates arraylist from existing indexes ArrayList<Integer> tempIndex = (artistSearch.containsKey(temp.getArtist().toLowerCase())) ? artistSearch.get(temp.getArtist().toLowerCase()) : new ArrayList<>(); tempIndex.add(index); artistSearch.put(temp.getArtist().toLowerCase(), tempIndex); } else { AudioBook temp = (AudioBook) c; // initializes arraylist if first encounter of author or creates arraylist from existing indexes ArrayList<Integer> tempIndex = (artistSearch.containsKey(temp.getAuthor().toLowerCase())) ? artistSearch.get(temp.getAuthor().toLowerCase()) : new ArrayList<>(); tempIndex.add(index); artistSearch.put(temp.getAuthor().toLowerCase(), tempIndex); } index++; } } // makes map with string genre as key and arraylist of integer indexes as value public void makeGenreSearchMap() { genreSearch = new HashMap(); int index = 1; for (AudioContent c : contents) { // only considers song types if (c.getType().equals(Song.TYPENAME)) { Song temp = (Song) c; String genre = temp.getGenre().toString(); // initializes arraylist if first encounter of genre or creates arraylist from existing indexes ArrayList<Integer> tempIndex = (genreSearch.containsKey(genre)) ? genreSearch.get(genre) : new ArrayList<>(); tempIndex.add(index); genreSearch.put(genre, tempIndex); index++; } } } // prints out given title's index and info using titleSearch map public void searchTitle(String title) { if (titleSearch.containsKey(title.toLowerCase())) { int index = titleSearch.get(title.toLowerCase()); System.out.print(index + ". "); contents.get(index-1).printInfo(); } else { System.out.println("No matches for " + title); } } // prints out given artist's indexes and info using artistSearch map public void searchArtist(String artist) { if (artistSearch.containsKey(artist.toLowerCase())) { ArrayList<Integer> index = artistSearch.get(artist.toLowerCase()); for (Integer i : index) { System.out.print(i + ". "); contents.get(i - 1).printInfo(); System.out.println(); } } else { System.out.println("No matches for " + artist); } } // prints out given genre's indexes and info using genreSearch map public void searchGenre(String genre) { if (genreSearch.containsKey(genre.toUpperCase())) { ArrayList<Integer> index = genreSearch.get(genre.toUpperCase()); for (Integer i : index) { System.out.print(i + ". "); contents.get(i - 1).printInfo(); System.out.println(); } } else { System.out.println("No matches for " + genre); } } // getters for maps public static Map<String, Integer> getTitleArtist() { return titleSearch; } public static Map<String, ArrayList<Integer>> getSearchArtist() { return artistSearch; } public static Map<String, ArrayList<Integer>> getSearchGenre() { return genreSearch; } // gets content at specific index public AudioContent getContent(int index) { if (index < 1 || index > contents.size()) { return null; } return contents.get(index-1); } public int getContentSize() { return contents.size(); } // getter for contents arraylist public static ArrayList<AudioContent> getAllContents() { return contents; } public void listAll() { for(int i = 0; i < this.contents.size(); ++i) { int index = i + 1; System.out.print("" + index + ". "); contents.get(i).printInfo(); System.out.println(); } } // creates objects in contents arraylist from reading store text file public void audioContentStore() { contents = new ArrayList<>(); try { Scanner in = new Scanner(new File("store.txt")); while(in.hasNextLine()) { String checkType = in.nextLine(); if (checkType.equals("SONG")) { // stores data for song content String id = in.nextLine(); String title = in.nextLine(); int year = in.nextInt(); int length = in.nextInt(); in.nextLine(); String author = in.nextLine(); String narrator = in.nextLine(); Song.Genre genre = Song.Genre.valueOf(in.nextLine()); int numLyricLines = in.nextInt(); String file = ""; for(int i = 0; i <= numLyricLines; i++) { file = file.concat(in.nextLine() + "\n"); } contents.add(new Song(title, year, id, "SONG", file, length, author, narrator, genre, file)); } else if (checkType.equals("AUDIOBOOK")) { // store data for audiobook content type String id = in.nextLine(); String title = in.nextLine(); int year = in.nextInt(); int length = in.nextInt(); in.nextLine(); String author = in.nextLine(); String narrator = in.nextLine(); ArrayList<String> titles = new ArrayList(); int numChapterTitles = in.nextInt(); in.nextLine(); for(int i = 0; i < numChapterTitles; i++) { titles.add(in.nextLine()); } ArrayList<String> chapters = new ArrayList(); for(int i = 0; i < numChapterTitles; ++i) { int chapterLines = in.nextInt(); in.nextLine(); String chapter = ""; for(int j = 0; j < chapterLines; ++j) { chapter = chapter + in.nextLine() + "\r\n"; } chapters.add(chapter); } contents.add(new AudioBook(title, year, id, "AUDIOBOOK", "", length, author, narrator, titles, chapters)); } } } catch (IOException e) { System.out.println(e.getMessage()); System.exit(1); } } }
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import PropTypes from 'prop-types'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import { DropdownItem, DropdownMenu, DropdownToggle, Input, InputGroup, InputGroupAddon, InputGroupText, UncontrolledDropdown, } from 'reactstrap'; import { findItemByValue } from '.'; export const FilterSearch = (props) => { const { isRightDropdown, label, onClick, onChange, options, value } = props; const hasOptions = options && options.length > 0; const [inputFieldText, setInputFieldText] = useState(''); const innerRef = useRef(null); const handleChange = useCallback(() => { const { value } = innerRef.current; setInputFieldText(value); onChange(value); }, [onChange]); const handleClick = useCallback( ({ label, value }) => () => { setInputFieldText(label); onClick(value); }, [onClick] ); /* eslint-disable react-hooks/exhaustive-deps */ useEffect(() => { if (hasOptions && value) { const optionsItem = findItemByValue(options, value); setInputFieldText(optionsItem ? optionsItem.label : value); } else { setInputFieldText(value || ''); } }, [options, value]); /* eslint-enable react-hooks/exhaustive-deps */ return ( <UncontrolledDropdown data-testid={props['data-testid']}> <DropdownToggle className="w-100 p-0" color="link"> <InputGroup> <Input data-testid={`${props['data-testid']}-input`} disabled={props.disabled} innerRef={innerRef} placeholder={label} type="text" value={inputFieldText} onChange={handleChange} /> <InputGroupAddon addonType="append"> <InputGroupText className="py-1"> <FontAwesomeIcon icon={['far', 'search']} /> </InputGroupText> </InputGroupAddon> </InputGroup> </DropdownToggle> {hasOptions && ( <DropdownMenu className="m-0" right={isRightDropdown} flip={false}> {options.map((item) => ( <DropdownItem key={item.value} onClick={handleClick(item)}> {item.label} </DropdownItem> ))} </DropdownMenu> )} </UncontrolledDropdown> ); }; FilterSearch.propTypes = { 'data-testid': PropTypes.string, disabled: PropTypes.bool, isRightDropdown: PropTypes.bool, label: PropTypes.string, onChange: PropTypes.func.isRequired, onClick: PropTypes.func, options: PropTypes.array, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; FilterSearch.defaultProps = { disabled: false, isRightDropdown: false, label: 'Search', options: [], };
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [https://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.neo4j.cypher.internal.runtime.interpreted.pipes import org.neo4j.cypher.internal.runtime.ClosingIterator import org.neo4j.cypher.internal.runtime.CypherRow import org.neo4j.cypher.internal.runtime.ExpressionCursors import org.neo4j.cypher.internal.runtime.QueryContext import org.neo4j.cypher.internal.runtime.ValuePopulation.populate import org.neo4j.cypher.internal.util.attribution.Id import org.neo4j.kernel.impl.query.QuerySubscriber import org.neo4j.memory.MemoryTracker case class ProduceResultsPipe(source: Pipe, columns: Array[String])(val id: Id = Id.INVALID_ID) extends PipeWithSource(source) { override def isRootPipe: Boolean = true protected def internalCreateResults( input: ClosingIterator[CypherRow], state: QueryState ): ClosingIterator[CypherRow] = { // do not register this pipe as parent as it does not do anything except filtering of already fetched // key-value pairs and thus should not have any stats val subscriber = state.subscriber if (state.prePopulateResults) { val memoryTracker = state.memoryTrackerForOperatorProvider.memoryTrackerForOperator(id.x) val query = state.query val cursors = query.createExpressionCursors() // NOTE: We need to create these through the QueryContext so that they get a profiling tracer if profiling is enabled input.map { original => produceAndPopulate(original, subscriber, query, cursors, memoryTracker) original } } else { input.map { original => produce(original, subscriber) original } } } private def produceAndPopulate( original: CypherRow, subscriber: QuerySubscriber, query: QueryContext, cursors: ExpressionCursors, memoryTracker: MemoryTracker ): Unit = { val nodeCursor = cursors.nodeCursor val relCursor = cursors.relationshipScanCursor val propertyCursor = cursors.propertyCursor var i = 0 subscriber.onRecord() while (i < columns.length) { subscriber.onField( i, populate(original.getByName(columns(i)), query, nodeCursor, relCursor, propertyCursor, memoryTracker) ) i += 1 } subscriber.onRecordCompleted() } private def produce(original: CypherRow, subscriber: QuerySubscriber): Unit = { var i = 0 subscriber.onRecord() while (i < columns.length) { subscriber.onField(i, original.getByName(columns(i))) i += 1 } subscriber.onRecordCompleted() } }
import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import jwtDecode from 'jwt-decode'; import { Navigate } from 'react-router-dom'; import { DecodedUser } from 'src/common/packages/user/types/models/User.model'; import { useLazyGetUserQuery } from 'src/common/store/api/packages/user/userApi'; import { useAppDispatch } from 'src/common/hooks/redux'; import { setUser } from 'src/common/store/slices/packages/user/userSlice'; export type ProtectedRouteProps = { children: JSX.Element; }; export const ConfigurateProtectedRoute = ({ children }: ProtectedRouteProps) => { const [getUser] = useLazyGetUserQuery(); const navigate = useNavigate(); const dispatch = useAppDispatch(); const jwt = localStorage.getItem('accessToken'); if (!jwt) return <Navigate to={'auth/signin'} replace />; const decoded: DecodedUser = jwtDecode(jwt); if (!decoded) return <Navigate to={'auth/signin'} replace />; useEffect(() => { getUser(decoded.id) .unwrap() .then(result => dispatch( setUser({ ...result, }), ), ) .catch(() => navigate('auth/signin')); }, []); return children; };
import React from 'react'; import Avatar from '@material-ui/core/Avatar'; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import Link from '@material-ui/core/Link'; import Grid from '@material-ui/core/Grid'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import Typography from '@material-ui/core/Typography'; import { makeStyles, createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import { Link as RouterLink } from 'react-router-dom'; import { useSnackbar } from 'notistack'; import axios from 'axios'; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: '#174572', }, form: { width: '100%', marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, })); const theme = createMuiTheme({ palette: { primary: { main: '#174572', }, }, }); export default function SignIn(props) { const [email, setEmail] = React.useState(''); const [password, setPassword] = React.useState(''); const { enqueueSnackbar, closeSnackbar } = useSnackbar(); const handleEmailChange = (event) => { setEmail(event.target.value) } const handlePasswordChange = (event) => { setPassword(event.target.value) } const handleAuth = (event) => { event.preventDefault(); let body = { mail: email, password: password }; axios.post('http://localhost:8080/auth/login', body).then(function (response) { props.tokenize(response.data.token); props.id(response.data.user_id); props.role(response.data.user_role); enqueueSnackbar('Success!', {variant: 'success'}); }) .catch(function (error) { enqueueSnackbar('Something went wrong!', {variant: 'error'}); }); } const classes = useStyles(); return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <form className={classes.form} noValidate> <ThemeProvider theme={theme}> <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" autoFocus onChange={handleEmailChange} color='primary' /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" onChange={handlePasswordChange} autoComplete="current-password" color='primary' /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} component={RouterLink} to="/dashboard" onClick={handleAuth} > Sign In </Button> <Grid container> <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> </Grid> </Grid> </ThemeProvider> </form> </div> </Container> ); }
#include "CIdioma.h" #include <iostream> CIdioma *CIdioma::instanciaIdioma = nullptr; CIdioma &CIdioma::getInstance() { if (instanciaIdioma == nullptr) { instanciaIdioma = new CIdioma(); } return *instanciaIdioma; }; CIdioma::CIdioma() { MemNombre = ""; this->ColIdiomas = map<string, Idioma *>(); }; CIdioma::~CIdioma() { map<string, Idioma *>::iterator it; for (it = ColIdiomas.begin(); it != ColIdiomas.end(); ++it) { Idioma *i = it->second; i->~Idioma(); } ColIdiomas.clear(); delete instanciaIdioma; }; bool CIdioma::existeIdioma(string nombre) { return ColIdiomas.find(nombre) != ColIdiomas.end(); }; Idioma *CIdioma::encontrarIdioma(string nombre) { return ColIdiomas.find(nombre)->second; }; set<string *> CIdioma::mostrarIdiomas() { set<string *> s; map<string, Idioma *>::iterator it; for (it = ColIdiomas.begin(); it != ColIdiomas.end(); ++it) { Idioma *i = it->second; string *d = new string(i->getNombre()); s.insert(d); } return s; }; string *CIdioma::getDataIdioma(string nombre) { Idioma *i = ColIdiomas.find(nombre)->second; string *d = new string(i->getNombre()); return d; }; bool CIdioma::ingresoDatos(string nombre) { if (!existeIdioma(nombre)) { Idioma *i = new Idioma(nombre); ColIdiomas.insert(pair<string, Idioma *>(nombre, i)); return true; } else { return false; } }; set<string> CIdioma::listarIdiomas() { set<string> s; map<string, Idioma *>::iterator it; for (it = ColIdiomas.begin(); it != ColIdiomas.end(); ++it) { Idioma *i = it->second; string d = i->getNombre(); s.insert(d); } return s; }; void CIdioma::selecIdioma(string idioma) { if (existeIdioma(idioma)) { MemNombre = idioma; } else { cout << "El idioma no está en el sistema" << endl; } }; set<string > CIdioma::listarNoSuscriptos(string nickname) { CUsuario *cu = &CUsuario::getInstance(); if (!(cu->existeUsuario(nickname))) { return set<string >(); } else { set<Idioma *> suscripciones = cu->listarIdiomasSuscriptos(nickname); set<string > s; map<string, Idioma *>::iterator it; for(it = ColIdiomas.begin(); it != ColIdiomas.end(); ++it){ Idioma *i = it->second; if(suscripciones.find(i) == suscripciones.end()){ string d = i->getNombre(); s.insert(d); } } return s; } }; void CIdioma::suscribirseANotificaciones(string nickname, string idioma) { if (this->ColIdiomas == map<string, Idioma *>()) { cout << "No hay idiomas en el sistema" << endl; } else { Idioma *i = ColIdiomas.find(idioma)->second; CUsuario *cu = &CUsuario::getInstance(); if (!(i->estaSuscrito(nickname)) && (cu->existeUsuario(nickname))) { Usuario *u = cu->buscarUsuario(nickname); i->agregarObservador(u); u->linkObserver(i); } else { cout << "El usuario ya esta suscrito a este idioma" << endl; } } // para probar que se agrega correctamente a la lista // set<Idioma *> suscripciones = cu->listarIdiomasSuscriptos(nickname); // set<Idioma *>::iterator it; // for (it = suscripciones.begin(); it != suscripciones.end(); ++it) // { // cout << "El usuario se ha suscrito a: " << (*it)->getNombre() << endl; // } }; set<string> CIdioma::listarSuscripciones(string nickname) { CUsuario *cu = &CUsuario::getInstance(); if (!(cu->existeUsuario(nickname))) { cout << "El usuario no existe" << endl; return set<string>(); } else { set<Idioma *> suscripciones = cu->listarIdiomasSuscriptos(nickname); set<string> s; map<string, Idioma *>::iterator it; for(it = ColIdiomas.begin(); it != ColIdiomas.end(); ++it){ Idioma *i = it->second; if(suscripciones.find(i) != suscripciones.end()){ string d = i->getNombre(); s.insert(d); } } return s; } }; void CIdioma::eliminarSuscripciones(string nickname, string idioma) { Idioma *i = ColIdiomas.find(idioma)->second; CUsuario *cu = &CUsuario::getInstance(); if (i->estaSuscrito(nickname) && cu->existeUsuario(nickname)) { Usuario *u = cu->buscarUsuario(nickname); u->borrarDataPorIdioma(idioma); i->eliminarObservador(u); u->unlinkObserver(i); } else { cout << "El usuario no esta suscrito a este idioma" << endl; } // para probar que se elimina correctamente de la lista // set<Idioma *> suscripciones = cu->listarIdiomasSuscriptos(nickname); // set<Idioma *>::iterator it; // for (it = suscripciones.begin(); it != suscripciones.end(); ++it) // { // cout << "El usuario se ha suscrito a: " << (*it)->getNombre() << endl; // } }; set<DataNotificacion> CIdioma::consultarNotificaciones(string nickname) { CUsuario *cu = &CUsuario::getInstance(); if (!(cu->existeUsuario(nickname))) { cout << "El usuario no existe" << endl; return set<DataNotificacion>(); } Usuario *u = cu->buscarUsuario(nickname); set<DataNotificacion> notificaciones = u->leerNotificaciones(); u->vaciarNotificaciones(nickname); return notificaciones; };
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { BlogCreateComponent } from './blog-create/blog-create.component'; import { BlogDisplayComponent } from './blog-display/blog-display.component'; import { BlogReadComponent } from './blog-read/blog-read.component'; import { MainComponent } from './main/main.component'; const routes: Routes = [ { path: '', component: MainComponent }, { path: 'blog', component: BlogDisplayComponent }, { path: 'create', component: BlogCreateComponent }, { path: 'main', component: MainComponent }, { path: 'post/:slug', component: BlogReadComponent }, { path: '**', redirectTo: '' }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using LootLocker; using LootLocker.Requests; namespace LootLocker.Requests { [System.Serializable] public class LootLockerSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string platform => CurrentPlatform.GetString(); public string player_identifier { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerSessionRequest(string player_identifier) { this.player_identifier = player_identifier; } public LootLockerSessionRequest() { } } [System.Serializable] public class LootLockerWhiteLabelSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string email { get; set; } public string password { get; set; } // DEPRECATED PARAMETER public string token { get; set; } public string game_version => LootLockerConfig.current.game_version; [Obsolete("StartWhiteLabelSession with password is deprecated")] public LootLockerWhiteLabelSessionRequest(string email, string password, string token) { this.email = email; this.password = password; this.token = token; } [Obsolete("StartWhiteLabelSession with password is deprecated")] public LootLockerWhiteLabelSessionRequest(string email, string password) { this.email = email; this.password = password; this.token = null; } public LootLockerWhiteLabelSessionRequest(string email) { this.email = email; this.password = null; this.token = null; } public LootLockerWhiteLabelSessionRequest() { this.email = null; this.password = null; this.token = null; } } [System.Serializable] public class LootLockerSessionResponse : LootLockerResponse { public string session_token { get; set; } public int player_id { get; set; } public bool seen_before { get; set; } public string public_uid { get; set; } public DateTime player_created_at { get; set; } public bool check_grant_notifications { get; set; } public bool check_deactivation_notifications { get; set; } public int[] check_dlcs { get; set; } public int xp { get; set; } public int level { get; set; } public LootLockerLevel_Thresholds level_thresholds { get; set; } public int account_balance { get; set; } } public class LootLockerGuestSessionResponse : LootLockerSessionResponse { public string player_identifier { get; set; } } [System.Serializable] public class LootLockerGoogleSessionResponse : LootLockerSessionResponse { public string player_identifier { get; set; } public string refresh_token { get; set; } } [System.Serializable] public class LootLockerAppleSessionResponse : LootLockerSessionResponse { public string player_identifier { get; set; } public string refresh_token { get; set; } } [System.Serializable] public class LootLockerEpicSessionResponse : LootLockerSessionResponse { public string refresh_token { get; set; } } [System.Serializable] public class LootLockerLevel_Thresholds { public int current { get; set; } public bool current_is_prestige { get; set; } public int? next { get; set; } public bool next_is_prestige { get; set; } } [System.Serializable] public class LootLockerNintendoSwitchSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string nsa_id_token { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerNintendoSwitchSessionRequest(string nsa_id_token) { this.nsa_id_token = nsa_id_token; } } [System.Serializable] public class LootLockerEpicSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string id_token { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerEpicSessionRequest(string id_token) { this.id_token = id_token; } } [System.Serializable] public class LootLockerEpicRefreshSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string refresh_token { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerEpicRefreshSessionRequest(string refresh_token) { this.refresh_token = refresh_token; } } public class LootLockerXboxOneSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string xbox_user_token { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerXboxOneSessionRequest(string xbox_user_token) { this.xbox_user_token = xbox_user_token; } } public class LootLockerGoogleSignInSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string id_token { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerGoogleSignInSessionRequest(string id_token) { this.id_token = id_token; } } public class LootLockerGoogleRefreshSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string refresh_token { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerGoogleRefreshSessionRequest(string refresh_token) { this.refresh_token = refresh_token; } } public class LootLockerAppleSignInSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string apple_authorization_code { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerAppleSignInSessionRequest(string apple_authorization_code) { this.apple_authorization_code = apple_authorization_code; } } public class LootLockerAppleRefreshSessionRequest : LootLockerGetRequest { public string game_key => LootLockerConfig.current.apiKey?.ToString(); public string refresh_token { get; private set; } public string game_version => LootLockerConfig.current.game_version; public LootLockerAppleRefreshSessionRequest(string refresh_token) { this.refresh_token = refresh_token; } } } namespace LootLocker { public partial class LootLockerAPIManager { public static void Session(LootLockerSessionRequest data, Action<LootLockerSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.authenticationRequest; if(data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerResponse.Deserialize<LootLockerSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.deviceID = data?.player_identifier; onComplete?.Invoke(response); }, false); } public static void WhiteLabelSession(LootLockerWhiteLabelSessionRequest data, Action<LootLockerSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.whiteLabelLoginSessionRequest; if(data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerResponse.Deserialize<LootLockerSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.deviceID = ""; onComplete?.Invoke(response); }, false); } public static void GuestSession(LootLockerSessionRequest data, Action<LootLockerGuestSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.guestSessionRequest; if(data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerGuestSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerResponse.Deserialize<LootLockerGuestSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.deviceID = (data as LootLockerSessionRequest)?.player_identifier; onComplete?.Invoke(response); }, false); } public static void GoogleSession(LootLockerGoogleSignInSessionRequest data, Action<LootLockerGoogleSessionResponse> onComplete) { if (data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerGoogleSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); GoogleSession(json, onComplete); } public static void GoogleSession(LootLockerGoogleRefreshSessionRequest data, Action<LootLockerGoogleSessionResponse> onComplete) { if (data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerGoogleSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); GoogleSession(json, onComplete); } private static void GoogleSession(string json, Action<LootLockerGoogleSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.googleSessionRequest; if (string.IsNullOrEmpty(json)) { return; } LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerGoogleSessionResponse.Deserialize<LootLockerGoogleSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.deviceID = response.player_identifier; LootLockerConfig.current.refreshToken = response.refresh_token; onComplete?.Invoke(response); }, false); } public static void NintendoSwitchSession(LootLockerNintendoSwitchSessionRequest data, Action<LootLockerSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.nintendoSwitchSessionRequest; if(data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerResponse.Deserialize<LootLockerSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.deviceID = ""; onComplete?.Invoke(response); }, false); } public static void EpicSession(LootLockerEpicSessionRequest data, Action<LootLockerEpicSessionResponse> onComplete) { if (data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerEpicSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); EpicSession(json, onComplete); } public static void EpicSession(LootLockerEpicRefreshSessionRequest data, Action<LootLockerEpicSessionResponse> onComplete) { if (data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerEpicSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); EpicSession(json, onComplete); } private static void EpicSession(string json, Action<LootLockerEpicSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.epicSessionRequest; LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerResponse.Deserialize<LootLockerEpicSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.refreshToken = response.refresh_token; LootLockerConfig.current.deviceID = ""; onComplete?.Invoke(response); }, false); } public static void XboxOneSession(LootLockerXboxOneSessionRequest data, Action<LootLockerSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.xboxSessionRequest; if(data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerResponse.Deserialize<LootLockerSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.deviceID = ""; onComplete?.Invoke(response); }, false); } public static void AppleSession(LootLockerAppleSignInSessionRequest data, Action<LootLockerAppleSessionResponse> onComplete) { if (data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerAppleSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); AppleSession(json, onComplete); } public static void AppleSession(LootLockerAppleRefreshSessionRequest data, Action<LootLockerAppleSessionResponse> onComplete) { if(data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerAppleSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); AppleSession(json, onComplete); } private static void AppleSession(string json, Action<LootLockerAppleSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.appleSessionRequest; if (string.IsNullOrEmpty(json)) { return; } LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { var response = LootLockerAppleSessionResponse.Deserialize<LootLockerAppleSessionResponse>(serverResponse); LootLockerConfig.current.token = response.session_token; LootLockerConfig.current.deviceID = response.player_identifier; LootLockerConfig.current.refreshToken = response.refresh_token; onComplete?.Invoke(response); }, false); } public static void EndSession(LootLockerSessionRequest data, Action<LootLockerSessionResponse> onComplete) { EndPointClass endPoint = LootLockerEndPoints.endingSession; if(data == null) { onComplete?.Invoke(LootLockerResponseFactory.InputUnserializableError<LootLockerAppleSessionResponse>()); return; } string json = JsonConvert.SerializeObject(data); LootLockerConfig.AddDevelopmentModeFieldToJsonStringIfNeeded(ref json); // TODO: Deprecated, remove in version 1.2.0 LootLockerServerRequest.CallAPI(endPoint.endPoint, endPoint.httpMethod, json, (serverResponse) => { LootLockerResponse.Deserialize(onComplete, serverResponse); }); } } }
require 'metasploit/framework' require 'metasploit/framework/tcp/client' require 'metasploit/framework/login_scanner/base' require 'metasploit/framework/login_scanner/rex_socket' require 'ruby_smb' module Metasploit module Framework module LoginScanner # This is the LoginScanner class for dealing with the Server Messaging # Block protocol. class SMB include Metasploit::Framework::Tcp::Client include Metasploit::Framework::LoginScanner::Base include Metasploit::Framework::LoginScanner::RexSocket # Constants to be used in {Result#access_level} module AccessLevels # Administrative access. For SMB, this is defined as being # able to successfully Tree Connect to the `ADMIN$` share. # This definition is not without its problems, but suffices to # conclude that such a user will most likely be able to use # psexec. ADMINISTRATOR = "Administrator" # Guest access means our creds were accepted but the logon # session is not associated with a real user account. GUEST = "Guest" end CAN_GET_SESSION = true DEFAULT_REALM = 'WORKSTATION' LIKELY_PORTS = [ 445 ] LIKELY_SERVICE_NAMES = [ "smb" ] PRIVATE_TYPES = [ :password, :ntlm_hash ] REALM_KEY = Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN module StatusCodes CORRECT_CREDENTIAL_STATUS_CODES = [ "STATUS_ACCOUNT_DISABLED", "STATUS_ACCOUNT_EXPIRED", "STATUS_ACCOUNT_RESTRICTION", "STATUS_INVALID_LOGON_HOURS", "STATUS_INVALID_WORKSTATION", "STATUS_LOGON_TYPE_NOT_GRANTED", "STATUS_PASSWORD_EXPIRED", "STATUS_PASSWORD_MUST_CHANGE", ].freeze.map(&:freeze) end # @!attribute dispatcher # @return [RubySMB::Dispatcher::Socket] attr_accessor :dispatcher # If login is successul and {Result#access_level} is not set # then arbitrary credentials are accepted. If it is set to # Guest, then arbitrary credentials are accepted, but given # Guest permissions. # # @param domain [String] Domain to authenticate against. Use an # empty string for local accounts. # @return [Result] def attempt_bogus_login(domain) if defined?(@result_for_bogus) return @result_for_bogus end cred = Credential.new( public: Rex::Text.rand_text_alpha(8), private: Rex::Text.rand_text_alpha(8), realm: domain ) @result_for_bogus = attempt_login(cred) end # (see Base#attempt_login) def attempt_login(credential) begin connect rescue ::Rex::ConnectionError => e result = Result.new( credential:credential, status: Metasploit::Model::Login::Status::UNABLE_TO_CONNECT, proof: e, host: host, port: port, protocol: 'tcp', service_name: 'smb' ) return result end proof = nil begin realm = credential.realm || "" username = credential.public || "" password = credential.private || "" client = RubySMB::Client.new(self.dispatcher, username: username, password: password, domain: realm) status_code = client.login if status_code == WindowsError::NTStatus::STATUS_SUCCESS # Windows SMB will return an error code during Session # Setup, but nix Samba requires a Tree Connect. Try admin$ # first, since that will tell us if this user has local # admin access. Fall back to IPC$ which should be accessible # to any user with valid creds. begin tree = client.tree_connect("\\\\#{host}\\admin$") # Check to make sure we can write a file to this dir if tree.permissions.add_file == 1 access_level = AccessLevels::ADMINISTRATOR end rescue Exception => e client.tree_connect("\\\\#{host}\\IPC$") end end case status_code.name when *StatusCodes::CORRECT_CREDENTIAL_STATUS_CODES status = Metasploit::Model::Login::Status::DENIED_ACCESS when 'STATUS_SUCCESS' status = Metasploit::Model::Login::Status::SUCCESSFUL when 'STATUS_ACCOUNT_LOCKED_OUT' status = Metasploit::Model::Login::Status::LOCKED_OUT when 'STATUS_LOGON_FAILURE', 'STATUS_ACCESS_DENIED' status = Metasploit::Model::Login::Status::INCORRECT else status = Metasploit::Model::Login::Status::INCORRECT end rescue ::Rex::ConnectionError, Errno::EINVAL => e status = Metasploit::Model::Login::Status::UNABLE_TO_CONNECT proof = e rescue RubySMB::Error::UnexpectedStatusCode => e status = Metasploit::Model::Login::Status::INCORRECT ensure client.disconnect! end if status == Metasploit::Model::Login::Status::SUCCESSFUL && credential.public.empty? access_level ||= AccessLevels::GUEST end result = Result.new(credential: credential, status: status, proof: proof, access_level: access_level) result.host = host result.port = port result.protocol = 'tcp' result.service_name = 'smb' result end def connect disconnect self.sock = super self.dispatcher = RubySMB::Dispatcher::Socket.new(self.sock) end def set_sane_defaults self.connection_timeout = 10 if self.connection_timeout.nil? self.max_send_size = 0 if self.max_send_size.nil? self.send_delay = 0 if self.send_delay.nil? end end end end end
--- title: OscillatorNode.type slug: Web/API/OscillatorNode/type tags: - API - OscillatorNode - Property - Reference - Type - Web Audio API browser-compat: api.OscillatorNode.type --- <p>{{ APIRef("Web Audio API") }}</p> <div> <p> The <strong><code>type</code></strong> property of the {{ domxref("OscillatorNode") }} interface specifies what shape of {{interwiki("wikipedia", "waveform")}} the oscillator will output. There are several common waveforms available, as well as an option to specify a custom waveform shape. The shape of the waveform will affect the tone that is produced. </p> </div> <h2 id="Syntax">Syntax</h2> <pre class="brush: js"><em>OscillatorNode</em>.type = <em>type</em>;</pre> <h3 id="Value">Value</h3> <p> A {{domxref("DOMString")}} specifying the shape of oscillator wave. The different available values are: </p> <dl> <dt><code>sine</code></dt> <dd>A {{interwiki("wikipedia", "sine wave")}}. This is the default value.</dd> <dt><code>square</code></dt> <dd> A {{interwiki("wikipedia", "square wave")}} with a {{interwiki("wikipedia", "duty cycle")}} of 0.5; that is, the signal is "high" for half of each period. </dd> <dt><code>sawtooth</code></dt> <dd>A {{interwiki("wikipedia", "sawtooth wave")}}.</dd> <dt><code>triangle</code></dt> <dd>A {{interwiki("wikipedia", "triangle wave")}}.</dd> <dt><code>custom</code></dt> <dd> A custom waveform. You never set <code>type</code> to <code>custom</code> manually; instead, use the {{domxref("OscillatorNode.setPeriodicWave", "setPeriodicWave()")}} method to provide the data representing the waveform. Doing so automatically sets the <code>type</code> to <code>custom</code>. </dd> </dl> <h3 id="Exceptions">Exceptions</h3> <dl> <dt><code>InvalidStateError</code></dt> <dd> The value <code>custom</code> was specified. To set a custom waveform, just call {{domxref("OscillatorNode.setPeriodicWave", "setPeriodicWave()")}}. Doing so automatically sets the type for you. </dd> </dl> <h2 id="Example">Example</h2> <p> The following example shows basic usage of an {{ domxref("AudioContext") }} to create an oscillator node. For an applied example, check out our <a href="https://mdn.github.io/violent-theremin/">Violent Theremin demo</a> (<a href="https://github.com/mdn/violent-theremin/blob/gh-pages/scripts/app.js" >see app.js</a > for relevant code). </p> <pre class="brush: js;highlight[7]"> // create web audio api context var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // create Oscillator node var oscillator = audioCtx.createOscillator(); oscillator.type = 'square'; oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz oscillator.start();</pre > <h2 id="Specifications">Specifications</h2> {{Specifications}} <h2 id="Browser_compatibility">Browser compatibility</h2> <p>{{Compat}}</p> <h2 id="See_also">See also</h2> <ul> <li> <a href="/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API" >Using the Web Audio API</a > </li> </ul>
<x-app-layout> <x-slot name="header"> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> {{ __('Dashboard') }} </h2> </x-slot> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.css"/> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/> <div class="m-5"> <div class="grid grid-cols-1 md:grid-cols-3 gap-4"> <div class="col-span-2"> <h1>Manage Products</h1> <h5>Click here to <a href="{{ URL::to('dashboard/products/create') }}"><button class="btn btn-success btn-sm uppercase">Add a Product</button></a></h5> <h5>Drag and Drop the table rows and <button class="btn btn-success btn-sm uppercase" onclick="window.location.reload()">Refresh</button> to update the Product Order.</h5> </div> <div class="border-2 border-dashed border-gray-300"> <p class="m-2">Legend:</p> <div class="m-2 p-2 bg-green-100">Enabled</div> <div class="m-2 p-2 bg-red-100">Disabled</div> </div> </div> <hr> @if ($message = Session::get('message')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif <table id="table" class="table table-bordered"> <thead> <tr> <th>#</th> <th class="w-1/6">Image</th> <th>Product Code</th> <th>Name</th> <th>Tagline</th> <th>Price</th> <th>Actions</th> </tr> </thead> <tbody id="tablecontents"> @foreach($products as $product) <tr class="row1 @if($product->enabled == 0) bg-red-100 @else bg-green-100 @endif " data-id="{{ $product->id }}"> <td class="pl-3"><i class="fa fa-sort"></i>{{$product->sort_order}}</td> <td><img src="{{$product->images[0]->src}}" class="w-full"> </td> <td>{{ $product->product_code }}</td> <td>{{ $product->name }}</td> <td>{{$product->tagline}}</td> <td>&pound;{{$product->price}} <span class="text-gray-200">({{$product->price}} ex vat)</span></td> <td class="text-right"> <a href="{{ URL::to('dashboard/products/' . $product->slug . '/edit') }}"><i class="far fa-edit"></i></a> @if($product->enabled == 0) <form method="POST" name="enable-product-form" id="enable-product-form" class="inline-block" action="{{route('dashboard.products.enable', [$product->slug])}}"> @csrf <button type="submit"><i class="far fa-check-circle" style="color: #007bff;"></i></button> </form> @else <form method="POST" name="disable-product-form" id="disable-product-form" class="inline-block" action="{{route('dashboard.products.disable', [$product->slug])}}" onsubmit="return confirm('Are you sure you want to disable this product?');" > @csrf <button type="submit"><i class="fas fa-ban" style="color: #007bff;"></i></button> </form> @endif <form method="POST" name="delete-product-form" id="delete-product-form" class="inline-block" action="{{route('dashboard.products.destroy', [$product->slug])}}" onsubmit="return confirm('Are you sure you want to delete this product?');" > @method('delete') @csrf <button type="submit"><i class="far fa-trash-alt" style="color: #007bff;"></i></button> </form> </td> </tr> @endforeach </tbody> </table> </div> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.js"></script> <script type="text/javascript"> $(function () { $("#table").DataTable(); $( "#tablecontents" ).sortable({ items: "tr", cursor: 'move', opacity: 0.6, update: function() { sendOrderToServer(); } }); function sendOrderToServer() { var order = []; var token = $('meta[name="csrf-token"]').attr('content'); $('tr.row1').each(function(index,element) { order.push({ id: $(this).attr('data-id'), position: index+1 }); }); $.ajax({ type: "POST", dataType: "json", url: "{{ url('dashboard/products/sort') }}", data: { order: order, _token: token }, success: function(response) { if (response.status == "success") { console.log(response); } else { console.log(response); } } }); } }); </script> </x-app-layout>
package org.orient.otc.dm.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.orient.otc.common.database.entity.BaseEntity; import org.orient.otc.dm.enums.IsHolidayEnum; import org.orient.otc.dm.enums.IsTradingDayEnum; import org.orient.otc.dm.enums.IsWeekendEnum; import java.io.Serializable; import java.time.LocalDate; @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName(autoResultMap = true) @ApiModel public class Calendar extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @TableId(value="id", type= IdType.AUTO) private Integer id; /** * 年份 */ @ApiModelProperty(value = "年份") private Integer year; /** * 日期 */ @ApiModelProperty(value = "日期") private LocalDate date; /** * 是否是假日 */ @ApiModelProperty(value = "是否是假日") private IsHolidayEnum isHoliday; /** * 是否是交易日 */ @ApiModelProperty(value = "是否是交易日") private IsTradingDayEnum isTradingDay; /** * 是否是周末 */ @ApiModelProperty(value = "是否是周末") private IsWeekendEnum isWeekend; }
def binary_search(list, item): low = 0 high = len(list) - 1 while low <= high: mid = (low + high) // 2 guess = list[mid] if guess == item: return mid if guess > item: return mid - 1 else: low = mid + 1 return False my_list = [1, 3, 5, 7, 9] print(binary_search(my_list, 3)) print(binary_search(my_list, 8)) print(binary_search(my_list, 9)) # class BinarySearch(): # # def search_iterative(self, list, item): # # low and high keep track of which part of the list you'll search in. # low = 0 # high = len(list) - 1 # # # While you haven't narrowed it down to one element ... # while low <= high: # # ... check the middle element # mid = (low + high) // 2 # guess = list[mid] # # Found the item. # if guess == item: # return mid # # The guess was too high. # if guess > item: # high = mid - 1 # # The guess was too low. # else: # low = mid + 1 # # # Item doesn't exist # return None # # def search_recursive(self, list, low, high, item): # # Check base case # if high >= low: # # mid = (high + low) // 2 # guess = list[mid] # # # If element is present at the middle itself # if guess == item: # return mid # # # If element is smaller than mid, then it can only # # be present in left subarray # elif guess > item: # return self.search_recursive(list, low, mid - 1, item) # # # Else the element can only be present in right subarray # else: # return self.search_recursive(list, mid + 1, high, item) # # else: # # Element is not present in the array # return None # # # if __name__ == "__main__": # # We must initialize the class to use the methods of this class # bs = BinarySearch() # my_list = [1, 3, 5, 7, 9] # # print(bs.search_iterative(my_list, 3)) # => 1 # # # 'None' means nil in Python. We use to indicate that the item wasn't found. # print(bs.search_iterative(my_list, -1)) # => None
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LoginComponent } from './pages/login/login.component'; import { RegisterComponent } from './pages/register/register.component'; import { WelcomeComponent } from './pages/welcome/welcome.component'; import { authGuard } from './auth/auth.guard'; const routes: Routes = [ { path:'login', component:LoginComponent }, { path:'register', component:RegisterComponent }, { path:'welcome', component:WelcomeComponent, canActivate: [authGuard] }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
package com.example.springstart; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class JavaSpringStartApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(JavaSpringStartApplication.class, args); NoteService noteService = context.getBean(NoteService.class); //To check NoteService Note note1 = new Note(); note1.setTitle("1Title"); note1.setContent("1Context"); System.out.println("add() = " + noteService.add(note1)); System.out.println("listAll() = " + noteService.listAll()); System.out.println("getById() = " + noteService.getById(note1.getId())); note1.setContent("1Context After Update"); note1.setTitle("1Title After Update"); noteService.update(note1); System.out.println("getById() after update = " + noteService.getById(note1.getId())); noteService.deleteById(note1.getId()); System.out.println("listAll() after delete = " + noteService.listAll()); } }
package com.michaelflisar.composepreferences.core import android.content.res.Configuration import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.material3.Icon import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.tooling.preview.Preview import com.michaelflisar.composepreferences.core.classes.Dependency import com.michaelflisar.composepreferences.core.classes.PreferenceStyle import com.michaelflisar.composepreferences.core.classes.PreferenceStyleDefaults import com.michaelflisar.composepreferences.core.composables.BasePreference import com.michaelflisar.composepreferences.core.composables.PreferenceItemSetup import com.michaelflisar.composepreferences.core.composables.PreviewPreference import com.michaelflisar.composepreferences.core.hierarchy.PreferenceScope /** * A section header preference item * * &nbsp; * * **Basic Parameters:** all params not described here are derived from [com.michaelflisar.composepreferences.core.composables.BasePreference], check it out for more details * */ @Composable fun PreferenceScope.PreferenceSectionHeader( // Special // Base Preference enabled: Dependency = Dependency.Enabled, visible: Dependency = Dependency.Enabled, title: @Composable () -> Unit, subtitle: @Composable (() -> Unit)? = null, icon: (@Composable () -> Unit)? = null, preferenceStyle: PreferenceStyle = PreferenceStyleDefaults.header() ) { BasePreference( setup = PreferenceItemSetup(ignoreForceNoIconInset = true), enabled = enabled, visible = visible, title = { CompositionLocalProvider( LocalTextStyle provides MaterialTheme.typography.titleMedium ) { title() } }, subtitle = subtitle, icon = icon, preferenceStyle = preferenceStyle ) } @Preview @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark") @Composable private fun Preview() { PreviewPreference { PreferenceSectionHeader( title = { Text(text = "Section Header") } ) } } @Preview @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark") @Composable private fun Preview2() { PreviewPreference { PreferenceSectionHeader( icon = { Icon(Icons.Default.Info, null) }, title = { Text(text = "Section Header") }, subtitle = { Text(text = "This is a description") } ) } }