text
stringlengths
184
4.48M
# Routing ✨ > HappyX provides powerful routing system for both parts (`SSG` and `SPA`) 💡 ## Path Params 🍍 Every route has typed `path params` 🙂 Here is example syntax of route 💡 ```nim "/user{id:int}" ``` This route will match any text like this: - `/user1` - `/user100` - `/user1293` And you can use `id` as immutable declared variable 🔥 ```nim "/user{id:int}": echo id ``` ## Typing 👮 > Every `path param` is typed 💡 Routes `"/user{id:int}"` and `"/user{id:word}"` is different routes that matches different variables. In case of `{id:int}` variable is integer. In case of `{id:word}` variable is string. Here is list of all available types: - `int`: matches any integer - `float`: matches any float - `bool`: matches any boolean (y, n, yes, no, true, false, 1, 0, on, off) - `word`: matches any word as string - `string`: matches any string excludes `'/'` chars - `path`: matches any string includes `'/'` chars - `regex`: matches any regex pattern as string (as example `{var:/[a-z][0-9]+/}`) ## (Im)mutable Params ⚙ Route path params is immutable by default. You can change it by add `[m]` after type: - `$arg:type[m]=val` - `$arg:type[m]` - `$arg[m]` - `$arg?[m]` ## pathParams Macro 🛠 macro `pathParams` provides path params assignment. With it you can assign path params and use it in routes. Example syntax: ```nim pathParams: # means that `arg` of type `int` is optional mutable param with default value `5` arg? int[m] = 5 # means that `arg1` of type `string` is optional mutable param with default value `"Hello"` arg1[m] = "Hello" # means that `arg2` of type `string` is immutable regex param arg2 re"\d+u" # means that `arg3` of type `float` is mutable param arg3 float[m] # means that `arg4` of type `int` is optional mutable param with default value `10` arg4: type int mutable optional default = 10 ``` ## Mounting 🔌 HappyX routing supports mounting also 🔥 Here is mounting declaration ```nim mount Settings: "/": ... mount Profile: mount "/settings" -> Settings mount "/config" -> Settings ``` And here is mounting usage 🎈 ```nim serve(...): # or appRoutes mount "/profile" -> Profile ``` --- This documentation was generated with [`HapDoc`](https://github.com/HapticX/hapdoc)
package herokuapptest; import browserfactory.BaseTest; import org.junit.Before; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.time.Duration; public class LoginTest extends BaseTest { String baseurl = "http://the-internet.herokuapp.com/login"; @Before public void setUp() { openBrowser(baseurl); driver.manage().window().maximize();// maximise the browser //implicit time to driver driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); } @Test public void loginWithValidCredentials() { WebElement username = driver.findElement(By.id("username")); username.sendKeys("tomsmith"); WebElement password = driver.findElement(By.id("password")); password.sendKeys("SuperSecretPassword!"); WebElement login = driver.findElement(By.xpath("//i[@class='fa fa-2x fa-sign-in']")); login.click(); WebElement verifyLogin = driver.findElement(By.xpath("//h2[text()=' Secure Area']")); System.out.println(verifyLogin); String actualText = verifyLogin.getText(); String expectedText = "Secure Area"; Assert.assertEquals(expectedText, actualText); } @Test public void verifyUsernameErrorMessage() { WebElement username = driver.findElement(By.id("username")); username.sendKeys("tomsmith1"); WebElement password = driver.findElement(By.id("password")); password.sendKeys("SuperSecretPassword!"); WebElement login = driver.findElement(By.xpath("//i[@class='fa fa-2x fa-sign-in']")); login.click(); WebElement verifyErrorMsg = driver.findElement(By.xpath("//div[@class='flash error']")); String actualText = verifyErrorMsg.getText().substring(0, 25); String expectedText = "Your username is invalid!"; Assert.assertEquals(expectedText, actualText); } @Test public void verifyPasswordMessage() { WebElement username = driver.findElement(By.id("username")); username.sendKeys("tomsmith"); WebElement password = driver.findElement(By.id("password")); password.sendKeys("SuperSecretPassword"); WebElement login = driver.findElement(By.xpath("//i[@class='fa fa-2x fa-sign-in']")); login.click(); WebElement verifyErrorMsg = driver.findElement(By.xpath("//div[@class='flash error']")); String actualText = verifyErrorMsg.getText().substring(0, 25); String expectedText = "Your password is invalid!"; Assert.assertEquals(expectedText, actualText); } }
import './Login-m.css'; import googleLogo from './google.png'; import api from '../../api/api.js'; import React, { useState, useReducer, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAuth } from "../../components/Auth/AuthWrapper.js"; const Login = () => { const { login } = useAuth(); const [formData, setFormData] = useReducer((formData, newItem) => { return ({ ...formData, ...newItem }); }, { userName: "", password: "" }); const navigate = useNavigate(); const [errorMessage, setErrorMessage] = useState(null); const [loginFailed, setLoginFailed] = useState(false); // Track login failure const doLogin = async (e) => { e.preventDefault(); // Prevent default form submission try { console.log('Attempting login with:', formData.userName, formData.password); const response = await login(formData.userName, formData.password); console.log('Login successful.'); navigate("/Personal"); } catch (error) { console.error('Login failed:', error); setErrorMessage(error.message || "An error occurred during login."); setLoginFailed(true); // Set login failure state to true alert("Login failed. Please check your credentials and try again."); navigate("/Login"); } }; useEffect(() => { console.log('Current path:', window.location.pathname); }, [navigate]); // Function to clear form fields const clearFormFields = () => { setFormData({ userName: "", password: "" }); }; // Function to handle alert on login failure const handleLoginFailureAlert = () => { if (loginFailed) { setLoginFailed(false); clearFormFields(); // Remove } }; return ( <> <div className="t-Login"> <h1>เข้าสู่ระบบ</h1> </div> <div className="login"> <h2>ยืนยันตัวตนด้วยบริการของ Google</h2> <h3>โดยใช้ Email Account ของสถาบันฯ</h3> <div className="GoogleLogin"> <button className="GoogleCss" onClick={() => { console.log('Google button clicked') }}> <img src={googleLogo} alt="google-logo" /> <span>LOGIN</span> </button> </div> <h4>หรือ</h4> <h2>ยืนยันตัวตนด้วยบริการของสถาบันฯ</h2> <form className="form-login" onSubmit={doLogin}> <input value={formData.userName} onChange={(e) => setFormData({ userName: e.target.value })} type="text" /> <input value={formData.password} onChange={(e) => setFormData({ password: e.target.value })} type="password" /> <input type="submit" value="เข้าสู่ระบบ"></input> </form> </div> {handleLoginFailureAlert()} {/* Render alert */} </> ) } export default Login;
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> /** * @brief allocating continuous memory block for 2d array * * @param rows_number * @param cols_number * @return double** */ double **calloc_2d_array(int rows_number, int cols_number); /** * @brief prints "An Error Has Occurred" * */ void other_error(void); /** * @brief free the continuous memmory block which allocated with calloc_2d_array() * * @param arr */ void free_2d(double **arr); /** * @brief calculating the weighted adjacency matrix * * @param points array of points represented as array * @param points_number number of points * @param point_dim dimension of point * @return 2d array */ double **wam(double **points, int points_number, int point_dim); /** * @brief calculating the diagonal degree matrix * * @param points array of points represented as array * @param points_number number of points * @param point_dim dimension of point * @return 2d array */ double **ddg(double **points, int points_number, int point_dim); /** * @brief calculating the normalized graph laplacian * * @param points array of points represented as array * @param points_number number of points * @param point_dim dimension of point * @return 2d array */ double **lnorm(double **points, int points_number, int point_dim); /** * @brief * * @param A matrix * @param dim dimension of matrix A * @return double** 2d array where the first row is the eiganvalues and the rest is matrix V which its columns are eiganvectors of A. * more precisely, the column below eignvalue at the first row is its eiganvector */ double **jacobi(double **A, int dim); /** * @brief K-means algorithm which clusters the given points to K centoids and return them * * @param K number of desired clusters * @param max_iter maximum of iterations to allow * @param points points to cluster * @param centroids initial centroids for the algorithm * @param points_length number of points * @param point_length dimension of point * @param eps epsilon - for desired precision * @return double** array of centroids */ double **k_means(int const K, int const max_iter, double **points, double **centroids, int const points_length, int const point_length, double eps);
import React from 'react'; import Layout from '../components/layout'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import Switch from '@material-ui/core/Switch'; import Container from '@material-ui/core/Container'; import PickerItem from '../components/pickerItem'; import Button from '@material-ui/core/Button'; import Select from '@material-ui/core/Select'; import MenuItem from '@material-ui/core/MenuItem'; import { makeStyles } from '@material-ui/core/styles'; const Settings = ({ modeToggle, mode, setPrimary, setSecondary }) => { const SettingItem = ({ label, control }) => { return ( <div className={classes.settingItem}> <Typography>{label}</Typography> {control} </div> ); }; const resetColors = () => { setPrimary('def'); setSecondary('def'); }; const useStyles = makeStyles((thm) => ({ settingItem: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginLeft: thm.spacing(0.75), marginTop: thm.spacing(1.5) }, section: { marginBottom: thm.spacing(5) } })); const classes = useStyles(); return ( <Layout title='Settings' thin> <div className={classes.section}> <Typography variant='h4' component='h2' gutterBottom> Units </Typography> <Divider /> <Container maxWidth='md'> <SettingItem label='Metric units' control={<Switch size='small' />} /> <SettingItem label='Date format' control={ <Select value={3}> <MenuItem value={1}>MM/DD/YY</MenuItem> <MenuItem value={2}>DD/MM/YY</MenuItem> <MenuItem value={3}>YY/MM/DD</MenuItem> </Select> } /> <SettingItem label='Currency' control={ <Select value={1}> <MenuItem value={1}>$</MenuItem> <MenuItem value={2}>€</MenuItem> <MenuItem value={3}>£</MenuItem> <MenuItem value={4}>¥</MenuItem> <MenuItem value={5}>₪</MenuItem> </Select> } /> <SettingItem label='Decimal seperator' control={ <Select value={2}> <MenuItem value={1}>Comma</MenuItem> <MenuItem value={2}>Period</MenuItem> </Select> } /> </Container> </div> <div className={classes.section}> <Typography variant='h4' component='h2' gutterBottom> Display </Typography> <Divider /> <Container maxWidth='md'> <SettingItem label='Dark theme' control={ <Switch size='small' onChange={modeToggle} checked={mode === 'dark'} /> } /> <PickerItem type='primary' set={setPrimary} /> <PickerItem type='secondary' set={setSecondary} /> <SettingItem label='Reset colors' control={ <Button size='small' onClick={resetColors}> Reset </Button> } /> </Container> </div> </Layout> ); }; export default Settings;
import Avatar from './avatar' import DateFormatter from './date-formatter' import CoverImage from './cover-image' import Link from 'next/link' import type Author from '../interfaces/author' type Props = { title: string coverImage: string date: string excerpt: string author: Author slug: string } const HeroPost = ({ title, coverImage, date, excerpt, author, slug, }: Props) => { return ( <section className="my-16 p-8 bg-white drop-shadow-md rounded-md "> <div className="mb-16 "> <h3 className="font-bold text-stone-800 mb-4 text-5xl lg:text-6xl leading-tight"> <Link as={`/posts/${slug}`} href="/posts/[slug]" className="hover:underline"> {title} </Link> </h3> <div className="mb-4 md:mb-8 text-sm text-stone-600"> <DateFormatter dateString={date} /> </div> <p className="text-stone-700 text-lg leading-relaxed mb-8">{excerpt}</p> <Avatar name={author.name} picture={author.picture} /> </div> <div className="mb-8 md:mb-16"> <CoverImage title={title} src={coverImage} slug={slug} /> </div> </section> ) } export default HeroPost
import './styles.css' import {Routes, Route,BrowserRouter} from "react-router-dom"; import { CssBaseline, ThemeProvider } from '@mui/material'; import {useState, useRef, useEffect} from "react" import {useMode, ColorModeContext} from "./theme" import * as FRAGS from "@thatopen/fragments"; import * as OBC from "@thatopen/components"; import ViewerFiber from './scenes/viewer/viewerFiber'; import ThreeViewer from './scenes/viewer/threeViewer'; import {ThreeScene} from './scenes/viewer/threeViewer'; import DashBoard from './scenes/dashboard/dashBoard'; import SetUpIfcComponents from "./components/setUpIfcComponents"; import Layout from './scenes/global/Layout'; import {GetBuildingElements} from "./utilities/IfcUtilities"; import {ComponentsProvider} from './context/ComponentsContext' import {BuildingElementsProvider} from './context/BuildingElementsContext' //TODO CREATE A CONTEXT FOR THE OBC.COMPONENTS function App() { const containerRef = useRef(null); const [ifcFile,setIfcFile] = useState(); const [components,setComponents] = useState(); const [theme,colorMode] = useMode(); const [buildingElements, setBuildingElements] = useState([]); const handleIFCLoad = (loadedifcFile) => { if(!loadedifcFile) return; console.log("App: upload complete") const fetchBuildingElements = async () => { console.log("fetching building elements",loadedifcFile) if(loadedifcFile && components) { const newBuildingElements = await GetBuildingElements(loadedifcFile,components); setBuildingElements(newBuildingElements); setComponents(components); console.log(buildingElements.length," building elements found and set") } }; fetchBuildingElements(); setIfcFile(loadedifcFile); } useEffect(() => { // const newComponents = SetUpIfcComponents(containerRef); const newComponents = new OBC.Components(); console.log("App: COMPONENTS CREATED",newComponents) setComponents(newComponents); },[]) const handleComponentsLoad = (newComponents) => { if(!newComponents) return; console.log("App: upload complete") setComponents(newComponents); } return ( <> <ColorModeContext.Provider value={colorMode}> <ThemeProvider theme={theme}> <CssBaseline/> <ComponentsProvider components={components}> <BuildingElementsProvider buildingElements={buildingElements}> <BrowserRouter> <div style={{ display: 'flex', height: '100%' }}> {/* Flex container */} <main ref={containerRef} style={{flex: 1, padding: "0"}}> <Routes> {/* <Route path='/' element={<LandingPage/>} /> */} <Route path='/*' element={<Layout components={components} onIfcFileLoad={handleIFCLoad}/>} > <Route path='' element={<ThreeScene ifcModel={ifcFile}/>} /> <Route path='dashboard' element={<DashBoard loadedBuildingElements={buildingElements}/>} /> </Route> </Routes> </main> </div> </BrowserRouter> </BuildingElementsProvider> </ComponentsProvider> </ThemeProvider> </ColorModeContext.Provider> </> ) } export default App
== Introduction It's time for us to put our cluster to work and deploy a workload! We're going to build an example Java application, https://github.com/redhat-mw-demos/microsweeper-quarkus/tree/ARO[microsweeper], using https://quarkus.io/[Quarkus] (a Kubernetes-native Java stack) and https://azure.microsoft.com/en-us/products/postgresql/[Azure Database for PostgreSQL]. After configuring the database, we will use both Quarkus, a Kubernetes-native Java framework optimized for containers, and Source-to-Image (S2I), a toolkit for building container images from source code, to deploy the microsweeper application. == Create Azure Database for PostgreSQL instance . First, let's create a namespace (also known as a project in OpenShift). To do so, run the following command: + [source,sh,role=execute] ---- oc new-project microsweeper-ex ---- + .Sample Output [source,text,options=nowrap] ---- Now using project "microsweeper-ex" on server "https://api.c90qz1cy.eastus.aroapp.io:6443". You can add applications to this project with the 'new-app' command. For example, try: oc new-app rails-postgresql-example to build a new example application in Ruby. Or use kubectl to deploy a simple Kubernetes application: kubectl create deployment hello-node --image=k8s.gcr.io/e2e-test-images/agnhost:2.33 -- /agnhost serve-hostname ---- . Create the Azure Database for Postgres server resource. To do so, run the following command (this command will take ~ 5mins) + [source,sh,role=execute] ---- az postgres server create --resource-group openenv-${GUID} \ --location eastus --sku-name GP_Gen5_2 \ --name microsweeper-${GUID} --storage-size 51200 \ --admin-user myAdmin --admin-pass %generated_password% \ --public 0.0.0.0 ---- + .Sample Output [source,text,options=nowrap] ---- Checking the existence of the resource group 'openenv-qsd7p'... Resource group 'openenv-qsd7p' exists ? : True Creating postgres Server 'microsweeper-qsd7p' in group 'openenv-qsd7p'... Your server 'microsweeper-qsd7p' is using sku 'GP_Gen5_2' (Paid Tier). Please refer to https://aka.ms/postgres-pricing for pricing details Configuring server firewall rule, 'azure-access', to accept connections from all Azure resources... Make a note of your password. If you forget, you would have to reset your password with 'az postgres server update -n microsweeper-qsd7p -g openenv-qsd7p -p <new-password>'. { "additionalProperties": {}, "administratorLogin": "myAdmin", [...Output omitted...] ---- + [NOTE] ==== For the sake of the workshop we are creating a public database that any host in Azure can connect to. In a real world scenario you would create a private database and connect to it over a private link service ==== . Make sure the PostgreSQL client software is installed on your bastion VM: + [source,sh,role=execute] ---- sudo dnf -y install postgresql ---- . Check connectivity to the database. To do so, run the following command: + [source,sh,role=execute] ---- psql \ "host=microsweeper-${GUID}.postgres.database.azure.com port=5432 dbname=postgres user=myAdmin@microsweeper-${GUID}.postgres.database.azure.com password=%generated_password% sslmode=require" \ -c "select now();" ---- + .Sample Output [source,text,options=nowrap] ---- ------------------------------- 2023-04-24 20:44:38.088556+00 (1 row) ---- == Build and deploy the Microsweeper app Now that we've got an Azure managed PostgreSQL instance up and running, let's build and deploy our application. . In order to build the application you will need the Java JDK 17 and the Quarkus CLI installed. Java JDK 17 is already installed on your bastion VM so let's install the Quarkus CLI: + [source,sh,role=execute] ---- curl -Ls https://sh.jbang.dev | bash -s - trust add https://repo1.maven.org/maven2/io/quarkus/quarkus-cli/ curl -Ls https://sh.jbang.dev | bash -s - app install --fresh --force quarkus@quarkusio source $HOME/.bashrc ---- . Double check the Quarkus CLI version: + [source,sh,role=execute] ---- quarkus --version ---- + .Sample Output [source,text,options=nowrap] ---- 3.1.0.Final ---- . Now, let's clone the application from GitHub to our local bastion VM. To do so, run the following command: + [source,sh,role=execute] ---- cd $HOME git clone https://github.com/rh-mobb/aro-workshop-app.git ---- + .Sample Output [source,text,options=nowrap] ---- Cloning into 'aro-workshop-app'... remote: Enumerating objects: 152, done. remote: Counting objects: 100% (16/16), done. remote: Compressing objects: 100% (14/14), done. remote: Total 152 (delta 12), reused 2 (delta 2), pack-reused 136 Receiving objects: 100% (152/152), 6.57 MiB | 31.29 MiB/s, done. Resolving deltas: 100% (55/55), done. ---- . Next, let's change directory into the newly cloned Git repository. To do so, run the following command: + [source,sh,role=execute] ---- cd $HOME/aro-workshop-app ---- . Next, we will add the OpenShift extension to the Quarkus CLI. To do so, run the following command: + [source,sh,role=execute] ---- quarkus ext add openshift ---- + .Sample Output [source,text,options=nowrap] ---- Looking for the newly published extensions in registry.quarkus.io [SUCCESS] ✅ Extension io.quarkus:quarkus-openshift has been installed ---- . We also want Quarkus to be able to use OpenShift ConfigMaps and Secrets: + [source,sh,role=execute] ---- quarkus ext add kubernetes-config ---- + .Sample Output [source,text,options=nowrap] ---- Looking for the newly published extensions in registry.quarkus.io [SUCCESS] ✅ Extension io.quarkus:quarkus-openshift has been installed ---- . Create a OpenShift secret containing Database credentials for Quarkus to use: + [source,sh,role=execute] ---- cat << EOF | oc apply -f - --- apiVersion: v1 kind: Secret metadata: name: microsweeper-secret namespace: microsweeper-ex type: Opaque stringData: PG_URL: jdbc:postgresql://microsweeper-${GUID}.postgres.database.azure.com:5432/postgres PG_USER: myAdmin@microsweeper-${GUID}.postgres.database.azure.com PG_PASS: %generated_password% EOF ---- + .Sample Output [source,text,options=nowrap] ---- secret/microsweeper-secret created ---- . Now, we'll configure Quarkus to use the PostgreSQL database that we created earlier in this section. To do so, we'll create an `application.properties` file using by running the following command: + [source,sh,role=execute] ---- cat <<"EOF" > $HOME/aro-workshop-app/src/main/resources/application.properties # Database configurations %prod.quarkus.datasource.db-kind=postgresql %prod.quarkus.datasource.jdbc.url=${PG_URL} %prod.quarkus.datasource.username=${PG_USER} %prod.quarkus.datasource.password=${PG_PASS} %prod.quarkus.datasource.jdbc.driver=org.postgresql.Driver %prod.quarkus.hibernate-orm.database.generation=drop-and-create %prod.quarkus.hibernate-orm.database.generation=update # OpenShift configurations %prod.quarkus.kubernetes-client.trust-certs=true %prod.quarkus.kubernetes.deploy=true %prod.quarkus.kubernetes.deployment-target=openshift %prod.quarkus.openshift.build-strategy=docker %prod.quarkus.openshift.expose=true %prod.quarkus.openshift.deployment-kind=Deployment %prod.quarkus.container-image.group=microsweeper-ex %prod.quarkus.openshift.env.secrets=microsweeper-secret EOF ---- . Now that we've provided the proper configuration, we will build our application. We'll do this using https://github.com/openshift/source-to-image[source-to-image], a tool built-in to OpenShift. To start the build and deploy, run the following command: + [source,sh,role=execute] ---- quarkus build --no-tests ---- + .Sample Output [source,text,options=nowrap] ---- [INFO] Scanning for projects... Downloading from central: https://repo.maven.apache.org/maven2/io/quarkus/platform/quarkus-maven-plugin/2.11.2.Final/quarkus-maven-plugin-2.11.2.Final.pom Downloaded from central: https://repo.maven.apache.org/maven2/io/quarkus/platform/quarkus-maven-plugin/2.11.2.Final/quarkus-maven-plugin-2.11.2.Final.pom (6.9 kB at 11 kB/s) [...Output omitted...] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 02:41 min [INFO] Finished at: 2023-04-24T20:58:59Z [INFO] ------------------------------------------------------------------------ ---- + [INFO] ==== Quarkus will build the .jar locally and then work with the OpenShift build system to inject it into a Red Hat UBI image, save that to the inbuild OpenShift registry, and then run the resulting image in OpenShift. ==== . We want to see custom metrics from the Quarkus app (they're exposed by the Quarkus micrometer plugin) so we can configure a Prometheus `ServiceMonitor` resource to watch for the applications label. + [source,sh,role=execute] ---- cat << EOF | oc apply -f - --- apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: labels: k8s-app: microsweeper-monitor name: microsweeper-monitor namespace: microsweeper-ex spec: endpoints: - interval: 30s targetPort: 8080 path: /q/metrics scheme: http selector: matchLabels: app.kubernetes.io/name: microsweeper-appservice EOF ---- + .Sample Output [source,text,options=nowrap] ---- servicemonitor.monitoring.coreos.com/microsweeper-monitor created ---- . Change back to your previous working directory + [source,sh,role=execute] ---- cd $HOME ---- == Review Let's take a look at what this command did, along with everything that was created in your cluster. Return to your tab with the OpenShift Web Console. === Container Images From the Administrator perspective, expand _Builds_ and then _ImageStreams_, and select the _microsweeper-ex_ project. image::../media/web-console-imagestreams.png[OpenShift Web Console - Imagestreams] You will see two images that were created on your behalf when you ran the quarkus build command. There is one image for `openjdk-11` that comes with OpenShift as a Universal Base Image (UBI) that the application will run under. With UBI, you get highly optimized and secure container images that you can build your applications with. For more information on UBI please read this https://www.redhat.com/en/blog/introducing-red-hat-universal-base-image[article]. The second image you see is the the `microsweeper-appservice` image. This is the image for the application that was built automatically for you and pushed to the built-in container registry inside of OpenShift. === Image Build How did those images get built you ask? Back on the OpenShift Web Console, click on _BuildConfigs_ and then the _microsweeper-appservice_ entry. image::../media/web-console-buildconfigs.png[OpenShift Web Console - BuildConfigs] image::../media/web-console-microsweeper-appservice-buildconfig.png[OpenShift Web Console - microsweeper-appservice BuildConfig] When you ran the `quarkus build` command, this created the BuildConfig you can see here. In our quarkus settings, we set the deployment strategy to build the image using Docker. The Dockerfile file from the git repo that we cloned was used for this BuildConfig. A build configuration describes a single build definition and a set of triggers for when a new build is created. Build configurations are defined by a BuildConfig, which is a REST object that can be used in a POST to the API server to create a new instance. You can read more about BuildConfigs https://docs.openshift.com/container-platform/latest/cicd/builds/understanding-buildconfigs.html[here]. Once the BuildConfig was created, the source-to-image process kicked off a Build of that BuildConfig. The build is what actually does the work in building and deploying the image. We started with defining what to be built with the BuildConfig and then actually did the work with the Build. You can read more about Builds https://docs.openshift.com/container-platform/latest/cicd/builds/understanding-image-builds.html[here]. To look at what the build actually did, click on Builds tab and then into the first Build in the list. image::../media/web-console-builds.png[OpenShift Web Console - Builds] On the next screen, explore around. Look specifically at the YAML definition of the build and the logs to see what the build actually did. If you build failed for some reason, the logs are a great first place to start to look at to debug what happened. image::../media/web-console-build-logs.png[OpenShift Web Console - Build Logs] === Image Deployment After the image was built, the source-to-image process then deployed the application for us. In the quarkus properties file, we specified that a deployment should be created. You can view the deployment under _Workloads_ \-> _Deployments_, and then click on the Deployment name. image::../media/web-console-deployments.png[OpenShift Web Console - Deployments] Explore around the deployment screen, check out the different tabs, look at the YAML that was created. image::../media/web-console-deployment-yaml.png[OpenShift Web Console - Deployment YAML] Look at the pod the deployment created, and see that it is running. image::../media/web-console-deployment-pods.png[OpenShift Web Console - Deployment Pods] The last thing we will look at is the route that was created for our application. In the quarkus properties file, we specified that the application should be exposed to the Internet. When you create a Route, you have the option to specify a hostname. To start with, we will just use the default domain that comes with ARO (`useast.aroapp.io` in our case). In next section, we will expose the same application to a custom domain leveraging Azure Front Door. You can read more about routes in the https://docs.openshift.com/container-platform/latest/networking/routes/route-configuration.html[Red Hat documentation]. From the OpenShift Web Console menu, click on _Networking_\->__Routes__, and the _microsweeper-appservice_ route. image::../media/web-console-routes.png[OpenShift Web Console - Routes] === Test the application While in the route section of the OpenShift Web Console, click the URL under _Location_: image::../media/web-console-route-link.png[OpenShift Web Console - Route Link] You can also get the the URL for your application using the command line: [source,sh,role=execute] ---- oc -n microsweeper-ex get route microsweeper-appservice -o jsonpath='{.spec.host}' ; echo ---- .Sample Output [source,text,options=nowrap] ---- microsweeper-appservice-microsweeper-ex.apps.c90qz1cy.eastus.aroapp.io ---- === View custom metrics for the App Switch the OpenShift Web Console to the Developer view, select the project `microsweeper-ex` and go to menu:Observe[Metrics] and type `process_uptime_seconds` into custom metrics. Switch the timeframe to `5min`. [INFO] ==== While you're here, you might also want to look at the Dashboard tab to see the Project's CPU/Memory usage. ==== == Summary Here you learned how to: * Create Azure Database for PostgreSQL instance. * Build and deploy the Microsweeper app.
/*********** * Class: BudgetsDetailPage * * Purpose: * The purpose of this class is to show information about certain entries in a particular store * * Manager Functions: * BudgetsDetailPage() * Initialize a BudgetsDetailPage * BudgetsDetailPage(Budget) * Initialize a BudgetsDetailPage with a certain store name to search for * * * Methods: * OnAppearing() * Initialize the list when the page appears to the user * SetStoreBudgetEntries() * Query the database and set up the list * BudgetEntrySearchBarChanged(object, TextChangedEventArgs) * Refresh list for search results * ***********/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using System.Collections.ObjectModel; using TrackIt_Mobile.Models; namespace TrackIt_Mobile.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class BudgetsDetailPage : ContentPage { ObservableCollection<Budget> budgets; private string Storename { get; set; } /* Purpose: Initialize the page * Input: None * Output: Page initialized */ public BudgetsDetailPage() { InitializeComponent(); } /* Purpose: Initialize the page * Input: Budget * Output: Page initialized */ public BudgetsDetailPage(Budget budget) { InitializeComponent(); Storename = budget.StoreName; } /* Purpose: Queries the database to display information * Input: None * Output: Data is listed to be formated to user */ protected override async void OnAppearing() { base.OnAppearing(); budgets = new ObservableCollection<Budget>(); await SetStoreBudgetEntries(); BudgetEntriesCollectionView.ItemsSource = budgets; } /* Purpose: Runs async method to add query results to list * Input: None * Output: List */ private async Task SetStoreBudgetEntries() { List<Budget> budgetEntriesForStore = await App.Database.GetBudgetEntriesForStore(Storename); foreach(Budget budget in budgetEntriesForStore) { budgets.Add(budget); } } /* Purpose: Refresh the list based on what is typed in search bar * Input: object, TextChangedEventArgs * Output: Filtered List */ private void BudgetEntrySearchBarChanged(object sender, TextChangedEventArgs e) { string textValues = e.NewTextValue.ToLower(); var budgetsFilteredList = budgets.Where(b => b.Date.ToString().ToLower().Contains(textValues)); BudgetEntriesCollectionView.ItemsSource = budgetsFilteredList; } } }
import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; public class Main { public static void main(String[] args) { Album arjitAlbum = new Album("Arjit Singh", "Arijit's album"); Album alanAlbum = new Album("Alen Walker", "Walker's Album" ); arjitAlbum.addSongToAlbum("Kesaria", 3.5); arjitAlbum.addSongToAlbum("Tum kya mile", 4.2); arjitAlbum.addSongToAlbum("Lal Ishq", 5.1); alanAlbum.addSongToAlbum("Faded",3.5); alanAlbum.addSongToAlbum("Alone",4.1); alanAlbum.addSongToAlbum("Darkside",2.5); LinkedList<Song> myPlaylist = new LinkedList<>(); // myplaylist System.out.println(arjitAlbum.addToPlaylistFromAlbum("Kesaria",myPlaylist)); System.out.println(arjitAlbum.addToPlaylistFromAlbum(2,myPlaylist)); System.out.println(arjitAlbum.addToPlaylistFromAlbum(5,myPlaylist)); System.out.println(alanAlbum.addToPlaylistFromAlbum("Alone",myPlaylist)); System.out.println(alanAlbum.addToPlaylistFromAlbum(3,myPlaylist)); play(myPlaylist) ; } private static void play(LinkedList<Song> myPlaylist) { if(myPlaylist.size() == 0) { System.out.println("Your playlist is empty"); return; } ListIterator<Song> itr = myPlaylist.listIterator(); System.out.println("Now Playing:" + itr.next()); boolean wasNext = true; Scanner sc = new Scanner(System.in); printMenu(); boolean quit = false; while(!quit) { System.out.println("Please enter your choice"); int choice = sc.nextInt(); switch(choice) { case 1: break; case 2: if(wasNext == false) { itr.next(); wasNext = true; } if(!itr.hasNext()) { System.out.println("You have reached the end of the playlist"); } else { System.out.println("Currently playing" + itr.next()); wasNext = true; } break; case 3: if(wasNext == true) { itr.previous(); wasNext = false; } if(!itr.hasPrevious()) { System.out.println("You are at start of the playlist: "); } else { System.out.println("Currently playing: " + itr.previous()); wasNext = false; } break; case 4: if(wasNext == true) { System.out.println("Currently playing" +itr.previous()); wasNext = false; } else { System.out.println("Currently playing"+itr.next()); wasNext = true; } break; case 5: break; case 6: printsongs(myPlaylist); break; case 7: quit = true; break; default: System.out.println("Enter the correct choice"); } } return ; } private static void printsongs(LinkedList<Song> myPlaylist) { for(Song song : myPlaylist ) { System.out.println(song); } return ; } private static void printMenu() { System.out.println("1. Show the menu again"); System.out.println("2. Play next song"); System.out.println("3. Play the previous song"); System.out.println("4. Play current song"); System.out.println("5. Delete current song from playlist"); System.out.println("6. Print all the songs in the playlist"); System.out.println("7. Quit the application"); } }
import 'dart:async'; import 'package:flutter/material.dart'; class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { static const twentyFiveMinutes = 1500; int totalSeconds = twentyFiveMinutes; bool isRunning = false; int totalPomodoros = 0; late Timer timer; void onTick(Timer timer) { if (totalSeconds == 0) { setState(() { totalPomodoros++; isRunning = false; totalSeconds = twentyFiveMinutes; }); timer.cancel(); } else { setState(() { totalSeconds--; }); } } void onStardPredssed() { // 1초마다 onTick 수행 timer = Timer.periodic( const Duration(seconds: 1), onTick, ); setState(() { isRunning = true; }); } void onPausePredssed() { timer.cancel(); setState(() { isRunning = false; }); } void onResetTimePressed() { setState(() { totalSeconds = twentyFiveMinutes; }); } void onResetPomodorosPressed() { setState(() { totalPomodoros = 0; }); } String formatTime(int seconds) { var duration = Duration(seconds: seconds); return duration.toString().substring(2, 7); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).backgroundColor, body: Column( children: [ Flexible( flex: 1, child: Container( alignment: Alignment.bottomCenter, child: Text( formatTime(totalSeconds), style: TextStyle( color: Theme.of(context).cardColor, fontSize: 90, fontWeight: FontWeight.w600, ), ), ), ), Flexible( flex: 2, child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( iconSize: 120, color: Theme.of(context).cardColor, onPressed: isRunning ? onPausePredssed : onStardPredssed, icon: Icon( isRunning ? Icons.pause_circle_outline : Icons.play_circle_outlined, ), ), IconButton( iconSize: 40, color: Theme.of(context).cardColor, onPressed: onResetTimePressed, icon: const Icon(Icons.restore_outlined), ), ], ), ), ), Flexible( flex: 1, child: Row( children: [ Expanded( child: Container( decoration: BoxDecoration( color: Theme.of(context).cardColor, // borderRadius: BorderRadius.circular(50), // 위에만 둥글게 borderRadius: const BorderRadius.vertical( top: Radius.circular(40), ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Pomodoros', style: TextStyle( fontSize: 20, fontWeight: FontWeight.w600, color: Theme.of(context).textTheme.headline1!.color, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '$totalPomodoros', style: TextStyle( fontSize: 60, fontWeight: FontWeight.w600, color: Theme.of(context) .textTheme .headline1! .color, ), ), IconButton( iconSize: 30, color: Theme.of(context).cardColor, onPressed: onResetPomodorosPressed, icon: Icon( Icons.settings_backup_restore_outlined, color: Theme.of(context) .textTheme .headline1! .color, ), ), ], ), ], ), ), ), ], ), ), ], ), ); } }
import http import json import typing as tp from urllib.parse import parse_qsl from .request import Request from .response import JsonResponse, Response from .router import Route class SlowAPI: def __init__(self): self.routes: tp.List[Route] = [] self.middlewares = [] def __call__(self, environ, start_response): resp_headers = [] body = [b""] is_paths_coincided = False response: tp.Optional[tp.Union[Response, JsonResponse]] = None path_ = environ["PATH_INFO"] if path_[-1] == "/" and path_ != "/": path = path_[:-1] method = environ["REQUEST_METHOD"] query = dict(parse_qsl(environ["QUERY_STRING"])) body = environ["wsgi.input"] headers = {k[5:]: v for k, v in environ.items() if k.startswith("HTTP_")} request = Request(path, method, query, body, headers) for route in self.routes: all_match, is_path_coincided, params_names, params_values = route.match( request.method, request.path ) if all_match: if params_names and params_values: response = self.dynamic_path_handler( route.func, request, params_names, params_values ) else: response = self.static_path_handler(route.func, request) break if is_path_coincided: is_paths_coincided = True if response: status = response.status body_1 = "" if isinstance(response, JsonResponse): body_1 = json.dumps(response.data, default=response.serializer) elif isinstance(response, Response): body_1 = str(response.body) body = [body_1.encode()] if response.content_type: resp_headers.append("CONTENT_TYPE", response.content_type) resp_headers.append("CONTENT_LENGTH", str(len(body[0]))) if response.headers: resp_headers.append(list(response.headers.items())) elif is_paths_coincided: status = 405 else: status = 404 status_phrase = str(http.HTTPStatus(status).value) + " " + http.HTTPStatus(status).phrase start_response(status_phrase, resp_headers) return body def route(self, path=None, method="GET", **options): def decorator(func): data = [] methods = [] if isinstance(path, (tuple, list, set, dict)): data = list(path) elif path: data = [path] for particular_path in data or ["/"]: if isinstance(method, (tuple, list, set, dict)): methods = list(method) elif method: methods = [method] for particular_method in methods: particular_method = particular_method.upper() route = Route(particular_path, particular_method, func) self.routes.append(route) return func return decorator def get(self, path=None, **options): return self.route(path, method="GET", **options) def post(self, path=None, **options): return self.route(path, method="POST", **options) def patch(self, path=None, **options): return self.route(path, method="PATCH", **options) def put(self, path=None, **options): return self.route(path, method="PUT", **options) def delete(self, path=None, **options): return self.route(path, method="DELETE", **options) def add_middleware(self, middleware) -> None: self.middlewares.append(middleware)
/* eslint-disable @next/next/no-img-element */ "use client" import React, { useState } from 'react' import { HiOutlineMail } from 'react-icons/hi' import { BsFillPersonLinesFill } from 'react-icons/bs' import Profile from '../assets/profile.png' import Image from 'next/image' import { Link } from 'react-scroll' //Icons and Logos import { FaBars, FaTimes, FaGithub, FaLinkedin, FaLink, FaGit } from 'react-icons/fa' import { BiDetail, BiHomeAlt, BiUser } from 'react-icons/bi' import { GiGamepadCross } from 'react-icons/gi' import { HiOutlineMailOpen } from 'react-icons/hi' import PSLogo from '../assets/logos/playstation.svg' import XboxLogo from '../assets/logos/xbox.svg' import NintendoLogo from '../assets/logos/nintendo.svg' export const Navbar = () => { const [menuClick, setMenuClick] = useState(false) const [logoCycle, setLogoCycle] = useState(0) const logos = [PSLogo, XboxLogo, NintendoLogo] const logoColour = ['#0172D0', '#2ca243', '#dd2020'] const [logoColourCycle, setLogoColourCycle] = useState(logoColour[0]) const currentLogo = logoCycle % logos.length const toggleMenu = () => { setMenuClick(!menuClick) if(!menuClick) { const nextLogo = (logoCycle + 1) % logos.length setLogoCycle(nextLogo) setLogoColourCycle(logoColour[currentLogo]) } } const [navbar, setNavbar] = useState(false) const hamburgerClick = () => setNavbar(!navbar) return( <div className="flex justify-center"> <div className={`w-full fixed flex justify-center items-center px-4 transition-all duration-500`} > <div className={`hidden md:flex md:justify-between md:items-center md:px-4 md:my-10 transition-all duration-500 ${ menuClick ? 'w-[400px] h-[80px]' : 'w-[80px] h-[80px]' } text-gray-300 rounded-full cursor-pointer`} onClick={toggleMenu} style={{ ...(menuClick ? {} : { backgroundImage: `url(${logos[logoCycle].src})`, backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundColor: logoColourCycle, }), backgroundColor: logoColourCycle }} > {/* Nav Menu - Desktop */} {menuClick ? ( <ul className='hidden md:flex items-center flex-grow justify-center'> <li className=''> <Link to='home' smooth={true} duration={300}><BiHomeAlt size={30} /></Link> </li> <li> <Link to='about' smooth={true} duration={300}><BiUser size={30} /></Link> </li> <li> <Link to='skills' smooth={true} duration={300}><BiDetail size={30} /></Link> </li> <li> <Link to='project' smooth={true} duration={300}><GiGamepadCross size={30} /></Link> </li> <li> <Link to='contact' smooth={true} duration={300}><HiOutlineMailOpen size={30} /></Link> </li> </ul> ) : null} </div> {/* Nav Menu - Hamburger */} <div onClick={hamburgerClick} className='md:hidden z-10 my-10'> {!navbar ? <FaBars /> : <FaTimes />} </div> {/* Nav Menu - Mobile */} <ul className={!navbar ? 'hidden' : 'absolute top-0 left-0 w-full h-screen bg-[#0a192f] flex flex-col justify-center items-center text-gray-300'} > <li className='py-6 text-4xl'> <Link onClick={hamburgerClick} to='home' smooth={true} duration={300}>Home</Link> </li> <li className='py-6 text-4xl'> <Link onClick={hamburgerClick} to='about' smooth={true} duration={300}>About</Link> </li> <li className='py-6 text-4xl'> <Link onClick={hamburgerClick} to='skills' smooth={true} duration={300}>Skills & Experience</Link> </li> <li className='py-6 text-4xl'> <Link onClick={hamburgerClick} to='project' smooth={true} duration={300}>Projects</Link> </li> <li className='py-6 text-4xl'> <Link onClick={hamburgerClick} to='contact' smooth={true} duration={300}>Contact</Link> </li> </ul> {/* Social Icons */} <div className='hidden lg:flex fixed flex-col justify-center items-center bottom-0 left-0 w-full' > <ul className='flex'> <div className='w-[160px] h-[70px]'> <li className='rounded-tl-lg flex justify-center items-center mt-10 hover:mt-[20px] duration-300 bg-[#0077B5]'> <a className='flex flex-col justify-between items-center w-full text-gray-300' href='/'> <FaLinkedin size={30} /> LinkedIn </a> </li> </div> <div className='w-[160px] h-[70px]'> <li className='flex justify-center items-center mt-10 hover:mt-[20px] duration-300 bg-[#171515]'> <a className='flex flex-col justify-between items-center w-full text-gray-300' href='/'> <FaGithub size={30} /> Github </a> </li> </div> <div className='w-[160px] h-[70px]'> <li className='flex justify-center items-center mt-10 hover:mt-[20px] duration-300 bg-[#F4B400]'> <a className='flex flex-col justify-between items-center w-full text-black' href='/'> <HiOutlineMail size={30} color='black' /> Email </a> </li> </div> <div className='w-[160px] h-[70px]'> <li className='rounded-tr-lg flex justify-center items-center mt-10 hover:mt-[20px] duration-300 bg-[#D6D2C7]'> <a className='flex flex-col justify-between items-center w-full text-black' href='/'> <BsFillPersonLinesFill size={30} color='black' /> Resumé </a> </li> </div> </ul> </div> </div> </div> ) }
use axum::{extract::Query, http::StatusCode, response::IntoResponse, routing::get, Json, Router}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct Model { key_one: String, key_two: String, } #[derive(Serialize, Deserialize, Debug)] pub struct Prefix { p: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct HealthCheck { status: String, } #[tokio::main] async fn main() { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .json() .with_target(false) .without_time() .init(); let address = std::env::var("BIND_ADDRESS").expect("BIND_ADDRESS is required"); let app = Router::new() .route("/route", get(handler)) .route("/health", get(health)); let listener = tokio::net::TcpListener::bind(address.clone()) .await .unwrap(); tracing::info!("Up and running ... listening on {}", address); axum::serve(listener, app).await.unwrap(); } async fn handler(query: Query<Prefix>) -> Result<impl IntoResponse, StatusCode> { let prefix: String; let passed_value = &query.p; if let Some(s) = passed_value { prefix = String::from(s.as_str()); } else { prefix = String::from("Unknown"); } tracing::info!("(Request)={}", prefix); let m: Model = Model { key_two: format!("({})Field 2", prefix), key_one: format!("({})Field 1", prefix), }; Ok(Json(m)) } async fn health() -> Result<impl IntoResponse, StatusCode> { let healthy = HealthCheck { status: String::from("Healthy"), }; Ok(Json(healthy)) }
# Laravel Storyblok CSS Class helpers --- - [Creating CSS class names](#creating-css-class-names) [![Latest Version on Packagist](https://img.shields.io/packagist/v/riclep/laravel-storyblok-css.svg?style=flat-square)](https://packagist.org/packages/riclep/laravel-storyblok-css) [![Total Downloads](https://img.shields.io/packagist/dt/riclep/laravel-storyblok-css.svg?style=flat-square)](https://packagist.org/packages/riclep/laravel-storyblok-css) [![Twitter](https://img.shields.io/twitter/follow/riclep.svg?style=social&label=Follow)](https://twitter.com/intent/follow?screen_name=riclep) [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/M4M2C42W6) A helper to create CSS class names from a Block’s properties. <a name="installation"> ## Installation </a> Install the package using Composer ```bash composer require riclep/laravel-storyblok-css ``` <a name="creating-css-class-names"> ## Creating CSS class names </a> A good naming convention to follow when styling your components is to match the CSS class to the component’s name. [Blocks](/{{route}}/{{version}}/blocks) have the CssClasses trait that provides several helpful methods using the [Block’s `$componentPath`.](/{{route}}/{{version}}/blocks#getting-a-blocks-position) > {info} If you use a different naming scheme override the methods in `Riclep\Storyblok\Traits\CssClasses` with your own. ```php // Returns the current Block’s css class - kebab case version of the component name $block->cssClass(); // Returns the current block’s class and it’s parent $block->cssClassWithParent(); // current-component@parent-component ``` We’re a big fan of the BEM naming methodology and it fits well with Storyblok, but you can use any system or scheme you prefer. (BEM + utilities are the way to go though 😉). The child@parent rule might be a bit controversial but it can be helpful when looping over varied nested components that may be used in several contexts or layouts such as single or multiple columns. > {warning} Don’t forget to escape the @ symbol in your CSS files .child\@parent { ... } ### Layouts In Storyblok some of your components might be solely used for sectioning or laying out content. There are several methods to help you work out when your Block is within a layout and you want to supply different CSS rules. ```php // $componentPath = ['root', 'body', 'layout_columns', 'text', 'title'] $title->cssClassWithLayout(); // title@layout_columns $title->isLayout(); // false $layoutColumns->isLayout(); // true $title->getLayout(); // layout_columns ``` By default we check for component names prefixed with ‘layout_’ when identifying a layout but you can define your own prefix by setting the `$layoutPrefix` on your Blocks (`App\Storyblok\DefaultBlock` is a good place for this). For more control override the existing methods or implement your own! ### Some examples ```php // when not in a layout add an additional class to centre the content <div class="scope-cms u-mb-40 @if (!$block->getLayout()) centred @endif"> {!! $block->text_html !!} </div> // add an extra class when inside a layout <section class="layout_columns"> <article class="text {{ $block->cssClassWithLayout() }}"> // text@layout_columns {{ $block->text }} </article> </section> ``` ```css .text { width: 100%; } /* Don’t forget to escape the @ symbol - and CSS Grid is probably a far better way to achieve outcome */ .text\@layout_columns { width: 50%; } ```
// https://learn.microsoft.com/en-us/dotnet/api/system.text.utf7encoding?view=netframework-4.8.1 using GSystem = global::System; using GText = global::System.Text; using System; using System.Text; using System.Runtime.InteropServices; using DotNetLib.Extensions; using System.ComponentModel; namespace DotNetLib.System.Text { [ComVisible(true)] [Description("Represents a UTF-7 encoding of Unicode characters.")] [Guid("DBDAE439-E236-446D-A55C-3F7A50D657D0")] [ProgId("DotNetLib.System.Text.UTF7Encoding")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IUTF7Encoding))] public class UTF7Encoding : IUTF7Encoding, Encoding, IWrappedObject { private GText.UTF7Encoding _UTF7Encoding; // Constructors internal UTF7Encoding(GText.UTF7Encoding utf7Encoding) { _UTF7Encoding = utf7Encoding; } public UTF7Encoding() { _UTF7Encoding = new GText.UTF7Encoding(); } public UTF7Encoding(bool allowOptionals) { _UTF7Encoding = new GText.UTF7Encoding(allowOptionals); } internal GText.UTF7Encoding WrappedUTF7Encoding => _UTF7Encoding; public object WrappedObject => _UTF7Encoding; public string BodyName => throw new NotImplementedException(); public int CodePage => throw new NotImplementedException(); public DecoderFallback DecoderFallback { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public EncoderFallback EncoderFallback { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public string EncodingName => _UTF7Encoding.EncodingName; public string HeaderName => _UTF7Encoding.HeaderName; public bool IsBrowserDisplay => _UTF7Encoding.IsBrowserDisplay; public bool IsBrowserSave => _UTF7Encoding.IsBrowserSave; public bool IsMailNewsDisplay => _UTF7Encoding.IsMailNewsDisplay; public bool IsMailNewsSave => _UTF7Encoding.IsMailNewsSave; public bool IsReadOnly => _UTF7Encoding.IsReadOnly; public bool IsSingleByte => _UTF7Encoding.IsSingleByte; public string WebName => _UTF7Encoding.WebName; public int WindowsCodePage => _UTF7Encoding.WindowsCodePage; // Methods public object Clone() { return new UTF7Encoding((GText.UTF7Encoding)_UTF7Encoding.Clone()); } public new bool Equals(object value) { return _UTF7Encoding.Equals(value.Unwrap()); } public int GetByteCount(string s) { return _UTF7Encoding.GetByteCount(s); } public int GetByteCount(string s, int index, int count) { return _UTF7Encoding.GetByteCount(s.ToCharArray(), index, count); } public byte[] GetBytes(string s) { return _UTF7Encoding.GetBytes(s); } public byte[] GetBytes(string s, int index, int count) { return _UTF7Encoding.GetBytes(s.ToCharArray(), index, count); } public int GetBytes(string s, int charIndex, int charCount, [In] ref byte[] bytes, int byteIndex) { return _UTF7Encoding.GetBytes(s, charIndex, charCount, bytes, byteIndex); } public int GetCharCount([In] ref byte[] bytes) { return _UTF7Encoding.GetCharCount(bytes); } public int GetCharCount([In] ref byte[] bytes, int index, int count) { return _UTF7Encoding.GetCharCount(bytes, index, count); } public Decoder GetDecoder() { return _UTF7Encoding.GetDecoder(); } public Encoder GetEncoder() { return _UTF7Encoding.GetEncoder(); } public override int GetHashCode() { return _UTF7Encoding.GetHashCode(); } public int GetMaxByteCount(int charCount) { return _UTF7Encoding.GetMaxByteCount(charCount); } public int GetMaxCharCount(int byteCount) { return _UTF7Encoding.GetMaxCharCount(byteCount); } public byte[] GetPreamble() { return _UTF7Encoding.GetPreamble(); } public string GetString([In] ref byte[] bytes) { return _UTF7Encoding.GetString(bytes); } public string GetString([In] ref byte[] bytes, int index, int count) { return _UTF7Encoding.GetString(bytes, index, count); } public bool IsAlwaysNormalized() { return _UTF7Encoding.IsAlwaysNormalized(); } public bool IsAlwaysNormalized(NormalizationForm form) { return _UTF7Encoding.IsAlwaysNormalized(form); } public new Type GetType() { return new Type(((GSystem.Object)this).GetType()); } public new virtual string ToString() { return _UTF7Encoding.ToString(); } } }
// Copyright (C) 2012 The Elastos Open Source Project // // 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. module { interface Elastos.Droid.Hardware.Camera2.ICaptureRequestKey; interface Elastos.Droid.Hardware.Camera2.ICaptureResultKey; interface Elastos.Droid.Hardware.Camera2.ICameraCharacteristicsKey; interface Elastos.Droid.Hardware.Camera2.Utils.ITypeReference; namespace Elastos { namespace Droid { namespace Hardware { namespace Camera2 { namespace Impl { interface ICameraMetadataNativeKey { /** * Return a camelCase, period separated name formatted like: * {@code "root.section[.subsections].name"}. * * <p>Built-in keys exposed by the Android SDK are always prefixed with {@code "android."}; * keys that are device/platform-specific are prefixed with {@code "com."}.</p> * * <p>For example, {@code CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP} would * have a name of {@code "android.scaler.streamConfigurationMap"}; whereas a device * specific key might look like {@code "com.google.nexus.data.private"}.</p> * * @return String representation of the key name */ GetName( [out] String* name); /** * <p> * Get the tag corresponding to this key. This enables insertion into the * native metadata. * </p> * * <p>This value is looked up the first time, and cached subsequently.</p> * * @return The tag numeric value corresponding to the string */ GetTag( [out] Int32* tag); /** * Get the raw class backing the type {@code T} for this key. * * <p>The distinction is only important if {@code T} is a generic, e.g. * {@code Range<Integer>} since the nested type will be erased.</p> */ GetClassType( [out] ClassID* type); /** * Get the type reference backing the type {@code T} for this key. * * <p>The distinction is only important if {@code T} is a generic, e.g. * {@code Range<Integer>} since the nested type will be retained.</p> */ GetTypeReference( [out] ITypeReference** ref); } /** * Proxy out invocations to the camera2 API callbacks into a {@link Dispatchable}. * * <p>Since abstract classes do not support Java's dynamic {@code Proxy}, we have to * to use our own proxy mechanism.</p> * * @invoke * interface IParcelable */ [deprecated] interface ICameraMetadataNative { // this should be in sync with HAL_PIXEL_FORMAT_BLOB defined in graphics.h const Int32 NATIVE_JPEG_FORMAT = 0x21; // Keep up-to-date with camera_metadata.h /** * @hide */ const Int32 TYPE_BYTE = 0; /** * @hide */ const Int32 TYPE_INT32 = 1; /** * @hide */ const Int32 TYPE_FLOAT = 2; /** * @hide */ const Int32 TYPE_INT64 = 3; /** * @hide */ const Int32 TYPE_DOUBLE = 4; /** * @hide */ const Int32 TYPE_RATIONAL = 5; /** * @hide */ const Int32 NUM_TYPES = 6; /** * @hide */ Get( [in] ICameraCharacteristicsKey* key, [out] IInterface** result); /** * @hide */ Get( [in] ICaptureResultKey* key, [out] IInterface** result); /** * @hide */ Get( [in] ICaptureRequestKey* key, [out] IInterface** result); /** * Look-up a metadata field value by its key. * * @param key a non-{@code null} key instance * @return the field corresponding to the {@code key}, or {@code null} if no value was set */ Get( [in] ICameraMetadataNativeKey* key, [out] IInterface** result); /** * Set a camera metadata field to a value. The field definitions can be * found in {@link CameraCharacteristics}, {@link CaptureResult}, and * {@link CaptureRequest}. * * @param key The metadata field to write. * @param value The value to set the field to, which must be of a matching * type to the key. */ Set( [in] ICameraMetadataNativeKey* key, [in] IInterface* value); Set( [in] ICaptureRequestKey* key, [in] IInterface* value); Set( [in] ICaptureResultKey* key, [in] IInterface* value); Set( [in] ICameraCharacteristicsKey* key, [in] IInterface* value); /** * <p>Perform a 0-copy swap of the internal metadata with another object.</p> * * <p>Useful to convert a CameraMetadata into e.g. a CaptureRequest.</p> * * @param other Metadata to swap with * @throws NullPointerException if other was null * @hide */ Swap( [in] ICameraMetadataNative* other); /** * @hide */ GetEntryCount( [out] Int32* count); /** * Does this metadata contain at least 1 entry? * * @hide */ IsEmpty( [out] Boolean* result); /** * <p>Updates the existing entry for tag with the new bytes pointed by src, erasing * the entry if src was null.</p> * * <p>An empty array can be passed in to update the entry to 0 elements.</p> * * @param tag An integer tag, see e.g. {@link #getTag} * @param src An array of bytes, or null to erase the entry * * @hide */ WriteValues( [in] Int32 tag, [in] ArrayOf<Byte>* src); /** * <p>Returns a byte[] of data corresponding to this tag. Use a wrapped bytebuffer to unserialize * the data properly.</p> * * <p>An empty array can be returned to denote an existing entry with 0 elements.</p> * * @param tag An integer tag, see e.g. {@link #getTag} * * @return {@code null} if there were 0 entries for this tag, a byte[] otherwise. * @hide */ ReadValues( [in] Int32 tag, [out, callee] ArrayOf<Byte>* values); /** * Dumps the native metadata contents to logcat. * * <p>Visibility for testing/debugging only. The results will not * include any synthesized keys, as they are invisible to the native layer.</p> * * @hide */ DumpToLog(); } interface ICameraMetadataNativeHelper { /** * Move the contents from {@code other} into a new camera metadata instance.</p> * * <p>After this call, {@code other} will become empty.</p> * * @param other the previous metadata instance which will get pilfered * @return a new metadata instance with the values from {@code other} moved into it */ Move( [in] ICameraMetadataNative* other, [out] ICameraMetadataNative** result); /** * Set the global client-side vendor tag descriptor to allow use of vendor * tags in camera applications. * * @return int A native status_t value corresponding to one of the * {@link CameraBinderDecorator} integer constants. * @see CameraBinderDecorator#throwOnError * * @hide */ NativeSetupGlobalVendorTagDescriptor( [out] Int32* descriptor); /** * Convert a key string into the equivalent native tag. * * @throws IllegalArgumentException if the key was not recognized * @throws NullPointerException if the key was null * * @hide */ GetTag( [in] String key, [out] Int32* tag); /** * Get the underlying native type for a tag. * * @param tag An integer tag, see e.g. {@link #getTag} * @return An int enum for the metadata type, see e.g. {@link #TYPE_BYTE} * * @hide */ GetNativeType( [in] Int32 tag, [out] Int32* type); } } // namespace Impl } // namespace Camera2 } // namespace Hardware } // namespace Droid } // namespace Elastos }
import { Test, TestingModule } from '@nestjs/testing'; import { SatReportEvaluationService } from 'src/evaluationTests/services/satReportEvaluation.service'; import { SubordinateEvaluationService } from 'src/evaluationTests/services/evaluation/subordinateEvaluation.service'; import { LeadershipEvaluationService } from 'src/evaluationTests/services/evaluation/leadershipEvaluation.service'; import { EmotionalStateEvaluationService } from 'src/evaluationTests/services/evaluation/emotionalStateEvaluation.service'; import { LifePurposeEvaluationService } from 'src/evaluationTests/services/evaluation/lifePurposeEvaluation.service'; import { HappinessEvaluationService } from 'src/evaluationTests/services/evaluation/happinessEvaluation.service'; import { HealtEvaluationService } from 'src/evaluationTests/services/evaluation/healtEvaluation.service'; import { SatReportQuestionsService } from 'src/evaluationTests/services/satReportQuestion.service'; import { CoachingAreaService } from 'src/coaching/services/coachingArea.service'; import { SatReportsService } from 'src/evaluationTests/services/satReport.service'; import { CoacheeService } from 'src/coaching/services/coachee.service'; import { TeamWorkEvaluationService } from 'src/evaluationTests/services/evaluation/teamworkEvaluation.service'; import { SatResultAreaObjectType } from 'src/evaluationTests/models/SatResultArea.model'; import { SatBasic } from 'src/evaluationTests/models/satBasic.model'; import { SatSectionResult } from 'src/evaluationTests/models/satSectionResult.model'; import { SatReport } from 'src/evaluationTests/models/satReport.model'; import { SectionCodenames } from 'src/evaluationTests/enums/sectionCodenames.enum'; import { DimensionAverages } from 'src/evaluationTests/models/dimensionAverages.model'; import { DevelopmentAreas } from 'src/coaching/models/dashboardStatistics/developmentAreas.model'; import { SatReportQuestion } from 'src/evaluationTests/models/satReportQuestion.model'; import { QuestionTypes } from 'src/evaluationTests/enums/questionTypes.enum'; import { SatBasicAnswer } from 'src/evaluationTests/models/satBasicAnswer.model'; import { SatBasicQuestion } from 'src/evaluationTests/models/satBasicQuestion.model'; import { SatBasicSection } from 'src/evaluationTests/models/satBasicSection.model'; import { Coachee } from 'src/coaching/models/coachee.model'; describe('SatReportEvaluationService', () => { let service: SatReportEvaluationService; const now = new Date(); const SatResultAreaObjectTypeMock = { area: 'area', areaCodeName: 'areaCodeName', puntuations: [], diagnostics: [], } as SatResultAreaObjectType; const SatResultAreaObjectTypeArrayMock = [ { ...SatResultAreaObjectTypeMock, }, ]; const SatBasicMock = { id: 1, sections: null, testsReports: null, title: 'title', translations: null, description: 'description', createdAt: now, updatedAt: now, } as SatBasic; const SatSectionResultMock = { id: 1, satReport: {}, section: null, questions: [ { id: 1, section: {}, question: {}, answersSelected: [], }, ], } as SatSectionResult; const SatReportMock = { id: 1, user: { id: 1 }, satRealized: SatBasicMock, suggestedCoaches: null, sectionsResults: [{ ...SatSectionResultMock }], result: SatResultAreaObjectTypeArrayMock, createdAt: now, updatedAt: now, } as SatReport; const SatReportArrayMock = [{ ...SatReportMock }]; const DimensionAveragesMock = { dimension: SectionCodenames.GENERAL, average: 0, base: 1, } as DimensionAverages; const DimensionAveragesArrayMock = [{ ...DimensionAveragesMock }]; const DevelopmentAreasMock = { strengths: [SectionCodenames.GENERAL], weaknesses: [SectionCodenames.GENERAL], } as DevelopmentAreas; const SatBasicSectionMock = { id: 1, title: 'title', codename: 'codename', order: 1, } as unknown as SatBasicSection; const SatBasicQuestionMock = { id: 1, answers: null, section: SatBasicSectionMock, reportQuestions: null, title: 'title', translations: null, type: QuestionTypes.SELECT, dimension: null, order: 1, } as SatBasicQuestion; const SatBasicAnswerMock = { id: 1, question: SatBasicQuestionMock, reportQuestions: null, title: 'title', translations: null, value: 0.5, answerDimension: null, order: 1, } as SatBasicAnswer; const SatReportQuestionMock = { id: 1, section: SatSectionResultMock, question: SatBasicQuestionMock, answersSelected: [{ ...SatBasicAnswerMock }], } as SatReportQuestion; const SatReportQuestionArrayMock = [{ ...SatReportQuestionMock }]; const CoachingAreaMock = { id: 1, coaches: [], coachees: [], name: 'name', codename: 'codename', coverPicture: 'coverPicture', description: 'description', }; const CoachingAreaArrayMock = [{ ...CoachingAreaMock }]; const CoacheeMock = { id: 1 } as Coachee; const SubordinateEvaluationServiceMock = { getEvaluation: jest.fn().mockResolvedValue(SatResultAreaObjectTypeMock), }; const LeadershipEvaluationServiceMock = { getEvaluation: jest.fn().mockResolvedValue(SatResultAreaObjectTypeMock), }; const EmotionalStateEvaluationServiceMock = { getEvaluation: jest.fn().mockResolvedValue(SatResultAreaObjectTypeMock), }; const LifePurposeEvaluationServiceMock = { getEvaluation: jest.fn().mockResolvedValue(SatResultAreaObjectTypeMock), }; const HappinessEvaluationServiceMock = { getEvaluation: jest.fn().mockResolvedValue(SatResultAreaObjectTypeMock), }; const TeamWorkEvaluationServiceMock = { getEvaluation: jest.fn().mockResolvedValue(SatResultAreaObjectTypeMock), }; const HealtEvaluationServiceMock = { getEvaluation: jest.fn().mockResolvedValue(SatResultAreaObjectTypeMock), }; const SatReportQuestionsServiceMock = { getReportQuestionsByAnswersDimention: jest .fn() .mockResolvedValue(SatReportQuestionArrayMock), }; const CoachingAreaServiceMock = { getManyCochingAreaByCodenames: jest .fn() .mockResolvedValue(CoachingAreaArrayMock), }; const SatReportsServiceMock = { findOne: jest.fn().mockResolvedValue(SatReportMock), }; const CoacheeServiceMock = { assignCoachingAreas: jest.fn().mockResolvedValue(CoacheeMock), }; beforeEach(async () => { jest.clearAllMocks(); const module: TestingModule = await Test.createTestingModule({ providers: [ SatReportEvaluationService, { provide: SubordinateEvaluationService, useValue: SubordinateEvaluationServiceMock, }, { provide: LeadershipEvaluationService, useValue: LeadershipEvaluationServiceMock, }, { provide: EmotionalStateEvaluationService, useValue: EmotionalStateEvaluationServiceMock, }, { provide: LifePurposeEvaluationService, useValue: LifePurposeEvaluationServiceMock, }, { provide: HappinessEvaluationService, useValue: HappinessEvaluationServiceMock, }, { provide: TeamWorkEvaluationService, useValue: TeamWorkEvaluationServiceMock, }, { provide: HealtEvaluationService, useValue: HealtEvaluationServiceMock, }, { provide: SatReportQuestionsService, useValue: SatReportQuestionsServiceMock, }, { provide: CoachingAreaService, useValue: CoachingAreaServiceMock, }, { provide: SatReportsService, useValue: SatReportsServiceMock, }, { provide: CoacheeService, useValue: CoacheeServiceMock, }, ], }).compile(); service = module.get<SatReportEvaluationService>( SatReportEvaluationService, ); }); it('should be defined', () => { expect(service).toBeDefined(); }); describe('getSatResult', () => { const satReportIdMock = 1; it('should return an array of SatResultAreaObjectType', async () => { SubordinateEvaluationServiceMock.getEvaluation(); LeadershipEvaluationServiceMock.getEvaluation(); EmotionalStateEvaluationServiceMock.getEvaluation(); LifePurposeEvaluationServiceMock.getEvaluation(); HappinessEvaluationServiceMock.getEvaluation(); HealtEvaluationServiceMock.getEvaluation(); jest.spyOn(service, 'assignCoacheeCoachingAreas').mockImplementation(); jest .spyOn(service, 'getSatResult') .mockImplementation() .mockResolvedValue(SatResultAreaObjectTypeArrayMock); const result = await service.getSatResult(satReportIdMock); expect(result).toEqual(SatResultAreaObjectTypeArrayMock); }); }); describe('getWeakAndStrongDimensionsBySatReports', () => { it('should return an development areas', async () => { jest .spyOn(service, 'getDimensionAveragesBySatReports') .mockImplementation() .mockReturnValue(DimensionAveragesArrayMock); jest .spyOn(service, 'getWeakAndStrongDimensionsBySatReports') .mockImplementation() .mockResolvedValue(DevelopmentAreasMock); const result = await service.getWeakAndStrongDimensionsBySatReports( SatReportArrayMock, ); expect(result).toEqual(DevelopmentAreasMock); }); }); describe('assignCoacheeCoachingAreas', () => { it('should assign to a Coachee the coaching areas to work into', async () => { SatReportQuestionsServiceMock.getReportQuestionsByAnswersDimention(); jest .spyOn(service, 'getAreasByAnswersSelected') .mockImplementation() .mockResolvedValue(['EMOTIONAL_INTELLIGENCE'] as never); CoachingAreaServiceMock.getManyCochingAreaByCodenames(); CoacheeServiceMock.assignCoachingAreas(); const result = await service.assignCoacheeCoachingAreas(SatReportMock.id); expect(result).toBeUndefined(); expect( SatReportQuestionsServiceMock.getReportQuestionsByAnswersDimention, ).toHaveBeenCalled(); expect( CoachingAreaServiceMock.getManyCochingAreaByCodenames, ).toHaveBeenCalled(); expect(CoacheeServiceMock.assignCoachingAreas).toHaveBeenCalled(); }); }); });
--- permalink: api/reference_element_api_getloginbanner.html sidebar: sidebar keywords: terms,use,banner,get,getting,getloginbanner,login summary: GetLoginBanner メソッドを使用すると、ユーザが Element Web インターフェイスにログインしたときに表示される現在アクティブな利用条件バナーを取得できます。 --- = GetLoginBanner :allow-uri-read: :icons: font :imagesdir: ../media/ [role="lead"] 「 GetLoginBanner 」メソッドを使用すると、ユーザが Element Web インターフェイスにログインしたときに表示される現在アクティブな利用条件バナーを取得できます。 == パラメータ このメソッドには入力パラメータはありません。 == 戻り値 このメソッドの戻り値は次のとおりです。 |=== | 名前 | 説明 | を入力します a| バナー a| 利用条件バナーの現在のテキスト。この値には、バナーが無効になっている場合でもテキストが含まれます。 a| 文字列 a| 有効 a| 利用条件バナーのステータス。有効な値は次のとおり * true : Web インターフェイスにログインしたときに利用条件バナーが表示されます。 * false : Web インターフェイスにログインしたときに利用条件バナーが表示されません。 a| ブール値 |=== == 要求例 このメソッドの要求例を次に示します。 [listing] ---- { "id": 3411, "method": "GetLoginBanner", "params": {} } ---- == 応答例 このメソッドの応答例を次に示します。 [listing] ---- { "id": 3411, "result": { "loginBanner": { "banner": "Welcome to NetApp!", "enabled": false } } } ---- == 新規導入バージョン 10.0
// // FromImageViewModel.swift // AIArtMagicMaker // // Created by Vasja Batryn on 28.06.2023. // import PhotosUI import SwiftUI final class FromImageViewModel: BaseGenerationViewModel { // MARK: - Public Properties @Published var selectedPromptExample: PromptExample? @Published var selectedImage: Image? @Published var isPhotoLibraryPresented = false @Published var isCameraPresented = false @Published var photosPickerItem: PhotosPickerItem? { didSet { isImageSourcePickerPresented = false fetchImage() } } @Published private(set) var isImageSourcePickerPresented = false @Published private(set) var isInstructionPresented = false @Published private(set) var isGenerationsLeftPresented = false // MARK: - Public Methods func onSelectImageSource(_ source: ImageSource) { switch source { case .camera: isCameraPresented.toggle() case .gallery: isPhotoLibraryPresented.toggle() } } func onTapInstruction() { isInstructionPresented.toggle() } func onTapAddChangeImage() { isImageSourcePickerPresented.toggle() } func onTapGenerate() { if paywallService.hasPremiumAccess { isLoadingPresented.toggle() } else { isGenerationsLeftPresented.toggle() } } func onTapInspireMe() { var example: PromptExample? if let selectedArtStyle { example = promptExamples .first(where: { $0.style == selectedArtStyle }) } else if let randomExample = promptExamples.randomElement() { example = randomExample selectedArtStyle = randomExample.style } prompt = example?.prompt ?? .empty } // MARK: - Private Methods private func fetchImage() { Task { let image = try? await photosPickerItem?.loadTransferable(type: Image.self) DispatchQueue.main.async { self.selectedImage = image } } } }
<div class="container"> <h1>Calculadora</h1> <mat-card> <mat-card-content> <div class="name"> <label for="name">Nombre build: </label> <input type="text" name="name" [(ngModel)]="name"> </div> <div> <label for="selectClass">Clase: </label> <select name="selectClass" id="" [(ngModel)]="build.buildclass" (ngModelChange) = "changeClass()"> <option *ngFor="let buildclass of buildclasses" [ngValue]="buildclass">{{buildclass.name}}</option> </select> </div> <div class="atributes"> <p>Nivel: {{build.level}}</p> </div> <div class="inputs"> <div class="atributes"> <div class="atribute"> <label for="dexterity">Destreza: </label> <input color="primary" type="text" name="dexterity" disabled="true" [(ngModel)]="build.dexterity"> <button [disabled] ="build.dexterity == build.buildclass.dexterity" (click)="putOffDex()">-</button> <button [disabled] ="build.dexterity >= 99" (click)="addDex()">+</button> </div> <div class="atribute"> <label for="strength">Fuerza: </label> <input color="primary" type="text" name="strength" disabled="true" [(ngModel)]="build.strength"> <button [disabled] ="build.strength == build.buildclass.strength" (click)="putOffStreng()">-</button> <button [disabled] ="build.strength >= 99" (click)="addStreng()">+</button> </div> <div class="atribute"> <label for="intelect">Intelecto: </label> <input color="primary" type="text" name="intelect" disabled="true" [(ngModel)]="build.intelect"> <button [disabled] ="build.intelect == build.buildclass.intelect" (click)="putOffInt()">-</button> <button [disabled] ="build.intelect >= 99" (click)="addInt()">+</button> </div> <div class="atribute"> <label for="faith">Fe: </label> <input color="primary" type="text" name="faith" disabled="true" [(ngModel)]="build.faith"> <button [disabled] ="build.faith == build.buildclass.faith" (click)="putOffFaith()">-</button> <button [disabled] ="build.faith >= 99" (click)="addFaith()">+</button> </div> <div class="atribute"> <label for="arcane">Arcano: </label> <input color="primary" type="text" name="arcane" disabled="true" [(ngModel)]="build.arcane"> <button [disabled] ="build.arcane == build.buildclass.arcane" (click)="putOffArc()">-</button> <button [disabled] ="build.arcane >= 99" (click)="addArc()">+</button> </div> </div> <div class="weapons"> <div> <label for="selectWeapon1">Arma 1: </label> <select name="selectWeapon1" [(ngModel)]="build.weapon1"> <option [ngValue]="null"></option> <ng-container *ngFor="let weapon of weapons"> <option *ngIf="weapon.dexReq<=build.dexterity && weapon.strengReq<=build.strength && weapon.intReq<=build.intelect && weapon.faithReq<=build.faith && weapon.arcaneReq<=build.arcane" [ngValue]="weapon">{{weapon.name}}</option> </ng-container> </select> </div> <div> <label for="selectWeapon2">Arma 2: </label> <select name="selectWeapon2" [(ngModel)]="build.weapon2"> <option [ngValue]="null"></option> <ng-container *ngFor="let weapon of weapons"> <option *ngIf="weapon.dexReq<=build.dexterity && weapon.strengReq<=build.strength && weapon.intReq<=build.intelect && weapon.faithReq<=build.faith && weapon.arcaneReq<=build.arcane" [ngValue]="weapon">{{weapon.name}}</option> </ng-container> </select> </div> </div> </div> </mat-card-content> <mat-card-actions> <button mat-stroked-button (click)="onSave()">Guardar Build</button> </mat-card-actions> </mat-card> </div>
// // LimousineCollectionViewCell.swift // QPay // // Created by Dev. Mohmd on 9/12/20. // Copyright © 2020 Dev. Mohmd. All rights reserved. // import UIKit import Cosmos protocol LimousineCollectionViewCellDelegate: AnyObject { func didTapAddToMyLimousine(_ cell: LimousineCollectionViewCell, for limousine: OjraDetails) func didTapRemoveToMyLimousine(_ cell: LimousineCollectionViewCell, for limousine: OjraDetails) func didTapCallLimousine(_ cell: LimousineCollectionViewCell, for limousine: OjraDetails) func didTapOpenMapLimousine(_ cell: LimousineCollectionViewCell, for limousine: OjraDetails) func didTapOpenEmailLimousine(_ cell: LimousineCollectionViewCell, for limousine: OjraDetails) func didTapOpenWebsiteLimousine(_ cell: LimousineCollectionViewCell, for limousine: OjraDetails) } class LimousineCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageViewDesign: ImageViewDesign! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var officeLabel: UILabel! @IBOutlet weak var workTimeLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var websiteLabel: UILabel! @IBOutlet weak var rateLabel: UILabel! @IBOutlet weak var rateCosmosView: CosmosView! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var removeButton: UIButton! @IBOutlet weak var imagesCollectionView: UICollectionView! weak var delegate: LimousineCollectionViewCellDelegate? var isDirectory: Bool = true { willSet { self.isDirectoryLimousine(newValue) } } var object: OjraDetails! { willSet { guard let data = newValue else { return } self.nameLabel.text = data._ojraAccountInfoList.first?._companyName // self.nameLabel.sizeToFit() // if let str = data._ojraAccountInfoList.first { // let attributedString = NSAttributedString(string: str._companyName) // self.nameLabel.attributedText = attributedString // self.nameLabel.sizeThatFits(CGSize(width: .zero, height: attributedString.size().height)) // self.nameLabel.sizeToFit() // } self.emailLabel.text = data._ojra_Email if let image = data._ojraUploadImagesList.first?._imageAd, image.isNotEmpty { self.imageViewDesign.kf.setImage(with: URL(string: image)) } guard let workingSetup = data._ojraWorkingSetUpList.first else { return } self.officeLabel.text = workingSetup._office self.websiteLabel.text = workingSetup._web let workTimeFrom = workingSetup._workingFrom let workTimeTo = workingSetup._workingTo /// 09:00:00.1234567 /// HH:mm:ss.SSSSSZ if let timeFrom = workTimeFrom.convertFormatStringToDate("HH:mm:ss"), let timeTo = workTimeTo.convertFormatStringToDate("HH:mm:ss") { self.workTimeLabel.text = "\(timeFrom.formatDate("HH:mm")) - \(timeTo.formatDate("HH:mm"))" } if let timeFrom = workTimeFrom.convertFormatStringToDate("HH:mm:ss.SSS"), let timeTo = workTimeTo.convertFormatStringToDate("HH:mm:ss.SSS") { self.workTimeLabel.text = "\(timeFrom.formatDate("HH:mm")) - \(timeTo.formatDate("HH:mm"))" } let rate = workingSetup._rating self.rateLabel.text = "\(Int(rate))/5" self.rateCosmosView.rating = rate if let type = data._ojraRideTypeList.first { self.images = type._carTypeDetails } let isAdded = workingSetup._isItemAdded if self.isDirectory { self.addButton.isHidden = isAdded self.removeButton.isHidden = !isAdded } } } private var images = [CarTypeDetails]() { didSet { self.imagesCollectionView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() self.imagesCollectionView.delegate = self self.imagesCollectionView.dataSource = self self.imagesCollectionView.registerNib(ImageCollectionViewCell.self) } } // MARK: - ACTIONS extension LimousineCollectionViewCell { @IBAction func addToMyLimousineAction(_ sender: UIButton) { self.delegate?.didTapAddToMyLimousine(self, for: self.object) } @IBAction func removeToMyLimousineAction(_ sender: UIButton) { self.delegate?.didTapRemoveToMyLimousine(self, for: self.object) } @IBAction func callAction(_ sender: UIButton) { self.delegate?.didTapCallLimousine(self, for: self.object) } @IBAction func openMapAction(_ sender: UIButton) { self.delegate?.didTapOpenMapLimousine(self, for: self.object) } @IBAction func openEmailAction(_ sender: UIButton) { self.delegate?.didTapOpenEmailLimousine(self, for: self.object) } @IBAction func openWebSiteAction(_ sender: UIButton) { self.delegate?.didTapOpenWebsiteLimousine(self, for: self.object) } } // MARK: - COLLECTION VIEW DELEGATE extension LimousineCollectionViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueCell(ImageCollectionViewCell.self, for: indexPath) let object = self.images[indexPath.row] cell.object = object return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellsInRow: CGFloat = CGFloat(5) let flowLayout: UICollectionViewFlowLayout = collectionViewLayout as! UICollectionViewFlowLayout let leftRightPadding: CGFloat = flowLayout.sectionInset.left + flowLayout.sectionInset.right let spaceBetweenCells: CGFloat = flowLayout.minimumInteritemSpacing * cellsInRow let cellWidth = (collectionView.width - leftRightPadding - spaceBetweenCells) / cellsInRow return CGSize(width: cellWidth, height: collectionView.height) } } // MARK: - CUSTOM FUNCTIONS extension LimousineCollectionViewCell { public func isDirectoryLimousine(_ status: Bool) { self.addButton.isHidden = !status self.removeButton.isHidden = status } func cellConfiguration(_ color :UIColor) { self.nameLabel.textColor = color } } struct CellConfiguration { var textColor : UIColor }
package error_test import ( "errors" "fmt" "testing" ) func GetFibonacci(n int) ([]int, error) { if n < 2 || n > 100 { return nil, errors.New("n should be in [2, 100]") } else { fibList := []int{1, 1} for i := 2; i < n; i++ { fibList = append(fibList, fibList[i-2]+fibList[i-1]) } return fibList, nil } } var LessThanTwoError = errors.New("n should not be less than 2") var LargerThanOneHundredError = errors.New("n should not be larger than 100") func GetFibonacci2(n int) ([]int, error) { if n < 2 { return nil, LessThanTwoError } else if n > 100 { return nil, LargerThanOneHundredError } else { fibList := []int{1, 1} for i := 2; i < n; i++ { fibList = append(fibList, fibList[i-2]+fibList[i-1]) } return fibList, nil } } func TestGetFibonacciSuccess(t *testing.T) { if v, err := GetFibonacci(5); err != nil { t.Error(err) } else { t.Log(v) } } func TestGetFibonacciFail(t *testing.T) { if v, err := GetFibonacci(-10); err != nil { t.Error(err) } else { t.Log(v) } } func TestGetFibonacci2(t *testing.T) { if v, err := GetFibonacci2(-5); err != nil { if errors.Is(err, LessThanTwoError) { fmt.Println("It is less.") } else if errors.Is(err, LargerThanOneHundredError) { fmt.Println("It is larger.") } } else { t.Log(v) } } // 最佳实践:避免嵌套,及早失败
import React from 'react'; import { Routes, Route } from 'react-router-dom'; import PatientContent from './components-supabase/contents/patient/PatientContent'; import FacilityContent from './components-supabase/contents/facility/FacilityContent'; import NurseContent from './components-supabase/contents/nurse/NurseContent'; import DeviceContent from './components-supabase/contents/device/DeviceContent'; import Account from './components-supabase/profile/Account'; import { useEffect, useState } from 'react'; import { supabase } from '@/shared/api/supabase/supabaseClient'; import { InfinitySpin } from 'react-loader-spinner'; import { client } from '@/shared/api/initClient_tenant'; import { useAtom, atom } from 'jotai'; import { telemetries, deviceList, facilityList, nurseList, patientList, messageList, notifList, allPatients, } from './App'; import Schedules from './components-supabase/contents/schedule/Schedules'; import Messages from './components-supabase/contents/message/Messages'; import { userSession } from '../Auth'; import Settings from './components-supabase/contents/settings/Settings'; let loadFacility = {}; const ContentContainer = (props) => { const [isUpdate, setIsUpdate] = useState(false); const [refresh, setRefresh] = useState(false); const [loading, setLoading] = useState(false); // const [isSocket, setIsSocket] = useState(false); // I forgot what this is for const [facilities, setFacilities] = useAtom(facilityList); const [devices, setDevices] = useAtom(deviceList); const [nurses, setNurses] = useAtom(nurseList); const [patients, setPatients] = useAtom(patientList); const [messages, setMessages] = useAtom(messageList); const [notif, setNotif] = useAtom(notifList); const [all, setAllPatients] = useAtom(allPatients); const [session] = useAtom(userSession); const handleLoadDevice = async () => { try { // setLoading(true); let { data: DEVICE, error } = await supabase .from('DEVICE') .select('*') .eq('D_Ssn', session.user.id); console.log('load devices success!'); await setDevices(() => DEVICE); if (error) throw error; } catch (error) { console.log(error.error_description || error.message); } // finally { // setLoading(false); // } }; const handleLoadFacility = async () => { try { loadFacility = {}; let { data: ROOM, error } = await supabase .from('ROOM') .select('*') .eq('D_Ssn', session.user.id); if (error) throw error; for (let room of ROOM) { loadFacility[`${room.R_Number}`] = { ...room, beds: [], nurses: [] }; let { data: BED, error } = await supabase .from('BED') .select('*') .eq('R_Number', room.R_Number); for (let bed of BED) { loadFacility[`${room.R_Number}`].beds.push(bed); } let { data: NURSEID } = await supabase .from('IS_ASSIGNED_TO') .select('*') .eq('R_Number', room.R_Number); for (let id of NURSEID) { let { data: NURSE } = await supabase .from('NURSE') .select('*') .eq('N_Ssn', id.N_Ssn); loadFacility[`${room.R_Number}`].nurses.push(NURSE[0]); } } console.log('load facilties success!'); setFacilities(loadFacility); } catch (error) { console.log(error.error_description || error.message); } // finally { // setLoading(false); // } }; const handleLoadNurse = async () => { try { // setLoading(true); let { data: NURSE, error } = await supabase .from('NURSE') .select('*') .eq('D_Ssn', session.user.id); if (error) throw error; console.log('load nurses success!'); setNurses(NURSE); } catch (error) { console.log(error.error_description || error.message); } // finally { // setLoading(false); // } }; const handleLoadPatient = async (type = 'all') => { try { // setLoading(true); let { data: PATIENT, error } = await supabase .from('PATIENT') .select('*') .eq('D_Ssn', session.user.id); if (error) throw error; let patients = {}; patients.critical = PATIENT.filter((patient) => patient.Status === 'Critical'); patients.all = [...patients.critical]; patients.febrile = PATIENT.filter((patient) => patient.Status === 'Febrile'); patients.all = patients.all.concat(patients.febrile); patients.recovery = PATIENT.filter((patient) => patient.Status === 'Recovery'); patients.all = patients.all.concat(patients.recovery); patients.none = PATIENT.filter((patient) => patient.Status === 'None'); patients.all = patients.all.concat(patients.none); console.log('load patients success!'); setAllPatients(patients); setPatients(patients[`${type}`]); } catch (error) { console.log(error.error_description || error.message); } // finally { // setLoading(false); // } }; const handleLoadMessage = async () => { const { data: MESSAGE, error } = await supabase.from('MESSAGE').select('*'); let lastMessage = { ...MESSAGE[MESSAGE.length - 1] }; if (lastMessage.Signature !== session.user.id) { setNotif(() => ({ ...lastMessage })); } setMessages(() => MESSAGE); }; useEffect(() => { setLoading(true); console.log('loading devices..'); handleLoadDevice(); console.log('loading facilities..'); handleLoadFacility(); console.log('loading nurses..'); handleLoadNurse(); console.log('loading patients..'); handleLoadPatient(); console.log('loading messages..'); handleLoadMessage(); setLoading(false); }, [isUpdate, refresh]); if (!loading) { return ( // <ContentContainerContext.Provider value={{ telemetries, setTelemetries }}> <div className="flex w-[75%] flex-auto flex-col"> <Routes> <Route path="/" element={ <PatientContent setRefresh={setRefresh} setIsChart={props.setIsChart} handleLoadPatient={handleLoadPatient} /> } /> <Route path="/account" element={<Account />} /> <Route path="/facilities" element={ <FacilityContent handleLoadFacility={handleLoadFacility} setRefresh={setRefresh} setIsUpdate={setIsUpdate} /> } /> <Route path="/nurses" element={ <NurseContent setRefresh={setRefresh} handleLoadNurse={handleLoadNurse} /> } /> <Route path="/devices" element={ <DeviceContent handleLoadDevice={handleLoadDevice} setRefresh={setRefresh} setIsUpdate={setIsUpdate} /> } /> <Route path="/schedules" element={<Schedules />} /> <Route path="/messages" element={<Messages handleLoadMessage={handleLoadMessage} />} /> <Route path="/settings" element={<Settings />} /> </Routes> </div> // </ContentContainerContext.Provider> ); } else { return ( <div className="flex w-[75%] items-center justify-center"> <InfinitySpin width="300" color="#475569" />; </div> ); } }; export default ContentContainer;
%% Define constants x1=pi; x2=0; l=1; m=1; b=0.1; g=9.8; Kp=1; Kd=1; thetaNoiseGain=0; thetaDotNoiseGain=0; %% Simulink out = sim('as1_3.slx',10); t=out.t; thetaDot=out.thetaDot; theta=out.theta; figure(1), clf subplot(2,1,1) plot(t,theta) title("PD feedback control given Kp=1, Kd=1") ylabel("Theta (Rad)") subplot(2,1,2) plot(t,thetaDot) ylabel("Theta Dot (Rad/s)") xlabel("Time (s)") %% Tune PD control KdArray=[0.01, 0.1, 1, 10, 100]; KpArray=[0.01, 0.1, 1, 10, 100]; figure(2), clf for i=1:5 for j=1:5 Kp=KpArray(i); Kd=KdArray(j); out = sim('as1_3.slx',10); t=out.t; thetaDot=out.thetaDot; theta=out.theta; subplot(5,5,i*5-5+j) plot(t,theta) if j==1 ylabel(sprintf("Kp=%.2f\nTheta (Rad)",Kp)) end if i==5 xlabel(sprintf("Kd=%.2f\nTime (s)",Kd)) end ylim([-5,5]) end end %% noise Kp=1; Kd=1; noiseArray=[0, 0.01, 0.1, 1, 10]; figure(3), clf figure(4), clf for i=1:length(noiseArray) thetaNoiseGain=noiseArray(i); thetaDotNoiseGain=noiseArray(i); out = sim('as1_3.slx',10); t=out.t; thetaDot=out.thetaDot; theta=out.theta; thetaObserved=out.thetaOb; figure(3) subplot(length(noiseArray),1,i), hold on plot(t, thetaObserved) plot(t,theta) legend("Observed Theta","True Theta") ylabel(sprintf("Noise %.0f%%\nTheta (Rad)",thetaNoiseGain*100)) ylim([-2,4]) figure(4), hold on plot(t,theta) end figure(4) legend("Noise 0%","Noise 10%","Noise 100%","Noise 1000%","Noise 10000%") figure(3) xlabel("Time (s)") %% PD control Under Noise KdArray=[0.1, 1, 10]; KpArray=[0.1, 1, 10]; figure(5), clf for i=1:length(KdArray) for j=1:length(KpArray) Kp=KpArray(i); Kd=KdArray(j); thetaNoiseGain=0; thetaDotNoiseGain=0; out = sim('as1_3.slx',10); t=out.t; thetaDot=out.thetaDot; theta=out.theta; thetaNoiseGain=3; thetaDotNoiseGain=3; out = sim('as1_3.slx',10); thetaUnderNoise=out.theta; subplot(length(KdArray),length(KpArray),i*length(KdArray)-length(KdArray)+j), hold on plot(t,theta) plot(t,thetaUnderNoise) if j==1 ylabel(sprintf("Kp=%.2f\nTheta (Rad)",Kp)) end if i==length(KdArray) xlabel(sprintf("Kd=%.2f\nTime (s)",Kd)) end ylim([-5,5]) end end
This use case has two parts. Building a device template that contains the desired configuration to test. Building a compliance report to check the configuration of a group of devices against a template. ## Building the device template ncs_cli -C -u admin config devices template COMPLIANCE-CHECK ned-id cisco-ios-cli-6.91 config ip name-server name-server-list 208.67.222.222 ip name-server name-server-list 208.67.220.220 exit service timestamps log datetime localtime show-timezone year logging host ipv4 10.225.1.11 exit ntp server peer-list 10.225.1.11 exit exit exit ! ned-id cisco-nx-cli-5.23 config ip name-server servers 208.67.222.222 ip name-server servers 208.67.220.220 logging timestamp milliseconds logging server 10.225.1.11 level 5 exit ntp server 10.225.1.11 exit exit exit ! ned-id cisco-asa-cli-6.6 config dns domain-lookup mgmt dns server-group DefaultDNS name-server 208.67.222.222 name-server 208.67.220.220 exit logging timestamp logging host mgmt 10.225.1.11 exit ntp server 10.225.1.11 exit exit exit top show configuration commit ## Building the compliance report * Results can come in in HTML, Bash, or XML format. XML is the default. * Because the results are likely very "verbose" and not something the engineer wants to see only at the CLI, NSO saves the results to a file located in the folder state/compliance-reports. * NSO runs a web server so these reports are available by navigating to the given URL, or you can find them by navigating the folders on your server. compliance reports report COMPLIANCE-CHECK compare-template COMPLIANCE-CHECK ALL commit end #All is a device group here. From the "enable mode" of NSO compliance reports report COMPLIANCE-CHECK run Output: admin@ncs# compliance reports report COMPLIANCE-CHECK run id 1 compliance-status violations info Checking 8 devices and no services location http://localhost:8080/compliance-reports/report_1_admin_1_2020-3-24T9:48:41:0.xml admin@ncs# Generate different type of reports: compliance reports report COMPLIANCE-CHECK run outformat text compliance reports report COMPLIANCE-CHECK run outformat html Note: Even though NSO evaluates different CLI device types (IOS, NX, ASA), NSO standardizes the "native" configuration into a uniform data model, in Junos curly bracket style, when showing the diff. ## Resolving Compliance Problems ncs_cli -C -u admin config devices device-group ALL apply-template template-name COMPLIANCE-CHECK show configuration commit dry-run outformat native commit end compliance reports report COMPLIANCE-CHECK run outformat text
# Data Explorations We'd first visualize the time series of the temperatures of indoor and outdoor at the locations, to understand the distribution, pattern, and trend of the datum. ```python import pandas as pd ``` ```python outdoor = pd.read_csv('../../data/outdoor-temperature-20220601-0912.csv.zip') ``` ```python outdoor ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>_time</th> <th>Location</th> <th>Temperature</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2022-09-12T23:59:49.000-0700</td> <td>S50</td> <td>64.0</td> </tr> <tr> <th>1</th> <td>2022-09-12T23:59:28.000-0700</td> <td>S10</td> <td>63.0</td> </tr> <tr> <th>2</th> <td>2022-09-12T23:58:56.000-0700</td> <td>W40</td> <td>60.0</td> </tr> <tr> <th>3</th> <td>2022-09-12T23:58:42.000-0700</td> <td>A20</td> <td>61.0</td> </tr> <tr> <th>4</th> <td>2022-09-12T23:58:21.000-0700</td> <td>C60</td> <td>64.0</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>608553</th> <td>2022-06-01T00:00:00.000-0700</td> <td>C80</td> <td>66.0</td> </tr> <tr> <th>608554</th> <td>2022-06-01T00:00:00.000-0700</td> <td>C40</td> <td>55.9</td> </tr> <tr> <th>608555</th> <td>2022-06-01T00:00:00.000-0700</td> <td>C30</td> <td>55.9</td> </tr> <tr> <th>608556</th> <td>2022-06-01T00:00:00.000-0700</td> <td>A60</td> <td>55.9</td> </tr> <tr> <th>608557</th> <td>2022-06-01T00:00:00.000-0700</td> <td>A58</td> <td>55.9</td> </tr> </tbody> </table> <p>608558 rows × 3 columns</p> </div> There might be redundancy. Let's remove the duplicated rows in outdoor. ```python outdoor = outdoor.drop_duplicates(subset=['_time', 'Location', 'Temperature'], keep='first') ``` ```python outdoor ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>_time</th> <th>Location</th> <th>Temperature</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2022-09-12T23:59:49.000-0700</td> <td>S50</td> <td>64.0</td> </tr> <tr> <th>1</th> <td>2022-09-12T23:59:28.000-0700</td> <td>S10</td> <td>63.0</td> </tr> <tr> <th>2</th> <td>2022-09-12T23:58:56.000-0700</td> <td>W40</td> <td>60.0</td> </tr> <tr> <th>3</th> <td>2022-09-12T23:58:42.000-0700</td> <td>A20</td> <td>61.0</td> </tr> <tr> <th>4</th> <td>2022-09-12T23:58:21.000-0700</td> <td>C60</td> <td>64.0</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>608553</th> <td>2022-06-01T00:00:00.000-0700</td> <td>C80</td> <td>66.0</td> </tr> <tr> <th>608554</th> <td>2022-06-01T00:00:00.000-0700</td> <td>C40</td> <td>55.9</td> </tr> <tr> <th>608555</th> <td>2022-06-01T00:00:00.000-0700</td> <td>C30</td> <td>55.9</td> </tr> <tr> <th>608556</th> <td>2022-06-01T00:00:00.000-0700</td> <td>A60</td> <td>55.9</td> </tr> <tr> <th>608557</th> <td>2022-06-01T00:00:00.000-0700</td> <td>A58</td> <td>55.9</td> </tr> </tbody> </table> <p>519537 rows × 3 columns</p> </div> The number of rows are ruduced from 797422 to 546586 ```python outdoor['Source'] = 'Outdoor' ``` /tmp/ipykernel_22441/646069649.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy outdoor['Source'] = 'Outdoor' ```python indoor = pd.read_csv('../../data/indoor-temperature-20220601-0912.csv.zip') ``` ```python indoor ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>_time</th> <th>Location</th> <th>Temperature</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2022-09-12T23:52:01.000-0700</td> <td>Y10</td> <td>76.3</td> </tr> <tr> <th>1</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W40</td> <td>76.7</td> </tr> <tr> <th>2</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W34</td> <td>75.5</td> </tr> <tr> <th>3</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W20</td> <td>71.8</td> </tr> <tr> <th>4</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W10</td> <td>72.9</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>528903</th> <td>2022-06-01T00:05:01.000-0700</td> <td>A40</td> <td>71.4</td> </tr> <tr> <th>528904</th> <td>2022-06-01T00:05:01.000-0700</td> <td>A20</td> <td>70.1</td> </tr> <tr> <th>528905</th> <td>2022-06-01T00:05:01.000-0700</td> <td>C60</td> <td>78.0</td> </tr> <tr> <th>528906</th> <td>2022-06-01T00:05:01.000-0700</td> <td>C76</td> <td>73.5</td> </tr> <tr> <th>528907</th> <td>2022-06-01T00:05:01.000-0700</td> <td>A30</td> <td>69.4</td> </tr> </tbody> </table> <p>528908 rows × 3 columns</p> </div> ```python indoor = indoor.drop_duplicates(subset=['_time', 'Location', 'Temperature'], keep='first') indoor ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>_time</th> <th>Location</th> <th>Temperature</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2022-09-12T23:52:01.000-0700</td> <td>Y10</td> <td>76.3</td> </tr> <tr> <th>1</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W40</td> <td>76.7</td> </tr> <tr> <th>2</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W34</td> <td>75.5</td> </tr> <tr> <th>3</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W20</td> <td>71.8</td> </tr> <tr> <th>4</th> <td>2022-09-12T23:52:01.000-0700</td> <td>W10</td> <td>72.9</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>528903</th> <td>2022-06-01T00:05:01.000-0700</td> <td>A40</td> <td>71.4</td> </tr> <tr> <th>528904</th> <td>2022-06-01T00:05:01.000-0700</td> <td>A20</td> <td>70.1</td> </tr> <tr> <th>528905</th> <td>2022-06-01T00:05:01.000-0700</td> <td>C60</td> <td>78.0</td> </tr> <tr> <th>528906</th> <td>2022-06-01T00:05:01.000-0700</td> <td>C76</td> <td>73.5</td> </tr> <tr> <th>528907</th> <td>2022-06-01T00:05:01.000-0700</td> <td>A30</td> <td>69.4</td> </tr> </tbody> </table> <p>528908 rows × 3 columns</p> </div> The number of rows in indoor data are reduced from 589056 to 579326 ```python indoor['Source'] = 'Indoor' indoor['Location'] = indoor['Location'].str[:3] ``` ```python import altair as alt from altair_data_server import data_server alt.data_transformers.enable('data_server') ``` DataTransformerRegistry.enable('data_server') to enable Altair to plot for more than 5000 rows. ## Plots of Indoor and Outdoor Temperatures at Different Locations ```python df = pd.concat([outdoor, indoor]) del outdoor, indoor # save unwanted memory ``` Convert the time column to datetime type, and convert the temperature to float type. ```python df['_time'] = pd.to_datetime(df['_time']) df['Temperature'] = df['Temperature'].astype(float) ``` ```python alt.Chart(df).mark_line().encode( x='_time:T', y=alt.Y("Temperature:Q", scale=alt.Scale(domain=[55, 110])), color='Source:N', tooltip=['Source', 'Temperature'] ).facet( 'Location:N', columns = 6 ) ``` /home/yshen/.local/lib/python3.10/site-packages/altair/utils/core.py:317: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead. for col_name, dtype in df.dtypes.iteritems(): <div id="altair-viz-3c3b8a9548024074b154e2288928ff07"></div> <script type="text/javascript"> var VEGA_DEBUG = (typeof VEGA_DEBUG == "undefined") ? {} : VEGA_DEBUG; (function(spec, embedOpt){ let outputDiv = document.currentScript.previousElementSibling; if (outputDiv.id !== "altair-viz-3c3b8a9548024074b154e2288928ff07") { outputDiv = document.getElementById("altair-viz-3c3b8a9548024074b154e2288928ff07"); } const paths = { "vega": "https://cdn.jsdelivr.net/npm//vega@5?noext", "vega-lib": "https://cdn.jsdelivr.net/npm//vega-lib?noext", "vega-lite": "https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext", "vega-embed": "https://cdn.jsdelivr.net/npm//vega-embed@6?noext", }; function maybeLoadScript(lib, version) { var key = `${lib.replace("-", "")}_version`; return (VEGA_DEBUG[key] == version) ? Promise.resolve(paths[lib]) : new Promise(function(resolve, reject) { var s = document.createElement('script'); document.getElementsByTagName("head")[0].appendChild(s); s.async = true; s.onload = () => { VEGA_DEBUG[key] = version; return resolve(paths[lib]); }; s.onerror = () => reject(`Error loading script: ${paths[lib]}`); s.src = paths[lib]; }); } function showError(err) { outputDiv.innerHTML = `<div class="error" style="color:red;">${err}</div>`; throw err; } function displayChart(vegaEmbed) { vegaEmbed(outputDiv, spec, embedOpt) .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`)); } if(typeof define === "function" && define.amd) { requirejs.config({paths}); require(["vega-embed"], displayChart, err => showError(`Error loading script: ${err.message}`)); } else { maybeLoadScript("vega", "5") .then(() => maybeLoadScript("vega-lite", "4.17.0")) .then(() => maybeLoadScript("vega-embed", "6")) .catch(showError) .then(() => displayChart(vegaEmbed)); } })({"config": {"view": {"continuousWidth": 400, "continuousHeight": 300}}, "data": {"url": "http://localhost:49229/77efc608e04424ef43a67deaa624380f.json"}, "facet": {"field": "Location", "type": "nominal"}, "spec": {"mark": "line", "encoding": {"color": {"field": "Source", "type": "nominal"}, "tooltip": [{"field": "Source", "type": "nominal"}, {"field": "Temperature", "type": "quantitative"}], "x": {"field": "_time", "type": "temporal"}, "y": {"field": "Temperature", "scale": {"domain": [55, 110]}, "type": "quantitative"}}}, "columns": 6, "$schema": "https://vega.github.io/schema/vega-lite/v4.17.0.json"}, {"mode": "vega-lite"}); </script> ## Investigate the pattern of the temperature curves By examming the above line charts visually, we can divide the locations into the following categories: - outdoor_only :: only with the outdoor data, not of value for the study - indoor_only :: only with the indoor data, maybe not of value - incomplete :: have significant number of days when there are missing data. These locations might be used for validation, with the portion available. Or, we might extract the portion with both indoor and outdoor temperature available to increase the amount of data for training - both_effective_AC :: with temperature both indoor and outdoor available, and showing AC being effective - both_ineffective_AC :: with temperature both indoor and outdoor available, and showing AC being ineffective ```python # Locations with outdoor temperature only outdoor_only = ['A10', 'A58', 'C55', 'C70', 'K10', 'K20', 'L10', 'L14', 'M16', 'M60', 'M70', 'R20', 'S10', 'W30', ''] # Locations with indoor temperature only indoor_only = ['E20', 'L06', 'ODY', 'OHY', 'ORY', 'S06'] incomplete = ['A40', 'C10', 'C76', 'C88', 'E10', 'E39', 'K30', 'L16', 'L18', 'M10', 'M20', 'M30', 'M40', 'M50', 'M80', 'M90', 'M94', 'R10', 'R30,', 'R40', 'R50', 'R60', 'S12', 'S24', 'S26', 'S44', 'W10', 'W20', 'W34', 'W40', 'Y10'] # Locations with both indoor and outdoor temperature ``` ```python both_effective_AC = ['A50', 'A60', 'A70', 'A80', 'A90', 'C30', 'C40', 'C50', 'C54', 'C60', 'C80', 'E30', 'L20', 'L30', 'S20', 'S40', 'S50'] both_ineffective_AC = ['A20', 'A30', 'A70'] ``` ```python df_ineffective_AC = df[df['Location'].isin(both_ineffective_AC)] df_effective_AC = df[df['Location'].isin(both_effective_AC)] ``` ```python df_incomplete = df[df['Location'].isin(incomplete)] df_indoor_only = df[df['Location'].isin(indoor_only)] ``` ```python del df ``` ## Ineffective AC ```python alt.Chart(df_ineffective_AC).mark_line().encode( x='_time:T', y=alt.Y("Temperature:Q", scale=alt.Scale(domain=[55, 110])), color='Source:N', tooltip=['Source', 'Temperature'] ).facet( 'Location:N', columns = 6 ) ``` /home/yshen/.local/lib/python3.10/site-packages/altair/utils/core.py:317: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead. for col_name, dtype in df.dtypes.iteritems(): <div id="altair-viz-267814f4c853411ca86b9d703e41d408"></div> <script type="text/javascript"> var VEGA_DEBUG = (typeof VEGA_DEBUG == "undefined") ? {} : VEGA_DEBUG; (function(spec, embedOpt){ let outputDiv = document.currentScript.previousElementSibling; if (outputDiv.id !== "altair-viz-267814f4c853411ca86b9d703e41d408") { outputDiv = document.getElementById("altair-viz-267814f4c853411ca86b9d703e41d408"); } const paths = { "vega": "https://cdn.jsdelivr.net/npm//vega@5?noext", "vega-lib": "https://cdn.jsdelivr.net/npm//vega-lib?noext", "vega-lite": "https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext", "vega-embed": "https://cdn.jsdelivr.net/npm//vega-embed@6?noext", }; function maybeLoadScript(lib, version) { var key = `${lib.replace("-", "")}_version`; return (VEGA_DEBUG[key] == version) ? Promise.resolve(paths[lib]) : new Promise(function(resolve, reject) { var s = document.createElement('script'); document.getElementsByTagName("head")[0].appendChild(s); s.async = true; s.onload = () => { VEGA_DEBUG[key] = version; return resolve(paths[lib]); }; s.onerror = () => reject(`Error loading script: ${paths[lib]}`); s.src = paths[lib]; }); } function showError(err) { outputDiv.innerHTML = `<div class="error" style="color:red;">${err}</div>`; throw err; } function displayChart(vegaEmbed) { vegaEmbed(outputDiv, spec, embedOpt) .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`)); } if(typeof define === "function" && define.amd) { requirejs.config({paths}); require(["vega-embed"], displayChart, err => showError(`Error loading script: ${err.message}`)); } else { maybeLoadScript("vega", "5") .then(() => maybeLoadScript("vega-lite", "4.17.0")) .then(() => maybeLoadScript("vega-embed", "6")) .catch(showError) .then(() => displayChart(vegaEmbed)); } })({"config": {"view": {"continuousWidth": 400, "continuousHeight": 300}}, "data": {"url": "http://localhost:49229/b19a2b13662f0b3fa28ff3a47869d9db.json"}, "facet": {"field": "Location", "type": "nominal"}, "spec": {"mark": "line", "encoding": {"color": {"field": "Source", "type": "nominal"}, "tooltip": [{"field": "Source", "type": "nominal"}, {"field": "Temperature", "type": "quantitative"}], "x": {"field": "_time", "type": "temporal"}, "y": {"field": "Temperature", "scale": {"domain": [55, 110]}, "type": "quantitative"}}}, "columns": 6, "$schema": "https://vega.github.io/schema/vega-lite/v4.17.0.json"}, {"mode": "vega-lite"}); </script> We might have an issue that the number of locations for ineffective AC as examples for training might be too few. The solution might be that we need to extract further from the incomplete data set. ## Effective AC ```python alt.Chart(df_effective_AC).mark_line().encode( x='_time:T', y=alt.Y("Temperature:Q", scale=alt.Scale(domain=[55, 110])), color='Source:N', tooltip=['Source', 'Temperature'] ).facet( 'Location:N', columns = 6 ) ``` /home/yshen/.local/lib/python3.10/site-packages/altair/utils/core.py:317: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead. for col_name, dtype in df.dtypes.iteritems(): <div id="altair-viz-2bc113c636564478a6de81b30d038c34"></div> <script type="text/javascript"> var VEGA_DEBUG = (typeof VEGA_DEBUG == "undefined") ? {} : VEGA_DEBUG; (function(spec, embedOpt){ let outputDiv = document.currentScript.previousElementSibling; if (outputDiv.id !== "altair-viz-2bc113c636564478a6de81b30d038c34") { outputDiv = document.getElementById("altair-viz-2bc113c636564478a6de81b30d038c34"); } const paths = { "vega": "https://cdn.jsdelivr.net/npm//vega@5?noext", "vega-lib": "https://cdn.jsdelivr.net/npm//vega-lib?noext", "vega-lite": "https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext", "vega-embed": "https://cdn.jsdelivr.net/npm//vega-embed@6?noext", }; function maybeLoadScript(lib, version) { var key = `${lib.replace("-", "")}_version`; return (VEGA_DEBUG[key] == version) ? Promise.resolve(paths[lib]) : new Promise(function(resolve, reject) { var s = document.createElement('script'); document.getElementsByTagName("head")[0].appendChild(s); s.async = true; s.onload = () => { VEGA_DEBUG[key] = version; return resolve(paths[lib]); }; s.onerror = () => reject(`Error loading script: ${paths[lib]}`); s.src = paths[lib]; }); } function showError(err) { outputDiv.innerHTML = `<div class="error" style="color:red;">${err}</div>`; throw err; } function displayChart(vegaEmbed) { vegaEmbed(outputDiv, spec, embedOpt) .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`)); } if(typeof define === "function" && define.amd) { requirejs.config({paths}); require(["vega-embed"], displayChart, err => showError(`Error loading script: ${err.message}`)); } else { maybeLoadScript("vega", "5") .then(() => maybeLoadScript("vega-lite", "4.17.0")) .then(() => maybeLoadScript("vega-embed", "6")) .catch(showError) .then(() => displayChart(vegaEmbed)); } })({"config": {"view": {"continuousWidth": 400, "continuousHeight": 300}}, "data": {"url": "http://localhost:49229/ab5709ce31d4859a05084bc83275f50b.json"}, "facet": {"field": "Location", "type": "nominal"}, "spec": {"mark": "line", "encoding": {"color": {"field": "Source", "type": "nominal"}, "tooltip": [{"field": "Source", "type": "nominal"}, {"field": "Temperature", "type": "quantitative"}], "x": {"field": "_time", "type": "temporal"}, "y": {"field": "Temperature", "scale": {"domain": [55, 110]}, "type": "quantitative"}}}, "columns": 6, "$schema": "https://vega.github.io/schema/vega-lite/v4.17.0.json"}, {"mode": "vega-lite"}); </script> ```python alt.Chart(df_incomplete).mark_line().encode( x='_time:T', y=alt.Y("Temperature:Q", scale=alt.Scale(domain=[55, 110])), color='Source:N', tooltip=['Source', 'Temperature'] ).facet( 'Location:N', columns = 6 ) # del df_incomplete ``` /home/yshen/.local/lib/python3.10/site-packages/altair/utils/core.py:317: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead. for col_name, dtype in df.dtypes.iteritems(): <div id="altair-viz-aced34eb67524a2d8835fc4529334505"></div> <script type="text/javascript"> var VEGA_DEBUG = (typeof VEGA_DEBUG == "undefined") ? {} : VEGA_DEBUG; (function(spec, embedOpt){ let outputDiv = document.currentScript.previousElementSibling; if (outputDiv.id !== "altair-viz-aced34eb67524a2d8835fc4529334505") { outputDiv = document.getElementById("altair-viz-aced34eb67524a2d8835fc4529334505"); } const paths = { "vega": "https://cdn.jsdelivr.net/npm//vega@5?noext", "vega-lib": "https://cdn.jsdelivr.net/npm//vega-lib?noext", "vega-lite": "https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext", "vega-embed": "https://cdn.jsdelivr.net/npm//vega-embed@6?noext", }; function maybeLoadScript(lib, version) { var key = `${lib.replace("-", "")}_version`; return (VEGA_DEBUG[key] == version) ? Promise.resolve(paths[lib]) : new Promise(function(resolve, reject) { var s = document.createElement('script'); document.getElementsByTagName("head")[0].appendChild(s); s.async = true; s.onload = () => { VEGA_DEBUG[key] = version; return resolve(paths[lib]); }; s.onerror = () => reject(`Error loading script: ${paths[lib]}`); s.src = paths[lib]; }); } function showError(err) { outputDiv.innerHTML = `<div class="error" style="color:red;">${err}</div>`; throw err; } function displayChart(vegaEmbed) { vegaEmbed(outputDiv, spec, embedOpt) .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`)); } if(typeof define === "function" && define.amd) { requirejs.config({paths}); require(["vega-embed"], displayChart, err => showError(`Error loading script: ${err.message}`)); } else { maybeLoadScript("vega", "5") .then(() => maybeLoadScript("vega-lite", "4.17.0")) .then(() => maybeLoadScript("vega-embed", "6")) .catch(showError) .then(() => displayChart(vegaEmbed)); } })({"config": {"view": {"continuousWidth": 400, "continuousHeight": 300}}, "data": {"url": "http://localhost:49229/3b170e400c669c72284d18a89a0382b5.json"}, "facet": {"field": "Location", "type": "nominal"}, "spec": {"mark": "line", "encoding": {"color": {"field": "Source", "type": "nominal"}, "tooltip": [{"field": "Source", "type": "nominal"}, {"field": "Temperature", "type": "quantitative"}], "x": {"field": "_time", "type": "temporal"}, "y": {"field": "Temperature", "scale": {"domain": [55, 110]}, "type": "quantitative"}}}, "columns": 6, "$schema": "https://vega.github.io/schema/vega-lite/v4.17.0.json"}, {"mode": "vega-lite"}); </script> ## Consider the difference between indoor and outdoor temperatures ### Case Study: A20 We use location A20 as a case to figure out how to align the indoor and outdoor data by matching roughly their timestamp. ```python df_A20 = df_ineffective_AC[df_ineffective_AC['Location'] == 'A20'] ``` ```python # convert the time stamps to datetime df_A20['_time'] = pd.to_datetime(df_A20['_time']) # convert string to float df_A20['Temperature'] = df_A20['Temperature'].astype(float) ``` /tmp/ipykernel_22441/3413013261.py:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df_A20['_time'] = pd.to_datetime(df_A20['_time']) /tmp/ipykernel_22441/3413013261.py:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df_A20['Temperature'] = df_A20['Temperature'].astype(float) ```python df_A20['_time'] ``` 3 2022-09-12 23:58:42-07:00 28 2022-09-12 23:48:33-07:00 54 2022-09-12 23:38:29-07:00 81 2022-09-12 23:28:16-07:00 108 2022-09-12 23:17:43-07:00 ... 528692 2022-06-01 01:05:01-07:00 528745 2022-06-01 00:50:01-07:00 528798 2022-06-01 00:35:01-07:00 528851 2022-06-01 00:20:01-07:00 528904 2022-06-01 00:05:01-07:00 Name: _time, Length: 20221, dtype: datetime64[ns, pytz.FixedOffset(-420)] ```python # The date of the first data point # df_A20['_time'].min() # The date of the last data point # df_A20['_time'].max() # The date portion of the first data point # df_A20['_time'].min().date() ``` ```python # import datetime # df_A20_first_day = df_A20[df_A20['_time'].dt.date == df_A20['_time'].min().date()] ``` ```python df_A20_first_day ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>_time</th> <th>Location</th> <th>Temperature</th> <th>Source</th> </tr> </thead> <tbody> <tr> <th>602578</th> <td>2022-06-01 23:45:00-07:00</td> <td>A20</td> <td>57.0</td> <td>Outdoor</td> </tr> <tr> <th>602611</th> <td>2022-06-01 23:30:00-07:00</td> <td>A20</td> <td>57.0</td> <td>Outdoor</td> </tr> <tr> <th>602675</th> <td>2022-06-01 23:15:00-07:00</td> <td>A20</td> <td>57.0</td> <td>Outdoor</td> </tr> <tr> <th>602748</th> <td>2022-06-01 23:00:00-07:00</td> <td>A20</td> <td>57.0</td> <td>Outdoor</td> </tr> <tr> <th>602801</th> <td>2022-06-01 22:45:00-07:00</td> <td>A20</td> <td>57.0</td> <td>Outdoor</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>528692</th> <td>2022-06-01 01:05:01-07:00</td> <td>A20</td> <td>69.3</td> <td>Indoor</td> </tr> <tr> <th>528745</th> <td>2022-06-01 00:50:01-07:00</td> <td>A20</td> <td>69.6</td> <td>Indoor</td> </tr> <tr> <th>528798</th> <td>2022-06-01 00:35:01-07:00</td> <td>A20</td> <td>69.5</td> <td>Indoor</td> </tr> <tr> <th>528851</th> <td>2022-06-01 00:20:01-07:00</td> <td>A20</td> <td>69.6</td> <td>Indoor</td> </tr> <tr> <th>528904</th> <td>2022-06-01 00:05:01-07:00</td> <td>A20</td> <td>70.1</td> <td>Indoor</td> </tr> </tbody> </table> <p>188 rows × 4 columns</p> </div> ```python import pickle with open('../../data/df_effective_AC.pickle', 'wb') as f: pickle.dump(df_effective_AC, f) with open('../../data/df_ineffective_AC.pickle', 'wb') as f: pickle.dump(df_ineffective_AC, f) with open('../../data/df_A20_first_day.pickle', 'wb') as f: pickle.dump(df_A20_first_day, f) with open('../../data/df_incomplete.pickle', 'wb') as f: pickle.dump(df_incomplete, f) with open('../../data/df_indoor_only.pickle', 'wb') as f: pickle.dump(df_indoor_only, f) ``` ```python ```
<template> <div> <h2> Articles </h2> <form @submit.prevent="addArticle" class="mb-3"> <div class="form-group"> <input type="text" class="form-control" placeholder="Title" v-model="article.title"> </div> <div class="form-group"> <textarea type="text" class="form-control" placeholder="Body" v-model="article.body"></textarea> </div> <button type="submit" class="btn btn-light btn-block">Save</button> </form> <nav aria-label="Page navigation example"> <ul class="pagination"> <li v-bind:class="[{disabled: !pagination.prev_page_url}]" class="page-item"> <a class="page-link" href="#" @click="fetchArticles(pagination.prev_page_url)">Previous</a> </li> <li class="page-item disabled"><a class="page-link text-dark" href="#">Page {{pagination.current_page}} of {{pagination.last_page}}</a></li> <li v-bind:class="[{disabled: !pagination.next_page_url}]" class="page-item"> <a class="page-link" href="#" @click="fetchArticles(pagination.next_page_url)">Next</a> </li> </ul> </nav> <div class="card card-body mb-2" v-for="article in articles" v-bind:key="article.id"> <h3>{{ article.title }}</h3> <p>{{ article.body }}</p> <hr> <button @click="editArticle(article)" class="btn btn-warning mb-2">edit</button> <button @click="deleteArticle(article.id)" class="btn btn-danger">delete</button> </div> </div> </template> <script> export default { name: "articles", data() { return { articles: [], article: { id: '', title: '', body: '' }, article_id: '', pagination: {}, edit: false }; }, created() { this.fetchArticles(); }, methods:{ fetchArticles(page_url){ let vm = this; page_url = page_url || '/api/articles'; fetch(page_url) .then(res => res.json()) .then(res =>{ ///console.log(res.data); this.articles = res.data; vm.makePagination(res.meta, res.links); }) .catch(err => console.log(err)); }, makePagination(meta, links){ let pagination = { current_page: meta.current_page, last_page:meta.last_page, next_page_url: links.next, prev_page_url: links.prev }; console.log(pagination); this.pagination = pagination; }, deleteArticle(id){ if(confirm('are you sure?')){ fetch(`api/article/${id}`,{method:'delete'}) .then(res => res.json()) .then(data => { alert('article removed'); this.fetchArticles(); }) .catch(err =>console.log(err)); } }, addArticle(){ console.log(this.edit); if(this.edit === false){ //add fetch('api/article',{ method: 'post', body : JSON.stringify(this.article), headers:{ 'content-type':'application/json' } }) .then(res => res.json()) .then(data =>{ this.article.title = ''; this.article.body = ''; alert('article added'); this.fetchArticles(); }) .catch(err => console.log(err)); } else { //update fetch('api/article',{ method: 'put', body : JSON.stringify(this.article), headers:{ 'content-type':'application/json' } }) .then(res => res.json()) .then(data =>{ this.edit = false; this.article = { id: '', title: '', body: '' }; alert('article updated'); this.fetchArticles(); }) .catch(err => console.log(err)); /*this.edit = false; this.article = { id: '', title: '', body: '' };*/ } }, editArticle(article){ this.edit = true; this.article.id = article.id; this.article.article_id = article.id; this.article.title = article.title; this.article.body = article.body; } } } </script> <style scoped> </style>
import { Plugin } from "vite"; export default function ClassGenerator(): Plugin { const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const charactersLength = characters.length; const generatedClasses: Record<string, string> = {}; function generateClass(key: string): string { if (generatedClasses[key]) { return generatedClasses[key]; } let result = ""; for ( let i = 0; i < 6; i++ ) { result += characters.charAt(Math.floor(Math.random() * (i == 0 ? (charactersLength - 10) : charactersLength))); } generatedClasses[key] = result; return result; } return { name: "vue-class-generator", // enforce: "pre", transform: (code, id?, options?) => { if (code.search(/GC\.[^"]+/) != -1) { let transformed = code.replace(/GC\.[^"\s]+/g, (value) => { let scopeId = ""; let start = value.indexOf("["); if (start > -1) { scopeId = value.slice(start); value = value.split(scopeId).join(""); } return generateClass(value) + scopeId; }); return { code: transformed, map: "" } } }, } }
package ru.unn.agile.Deque.viewmodel; import org.junit.Before; import org.junit.Test; import ru.unn.agile.Deque.model.Deque; import ru.unn.agile.Deque.viewmodel.DequeViewModel.Action; import static org.junit.Assert.*; public class DequeViewModelTest { private DequeViewModel viewModel; @Before public void initializeDequeViewModel() { viewModel = new DequeViewModel(); } @Test public void byDefaultPushActionIsDisabled() { assertFalse(viewModel.isPushActionEnabled()); } @Test public void byDefaultPopActionIsDisabled() { assertFalse(viewModel.isPopActionEnabled()); } @Test public void byDefaultClearActionIsDisabled() { assertFalse(viewModel.isClearActionEnabled()); } @Test public void byDefaultCheckActionIsDisabled() { assertFalse(viewModel.isContainsActionEnabled()); } @Test public void whenEnteredNumberPushActionIsEnabled() { viewModel.setInputNumber("4"); assertTrue(viewModel.isPushActionEnabled()); } @Test public void whenDequeIsNotEmptyPopActionIsEnabled() { viewModel.setInputNumber("15"); viewModel.setAction(Action.PushFront); viewModel.doAction(); assertTrue(viewModel.isPopActionEnabled()); } @Test public void whenClearedNumberPushActionIsDisabled() { viewModel.setInputNumber("23"); viewModel.setInputNumber(""); assertFalse(viewModel.isPushActionEnabled()); } @Test public void whenEnteredNotNumberPushActionIsDisabled() { viewModel.setInputNumber("1a"); assertFalse(viewModel.isPushActionEnabled()); } @Test public void whenDequeIsEmptyPopActionIsDisabled() { viewModel.setInputNumber("4"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setAction(Action.PopFront); viewModel.doAction(); assertFalse(viewModel.isPopActionEnabled()); } @Test public void pushFrontAddsIntegersToDequeFront() { viewModel.setInputNumber("15"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setInputNumber("16"); viewModel.doAction(); Deque<Integer> testDeque = new Deque<>(); testDeque.pushFront(15); testDeque.pushFront(16); assertArrayEquals(viewModel.getAction().toArray(), testDeque.toArray()); } @Test public void pushBackAddsIntegersToDequeBack() { viewModel.setInputNumber("23"); viewModel.setAction(Action.PushBack); viewModel.doAction(); viewModel.setInputNumber("42"); viewModel.doAction(); Deque<Integer> testDeque = new Deque<>(); testDeque.pushBack(23); testDeque.pushBack(42); assertArrayEquals(viewModel.getAction().toArray(), testDeque.toArray()); } @Test public void popBackReturnsBackInteger() { viewModel.setInputNumber("4"); viewModel.setAction(Action.PushBack); viewModel.doAction(); viewModel.setInputNumber("8"); viewModel.doAction(); viewModel.setAction(Action.PopBack); viewModel.doAction(); assertEquals("8", viewModel.getOutput()); } @Test public void popFrontReturnsFrontInteger() { viewModel.setInputNumber("15"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setInputNumber("16"); viewModel.doAction(); viewModel.setAction(Action.PopFront); viewModel.doAction(); assertEquals("16", viewModel.getOutput()); } @Test public void clearActionClearsDeque() { viewModel.setInputNumber("4"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setAction(Action.Clear); viewModel.doAction(); assertTrue(viewModel.getAction().isEmpty()); } @Test public void whenDequeIsClearedClearActionIsDisabled() { viewModel.setAction(Action.Clear); viewModel.doAction(); assertFalse(viewModel.isClearActionEnabled()); } @Test public void whenDequeIsEmptyAfterPopClearActionIsDisabled() { viewModel.setInputNumber("15162342"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setAction(Action.PopFront); viewModel.doAction(); assertFalse(viewModel.isClearActionEnabled()); } @Test public void whenDequeIsClearedPopActionIsDisabled() { viewModel.setInputNumber("4"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setAction(Action.Clear); viewModel.doAction(); assertFalse(viewModel.isPopActionEnabled()); } @Test public void dequeContains4() { viewModel.setInputNumber("4"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setAction(Action.Contains); viewModel.doAction(); assertEquals("true", viewModel.getOutput()); } @Test public void dequeDoesNotContain8() { viewModel.setInputNumber("15"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setInputNumber("8"); viewModel.setAction(Action.Contains); viewModel.doAction(); assertEquals("false", viewModel.getOutput()); } @Test public void whenDequeIsClearedCheckActionIsDisabled() { viewModel.setInputNumber("4"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setAction(Action.Clear); viewModel.doAction(); assertFalse(viewModel.isContainsActionEnabled()); } @Test public void whenDequeIsEmptyAfterPopCheckActionIsDisabled() { viewModel.setInputNumber("15162342"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setAction(Action.PopFront); viewModel.doAction(); assertFalse(viewModel.isContainsActionEnabled()); } @Test public void dequeSizeIs3() { viewModel.setInputNumber("4"); viewModel.setAction(Action.PushFront); viewModel.doAction(); viewModel.setInputNumber("8"); viewModel.doAction(); viewModel.setInputNumber("15"); viewModel.doAction(); assertEquals(3, viewModel.getAction().getSize()); } @Test public void byDefaultDequeIsEmpty() { assertTrue(viewModel.getAction().isEmpty()); } @Test public void byDefaultDoActionButtonIsDisabled() { assertFalse(viewModel.isDoActionButtonEnabled()); } @Test public void whenPushBackIsSelectedActionIsPushBack() { viewModel.setAction(Action.PushBack); assertEquals(Action.PushBack, viewModel.getAction()); } @Test public void whenPopFrontIsSelectedActionIsPopFront() { viewModel.setAction(Action.PopFront); assertEquals(Action.PopFront, viewModel.getAction()); } @Test public void whenPopBackIsSelectedActionIsPopBack() { viewModel.setAction(Action.PopBack); assertEquals(Action.PopBack, viewModel.getAction()); } @Test public void whenClearIsSelectedActionIsClear() { viewModel.setAction(Action.Clear); assertEquals(Action.Clear, viewModel.getAction()); } @Test public void whenCheckIsSelectedActionIsCheck() { viewModel.setAction(Action.Contains); assertEquals(Action.Contains, viewModel.getAction()); } @Test public void whenActionIndexIs1ActionIsPushBack() { viewModel.setAction(1); assertEquals(Action.PushBack, viewModel.getAction()); } @Test public void whenActionIndexIs3ActionIsPopBack() { viewModel.setAction(3); assertEquals(Action.PopBack, viewModel.getAction()); } }
package com.example.travels; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageSwitcher; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; /** TravelAdapter es el adaptador para el RecyclerView que muestra la lista de imágenes de viajes. * @see TravelViewHolder ViewHolder para el RecyclerView. * @author Oscar Tena Marin * @version 2024-02-05 */ public class TravelAdapter extends RecyclerView.Adapter<TravelViewHolder> { private List<Integer> imagenes; public TravelAdapter(List<Integer> imagenes) { this.imagenes = imagenes; } /** * Método que se ejecuta al crear el ViewHolder. * @param parent Grupo de vistas al que pertenece el ViewHolder. * @param viewType Tipo de vista. * @return Nuevo ViewHolder. */ @NonNull @Override public TravelViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.travel_item,parent,false); return new TravelViewHolder(v); } /** * Método que se ejecuta al enlazar el ViewHolder con la posición. * @param holder ViewHolder que se va a enlazar. * @param position Posición del ViewHolder. */ @Override public void onBindViewHolder(@NonNull TravelViewHolder holder, int position) { int idImagen = imagenes.get(position); holder.imageView.setImageResource(idImagen); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ImageSwitcher imageSwitcher = view.getRootView().findViewById(R.id.imageSwitcher); imageSwitcher.setImageResource(idImagen); } }); } /** * Método que devuelve el número de elementos en la lista. * @return Número de elementos en la lista. */ @Override public int getItemCount() { return imagenes.size(); } }
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('sal.csv', names = ['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'salary'], na_values = ' ?') X = dataset.iloc[:, 0:14].values y = dataset.iloc[:, -1].values #encoding salary from sklearn.preprocessing import LabelEncoder labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) # Encoded Workclass(column by column differently) #labelencoder doesn't accept list labelencoder_X = LabelEncoder() X[:, 13] = labelencoder_X.fit_transform(X[:, 13].astype(str)) X[:, 1] = labelencoder_X.fit_transform(X[:, 1].astype(str)) X[:, 5] = labelencoder_X.fit_transform(X[:, 5].astype(str)) X[:, 3] = labelencoder_X.fit_transform(X[:, 3].astype(str)) X[:, 7] = labelencoder_X.fit_transform(X[:, 7].astype(str)) X[:, 8] = labelencoder_X.fit_transform(X[:, 8].astype(str)) X[:, 9] = labelencoder_X.fit_transform(X[:, 9].astype(str)) X[:, 6] = labelencoder_X.fit_transform(X[:, 6].astype(str)) #X[:, 14] = labelencoder_X.fit_transform(X[:, 14].astype(str)) #X[:, 13] = labelencoder_X.fit_transform(X[:, 13].astype(str)) #X[:, 13] = labelencoder_X.fit_transform(X[:, 13].astype(str)) #X[:, 13] = labelencoder_X.fit_transform(X[:, 13].astype(str)) #X[:, 13] = labelencoder_X.fit_transform(X[:, 13].astype(str)) #Dummy variable encoding from sklearn.preprocessing import OneHotEncoder onehotencoder=OneHotEncoder(categorical_features=[1,3,5,7,8,9,6,13]) X=onehotencoder.fit_transform(X) X=X.toarray from sklearn.preprocessing import Imputer imputer = Imputer() X[:, 0:14] = imputer.fit_transform(X[:, 0:14]) from sklearn.linear_model import LogisticRegression log_reg = LogisticRegression() log_reg.fit(X, y) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) from sklearn.naive_bayes import GaussianNB clf = GaussianNB() clf.fit(X_train,y_train) clf.score(X_train, y_train) clf.score(X_test, y_test) clf.score(X, y) log_reg.score(X, y)
import { useState } from "react" export const AppClima = () => { const urlBase = `https://api.openweathermap.org/data/2.5/weather` const APY_KEY = `005bfd3b81b2d6d5a926320d6106e602` const [ciudad, setCiudad] = useState('') const [dataClima, setDataClima] = useState(null) const cambioCiudad = (e) => { setCiudad(e.target.value) } const submit = (e) => { e.preventDefault() if (ciudad.length > 0) fetchClima() } const fetchClima = async () => { try { const response = await fetch(`${urlBase}?q=${ciudad}&appid=${APY_KEY}`) const data = await response.json() setDataClima(data) } catch (error) { console.error('Ha ocurrido un error: ', error) } } const difKelvin = 273.15 return ( <div className="container"> <h1>Aplicacion del Clima</h1> <form onSubmit={submit}> <input type="text" value={ciudad} onChange={cambioCiudad} /> <button type="submit">Buscar Ciudad</button> </form> { dataClima && ( <div> <p>{parseInt(dataClima.main.temp-difKelvin)}°</p> <h2>{dataClima.name}</h2> <h3>{parseInt(dataClima.main.temp_max-difKelvin)}°/{parseInt(dataClima.main.temp_min-difKelvin)}° Sensación térmica: {parseInt(dataClima.main.feels_like-difKelvin)}° </h3> <img src={`https://openweathermap.org/img/wn/${dataClima.weather[0].icon}@2x.png`} /> </div> ) } </div> ) }
#include "UiElement.h" #include <ofApp.h> long UiElement::uniqueIdCounter = 0; bool UiElement::isInBounds(float relX, float relY) { // Take coorditanes of a point relative to the top left corner of this element, and determine if the given point is inside this element or not return relX >= 0 && relY >= 0 && relX < this->width && relY < this->height; } void UiElement::onRender(float x, float y) { for (auto child : this->Children) { // Call onRender on all the child elements child->onRender(x + child->xPosition, y + child->yPosition); } } void UiElement::onUpdate() { for (auto child : this->Children) { // Call onUpdate on all the child elements child->onUpdate(); } } UiElement::UiElement(float x, float y, float width, float height) { this->width = width; // Save the arguments of this constructor as fields of this class. this->height = height; this->xPosition = x; this->yPosition = y; this->uniqueId = uniqueIdCounter++; // Generates a unique id for this element. I have done the maths, and even if this program created 1000 elements per second (1 every millisecond), the computer running this program will decompose before this counter overflows (time for e-waste to decompose is somewhere between 50 years and 1 million years, and this will take aproximately 584 million years to overflow). This means that we can safely assume this id is going to be unique. } /// <summary> /// Checks if this element or one of its children is being hovered over. /// </summary> /// <returns></returns> bool UiElement::isHoveredOver() { if (ofApp::hoveredElement.expired()) return false; // If the pointer has expired then that means the screen has changed, or the hovered over element somehow went out of scope. Either way we need to update the currently hovered over element, so we can return false for now. auto fullPointer = ofApp::hoveredElement.lock(); // Gets a shared pointer to the element which is being hovered over if (fullPointer->uniqueId == this->uniqueId) return true; for (auto child : this->Children) { if (child->isHoveredOver()) return true; // Calls itself on this element's children. If one of the children is being hovered over, then this element is as well. } return false; } bool UiElement::onClick(float x, float y) { for (auto child : this->Children) { //Go through all the child elements in order to determine which one handled the click float relX = x - child->xPosition; float relY = y - child->yPosition; if (child->isInBounds(relX, relY) && child->onClick(relX, relY)) return true; } return false; } void UiElement::centerHorizontallyOnScreen() { this->xPosition = ofGetWidth() / 2 - this->width / 2; } void UiElement::centerHorizontallyInParent(std::shared_ptr<UiElement> parent) { this->xPosition = parent->width / 2 - this->width / 2; }
/** * type of the class stage * @author euric */ class Desenvolvimento extends Tarefa{ private double esforcoReal; public Desenvolvimento() { } /** * receives the input value of the real amount of effort spent on a stage * @param esforcoReal */ @Override public void setEsforcoReal(double esforcoReal) { this.esforcoReal = esforcoReal; } /** * returns the value of real amount of effort spent on a stage * @return */ @Override public double getEsforcoReal() { return esforcoReal; } /** * returns the amount of hours of expected effort to be made on this stage, per day * @return */ @Override public double getTaxaEsforco() { return 24; } /** * print info about this type of stage * @return */ @Override public String toString() { return "\n---Tarefa de Desenvolvimento---" + super.toString(); } }
<template> <div class="section"> <div class="top-section d-flex justify-content-between align-items-center mb-4"> <h2 class="font-weight-bold">Contact Details</h2> <div> <button @click="saveContact" class="btn btn-primary">Save</button> <button @click="goBack" class="btn btn-outline-secondary">Back</button> </div> </div> <div class="d-flex align-items-center mb-4"> <img :src="getAvatarURL(contact.email)" alt="Contact Avatar" class="avatar rounded-circle mr-3" /> <div> <p class="mb-1"><strong>Name:</strong> {{ contact.name }}</p> <p class="mb-0"><strong>Email:</strong> {{ contact.email }}</p> </div> </div> <!-- Add TransferFunds component --> <TransferFunds v-if="isLoggedIn" :contact="contact" /> <!-- Conditionally render TransactionList component --> <TransactionList v-if="isLoggedIn" :contactId="contact._id" /> </div> </template> <script> import { contactService } from '../../services/contactService' import TransferFunds from '../transfers/TransferFunds.vue' import TransactionList from '../transfers/TransactionList.vue' import { mapGetters } from 'vuex' export default { components: { TransferFunds, TransactionList }, data() { return { contact: null, editedContact: { name: '', email: '' } } }, computed: { ...mapGetters('user', ['isLoggedIn']) }, created() { const contactId = this.$route.params.id this.fetchContact(contactId) }, methods: { fetchContact(contactId) { contactService .getContactById(contactId) .then((contact) => { this.contact = contact // Clone the contact object to keep the original data this.editedContact = { ...contact } }) .catch((error) => { console.error('Error fetching contact:', error) }) }, async saveContact() { try { // Call the saveContact action and pass the editedContact object await this.$store.dispatch('contact/saveContact', this.editedContact) // Handle successful save, e.g., show a success message this.goBack() } catch (error) { console.error('Error saving contact:', error) // Handle error, e.g., show an error message } }, getAvatarURL(email) { const hash = this.generateHash(email) return `https://robohash.org/${hash}.png` }, generateHash(email) { let hash = 0 for (let i = 0; i < email.length; i++) { hash = email.charCodeAt(i) + ((hash << 5) - hash) } return hash }, goBack() { this.$router.go(-1) } } } </script> <style scoped> h2 { margin-bottom: 1rem; } .avatar { height: 100px; } .btn-primary { background-color: #007bff; color: white; } .btn-outline-secondary { border-color: #6c757d; color: #6c757d; } .btn-outline-secondary:hover { background-color: #6c757d; color: white; } .rounded-circle { width: 100px; height: 100px; } .mb-0 { margin-bottom: 0; } </style>
//SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; // Libraries import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; library UserInfoLib { using EnumerableSet for EnumerableSet.UintSet; using SafeMath for uint256; uint256 private constant AMOUNT_SCALE = 1e12; // Info of each user. struct UserInfo { EnumerableSet.UintSet tokenIds; uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of TOKENs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accTokenPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accTokenPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } function hasTokenId(UserInfo storage self, uint256 tokenId) internal view returns (bool) { return self.tokenIds.contains(tokenId); } function getTotalTokens(UserInfo storage self) internal view returns (uint256) { return self.tokenIds.length(); } function getTokenIdAt(UserInfo storage self, uint256 index) internal view returns (uint256) { return self.tokenIds.at(index); } function getTokenIds(UserInfo storage self) internal view returns (uint256[] memory tokenIDs) { tokenIDs = new uint256[](self.tokenIds.length()); for (uint256 indexAt = 0; indexAt < self.tokenIds.length(); indexAt++) { tokenIDs[indexAt] = self.tokenIds.at(indexAt); } return tokenIDs; } function requireHasTokenId(UserInfo storage self, uint256 tokenId) internal view { require(hasTokenId(self, tokenId), "ACCOUNT_DIDNT_STAKE_TOKEN_ID"); } function addTokenId(UserInfo storage self, uint256 tokenId) internal { self.tokenIds.add(tokenId); } function removeTokenId(UserInfo storage self, uint256 tokenId) internal { self.tokenIds.remove(tokenId); } function stake( UserInfo storage self, uint256 valuedAmountOrId, uint256 accTokenPerShare ) internal { self.amount = self.amount.add(valuedAmountOrId); self.rewardDebt = self.amount.mul(accTokenPerShare).div(AMOUNT_SCALE); } function unstake( UserInfo storage self, uint256 valuedAmountOrId, uint256 accTokenPerShare ) internal { self.amount = self.amount.sub(valuedAmountOrId); self.rewardDebt = self.amount.mul(accTokenPerShare).div(AMOUNT_SCALE); } function emergencyUnstakeAll(UserInfo storage self) internal { self.amount = 0; self.rewardDebt = 0; } function cleanTokenIDs(UserInfo storage self) internal { delete self.tokenIds; } }
<!-- Draft version by Peter HU --> ## DVFS Thermal Model and Algorithm - Uniform / Variable Frequency Setting - Uniform: the operating frequencies of all the cores are the same. For such systems, when DFS is applied, the core frequencies are varied uniformly. ### [Pro-Temp] Temperature Control in 2008 [SMP-Temperature_Control_Using_Convex_Optimization](../SMP/SMP-AM-2008-Joint_Murali-Temperature_Control_Using_Convex_Optimization.pdf) Ref: S. Murali et al., “Temperature control of high-performance multi-core platforms using convex optimization,” in Proc. of DATE, 2008. - Temperature control techniques for homogeneous multicore systems (SMP) through DVFS - To proactively **vary the frequencies of the cores** instead of setting them as the average speed. ### Details of the design **1st phase [Design-Time]** - to obtain the set of feasible frequencies for the cores for different temperature and workload constraints <img src="./Pic/DTPM-2008-Phase1.png" alt="DTPM-2008-Phase1" width="480px" height="400px"/> Denote | Core 1 | ...... | Core i | ..... | Core j | ..... | Core n | | ------------- | ------ | ------------- | ----- | ------ | ----- | ------------- | | Power-$p_1$ | ..... | Power-$p_i$ | | | | Power-$p_n$ | - The power consumption of a core i := $ p_i$ - obtained by quadratically scaling the power consumption of the processors at f_max. $$ p \propto f ^2 $$ - $$ p_i = p_{max} \frac{f_i^2}{f_{max}^2} $$ - The set of cores that are adjacent to a core i := Adj_i - The proportionality constants ai,j and bi are based on the thermal behavior of the chip. - to get them, using finite element simulations or a thermal modeling framework like Hotspot - The number of time-steps needed for thermal calculations := m #### Compact Model in Thermal-design There exists a well-known duality [Krum 2000]. The rationale behind is that current and heat flow are described by exactly the same differential equations for a potential difference. This duality provides a convenient basis for an architecture-level thermal model. For a microarchitectural unit, heat conduction to the thermal package and to neighboring units are the dominant mechanisms that determine the temperature. | Heat Transfer | Electrical Phenomena | | -------------------------------------------------------- | ------------------------------------------ | | Heat flow passing through a thermal resistance | Current passing through a resistance | | Heat:$Q$ | Charge:$q$ | | Temperature Difference:$ \Delta T$ | Voltage:$V$ | | Thermal capacitance:$ C_t =\frac{\Delta Q}{\Delta T} $ | Capacitance:$C =\frac{q}{V} $ | | $ R C_t \frac{d T(t)}{dt} +T(t) = R P(t) $ | $ R C \frac {d V(t)}{dt} +V(t) = V_I $ | Explanation: - Heat flow can be described as a “current” passing through a thermal resistance, leading to a temperature difference analogous to a “voltage.” - Thermal capacitance is also necessary for modeling transient behavior, to capture the time required for a mass to change temperature and hence to account for the delay before a change in power results in the temperature’s reaching steady state. - Lumped values of thermal R and C can be computed to represent the heat flow among regions of a chip and from each region to the thermal package. - The thermal Rs and Cs together lead to exponential rise and fall times characterized by thermal RC time constants analogous to the electrical RC time constants. - These equivalent circuits are called compact models and dynamic compact models if they include thermal capacitors [2] K. Skadron, M. Stan, W. Huang, S. Velusamy, K. Sankaranarayanan and D. Tarjan, “Temperature-aware microarchitecture: Modeling and implementation,” ACM Trans. Archit. Code Optim., vol. 1, no. 1, pp. 94–125, Mar. 2004. #### Thermal Equation We discretize the equation above assuming a sampling period of Ts seconds. The thermal equation of core i at current time (k+1) is based on the previous one timestamp (k). $$ t_i ' = t_i + \sum_{\forall j \in Adj_i} a_{i,j} (t_j - t_i) + b_i p_i $$ Need to be smaller than maximum allowable temperature := t_max $$ s.t. \quad t_i' \leq t_{max}\quad (\forall i, timestamp_k) $$ - Starting value (k=0) of the thermal equation := t_start. - The target operating frequency of the cores that need to meet := f_target - The frequency of operation of core i := $f_i \geq 0$ $$ s.t. \quad \frac {\sum_i f_i}{n} \geq f_{target} $$ **Temperature Gradients** a **[physical quantity](https://en.wikipedia.org/wiki/Physical_quantity "Physical quantity") that describes in which direction and at what rate the** [temperature](https://en.wikipedia.org/wiki/Temperature "Temperature") changes the most rapidly around a particular location. Assumption: Uniform spatial temperature gradients across the cores $$ t_i - t_j \leq tgrad \quad (\forall i,j) $$ #### Objective Find a vector $f_i \geq 0$ that satisfies the above restrictions and $$ min \quad \sum_i p_i + tgrad $$ $$ min \quad \sum_i p_{max} \frac{f_i^2}{f_{max}^2} + tgrad $$ Solving convex optimization models - using interior point methods [Non-Linear w.r.t $f_i$] - polynomial time complexity (in the number of variables and constraints) #### Design Time Implementation We use the execution characteristics of tasks from a mix of different benchmarks, ranging from web-accessing to playing multimedia files [26]. The maximum task/thread lengths of the benchmarks is around 10 ms. The experiments are conducted using a large trace with around 60,000 tasks, modeling several hundredseconds of actual system execution. <img src="./Pic/DTPM-2008-Phase1-Output.png" alt="DTPM-2008-Phase1-Output" width="600px"/> **2nd phase [Run-Time]** - The Thermal Management Unit - tracks - the utilization and temperature information of the different processors - workload of the tasks waiting in the task queue - calculates the required average operating frequency across all the processors for the next period. - chooses the frequency assignment for the processors from the table. - If the frequency point cannot be supported, the unit chooses the next lower frequency point in the table that can support the temperature constraints. #### Effects With the integration of the efficient task assignment policy with our Pro-Temp method, the spatial temperature difference across the cores reducesfurther (by 16%). <img src="././Pic/DTPM-2008-Thermal.png" alt="High level of DTPM" height="400"> ### Variable Frequency Setting considering floorplan of the chip The processors near the cooler caches ( compare with near other hotter processors ) - can more easily dissipate their heat than the other processors. - can be set at a larger frequency. ----- Appendix : List of related literature ---- #### [Related] Temperature aware task scheduling and migration techniques [13] A. K. Coskun, J. L. Ayala, D. Atienza, T. S. Rosing, and Y. Leblebici, “Dynamic thermal management in 3d multicore architectures,” in Proc. of DATE, 2009. [14] V. Hanumaiah, S. Vrudhula, and K. S. Chatha, “Performance optimal online dvfs and task migration techniques for thermally constrained multi-core processors,” IEEE Trans on CAD of Integrated Circuits and Syst., vol. 30, no. 11, pp. 1677–1690, 2011. #### [Related] Model predictive and optimal control theory employed for thermal management to achieve smooth control with minimal performance loss [15] F. Zanini, D. Atienza, L. Benini, and G. De Micheli, “Multicore thermal management with model predictive control,” in European Conf. on Circuit Theory and Design, 2009. [16] Y. Wang, K. Ma, and X. Wang, “Temperature-constrained power control for chip multiprocessors with online model estimation,” in AC M SIGARCH Comp. Arch. News, vol. 37, no. 3, 2009, pp. 314–324. #### [Related] Others Agent [17] M.A.AlFaruque,J.Jahn,T.Ebi,andJ.Henkel,“Runtimethermalmanagement using software agents for multi-and many-core architectures,”IEEE Design & Test of Computers, vol. 27(6), pp. 58–68, 2010. [4] T. S. Muthukaruppan et al., “Hierarchical power management for asymmetric multi-core in dark silicon era,” in Proc. of DAC, 2013. ----- Appendix : List of related literature ---- ### [PROMETHEUS-framework] Thermal Power in HMP Embedded [Proactive_Method_for_Thermal](../HMP/Thermal/HMP-AM-2013-USA_Sharifi-Proactive_Method_for_Thermal.pdf) Ref: PROMETHEUS: A Proactive Method for Thermal Management of Heterogeneous MPSoCs, Shervin Sharifi, Member, IEEE, Dilip Krishnaswamy, Senior Member, IEEE, and Tajana Sˇimunic ́ Rosing, Member, IEEE #### Thermal Model - consider various performance, power, and thermal characteristics for cores - Same compact model $ R C_t \frac{d T(t)}{dt} +T(t) = R P(t) $, with analytical solution to the non-homogeneous system of differential equations. <img src="././Pic/DTPM-2013-Network.png" alt="2013-Network" height="400"> - Lack of thermal information of internal nodes : break the vector of temperature values (T) into two subvectors. - Good news: F_u doesn't change quickly! Assumption: Fu[k + 1] ≈ Fu[k] - Subvector To represents *observable nodes* by thermal sensors (core temperatures) - Subvector Tu represents the internal nodes whose temperatures are *unobservable* <img src="././Pic/DTPM-2013-Analytical.png" alt="Analytical Solution" height="400"> <img src="././Pic/DTPM-2013-TempBreakDown.png" alt="2013-TempBreakDown" height="400"> - $$ T_o[k + 1] = \Psi_{oo}T_o[k] + \Psi_{uo}T_u[k] + \Phi_{oo}P[k + 1] $$ $$ T_o[k + 1] = F_o+F_u+F_p $$ - Consider the difference between time k and k+1, T_u can be eliminated. - $$ T_o[k+1] = (\Psi_{oo} +I)T_o[k]−\Psi_{oo}T_o[k−1]+\Phi_{oo}(P[k+1]−P[k]). $$ - Incorporate the leakage power and its temperature dependence $Pleak(t) = LT(t) + Q$ - Linear approximation of the leakage as suggested in [13] with an approximate estimation error of up to 5% - L is a diagonal matrix containing the coefficients for the linear terms and Q is a vector of constant terms for different cores. #### Proactive Temperature Aware Scheduling <img src="././Pic/DTPM-2013-Scheduler.png" alt="DTPM-2013-Scheduler" height="200"> - guarantees that the maximum temperature threshold will not be exceeded. - can be applied to any preemptive, multitasking scheduling system that is able to preempt the tasks or migrate them to other cores at scheduling intervals. **Power State Decision Modules** Two scheduling techniques - TempoMP - determines the safe power states based on an optimization stage that is performed offline and its results are stored for runtime use. Although the optimization technique can provide locally optimal power state decisions, storing and fetching the optimization results incurs overhead. - TemPromp - To avoid this overhead of storing and retreiving, use a heuristic for its power state decision module. ### Multi-parametric programming Multiparametric optimization approach splits the optimization process into offline and online stages. We describe how we deal with the general case of systems with **multiple cores** and different representation of performance requirements. - $\Omega$ := The core type - Power states for each type of the cores $$ \alpha_{n,v} = 1 \quad iff. core_n-is-set-to-Power-state_v $$ the Varying Parameters (Inputs) - Performance Requirements $$ s.t. \quad \forall \Omega,v: number-of-cores-used \sum_\Omega -\alpha_{w,v} \geq minimum-number-of-cores -\sigma_{\Omega,v} $$ - the Thermal State of the MPSoC $$ s.t. \quad T(\alpha[k+1],\alpha[k],T_o[k+1])< T_{Threshold} $$ #### Objective $$ min_\alpha \quad P_{total}(\alpha[k+1],T_o[k+1]) $$ #### TempoMP - Instead of solving the optimization problem at each scheduling tick, use multiparametric programming, the optimization problem is solved offline. - The set of critical regions (one-to-one mapping) and parametric solutions are provided as output. - Memory required for the critical regions of the MPSoC of Fig. 7 is less than 500 KB. <img src="././Pic/DTPM-2013-Multi-Prog.png" alt="DTPM-2013-Multi-Prog" height="200"> - No optimization needs to be done at runtime. Only a limited number of operations need to be performed at runtime in order to find the critical regions corresponding to the current solution. - Then the Fr values are used to find the proper region within this set. If nr is the average number of regions in each set of regions (nr < 5 in our experiments) and nc is the number of the cores, then finding the right region within a set needs nr × nc multiply/add operations on average[17]. - Therefore, the complexity of this algorithm is $O(nr × nc )$. #### TemPromp To avoid this overhead of storing and retreiving, use a heuristic for its power state decision module. - Sorting the core types in the decreasing order of their performance (average IPS). $O(n_c log(n_c))$ - Sort the set of cores with the same type in increasing order of the cores’ Ti[k + 1] - Checks the instances of each type of cores in the increasing order of T [k + 1]. $O(n_c)$ - Core i is set to the lower of p_req and **p_safe** ($T_o[k+1]< T_{Threshold}$) to provide just enough performance for the workload and not to exceed the temperature threshold. #### Task Assignment to the cores - make sure that the task with the highest performance requirement (earliest ddl) is provided with the highest performance core (at the highest power state) available. - the algorithm always finishes because at each iteration it assigns a task to an available core and finishes when no core or no task is left. - using a binary heap, no sorting is necessary for the tasks - Complexity: $O(max (n_r×n_c, n_t, n_c log(n_t) )$ ### [DTPM] Thermal Power in HMP Mobile [HMP-AM-2015-USA_Singla-Thermal_Power-Mobile](../HMP/Thermal/HMP-AM-2015-USA_Singla-Thermal_Power.pdf) Ref: Predictive_dynamic_thermal_and_power_management_for_heterogeneous_mobile_platforms, 2015 #### DTPM Linux implementation of DTPM: please refer to [DTPM Linux](https://docs.kernel.org/power/powercap/dtpm.html) <img src="././Pic/DTPM-high-level.png" alt="High level of DTPM" height="100"> The proposed DTPM approach is **non-intrusive** when the temperature is within permissible levels (i.e. when Thermal Violation == NO). #### Power and Thermal Models with experimental validation using one of the first commercial big.LITTLE architectures (Samsung Exynos 5410 octa-core chip). Compute power budget using temperature prediction Thermal Equation also enables temperature prediction at an arbitrary number of time steps $ t_i^{n}$ ahead. In particular, the temperature at time step k + n can be derived. $$ t_i ' = t_i + \sum_{\forall j \in Adj_i} a_{i,j} (t_j - t_i) + b_i p_i $$ $$ t_i '' = t_i' + \sum_{\forall j \in Adj_i} a_{i,j} (t_j' - t'_i) + b_i p'_i $$ - Prediction interval A prediction interval of “1s” since it is sufficient to control the temperature of our target platform. In general, accurate predictions up to“5s” can be made. #### Algorithm - If the predicted temperature exceeds the specified constraint for any one of the hotspots, the power budget is computed, as explained in Section V-B. - To minimize the impact on performance, the pro-posed algorithm - First finds the maximum feasible frequencies under the available power budget. - If the power budget cannotbe met with the current number of active cores, then the hottest core is put to sleep, and the tasks running on this core aremigrated to the other cores by the kernel. - Finally, when the power budget is so small that it cannot be satisfied even witha single big core, then all the active tasks are migrated to the little cluster and big cores are put to sleep. - Moving to the little cluster and reducing the GPU frequency (if GPU is active) are used as the last resort, - since they have the biggest performance impact and the migrating across clusters has a larger overhead based on our empirical evaluations. #### Effects Exhaustive experimental evaluation which demonstrates effective thermal regulation with 6× smaller variance and as much as 16% reduction in total platform power. In particular, it regulates the temperature more effectively than the default configuration which uses a fan, and on average offers 10% platform power savings with 3.3% **loss** in performance. ### Appendix: TO DO [HMP-AM-2017-Bhat-Thermal_Power](../HMP/Thermal/HMP-AM-2017-Bhat-Thermal_Power.pdf) Ref: Algorithmic Optimization of Thermal and Power Management for Heterogeneous Mobile Platforms, 2017 [HMP-AM-2017-Pakistan_Khan-Thermal_Power](../HMP/Thermal/HMP-AM-2017-Pakistan_Khan-Thermal_Power.pdf) Ref: Scheduling_based_energy_optimization_technique_in_multiprocessor_embedded_systems
<?php /* @var $this \yii\web\View */ /* @var $content string */ use backend\assets\AppAsset; use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use common\widgets\Alert; AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <meta charset="<?= Yii::$app->charset ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <div class="wrap"> <?php NavBar::begin([ 'brandLabel' => '商品后台管理', 'brandUrl' => Yii::$app->homeUrl, 'options' => [ 'class' => 'navbar-inverse navbar-fixed-top', ], ]); // $menuItems=[ // ['label' => '登录', 'url' => ['user/login']],//可跳转的一级菜单 // ['label' => '用户管理', 'items' => [ // ['label' => '添加用户', 'url' => ['user/add']],//添加用户 // ['label' => '用户列表', 'url' => ['user/index']],//用户列表 // ]],//不可跳转,带下来列表的一级菜单 // ['label' => '文章管理', 'items' => [ // ['label' => '添加文章', 'url' => ['user/add']],//添加用户 // ['label' => '文章列表', 'url' => ['user/index']],//用户列表 // ]],//不可跳转,带下来列表的一级菜单 // ]; $menuItems=[]; $menus=backend\models\Menu::findAll(['parent_id'=>0]); foreach ($menus as $menu){ $items=[]; foreach ($menu->children as $child){ if (Yii::$app->user->can($child->url)){ $items[]=['label'=>$child->name,'url'=>[$child->url]]; } } if (!empty($items)){ $menuItems[]=['label'=>$menu->name,'items'=>$items]; } } if (Yii::$app->user->isGuest) { $menuItems[] = ['label' => '登录', 'url' => ['/admin/login']]; } else { $menuItems[] = '<li>' . Html::beginForm(['/admin/logout'], 'post') . Html::submitButton( '注销 (' . Yii::$app->user->identity->username . ')', ['class' => 'btn btn-link logout'] ) . Html::endForm() . '</li>'; } echo Nav::widget([ 'options' => ['class' => 'navbar-nav navbar-right'], 'items' => $menuItems, ]); NavBar::end(); ?> <div class="container"> <?= Breadcrumbs::widget([ 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ]) ?> <?= Alert::widget() ?> <?= $content ?> </div> </div> <footer class="footer"> <div class="container"> <p class="pull-left">&copy; My Company <?= date('Y') ?></p> <p class="pull-right"><?= Yii::powered() ?></p> </div> </footer> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?>
import React from "react"; import { Link } from "react-router-dom"; import Product from "../components/Product"; import Rating from "../components/Rating"; import data from "../data"; export default function ProductScreen(props) { // using find method to match the product id with the routing id const product = data.products.find((x) => x._id === props.match.params.id); if (!product) { return <div> product Not Found</div>; } return ( <div> <Link to="/">Back to results</Link> <div className="row top"> {/* photo column */} <div className="col-2"> <img className="large" src={product.image} alt={Product.name}></img> </div> {/* information div */} <div className="col-1"> <ul> <li><h2>{product.name}</h2></li> <li> <Rating rating={product.rating} numReviews={product.numReviews} ></Rating> </li> <li>Price : ${product.price}</li> <li> Description: <p>{product.description}</p> </li> </ul> </div> {/*Action column */} <div className="col-1"> <div className="card card-body"> <ul> <li> <div className="row"> <div>price</div> <div className="price">$ {product.price}</div> </div> </li> <li> <div className="row"> <div>Status</div> <div className=""> {product.countInStock > 0 ? ( <span className="success">In Stock</span> ) : ( <span className="error">Out Of Stock</span> )} </div> </div> </li> <li> <button className="primary block"> Add to Cart</button> </li> </ul> </div> </div> </div> </div> ); }
""" 23. Merge k Sorted Lists You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6 """ from typing import List, Optional class ListNode(object): def __init__(self, val=0, next=None) -> None: self.val = val self.next = next def merge_lists(l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: sentinel = ListNode() current = sentinel while l1 is not None and l2 is not None: if l1.val < l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next if l1 is not None: current = l1 elif l2 is not None: current = l2 return sentinel.next def merge_k_lists(lists: List[Optional[ListNode]]) -> Optional[ListNode]: # Time Complexity: O(n log k) if not lists: return None if len(lists) == 1: return lists[0] mid = len(lists) // 2 left = merge_k_lists(lists[:mid]) right = merge_k_lists(lists[mid:]) return merge_lists(left, right)
package com.athena.mis.integration.projecttrack import com.athena.mis.PluginConnector import com.athena.mis.application.entity.Company import com.athena.mis.application.service.* import com.athena.mis.projecttrack.service.* import org.hibernate.SessionFactory import org.springframework.transaction.annotation.Transactional class ProjectTrackDefaultDataBootStrapService { SessionFactory sessionFactory SystemEntityTypeService systemEntityTypeService SystemEntityService systemEntityService ReservedSystemEntityService reservedSystemEntityService RoleService roleService RoleTypeService roleTypeService RequestMapService requestMapService RoleFeatureMappingService roleFeatureMappingService AppMailService appMailService PtAcceptanceCriteriaService ptAcceptanceCriteriaService PtBacklogService ptBacklogService PtBugService ptBugService PtModuleService ptModuleService PtProjectModuleService ptProjectModuleService PtProjectService ptProjectService PtSprintService ptSprintService @Transactional public void init() { Company defaultCompany = Company.list(readOnly: true)[0] // read the only object long companyId = defaultCompany.id systemEntityTypeService.createDefaultDataForProjectTrack() reservedSystemEntityService.createDefaultDataForPT() systemEntityService.createDefaultContentEntityTypeForPT(companyId) systemEntityService.createDefaultDataBacklogPriorityForPT(companyId) systemEntityService.createDefaultDataBacklogStatusForPT(companyId) systemEntityService.createDefaultDataAcceptanceCriteriaStatusForPT(companyId) systemEntityService.createDefaultDataBugSeverityForPT(companyId) systemEntityService.createDefaultDataBugStatusForPT(companyId) systemEntityService.createDefaultDataSprintStatusForPt(companyId) systemEntityService.createDefaultDataBugTypeForPT(companyId) systemEntityService.createDefaultDataAcceptanceCriteriaTypeForPT(companyId) systemEntityService.createDefaultNoteEntityTypeForPT(companyId) roleTypeService.createDefaultDataForPT() roleService.createDefaultDataForPT(companyId) requestMapService.createRequestMapForProjectTrack() roleFeatureMappingService.createRoleFeatureMapForProjectTrackPlugin() flushSession() requestMapService.appendRoleInRequestMap(PluginConnector.PROJECT_TRACK_ID) ptModuleService.createDefaultDataForPtModule(companyId) ptProjectService.createDefaultDataForPtProject(companyId) ptProjectModuleService.createDefaultDataForPtProjectModule(companyId) ptAcceptanceCriteriaService.createDefaultDataForPtAcceptanceCriteria(companyId) ptBacklogService.createDefaultDataForPtBacklog(companyId) ptBugService.createDefaultDataForPtBug(companyId) ptSprintService.createDefaultDataForPtSprint(companyId) appMailService.createDefaultDataForProjectTrack(companyId) } private void flushSession() { def hibSession = sessionFactory.getCurrentSession() if (hibSession) { hibSession.flush() } } }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Assignment 1: Matlab Scavenger Hunt and HelloWorld % % Submitted by: Gustavo Sandri Heidner % % Due: August 31, 2017 % % Instructions: % There are two parts to this assignment. Part 1 deals with using the % Matlab documentation to answer some questions or perform some tasks. Part % 2 involves you writing your very first Matlab program!! % Please write all of your responses in the following .mfile. % If there are comments after the question (as in question 2) please % write your answer inside those comments. If there are not comments % please write your answer with correct matlab syntax. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%% Part 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 1. Set the url of the matlab documentation to a variable called helpURL helpURL = 'https://www.mathworks.com/help/matlab/'; % 2. What does the command 'clear all' do? % % Answer: clear ALL removes all variables, globals, functions and MEX links. % clear ALL at the command prompt also clears the base import list. % Calling clear ALL decreases code performance and is usually unnecessary. % % 3. What function would you use to take the average of the following % numbers [1 7 21 32 67 32453]? Store your answer in a variable called % averageAnswer. averageAnswer = mean([1 7 21 32 67 32453]); % 4. What command would you type to see a list of all installed toolboxes? ver % 5. What command would return a list of all of the available functions in % the image processing toolbox? help images % 6. On the line below figure, write a command to draw a graph of % x and y. x = linspace(-2*pi,2*pi); y = sin(x); figure plot(x,y) %<- command goes here % 7. Find a function that performs a statistical test you've seen used % in a journal article (there are many possible answers to this). % % Answer: corrcoef() % % 8. What are the 2 major types of loops that MATLAB supports? What is the % difference between them? % % Answer: For and While loops. While loops repeat a statement for an % infinite number of times while the "condition" is True. For loops repeat % the statement for a pre-set, specific, number of times. % % 9. What does NaN stand for? Give an example of when you would get NaN as % an answer. % % Answer: Not-a-Number. It is the result for a mathematically undefined % operation, like 0 divided by 0 and/or inf-inf. % % 10. The following code snippet executes but contains an error (we don't % get a useful answer). See if you can use the documentation to fix the % error to get the sum of the numbers in A. Do not change or remove % any of the values in A. A = [1 2 3 2 1 NaN 1 2 3 NaN]; S = sum(A, 'omitnan') % 11. I used to love playing the game minesweeper. Is there a way that I % could play a similar game on Matlab? Write the command that would launch % the game if so. xpbombs % 12. What happens if you type why and hit enter in the command window? % Repeat this a few times and copy your result below (Make sure everything % is commented out). % % Answer: why % Some mathematician obeyed a kid. % why % For the love of Pete. % why % Some terrified hamster wanted it. % why % Why not? % why % A engineer insisted on it. % why % For the approval from the rich hamster. % why % I obeyed a very smart mathematician. % why % Mary Ann wanted it that way. % why % How should I know? % why % Because they asked the terrified and smart and tall and tall programmer. % why % To fool a young tall hamster. % %%%%%%%%%%%%%%%%%%%%%%%%%% Part 2: Hello World %%%%%%%%%%%%%%%%%%%%%%%%%% % Write some code that will print the string 'Hello World' to the screen. % There are several ways that you could do this. For an extra challenge, % make your program able to take text input from the user and output % whatever they input. (For ease of running and executing your solution, % you should comment all the lines of code from Part 1. Just make sure you % remove the comments before you submit.) %%% Enter the code for your program below this line fprintf('Hello World\n') % Prompts user for input and prints what was written, then jumps to next % line. fprintf(strcat(input('Please type whatever you want: ', 's'),'\n')) %%%%% When you have completed everything, type the following two commands %%%%% (without comments) into your command window. %%% load handel %%% sound(y, Fs)
import React, { Fragment, useEffect, useState } from 'react'; import {useDispatch, useSelector} from 'react-redux'; import { useAlert } from 'react-alert'; import { useParams } from 'react-router-dom'; import Pagination from 'react-js-pagination'; import Slider from '@material-ui/core/Slider'; import Typography from '@material-ui/core/Typography'; import './Products.css'; import Loader from '../layout/Loader/Loader'; import ProductCard from '../../component/Home/ProductCard.js'; import { getProduct,clearErrors } from '../../actions/productAction'; import MetaData from '../layout/MetaData'; const Products = () => { const categories = [ "Laptop", "Footwear", "Bottom", "Tops", "Attire", "Camera", "SmartPhones", ] const dispatch = useDispatch(); const [currentPage,setCurrentPage] = useState(1); const [price,setPrice] = useState([0,25000]); const [category,setCategory] = useState(""); const {keyword} = useParams(); const { products, loading, error, productsCount, resultPerPage, filteredProductsCount, } = useSelector((state) => state.products); const [ratings, setRatings] = useState(0); const alert = useAlert(); let count = filteredProductsCount; const setCurrentPageNo = (e) => { setCurrentPage(e); } const priceHandler = (event, newPrice) => { setPrice(newPrice); }; useEffect(() => { if(error){ alert.error(error); dispatch(clearErrors()) } dispatch(getProduct(keyword,currentPage,price,category,ratings)); }, [dispatch,keyword,currentPage,price,category,ratings,alert,error]); return ( <Fragment> <MetaData title = "PRODUCTS"/> <h2 className="productsHeading">Products</h2> <div className="filterBox"> <Typography>Price</Typography> <Slider value = {price} onChange = {priceHandler} valueLabelDisplay="auto" aria-labelledby='range-slider' min = {0} max = {25000} /> <Typography>Categories</Typography> <ul className="categoryBox"> {categories.map((category)=>( <li className='category-link' key={category} onClick = {() => setCategory(category)} > {category} </li> ))} </ul> <fieldset> <Typography component="legend" >Ratings Above</Typography> <Slider value = {ratings} onChange = {(e, newRating) => { setRatings(newRating); }} aria-labelledby = "continuous-slider" min={0} max={5} valueLabelDisplay="auto" > </Slider> </fieldset> </div> {loading ? <Loader /> : ( <Fragment> <div className="products"> {products && products.map((product) => ( <ProductCard key={product._id} product={product} /> ))} </div> {resultPerPage < count && ( <div className="paginationBox"> <Pagination activePage = {currentPage} itemsCountPerPage={resultPerPage} totalItemsCount={productsCount} onChange={setCurrentPageNo} nextPageText=">" prevPageText="<" firstPageText="<<" lastPageText=">>" itemClass="page-item" linkClass="page-link" activeClass="pageItemActive" activeLinkClass="pageLinkActive" /> </div> )} </Fragment> )} </Fragment> ) } export default Products;
import json from dataclasses import dataclass from os import environ from typing import List import boto3 from dotenv import load_dotenv from injector import Module, provider, singleton from tastytrade_sdk import Tastytrade load_dotenv() @dataclass class Environment: login: str password: str portfolio_symbols: List[str] account_number: str class CommonModule(Module): @singleton @provider def provide_tastytrade(self, env: Environment) -> Tastytrade: return Tastytrade().login(login=env.login, password=env.password) class LocalModule(CommonModule): @singleton @provider def provide_environment(self) -> Environment: return Environment( login=environ.get('LOGIN'), password=environ.get('PASSWORD'), account_number=environ.get('ACCOUNT_NUMBER'), portfolio_symbols=environ.get('PORTFOLIO_SYMBOLS').split(',') ) class LambdaModule(CommonModule): @singleton @provider def provide_environment(self) -> Environment: secret = json.loads( boto3.client('secretsmanager').get_secret_value(SecretId=environ.get('SECRET_ID'))['SecretString'] ) return Environment( login=secret['LOGIN'], password=secret['PASSWORD'], account_number=secret['ACCOUNT_NUMBER'], portfolio_symbols=environ.get('PORTFOLIO_SYMBOLS').split(',') )
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:dio/dio.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:get_it/get_it.dart'; import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:speedy_go/domain/usecase/change_account_info_usecase.dart'; import 'package:speedy_go/domain/usecase/show_buses_usecase.dart'; import '../data/data_source/cache_data_source.dart'; import '../data/data_source/local_data_source.dart'; import '../data/data_source/remote_data_source.dart'; import '../data/data_source/runtime_data_source.dart'; import '../data/network/app_api.dart'; import '../data/network/app_prefs.dart'; import '../data/network/assets_loader.dart'; import '../data/network/dio_factory.dart'; import '../data/network/fireauth_factory.dart'; import '../data/network/firebase_app_check_factory.dart'; import '../data/network/firestorage_factory.dart'; import '../data/network/firestore_factory.dart'; import '../data/network/network_info.dart'; import '../data/repository/repository_impl.dart'; import '../domain/models/user_manager.dart'; import '../domain/repository/repository.dart'; import '../domain/usecase/accept_driver_usecase.dart'; import '../domain/usecase/accept_trip_usecase.dart'; import '../domain/usecase/add_bus_trip_usecase.dart'; import '../domain/usecase/add_bus_usecase.dart'; import '../domain/usecase/authenticate_usecase.dart'; import '../domain/usecase/book_bus_trip_usecase.dart'; import '../domain/usecase/buses_driver_trips_usecase.dart'; import '../domain/usecase/calculate_two_points_usecase.dart'; import '../domain/usecase/cancel_accept_trip_usecase.dart'; import '../domain/usecase/cancel_trip_usecase.dart'; import '../domain/usecase/change_driver_status_usecase.dart'; import '../domain/usecase/end_trip_usecase.dart'; import '../domain/usecase/find_bus_trips_usecase.dart'; import '../domain/usecase/find_drivers_usecase.dart'; import '../domain/usecase/find_trips_usecase.dart'; import '../domain/usecase/history_bus_current_trips_usecase.dart'; import '../domain/usecase/history_bus_past_trips_usecase.dart'; import '../domain/usecase/history_trips_usecase.dart'; import '../domain/usecase/login_usecase.dart'; import '../domain/usecase/logout_usecase.dart'; import '../domain/usecase/rate_usecase.dart'; import '../domain/usecase/register_usecase.dart'; import '../domain/usecase/signed_user_usecase.dart'; import '../domain/usecase/start_verify_usecase.dart'; import '../domain/usecase/verify_otp_usecase.dart'; import 'date_ntp.dart'; final sl = GetIt.instance; Future<void> initAppModule() async { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); sl.registerLazySingleton<DateNTP>(() => DateNTPImpl()); sl.registerLazySingleton<AppPrefs>(() => AppPrefsImpl(sharedPreferences)); sl.registerLazySingleton<NetworkInfo>( () => NetworkInfoImpl(InternetConnection())); // sl.registerLazySingleton<GSheetFactory>(() => GSheetFactoryImpl()); sl.registerLazySingleton<AssetsLoader>(() => AssetsLoaderImpl()); var dio = await DioFactory().getDio(); sl.registerLazySingleton<Dio>(() => dio); var firestore = await FirestoreFactoryImpl().create(); sl.registerLazySingleton<FirebaseFirestore>(() => firestore); var fireAuth = await FireAuthFactoryImpl().create(); sl.registerLazySingleton<FirebaseAuth>(() => fireAuth); var fireStorage = await FireStorageFactoryImpl().create(); sl.registerLazySingleton<FirebaseStorage>(() => fireStorage); await FirebaseAppCheckFactoryImpl().create(); sl.registerLazySingleton<UserManager>(() => UserManager()); // sl.registerLazySingleton<UserManager<PassengerModel>>( // () => UserManager<PassengerModel>()); // sl.registerLazySingleton<UserManager<DriverModel>>( // () => UserManager<DriverModel>()); sl.registerLazySingleton<AppServiceClient>(() => AppServiceClientImpl(sl())); sl.registerLazySingleton<RemoteDataSource>( () => RemoteDataSourceImpl(sl(), sl(), sl())); sl.registerLazySingleton<RuntimeDataSource>(() => RuntimeDataSourceImpl()); sl.registerLazySingleton<CacheDataSource>( () => CacheDataSourceImpl(sl(), sl()), ); sl.registerLazySingleton<LocalDataSource>(() => LocalDataSourceImpl(sl())); sl.registerLazySingleton<Repository>( () => RepositoryImpl(sl(), sl(), sl(), sl())); } void initAuthenticateUseCase() { if (GetIt.instance.isRegistered<AuthenticateUseCase>() == false) { sl.registerFactory<AuthenticateUseCase>(() => AuthenticateUseCase(sl())); } } void initStartVerifyUseCase() { if (GetIt.instance.isRegistered<StartVerifyUseCase>() == false) { sl.registerFactory<StartVerifyUseCase>(() => StartVerifyUseCase(sl())); } } void initVerifyOtpUseCase() { if (GetIt.instance.isRegistered<VerifyOtpUseCase>() == false) { sl.registerFactory<VerifyOtpUseCase>(() => VerifyOtpUseCase(sl())); } } void initRegisterUseCase() { if (GetIt.instance.isRegistered<RegisterUseCase>() == false) { sl.registerFactory<RegisterUseCase>(() => RegisterUseCase(sl())); } } void initLoginUseCase() { if (GetIt.instance.isRegistered<LoginUseCase>() == false) { sl.registerFactory<LoginUseCase>(() => LoginUseCase(sl())); } } void initLogOutUseCase() { if (GetIt.instance.isRegistered<LogoutUseCase>() == false) { sl.registerFactory<LogoutUseCase>(() => LogoutUseCase(sl())); } } void initFindDriversUseCase() { if (GetIt.instance.isRegistered<FindDriversUseCase>() == false) { sl.registerFactory<FindDriversUseCase>(() => FindDriversUseCase(sl())); } } void initCalculateTwoPointsUseCase() { if (GetIt.instance.isRegistered<CalculateTwoPointsUseCase>() == false) { sl.registerFactory<CalculateTwoPointsUseCase>( () => CalculateTwoPointsUseCase(sl())); } } void initCancelTripUseCase() { if (GetIt.instance.isRegistered<CancelTripUseCase>() == false) { sl.registerFactory<CancelTripUseCase>(() => CancelTripUseCase(sl())); } } void initAcceptDriverUseCase() { if (GetIt.instance.isRegistered<AcceptDriverUseCase>() == false) { sl.registerFactory<AcceptDriverUseCase>(() => AcceptDriverUseCase(sl())); } } void initEndTripUseCase() { if (GetIt.instance.isRegistered<EndTripUseCase>() == false) { sl.registerFactory<EndTripUseCase>(() => EndTripUseCase(sl())); } } void initRateUseCase() { if (GetIt.instance.isRegistered<RateUseCase>() == false) { sl.registerFactory<RateUseCase>(() => RateUseCase(sl())); } } void initGetSignedUserUseCase() { if (GetIt.instance.isRegistered<GetSignedUserUseCase>() == false) { sl.registerFactory<GetSignedUserUseCase>(() => GetSignedUserUseCase(sl())); } } void initChangeDriverStatusUseCase() { if (GetIt.instance.isRegistered<ChangeDriverStatusUseCase>() == false) { sl.registerFactory<ChangeDriverStatusUseCase>( () => ChangeDriverStatusUseCase(sl())); } } void initFindTripsUseCase() { if (GetIt.instance.isRegistered<FindTripsUseCase>() == false) { sl.registerFactory<FindTripsUseCase>(() => FindTripsUseCase(sl())); } } void initAcceptTripUseCase() { if (GetIt.instance.isRegistered<AcceptTripUseCase>() == false) { sl.registerFactory<AcceptTripUseCase>(() => AcceptTripUseCase(sl())); } } void initCancelAcceptTripUseCase() { if (GetIt.instance.isRegistered<CancelAcceptTripUseCase>() == false) { sl.registerFactory<CancelAcceptTripUseCase>( () => CancelAcceptTripUseCase(sl())); } } void initAddBusUseCase() { if (GetIt.instance.isRegistered<AddBusUseCase>() == false) { sl.registerFactory<AddBusUseCase>(() => AddBusUseCase(sl())); } } void initAddBusTripUseCase() { if (GetIt.instance.isRegistered<AddBusTripUseCase>() == false) { sl.registerFactory<AddBusTripUseCase>(() => AddBusTripUseCase(sl())); } } void initFindBusTripsUseCase() { if (GetIt.instance.isRegistered<FindBusTripsUseCase>() == false) { sl.registerFactory<FindBusTripsUseCase>(() => FindBusTripsUseCase(sl())); } } void initDisplayBusesUseCase() { if (GetIt.instance.isRegistered<DisplayBusesUseCase>() == false) { sl.registerFactory<DisplayBusesUseCase>(() => DisplayBusesUseCase(sl())); } } void initBusesDriverTripsUseCase() { if (GetIt.instance.isRegistered<BusesDriverTripsUseCase>() == false) { sl.registerFactory<BusesDriverTripsUseCase>( () => BusesDriverTripsUseCase(sl())); } } void initBookBusTripUseCase() { if (GetIt.instance.isRegistered<BookBusTripUseCase>() == false) { sl.registerFactory<BookBusTripUseCase>(() => BookBusTripUseCase(sl())); } } void initChangeAccountInfoUseCase() { if (GetIt.instance.isRegistered<ChangeAccountInfoUseCase>() == false) { sl.registerFactory<ChangeAccountInfoUseCase>( () => ChangeAccountInfoUseCase(sl())); } } void initHistoryTripsUseCase() { if (GetIt.instance.isRegistered<HistoryTripsUseCase>() == false) { sl.registerFactory<HistoryTripsUseCase>(() => HistoryTripsUseCase(sl())); } } void initHistoryBusCurrentTripsUseCase() { if (GetIt.instance.isRegistered<HistoryBusCurrentTripsUseCase>() == false) { sl.registerFactory<HistoryBusCurrentTripsUseCase>( () => HistoryBusCurrentTripsUseCase(sl())); } } void initHistoryBusPastTripsUseCase() { if (GetIt.instance.isRegistered<HistoryBusPastTripsUseCase>() == false) { sl.registerFactory<HistoryBusPastTripsUseCase>( () => HistoryBusPastTripsUseCase(sl())); } }
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import 'exercise_page.dart'; void main() { runApp(GetMaterialApp( home: LevelPage(), )); } class LevelPage extends StatefulWidget { @override _LevelPageState createState() => _LevelPageState(); } class _LevelPageState extends State<LevelPage> { List<Map<String, String>> levels = []; bool isLoading = true; int completedLevel = 0; @override void initState() { super.initState(); fetchLevels(); _getCompletedLevel(); } Future<void> fetchLevels() async { final response = await http.get( Uri.parse('https://db.nyanhosting.id/game/api/?query=level')); if (response.statusCode == 200) { final List<dynamic> data = json.decode(response.body); setState(() { levels = data .map((item) => { 'id': item['id'].toString(), 'level': item['level'].toString(), }) .toList(); isLoading = false; }); } else { throw Exception('Failed to load levels'); } } Future<void> _getCompletedLevel() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { completedLevel = prefs.getInt('completedLevel') ?? 0; }); } Future<void> _refresh() async { await fetchLevels(); _getCompletedLevel(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.transparent, body: Stack( children: [ Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [ Color(0xFF301F40), Color(0xFF46244C), ], ), ), child: RefreshIndicator( onRefresh: _refresh, child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox(height: 60), const Text( 'Tentukan Levelmu!', style: TextStyle( color: Color.fromARGB(255, 255, 255, 255), fontFamily: 'Galindo', fontSize: 30, fontWeight: FontWeight.bold, ), ), Column( children: levels.map((level) { bool isLevelEnabled = int.parse(level['level']!) == 1 || int.parse(level['level']!) <= completedLevel + 1; return buildLevelContainer( context, 'Level ${level['level']}', getIconPath(int.parse(level['level']!)), () { if (isLevelEnabled) { Get.to(() => ExercisePage( levelId: int.parse(level['id']!))); } }, isLevelEnabled ? Colors.white : Colors.black, ); }).toList(), ), ], ), ), ), ), if (isLoading) Container( color: Colors.black, child: const Center( child: CircularProgressIndicator(), ), ), ], ), ); } String getIconPath(int level) { int iconIndex = (level - 1) % 3 + 1; return 'assets/icon$iconIndex-wow.png'; } Widget buildLevelContainer(BuildContext context, String level, String? imagePath, VoidCallback onPressed, Color levelColor) { return GestureDetector( onTap: onPressed, child: Container( margin: const EdgeInsets.symmetric(vertical: 15, horizontal: 45), width: MediaQuery.of(context).size.width * 0.8, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: levelColor, ), child: Row( children: [ Padding( padding: const EdgeInsets.all(10.0), child: Text( level, style: const TextStyle( color: Color.fromRGBO(40, 18, 75, 0.776), fontFamily: 'Galindo', fontSize: 30, fontWeight: FontWeight.bold, letterSpacing: 1.35, ), ), ), Expanded( child: Container( alignment: Alignment.centerRight, child: imagePath != null ? Image.asset( imagePath, width: 50, height: 50, ) : const SizedBox.shrink(), ), ), ], ), ), ); } }
#ifndef IDOCUMENT_ #define IDOCUMENT_ #include <string> #include "ISerializable.h" class IDocument : public ISerializable { public: enum class Type : int { PLAIN_TEXT, MATH_TEXT, }; public: using text_type = std::string; public: virtual ~IDocument() = default; public: virtual const text_type& get_text() const noexcept = 0; virtual void append_text(const text_type&) = 0; virtual void clear() noexcept = 0; virtual Type type() const noexcept = 0; }; #endif // !IDOCUMENT_
package pages; import browser.BrowserType; import browser.DriverInitializer; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import static org.junit.jupiter.api.Assertions.fail; public class BasePage { protected static WebDriver driver; protected static WebDriverWait wait; public BasePage() { PageFactory.initElements(driver, this); } public static void openPage(String url) { driver.get(url); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div#content"))); } public boolean isLoaded(WebElement element) { try { return wait.until(ExpectedConditions.visibilityOf(element)).isDisplayed(); } catch (TimeoutException e) { fail(e); return false; } } public boolean isInteractable(WebElement element) { return wait.until(ExpectedConditions.elementToBeClickable(element)).isEnabled(); } public static void initAll() { driver = DriverInitializer.initDriver(BrowserType.CHROME_SELENIUM_MGR); //driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5)); wait = new WebDriverWait(driver, Duration.ofSeconds(15)); } public static void cleanupAll() { driver.quit(); } }
package acceptance import ( "context" "fmt" "testing" "golang.org/x/exp/maps" "github.com/databricks/databricks-sdk-go" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var mountHcl = ` data "databricks_spark_version" "latest" {} # Test cluster to create the mount using. resource "databricks_cluster" "this" { cluster_name = "acc-test-mounts-{var.STICKY_RANDOM}" spark_version = data.databricks_spark_version.latest.id instance_pool_id = "{env.TEST_INSTANCE_POOL_ID}" num_workers = 1 aws_attributes { instance_profile_arn = "{env.TEST_INSTANCE_PROFILE_ARN}" } } resource "databricks_mount" "my_mount" { name = "test-mount-{var.STICKY_RANDOM}" cluster_id = databricks_cluster.this.id s3 { bucket_name = "{env.TEST_S3_BUCKET_NAME}" } }` func TestAccCreateDatabricksMount(t *testing.T) { workspaceLevel(t, step{ Template: mountHcl, }) } func TestAccCreateDatabricksMountIsFineOnClusterRecreate(t *testing.T) { clusterId1 := "" clusterId2 := "" workspaceLevel(t, // Step 1 creates the cluster and mount. step{ Template: mountHcl, Check: func(s *terraform.State) error { resources := s.RootModule().Resources cluster := resources["databricks_cluster.this"] if cluster == nil { return fmt.Errorf("expected to find databricks_cluster.this in resources keys: %v", maps.Keys(resources)) } clusterId1 = cluster.Primary.ID // Assert cluster id is not empty. This is later used to ensure // the cluster has been recreated. assert.NotEmpty(t, clusterId1) // Assert the mount points to the created cluster. mount := resources["databricks_mount.my_mount"] assert.Equal(t, clusterId1, mount.Primary.Attributes["cluster_id"]) return nil }, }, // Step 2: Manually delete the cluster, and then reapply the config. The mount // will be recreated in this case. step{ PreConfig: func() { w, err := databricks.NewWorkspaceClient(&databricks.Config{}) require.NoError(t, err) err = w.Clusters.PermanentDeleteByClusterId(context.Background(), clusterId1) assert.NoError(t, err, "failed to delete the cluster, id: "+clusterId1) }, Template: mountHcl, Check: func(s *terraform.State) error { resources := s.RootModule().Resources cluster := resources["databricks_cluster.this"] if cluster == nil { return fmt.Errorf("expected to find databricks_cluster.this in resources keys: %v", maps.Keys(resources)) } clusterId2 = cluster.Primary.ID // Assert cluster was indeed recreated assert.NotEmpty(t, clusterId1) assert.NotEmpty(t, clusterId2) assert.NotEqual(t, clusterId1, clusterId2) // Assert the mount points to the newly recreated cluster. mount := resources["databricks_mount.my_mount"] assert.Equal(t, clusterId2, mount.Primary.Attributes["cluster_id"]) return nil }, }, ) }
from dateutil.relativedelta import relativedelta from django.test import TestCase from django.urls import reverse from django.utils import timezone from rest_framework import status from agir.groups import admin from agir.groups.admin.filters import LastManagerLoginFilter from agir.groups.models import SupportGroup, TransferOperation, Membership from agir.people.models import Person class TransferOperationAdmin(TestCase): def setUp(self) -> None: self.super_user = Person.objects.create_superperson("super@user.fr", "prout") self.client.force_login( self.super_user.role, "agir.people.backend.PersonBackend" ) self.people = [ Person.objects.create_person( email=f"{i:02d}@exemple.fr", is_political_support=True ) for i in range(20) ] self.groups = [ SupportGroup.objects.create(name="Groupe {i:02d}") for i in range(5) ] transfers = [(1, 2, [0, 5, 10, 18]), (4, 3, [2, 5, 19])] self.transfer_operations = [ TransferOperation.objects.create( former_group=self.groups[i], new_group=self.groups[j], ) for i, j, _ in transfers ] for t, (_, _, k) in zip(self.transfer_operations, transfers): t.members.set([self.people[i] for i in k]) def test_showing_transfer_operation_list(self): res = self.client.get(reverse("admin:groups_transferoperation_changelist")) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_can_display_transfer_operation(self): res = self.client.get( reverse( "admin:groups_transferoperation_change", args=(self.transfer_operations[0].id,), ) ) self.assertEqual(res.status_code, status.HTTP_200_OK) class LastManagerLoginFilterTest(TestCase): def setUp(self) -> None: today = timezone.now() self.recently_logged_in_group = SupportGroup.objects.create( name="recently_logged_in" ) self.recently_logged_in_person = Person.objects.create_person( "today@agir.test", create_role=True ) self.recently_logged_in_person.role.last_login = today self.recently_logged_in_person.role.save() Membership.objects.create( person=self.recently_logged_in_person, supportgroup=self.recently_logged_in_group, membership_type=Membership.MEMBERSHIP_TYPE_MANAGER, ) self.one_month_old_login_group = SupportGroup.objects.create( name="one_month_old_login" ) self.one_month_old_login_person = Person.objects.create_person( "one_month@agir.test", create_role=True ) self.one_month_old_login_person.role.last_login = today - relativedelta(days=36) self.one_month_old_login_person.role.save() Membership.objects.create( person=self.one_month_old_login_person, supportgroup=self.one_month_old_login_group, membership_type=Membership.MEMBERSHIP_TYPE_MANAGER, ) self.two_month_old_login_group = SupportGroup.objects.create( name="two_month_old_login" ) self.two_month_old_login_person = Person.objects.create_person( "two_month@agir.test", create_role=True ) self.two_month_old_login_person.role.last_login = today - relativedelta(days=64) self.two_month_old_login_person.role.save() Membership.objects.create( person=self.two_month_old_login_person, supportgroup=self.two_month_old_login_group, membership_type=Membership.MEMBERSHIP_TYPE_MANAGER, ) self.not_yet_logged_in_group = SupportGroup.objects.create( name="not_yet_logged_in" ) self.not_yet_logged_in_person = Person.objects.create_person( "never@agir.test", create_role=False ) Membership.objects.create( person=self.not_yet_logged_in_person, supportgroup=self.not_yet_logged_in_group, membership_type=Membership.MEMBERSHIP_TYPE_MANAGER, ) def test_test_data_is_ok(self): self.assertEqual( self.recently_logged_in_person.role.last_login, self.recently_logged_in_group.get_last_manager_login(), ) self.assertEqual( self.one_month_old_login_person.role.last_login, self.one_month_old_login_group.get_last_manager_login(), ) self.assertEqual( self.two_month_old_login_person.role.last_login, self.two_month_old_login_group.get_last_manager_login(), ) self.assertIsNone(self.not_yet_logged_in_group.get_last_manager_login()) def test_empty_filter(self): f = LastManagerLoginFilter( None, {"last_manager_login": None}, SupportGroup, admin.SupportGroupAdmin, ) filtered_qs = f.queryset(None, SupportGroup.objects.all()) self.assertIn(self.recently_logged_in_group, filtered_qs) self.assertIn(self.one_month_old_login_group, filtered_qs) self.assertIn(self.two_month_old_login_group, filtered_qs) self.assertIn(self.not_yet_logged_in_group, filtered_qs) def test_invalid_filter(self): f = LastManagerLoginFilter( None, {"last_manager_login": "2_months_from_now"}, SupportGroup, admin.SupportGroupAdmin, ) filtered_qs = f.queryset(None, SupportGroup.objects.all()) self.assertIn(self.recently_logged_in_group, filtered_qs) self.assertIn(self.one_month_old_login_group, filtered_qs) self.assertIn(self.two_month_old_login_group, filtered_qs) self.assertIn(self.not_yet_logged_in_group, filtered_qs) def test_one_week_ago_filter(self): f = LastManagerLoginFilter( None, {"last_manager_login": "1_week_ago"}, SupportGroup, admin.SupportGroupAdmin, ) filtered_qs = f.queryset(None, SupportGroup.objects.all()) self.assertNotIn(self.recently_logged_in_group, filtered_qs) self.assertIn(self.one_month_old_login_group, filtered_qs) self.assertIn(self.two_month_old_login_group, filtered_qs) self.assertIn(self.not_yet_logged_in_group, filtered_qs) def test_one_month_ago_filter(self): f = LastManagerLoginFilter( None, {"last_manager_login": "1_month_ago"}, SupportGroup, admin.SupportGroupAdmin, ) filtered_qs = f.queryset(None, SupportGroup.objects.all()) self.assertNotIn(self.recently_logged_in_group, filtered_qs) self.assertIn(self.one_month_old_login_group, filtered_qs) self.assertIn(self.two_month_old_login_group, filtered_qs) self.assertIn(self.not_yet_logged_in_group, filtered_qs) def test_two_month_ago_filter(self): f = LastManagerLoginFilter( None, {"last_manager_login": "2_month_ago"}, SupportGroup, admin.SupportGroupAdmin, ) filtered_qs = f.queryset(None, SupportGroup.objects.all()) self.assertNotIn(self.recently_logged_in_group, filtered_qs) self.assertNotIn(self.one_month_old_login_group, filtered_qs) self.assertIn(self.two_month_old_login_group, filtered_qs) self.assertIn(self.not_yet_logged_in_group, filtered_qs) def test_three_month_ago_filter(self): f = LastManagerLoginFilter( None, {"last_manager_login": "3_month_ago"}, SupportGroup, admin.SupportGroupAdmin, ) filtered_qs = f.queryset(None, SupportGroup.objects.all()) self.assertNotIn(self.recently_logged_in_group, filtered_qs) self.assertNotIn(self.one_month_old_login_group, filtered_qs) self.assertNotIn(self.two_month_old_login_group, filtered_qs) self.assertIn(self.not_yet_logged_in_group, filtered_qs) def test_exact_date_ago_filter(self): f = LastManagerLoginFilter( None, { "last_manager_login": (timezone.now() - relativedelta(days=40)) .date() .strftime("%Y-%m-%d") }, SupportGroup, admin.SupportGroupAdmin, ) filtered_qs = f.queryset(None, SupportGroup.objects.all()) self.assertNotIn(self.recently_logged_in_group, filtered_qs) self.assertNotIn(self.one_month_old_login_group, filtered_qs) self.assertIn(self.two_month_old_login_group, filtered_qs) self.assertIn(self.not_yet_logged_in_group, filtered_qs)
<template> <div style="margin-left:12px;margin-top:5px;"> <el-button type="primary" icon="el-icon-circle-plus-outline" @click="create()">添加</el-button> <el-input placeholder="请输入内容" style="width:220px;margin-left:5px;" v-model="filter" prefix-icon="el-icon-search"> </el-input> <el-table style="margin-top:5px; width: 100%" border :data="tableData" @sort-change="SortChange"> <template v-for="(item,index) in tableHead"> <el-table-column :prop="item.columnName" :label="item.columnDescription || item.columnName" v-if="hiddenColumn[item.columnName] !== true && item.columnName!='password'" :key="index" show-overflow-tooltip sortable="custom"></el-table-column> </template> <el-table-column label="操作" width="400"> <template slot-scope="scope"> <!--<el-button type="success" size="small" @click="Grant(scope.row)">用户角色</el-button> <el-button type="success" size="small" @click="Grant(scope.row)">用户部门</el-button>--> <el-button type="success" size="small" @click="Grant(scope.row)">授权</el-button> <el-button type="success" size="small" @click="Modify(scope.row)">编辑</el-button> <el-button type="danger" size="small" @click="Remove(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="paging.PageIndex" :page-sizes="[5, 10, 20, 40]" :page-size="paging.PageSize" layout="total, sizes, prev, pager, next, jumper" :total="paging.TotalCount"> </el-pagination> <el-dialog :title="title" :visible.sync="createdialog" :close-on-click-modal="false" :close-on-press-escape="false" @close="reset"> <el-form id="#create" :model="model" :rules="rules" ref="create" label-width="130px"> <template v-for="(item,index) in tableHead"> <el-form-item v-if="item.sqlType == 'nvarchar' && item.maxLength > 0 && hiddenColumn[item.columnName] !== true" :label="item.columnDescription || item.columnName" :prop="item.columnName"> <el-input v-model="model[item.columnName]" type="text" clearable></el-input> </el-form-item> <el-form-item v-else-if="item.sqlType == 'nvarchar' && item.maxLength < 0 && hiddenColumn[item.columnName] !== true" :label="item.columnDescription || item.columnName" :prop="item.columnName"> <el-input v-model="model[item.columnName]" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" clearable></el-input> </el-form-item> <el-form-item v-else-if="item.sqlType == 'bit'" :label="item.columnDescription || item.columnName"> <el-radio-group v-model="model[item.columnName]"> <el-radio :label="true">是</el-radio> <el-radio :label="false">否</el-radio> </el-radio-group> </el-form-item> </template> <!--树--> <el-form-item label="部门" prop="departmentId"> <wlTreeSelect width="300" checkbox checkStrictly="true" :props="departmentprops" :data="departmenttreedata" nodeKey="id" @change="hindleChanged" v-model="model.departmentId"></wlTreeSelect> </el-form-item> <el-form-item label="角色"> <el-select v-model="model.roleId" collapse-tags placeholder="请选择角色" multiple style="width:300px"> <div class="el-input" style="width:90%;margin-left:5%;"> <input type="text" placeholder="请输入" class="el-input__inner" v-model="searchrole" @keyup="dropDownSearch"> </div> <el-option v-for="item in roleShow" :key="item.id" :value="item.id" :label="item.roleName" ></el-option> </el-select> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="createdialog=false">取 消</el-button> <el-button type="primary" :loading="createLoading" @click="Save">确 定</el-button> </div> </el-dialog> <el-dialog title="用户授权" :visible.sync="grantdialog" :close-on-click-modal="false" :close-on-press-escape="false"> <div> <el-tree :data="treedata" show-checkbox ref="tree" :default-checked-keys="usermenus" node-key="id" :props="defaultProps"> </el-tree> </div> <div slot="footer" class="dialog-footer"> <el-button @click="grantdialog=false">取 消</el-button> <el-button type="primary" @click="SaveGrant">确 定</el-button> </div> </el-dialog> </div> </template> <script> import { getHeader, GetResult, Save, Remove, SaveGrant, GetMenus } from '@/api/user' import { debounce } from '@/utils'; import { GetCompanyTree as GetTree } from '@/api/menus' import { GetGrantMode } from '@/api/enum' import { GetResult as GetRoles } from '@/api/role' import { GetTree as GetDepartmentTree } from '@/api/department' export default { name: 'Roles', data() { return { roleShow: [], roleShowAll:[], searchrole:'', departmentprops: { label: "departmentName", value: "id" }, selecteddepartment:[], defaultProps: { children: 'children', label: 'menuName' }, title: '新建用户', usermenus: [], selectuser: {}, grantdialog: false, treedata: [], departmenttreedata:[], hiddenColumn: { id: true , parentId: true , createUserId: true , createUserName: true , createTime: false , modifyUserId: true , modifyUserName: true , modifyTime: true , parentName: true , companyId: true , password:true }, tableData: [], tableHead: [], model: { roleId: [], departmentId:[]}, createLoading: false, createdialog: false, rules: {}, filter: '', paging: { PageSize: 20, PageIndex: 1, TotalCount: 0, Sort: 'Id', Asc: true, Filter: '', Model: { } }, } }, watch: { filter: function (searchvalue) { this.paging.Filter = searchvalue; this.GetResult(); } }, mounted() { this.getHeader(); this.GetResult(); }, methods: { GetRoles: function (isall) { const owner = this GetRoles(owner.paging).then(response => { if (!isall) { owner.roleShow = response.data; owner.roleShowAll = response.data; } else { owner.roleShowAll = response.data; } }) }, dropDownSearch() { this.GetRoles(true) var owner = this; owner.roleShow = owner.roleShowAll.filter(owner.filterSearch); }, filterSearch(item) { return item.roleName.includes(this.searchrole); }, GetDepartmentTree: function () { const owner = this GetDepartmentTree().then(response => { owner.departmenttreedata = response.data }) }, hindleChanged: function (val) { let departmentid = []; val.forEach(function (item, index) { departmentid.push(item.id); }) this.model.departmentId = departmentid; //this.model.departmentName = val[0].departmentName; }, GetTree: function () { const owner = this GetTree().then(response => { owner.treedata = response.data }) }, SaveGrant: function () { const owner = this let keys = owner.$refs.tree.getCheckedKeys() let userId = owner.selectuser.id let requestdata = [] keys.forEach(function (item, index) { //item 就是当日按循环到的对象 //index是循环的索引,从0开始 requestdata.push({ userId: userId, menuId: item }) }) SaveGrant(requestdata).then(response => { owner.grantdialog = false }) }, GetMenus: function (row) { const owner = this GetMenus({ id: row.id }).then(response => { owner.usermenus = [] response.data.forEach(function (item, index) { owner.usermenus.push(item.menuId); }); this.GetTree() }) }, Grant: function (row) { this.GetMenus(row) this.grantdialog = true; this.selectuser = row }, GetGrantMode: function () { const owner = this GetGrantMode().then(response => { owner.grantModes = response.data }) }, SortChange: function (column) { this.paging.Sort = column.prop; this.paging.Asc = column.order == "ascending"; this.GetResult(); }, handleSizeChange: function (size) { this.paging.PageSize = size; this.GetResult(); }, handleCurrentChange: function (currentPage) { this.paging.PageIndex = currentPage; this.GetResult(); }, Modify: function (row) { this.GetRoles() this.GetDepartmentTree() this.createdialog = true this.title = "编辑用户" this.model = row; }, Remove: function (row) { const owner = this Remove(row).then(response => { owner.GetResult(); }) }, getHeader: function () { const owner = this getHeader().then(response => { owner.tableHead = response.data }) }, GetResult: function () { const owner = this GetResult(owner.paging).then(response => { owner.tableData = response.data; owner.paging.TotalCount = response.total; }) }, Save: function () { const owner = this; Save(owner.model).then(response => { owner.createdialog = false; owner.reset(); owner.GetResult(); }) }, create: function () { this.GetRoles(); this.GetDepartmentTree() this.createdialog = true; }, // 重置表单 reset() { this.$refs.create.resetFields(); this.model = {}; }, } }</script> <style scoped> </style>
package com.example.mygreenactivities.view.posts import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.mygreenactivities.databinding.FragmentSettingsBinding import com.example.mygreenactivities.view.auth.AuthActivity import com.example.mygreenactivities.viewmodel.AuthViewModel import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase class SettingsFragment : Fragment() { private var _binding: FragmentSettingsBinding? = null private val binding get() = _binding!! private lateinit var viewModel: AuthViewModel private lateinit var auth: FirebaseAuth override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSettingsBinding.inflate(inflater, container, false) viewModel = ViewModelProvider(this)[AuthViewModel::class.java] auth = Firebase.auth binding.bChangeEmail.setOnClickListener { val currentUserEmail = auth.currentUser?.email if (currentUserEmail != null) { auth.sendPasswordResetEmail(currentUserEmail).addOnCompleteListener { if (it.isSuccessful) { Toast.makeText(context, "To change pass follow to your email", Toast.LENGTH_SHORT).show() } else { Toast.makeText(context, "Err", Toast.LENGTH_SHORT).show() } } } logout() } binding.bLogout.setOnClickListener { logout() } val myRef = Firebase.database.getReference("users") myRef.child(auth.currentUser?.uid ?: "Without UID").get().addOnSuccessListener { binding.sEmailVisibility.isChecked = it.child("showEmail").value as Boolean binding.tvInterest.text = it.child("interests").value.toString() } binding.sEmailVisibility.setOnCheckedChangeListener { _, isChecked -> myRef.child(auth.currentUser?.uid ?: "Without UID") .updateChildren(hashMapOf<String, Any?>("showEmail" to isChecked)) } binding.tvEmail.text = auth.currentUser?.email ?: "Not auth" binding.bSaveInterests.setOnClickListener { val tags = binding.groupTag.checkedRadioButtonId if (tags == -1) { Toast.makeText(context, "Choose interests", Toast.LENGTH_SHORT).show() } else { val tag = (when (tags) { binding.rbActivities.id -> "activities" binding.rbThreads.id -> "threads" else -> "other" }) myRef.child(auth.currentUser?.uid ?: "Without UID") .updateChildren(hashMapOf<String, Any?>("interests" to tag)) myRef.child(auth.currentUser?.uid ?: "Without UID") .get().addOnSuccessListener { binding.tvInterest.text = it.child("interests").value.toString() Toast.makeText(context, "Interests changed", Toast.LENGTH_SHORT).show() } } } return binding.root } private fun logout() { auth.signOut() val i = Intent(context, AuthActivity::class.java) startActivity(i) } }
// Obtener referencias a los elementos del DOM let chartContainer = document.getElementById('chartContainer'); let ctxBarConcerts = document.getElementById('myChartBarConcerts'); let ctxBarPayment = document.getElementById('myChartBarPayment'); let ctxPiePayment = document.getElementById('myChartPiePayment'); let chartHTML = document.getElementById('chart'); let chartBarConcerts = null; let chartBarPayment = null; let chartPiePayment = null; // Función para generar los gráficos function generateCharts() { // Eliminar los gráficos existentes si los hay if (chartBarConcerts) { chartBarConcerts.destroy(); } if (chartBarPayment) { chartBarPayment.destroy(); } if (chartPiePayment) { chartPiePayment.destroy(); } chartHTML.hidden = true; // Generar los gráficos de los conciertos y los métodos de pago fetch('/all-concert-sales') .then(response => response.json()) .then(concerts => { console.log(concerts); const labelsConcerts = concerts.map(concert => concert.name); const valuesConcerts = concerts.map(concert => parseInt(concert.detail_order_sum_total) || 0); // Crea el contexto del gráfico de barras de conciertos const ctxBarConcerts = document.getElementById('myChartBarConcerts'); // Crea el gráfico de barras de conciertos chartBarConcerts = new Chart(ctxBarConcerts, { type: 'bar', data: { labels: labelsConcerts, datasets: [{ label: 'Total Vendido', data: valuesConcerts, backgroundColor: 'rgba(4, 101, 255, 0.25)', borderWidth: 1 }] }, options: { plugins: { legend: { display: false }, datalabels: { align: 'end', anchor: 'end' } }, scales: { x: { ticks: { autoSkip: false, maxRotation: labelsConcerts.length > 7 ? 90 : 0, minRotation: labelsConcerts.length > 7 ? 90 : 0, callback: function (value) { const truncatedLabel = this.getLabelForValue(value).substr(0, 10); // Trunca los nombres a 10 caracteres if (truncatedLabel.length < this.getLabelForValue(value).length) { return truncatedLabel + '...'; // Agrega "..." al final si el nombre se truncó } return truncatedLabel; } } }, y: { beginAtZero: true } } } }); // Generar los gráficos de los métodos de pago fetch('/all-detail-orders') .then(response => response.json()) .then(detailOrders => { console.log(detailOrders); const paymentTotals = { 'Efectivo': 0, 'Transferencia': 0, 'Débito': 0, 'Crédito': 0, }; detailOrders.forEach(detail => { let paymentMethod = detail.payment_method; const total = detail.total; switch (paymentMethod) { case 1: paymentMethod = 'Efectivo'; break; case 2: paymentMethod = 'Transferencia'; break; case 3: paymentMethod = 'Débito'; break; case 4: paymentMethod = 'Crédito'; break; } paymentTotals[paymentMethod] += total; }); const labelsPayment = Object.keys(paymentTotals); const valuesPayment = Object.values(paymentTotals); // Crea el contexto del gráfico de barras de métodos de pago const ctxBarPayment = document.getElementById('myChartBarPayment'); // Crea el gráfico de barras de métodos de pago chartBarPayment = new Chart(ctxBarPayment, { type: 'bar', data: { labels: labelsPayment, datasets: [{ label: 'Monto Total Vendido', data: valuesPayment, backgroundColor: [ 'rgba(90, 0, 255, 0.25)', 'rgba(168, 178, 255, 0.25)', 'rgba(234, 255, 0, 0.25)', 'rgba(0, 81, 255,0.25)', 'rgba(0, 212, 161, 0.25)' ], borderWidth: 1 }] }, options: { plugins: { legend: { display: false }, datalabels: { align: 'end', anchor: 'end' } }, scales: { x: { ticks: { autoSkip: false, maxRotation: 0, minRotation: 0 } }, y: { beginAtZero: true } } } }); // Crea el contexto del gráfico de pie de métodos de pago const ctxPiePayment = document.getElementById('myChartPiePayment'); // Crea el gráfico de pie de métodos de pago con los porcentajes chartPiePayment = new Chart(ctxPiePayment, { type: 'pie', data: { labels: labelsPayment, datasets: [{ data: valuesPayment, backgroundColor: [ 'rgba(90, 0, 255, 0.25)', 'rgba(168, 178, 255, 0.25)', 'rgba(234, 255, 0, 0.25)', 'rgba(0, 81, 255,0.25)', 'rgba(0, 212, 161, 0.25)' ], borderWidth: 1 }] }, options: { plugins: { legend: { display: true }, tooltips: { enabled: true }, datalabels: { formatter: (value, ctxPiePayment) => { const datapoints = ctxPiePayment.chart.data.datasets[0].data; function sumaTotal(total, datapoint) { return total + datapoint } const porcentajeTotal = datapoints.reduce(sumaTotal, 0); const valorPorcentaje = (value / porcentajeTotal * 100).toFixed(2); const despliegue = [`${valorPorcentaje}%`] return despliegue; } } }, animation: { duration: 0 } }, plugins: [ChartDataLabels] }); chartHTML.hidden = false; }) .catch(error => { console.error('Error al obtener los detalles de orden:', error); }); }) .catch(error => { console.error('Error al obtener los datos de los conciertos:', error); }); } // Generar los gráficos al cargar la página generateCharts();
import 'dart:io'; import 'package:dartz/dartz.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:hankofiles/domain/facades/i_storage_facade.dart'; import 'package:injectable/injectable.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; part 'storage_state.dart'; part 'storage_cubit.freezed.dart'; @lazySingleton class StorageCubit extends Cubit<StorageState> { final IStorageFacade iStorageFacade; StorageCubit(this.iStorageFacade) : super(StorageState.empty()); //SELECT FILE FROM DEVICE AND SAVE TO STATE void selectFile(File file) => emit(state.copyWith(selectedFile: file)); //SELECT FILE IN APP AND SAVE TO STATE void selectSupabaseFile(FileObject file) => emit(state.copyWith(supabaseFile: file)); // SET FILE NAME void setFileName(String fileName) => emit(state.copyWith(fileName: fileName)); //SET SEARCH QUERY void setSearchQuery(String searchQuery) { emit(state.copyWith(searchQuery: searchQuery)); //RUN SEARCH FUNCTION 500MS AFTER CHANGE EVENT searchFiles(); } // SELECT FILES TO DELETE void selectFilesToDelete(String filePath) { List<String> pathsToDelete = state.filePathsToDelete.toList(); print(pathsToDelete.contains(filePath)); if(pathsToDelete.contains(filePath)) { pathsToDelete.remove(filePath); emit(state.copyWith(filePathsToDelete: pathsToDelete)); return; } pathsToDelete.add(filePath); emit(state.copyWith(filePathsToDelete: pathsToDelete)); } // DELETE ALL FILES FROM STORAGE void selectAllFilesToDelete({required String id}) { List<String> pathsToDelete = state.files.map((e) => "$id/${e.id!}").toList(); emit(state.copyWith(filePathsToDelete: pathsToDelete)); } //LIST FILES FROM STORAGE void listFiles({required String id})async{ load(); final uploadRequest = await iStorageFacade.listFiles(id: id); uploadRequest.fold((l) => fail(l), (r) => emit(state.copyWith(files: r, queryFiles: r, isLoading: false))); } // SEARCH FILES FROM FILE LIST void searchFiles(){ final query = state.searchQuery; final files = state.files; final sortFiles = files.where((element) => element.name.contains(query)).toList(); emit(state.copyWith(queryFiles: sortFiles)); } // UPLOAD FILES void uploadFile({required String id})async{ final file = state.selectedFile; final fileName = state.fileName; Either<String, String> uploadRequest; load(); uploadRequest = await iStorageFacade.uploadFile(file: file, id: id, fileName: fileName); uploadRequest.fold((l) => fail(l), (r) => pass(r)); } // DELETE A FILE void deleteFile({required String id})async{ final file = state.supabaseFile; load(); final uploadRequest = await iStorageFacade.deleteFile(path: file.name); uploadRequest.fold((l) => fail(l), (r) => pass(r)); listFiles(id: id); } // DELETE MULTIPLE FILES void deleteFiles({required String id})async{ List<String> pathsToDelete = state.filePathsToDelete; load(); final uploadRequest = await iStorageFacade.deleteFiles(paths: pathsToDelete); uploadRequest.fold((l) => fail(l), (r) => pass(r)); listFiles(id: id); } // CREATE A BYTES ARRAY OF THE FILE TO BE SAVED ON THE DEVICE downloadFile({required void Function(int, int)? onReceiveProgress, required String path})async{ final url = getPublicUrl(); load(); final uploadRequest = await iStorageFacade.downloadFile(path: path, onReceiveProgress: onReceiveProgress, url: url); uploadRequest.fold((l) => fail(l), (r) { pass("File downloaded from network"); } ); } // GETS A PUBLICLY VISIBLE URL OF THE FILE String getPublicUrl(){ final id = state.supabaseFile.id; final name = state.supabaseFile.name; final url = iStorageFacade.getPublicUrl(id:"$id/$name"); return url; } //HELPER FUNCTIONS void fail(String failure) => emit(state.copyWith(success: "", failure: failure, isLoading: false)); void pass(String success) => emit(state.copyWith(success: success, failure: "", isLoading: false)); void load() => emit(state.copyWith(success: "", failure: "", isLoading: true)); void reset() => emit(state.copyWith( failure: '', success: '', isLoading: false, searchQuery: '', fileName: '', selectedFile: File(''), files: [], queryFiles: [])); }
package com.deliveryou.configuration; import com.cloudinary.Cloudinary; import com.deliveryou.pojo.Role; import com.deliveryou.pojo.User; import com.deliveryou.service.interfaces.UserService; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import java.util.HashMap; import java.util.Map; @ComponentScan(basePackages = { "com.deliveryou.repository", "com.deliveryou.service" }) @EnableWebSecurity public class SpringSecurityConfiguration { @Configuration @Order(1) public class UserSecurityConfiguration extends WebSecurityConfigurerAdapter{ @Autowired private UserService userDetailsService; @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(10); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().disable(); http.formLogin() .loginPage("/login") .usernameParameter("phone_number") .passwordParameter("password") .successHandler((request, response, authentication) -> { User user = userDetailsService.getUser(authentication.getName()); if (user.getRole().getName().equals(Role.ADMIN)) response.setStatus(HttpStatus.UNAUTHORIZED.value()); else { response.setStatus(HttpStatus.OK.value()); request.getSession().setAttribute("current_user", user); System.out.println("current user: " + user); switch (user.getRole().getName()) { case Role.REGULAR_USER: response.sendRedirect("/deliveryou_war_exploded/user/app"); break; case Role.SHIPPER: response.sendRedirect("/deliveryou_war_exploded/shipper/app"); break; } } }) .failureHandler(((request, response, exception) -> { response.setStatus(HttpStatus.UNAUTHORIZED.value()); Map<String, Object> data = new HashMap<>(); data.put("msg", "failed to log in"); response.getOutputStream() .println(new ObjectMapper().writeValueAsString(data)); })); http.logout().logoutSuccessHandler((request, response, authentication) -> { request.getSession().removeAttribute("current_user"); response.sendRedirect("/deliveryou_war_exploded/"); }); http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/user/**").authenticated() .antMatchers("/user/**").access("hasRole('ROLE_USER')") .antMatchers("/shipper/**").authenticated() .antMatchers("/shipper/**").access("hasRole('ROLE_SHIPPER')") .antMatchers("/common/**").authenticated(); http.authorizeRequests() .antMatchers("/test/**").permitAll() .antMatchers("/public/**").permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } @Bean public Cloudinary cloudinary() { return new Cloudinary(new HashMap() {{ put("cloud_name", "quocnv0707"); put("api_key", "252896799917597"); put("api_secret", "LhJpqRPCnCr6AxVsaSnsG7TpjtA"); put("secure", true); }}); } } @Configuration @Order(-1) public class AdminSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserService userDetailsService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().disable(); http.formLogin() .loginPage("/admin") .usernameParameter("phone_number") .passwordParameter("password") .successHandler( (request, response, authentication) -> { User user = userDetailsService.getUser(authentication.getName()); if (!user.getRole().getName().equals(Role.ADMIN)) response.setStatus(HttpStatus.UNAUTHORIZED.value()); else { response.setStatus(HttpStatus.OK.value()); request.getSession().setAttribute("current_user", user); System.out.println("current user: " + user); response.sendRedirect("/deliveryou_war_exploded/admin/app"); } } ) .failureHandler( ((request, response, exception) -> { response.setStatus(HttpStatus.UNAUTHORIZED.value()); Map<String, Object> data = new HashMap<>(); data.put("msg", "failed to log in"); response.getOutputStream() .println(new ObjectMapper().writeValueAsString(data)); }) ); http.logout().logoutSuccessHandler((request, response, authentication) -> { request.getSession().removeAttribute("current_user"); response.sendRedirect("/deliveryou_war_exploded/"); }); http.requestMatchers().antMatchers("/admin/**").and() .authorizeRequests() .antMatchers("/admin").permitAll() .antMatchers("/admin/**").authenticated() .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } } }
from django.db import models from django.contrib.auth.models import User from taggit.managers import TaggableManager from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() image = models.ImageField(upload_to='blog/', default='blog/default.jpg') tags = TaggableManager() category = models.ManyToManyField(Category) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) counted_views = models.IntegerField(default=0) status = models.BooleanField(default=False) published_date = models.DateTimeField(null=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['created_date'] def __str__(self): return " {} - {} ".format(self.title, self.id) def snippets(self): return self.content[:100] + '...' # def get_absolute_url(self): # return reverse('blog:single', kwargs={'pid': self.id})
package Ritesh; import java.util.HashMap; import java.util.Map; public class MaxScoreWord { static class Solution { public int maxScoreWords(String[] words, char[] letters, int[] score) { Map<Character, Integer> letterCount = new HashMap<>(); for (char letter : letters) { letterCount.put(letter, letterCount.getOrDefault(letter, 0) + 1); } return backtrack(words, letterCount, score, 0); } private int backtrack(String[] words, Map<Character, Integer> letterCount, int[] score, int index) { if (index == words.length) { return 0; } int maxScore = backtrack(words, letterCount, score, index + 1); String word = words[index]; boolean canFormWord = true; int wordScore = 0; Map<Character, Integer> tempCount = new HashMap<>(letterCount); for (char c : word.toCharArray()) { if (tempCount.getOrDefault(c, 0) > 0) { tempCount.put(c, tempCount.get(c) - 1); wordScore += score[c - 'a']; } else { canFormWord = false; break; } } if (canFormWord) { wordScore += backtrack(words, tempCount, score, index + 1); maxScore = Math.max(maxScore, wordScore); } return maxScore; } public static void main(String[] args) { Solution solution = new Solution(); String[] words1 = {"dog", "cat", "dad", "good"}; char[] letters1 = {'a', 'a', 'c', 'd', 'd', 'd', 'g', 'o', 'o'}; int[] score1 = {1, 0, 9, 5, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; System.out.println(solution.maxScoreWords(words1, letters1, score1)); // Output: 23 String[] words2 = {"xxxz", "ax", "bx", "cx"}; char[] letters2 = {'z', 'a', 'b', 'c', 'x', 'x', 'x'}; int[] score2 = {4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 10}; System.out.println(solution.maxScoreWords(words2, letters2, score2)); // Output: 27 String[] words3 = {"leetcode"}; char[] letters3 = {'l', 'e', 't', 'c', 'o', 'd'}; int[] score3 = {0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}; System.out.println(solution.maxScoreWords(words3, letters3, score3)); // Output: 0 } } }
# numpy import numpy as np # sklearn from sklearn import datasets from sklearn.preprocessing import minmax_scale from sklearn.model_selection import train_test_split # datasets class Datasets(): """ Description: Holds different classification datasets """ # constructor def __init__(self, test_size, random_state): """ Description: Constructor for our Datasets class Parameters: test_size: percentage of data to be allocated for testing random_state: random state chosen for reproducible output Returns: None """ self.test_size = test_size self.random_state = random_state # blobs def make_blobs(self, num_samples, num_features): """ Description: Loads toy dataset using sklearn make_blobs Parameters: num_samples: number of samples to generate for toy dataset num_features: number of features per training sample Returns: X, y, class_names, X_train, X_test, y_train, y_test """ # make blobs of data X, y = datasets.make_blobs(n_samples = num_samples, n_features = num_features, centers = 2, cluster_std = 1.05, random_state = self.random_state) # normalize X features to range = [0, 1] to avoid explosive computations X = minmax_scale(X, feature_range = (0, 1), axis = 0, copy = True) # perform train test split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = self.test_size, random_state = self.random_state) # class names class_names = ['positive', 'negative'] # return return X, y, class_names, X_train, X_test, y_train, y_test # breast cancer def load_breast_cancer(self): """ Description: Loads sklearn's Breast Cancer Dataset Parameters: None Returns: X, y, feature_names, class_names, X_train, X_test, y_train, y_test """ # load dataset data = datasets.load_breast_cancer() # load features, labels, and class names X, y, feature_names, class_names = data.data, data.target, data.feature_names, data.target_names # normalize X features to range = [0, 1] to avoid explosive computations X = minmax_scale(X, feature_range = (0, 1), axis = 0, copy = True) # perform train test split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = self.test_size, random_state = self.random_state) # return return X, y, feature_names, class_names, X_train, X_test, y_train, y_test # diabetes def load_diabetes(self): """ Description: Loads sklearn's Diabetes Dataset Parameters: None Returns: X, y_classification, feature_names, class_names, X_train, X_test, y_train, y_test """ # This is a regression dataset but we will convert it to classification # load the dataset data = datasets.load_diabetes() # load features, "labels", and class names X, y, feature_names = data.data, data.target, data.feature_names # normalize X features to range = [0, 1] to avoid explosive computations X = minmax_scale(X, feature_range = (0, 1), axis = 0, copy = True) # convert y to labels we want using median, if valua > median assign True, else False # we will use 1 (True) for has diabetes and 0 (False) for no diabetes y_classification = np.array([y > np.median(y)]).reshape(-1) # (y > y.median()).astype(int) class_names = ['non-diabetic', 'diabetic'] # perform train test split X_train, X_test, y_train, y_test = train_test_split(X, y_classification, test_size = self.test_size, random_state = self.random_state) # return return X, y_classification, feature_names, class_names, X_train, X_test, y_train, y_test
/** * @param {number[]} arr * @return {boolean} */ var validMountainArray = function (arr) { let peak = 0; for (let i = 1; i < arr.length - 1; i++) { if (arr[i] === arr[i + 1]) { return false; } if (arr[i - 1] > arr[i] && arr[i] < arr[i + 1]) { return false; } if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1]) { peak++; } } return peak === 1; }; // console.log(validMountainArray([0, 2, 3, 4, 5, 2, 1, 0])); // console.log(validMountainArray([0, 2, 3, 3, 5, 2, 1, 0])); // console.log(validMountainArray([3, 5, 5])); // console.log(validMountainArray([0, 1, 2, 1, 2])); /** * @param {number[]} arr * @return {boolean} */ var validMountainArray2 = function (arr) { let currentIdx = 0; // 정상까지 오르기 while (currentIdx + 1 < arr.length && arr[currentIdx] < arr[currentIdx + 1]) { currentIdx++; } // 정상이 첫 번째 인덱스거나 마지막 인덱스일 수 없음 if (currentIdx === 0 || currentIdx === arr.length - 1) { return false; } // 내려오기 while (currentIdx + 1 < arr.length && arr[currentIdx] > arr[currentIdx + 1]) { currentIdx++; } // 정상적으로 모두 내려오면 true, 아니면 false return currentIdx === arr.length - 1; }; console.log(validMountainArray2([0, 2, 3, 4, 5, 2, 1, 0])); console.log(validMountainArray2([0, 2, 3, 3, 5, 2, 1, 0])); console.log(validMountainArray2([3, 5, 5])); console.log(validMountainArray2([0, 1, 2, 1, 2]));
import { CssBaseline, ThemeProvider } from "@mui/material"; import React from "react"; import { RouterProvider } from "react-router-dom"; import { useAppSelector } from "./state/hooks"; import { darkTheme, lightTheme } from "./theme/theme"; import router from "./components/layout/router/router"; import { SnackbarProvider } from "notistack"; export default function App() { const darkMode = useAppSelector((state) => state.user.darkMode); return ( <React.Fragment> <CssBaseline /> <ThemeProvider theme={darkMode ? darkTheme : lightTheme}> <SnackbarProvider> <RouterProvider router={router} /> </SnackbarProvider> </ThemeProvider> </React.Fragment> ); }
/** * @jest-environment jsdom */ import { render, screen, waitFor } from "@testing-library/react"; import noop from "lodash/noop"; import React from "react"; import { usePollingIf } from "./usePollingIf"; describe("usePollingIf with an error", () => { it("should keep on going even if there are errors", async () => { jest.useFakeTimers(); const callback = jest.fn(); const errorMock = jest.fn(); callback.mockImplementation(() => { throw new Error("fail"); }); let renderCount = 0; function MyComponent() { usePollingIf(() => true, callback, { onError: errorMock }); ++renderCount; return <div data-testid="test">{renderCount}</div>; } render(<MyComponent />); expect(screen.getByTestId("test").textContent).toEqual("1"); await waitFor(() => { expect(renderCount).toEqual(1); }); expect(callback).toHaveBeenCalledTimes(1); expect(errorMock.mock.calls[0][0]).toEqual(new Error("fail")); jest.runAllTimers(); await waitFor(() => { expect(renderCount).toEqual(1); }); expect(callback).toHaveBeenCalledTimes(2); expect(errorMock.mock.calls[1][0]).toEqual(new Error("fail")); jest.runAllTimers(); await waitFor(() => { expect(renderCount).toEqual(1); }); expect(callback).toHaveBeenCalledTimes(3); expect(errorMock.mock.calls[2][0]).toEqual(new Error("fail")); }); afterEach(() => { jest.useRealTimers(); }); });
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Address; use Illuminate\Mail\Mailables\Attachment; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; use Illuminate\Queue\SerializesModels; class SendSourceImages extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. */ public function __construct(private $user,private array $images) { // } /** * Get the message envelope. */ public function envelope(): Envelope { return new Envelope( from: new Address('amirmahdishahbazi1382@gmail.com', 'Graphic-shop'), subject: 'Send Source Images', ); } /** * Get the message content definition. */ public function content(): Content { return new Content( view: 'email.master', with:['user'=>$this->user] ); } /** * Get the attachments for the message. * * @return array<int, \Illuminate\Mail\Mailables\Attachment> */ public function attachments(): array { $attachment=[]; foreach($this->images as $image) { $attachment[]=Attachment::fromPath(storage_path('app/local_storage/').$image); } return $attachment; } }
import { Meta, Story, Props } from '@storybook/addon-docs'; import { NewsKitProvider } from 'newskit'; import { PuzzlesWebLightTheme } from '../../../../theme'; import { HintButton } from './index'; <Meta title="Newskit Components/Puzzles/HintButton" component={HintButton} /> # HintButton The `HintButton` component is used to display a button for requesting hints for daily quiz. ## Props <Props of={HintButton} /> ### `onClick` (required) A function to be called when the button is clicked. ### `disabled` (required) A boolean value that determines whether the button is disabled. ### `title` (optional) The text to be displayed on the button. If not provided, the default text is "Give me a hint". ## Code Example `<HintButton onClick={() => alert('Button clicked')} disabled={false} title="Get Hint" />` An example of the `data` structure can be found in the 'Controls' section on the 'Canvas' tab, where you can customise the data being fed to the FinalScreen component. ## View Component Please click the 'Canvas' tab for a better viewing experience, where you can update the props and review at the different breakpoints by clicking the preview icon and selecting from our list of pre-defined breakpoints (XS, SM, MD, LG and XL). export const HintButtonStory = ({ onClick, disabled, title }) => ( <NewsKitProvider theme={PuzzlesWebLightTheme}> <HintButton onClick={onClick} disabled={disabled} title={title} /> </NewsKitProvider> ); <Story name="HintButton" args={{ onClick: () => alert('Button clicked'), disabled: false, title: "Give me a hint" }}> {HintButtonStory} </Story>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Movie Ticket Booking</title> <link rel="stylesheet" href="styles.css"> <!-- You can link your custom styles here --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> /* Add your custom styles here */ body, h1, h2, h3, h4, h5, h6 { font-family: "Raleway", Arial, Helvetica, sans-serif; } .myLink { display: none; } /* Styles for the movie ticket booking app */ .movie-header { position: relative; height: 700px; } .video-container { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; } video { width: 100%; height: 100%; object-fit: cover; } .movie-header-content { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); /* Optional: Add a semi-transparent overlay */ display: flex; flex-direction: column; align-items: center; justify-content: center; color: white; } .movie-header h1 { font-size: 48px; } .movie-search { text-align: center; padding-top: 20px; } .movie-search input[type="text"] { width: 80%; padding: 10px; font-size: 18px; } .movie-search button { background-color: red; color: white; border: none; padding: 10px 20px; font-size: 18px; cursor: pointer; } .movie-search button:hover { background-color: darkred; } /* Movie Card */ .movie-card { position: relative; width: 100%; /* Set the width to 100% for smaller movie cards */ margin-bottom: 30px; cursor: pointer; transition: transform 0.2s; } .movie-card img { width: 30%; height: auto; } .movie-card:hover { transform: scale(1.05); } .movie-card .movie-title { position: absolute; bottom: 0; left: 0; right: 0; background-color: rgba(0, 0, 0, 0.7); color: white; padding: 10px; text-align: center; font-size: 18px; } </style> </head> <body class="w3-light-grey"> <!-- Navigation Bar --> <div class="w3-bar w3-white w3-border-bottom w3-xlarge"> <a href="#" class="w3-bar-item w3-button w3-text-red w3-hover-red"><b><i class="fa fa-film w3-margin-right"></i>Movie Tickets</b></a> <a href="#" class="w3-bar-item w3-button w3-right w3-hover-red w3-text-grey"><i class="fa fa-search"></i></a> <a href="login.html" class="w3-bar-item w3-button w3-right w3-hover-red w3-text-grey"><i class="fa fa-sign-in"></i> Login</a> <!-- Add your login page link here --> </div> <!-- Header --> <header class="movie-header"> <div class="video-container"> <video autoplay muted loop> <source src="C:\Users\User\Downloads\pexels-tima-miroshnichenko-7989632 (2160p).mp4" type="video/mp4"> <!-- Add more source elements for different video formats if needed --> Your browser does not support the video tag. </video> </div> <div class="movie-header-content"> <h1>Book Your Movie Tickets</h1> <div class="movie-search"> <input type="text" placeholder="Search for movies, theaters, or cities"> <button>Search</button> </div> </div> </header> <!-- Page content --> <div class="w3-content" style="max-width:1100px;"> <!-- Movie Listings --> <div class="w3-container w3-margin-top"> <h3>Now Showing</h3> <p>Discover the latest movies and showtimes.</p> </div> <!-- Movie Cards --> <div class="w3-row-padding"> <div class="w3-half w3-margin-bottom"> <div class="movie-card"> <img src="C:\Users\User\Downloads\leo.jpg" alt="Leo-Tamil"> <div class="movie-title">Leo</div> </div> </div> <div class="w3-half w3-margin-bottom"> <!-- Image Map for Movie Card --> <div class="movie-card"> <!-- Use the image as the base for the image map --> <img src="C:\Users\User\Downloads\cm.jpg" alt="Movie 2" usemap="#movie-map"> <!-- Define the image map --> <map name="movie-map"> <!-- Define the area with the link coordinates --> <area target="" alt="ChandraMukhi-2" title="ChandraMukhi-2" href="movie.html" coords="0,0,317,470" shape="rect"> </map> <!-- Movie title --> <div class="movie-title">ChandraMukhi-2</div> </div> </div> </div> <!-- End Movie Cards --> <!-- Explore More --> <div class="w3-container"> <h3>Coming Soon</h3> <p>Get ready for these upcoming movies.</p> </div> <!-- Upcoming Movie Cards --> <div class="w3-row-padding"> <div class="w3-half w3-margin-bottom"> <div class="movie-card"> <img src="C:\Users\User\Downloads\Aruvi_poster.jpg" alt="Movie 3"> <div class="movie-title">Aruvi</div> </div> </div> <div class="w3-half w3-margin-bottom"> <div class="movie-card"> <img src="C:\Users\User\Downloads\download.jpg" alt="Movie 4"> <div class="movie-title">Marvel</div> </div> </div> </div> <!-- End Upcoming Movie Cards --> <div class="w3-row-padding"> <div class="w3-half w3-margin-bottom"> <div class="movie-card"> <img src="C:\Users\User\Downloads\vaazhl_tamil_21nov_landscape_thumb.jpg" alt="Movie 3"> <div class="movie-title">Vaazh</div> </div> </div> </div> <!-- Newsletter --> <div class="w3-container"> <h3>Newsletter</h3> <p>Subscribe to our newsletter for the latest updates.</p> <label>Email</label> <input class="w3-input w3-border" type="text" placeholder="Your Email address"> <button type="button" class="w3-button w3-red w3-margin-top">Subscribe</button> </div> <!-- Rest of your content here --> <!-- Contact --> <div class="w3-container"> <h3>Contact Us</h3> <p>If you have any questions or need assistance, feel free to reach out.</p> <i class="fa fa-map-marker" style="width:30px"></i> Your Address, City, Country<br> <i class="fa fa-phone" style="width:30px"></i> Phone: +00 1234567890<br> <i class="fa fa-envelope" style="width:30px"> </i> Email: info@movietickets.com<br> </div> <!-- Rest of your content here --> <!-- End page content --> </div> <!-- Footer --> <footer class="w3-container w3-center w3-opacity w3-margin-bottom"> <h5>Follow Us On</h5> <div class="w3-xlarge w3-padding-16"> <i class="fa fa-facebook-official w3-hover-opacity"></i> <i class="fa fa-instagram w3-hover-opacity"></i> <i class="fa fa-twitter w3-hover-opacity"></i> </div> <p>Powered by <a href="https://www.w3schools.com/w3css/default.asp" target="_blank" class="w3-hover-text-green">w3.css</a></p> </footer> <!-- Rest of your content here --> <script> // Your JavaScript logic can be added here </script> </body> </html>
package com.epam.java.se.task2; import org.junit.Test; import java.util.Locale; import java.util.ResourceBundle; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class QuizTest { @Test public void testCreateQuizEnglishLanguage() { final Quiz quiz = new Quiz("en"); final Locale expectedLocale = new Locale("en"); assertThat(quiz.getLocale(), is(expectedLocale)); } @Test public void testCreateQuizRussianLanguage() { final Quiz quiz = new Quiz("ru"); final Locale expectedLocale = new Locale("ru"); assertThat(quiz.getLocale(), is(expectedLocale)); } @Test(expected = IllegalArgumentException.class) public void testCreateQuizUnsupportedLanguageThrowsIllegalArgumentException() { final Quiz quiz = new Quiz("fr"); } @Test(expected = NullPointerException.class) public void testCreateQuizNullArgumentLanguageThrowsNullPointerException() { final Quiz quiz = new Quiz(null); } @Test public void testThatQuizConstructsWithCorrectResourcesBundlesForEnglish() { final Quiz quiz = new Quiz("en"); final ResourceBundle realQuestions = quiz.getQuestions(); final ResourceBundle realAnswers = quiz.getAnswers(); final ResourceBundle expectedQuestions = ResourceBundle.getBundle("questions", new Locale("en")); final ResourceBundle expectedAnswers = ResourceBundle.getBundle("answers", new Locale("en")); assertThat(realQuestions.equals(expectedQuestions), is(true)); assertThat(realAnswers.equals(expectedAnswers), is(true)); } @Test public void testThatQuizConstructsWithCorrectResourcesBundlesForRussian() { final Quiz quiz = new Quiz("ru"); final ResourceBundle realQuestions = quiz.getQuestions(); final ResourceBundle realAnswers = quiz.getAnswers(); final ResourceBundle expectedQuestions = ResourceBundle.getBundle("questions", new Locale("ru")); final ResourceBundle expectedAnswers = ResourceBundle.getBundle("answers", new Locale("ru")); assertThat(realQuestions.equals(expectedQuestions), is(true)); assertThat(realAnswers.equals(expectedAnswers), is(true)); } @Test public void testThatWeCanGetEnglishQuestionByNumber() { final Quiz quiz = new Quiz("en"); final String realQuestionNumber5 = quiz.getQuestion(5); final String expectedQuestionNumber5 = ResourceBundle. getBundle("questions", new Locale("en")) .getString("question5"); assertThat(realQuestionNumber5.equals(expectedQuestionNumber5), is(true)); } @Test public void testThatWeCanGetRussianQuestionByNumber() { final Quiz quiz = new Quiz("ru"); final String realQuestionNumber5 = quiz.getQuestion(5); final String expectedQuestionNumber5 = ResourceBundle. getBundle("questions", new Locale("ru")) .getString("question5"); assertThat(realQuestionNumber5.equals(expectedQuestionNumber5), is(true)); } @Test(expected = IllegalArgumentException.class) public void testThatGettingNotExistingEnglishQuestionThrowsIllegalArgumentException() { final Quiz quiz = new Quiz("ru"); quiz.getQuestion(12); } @Test(expected = IllegalArgumentException.class) public void testThatGettingNotExistingRussianQuestionThrowsIllegalArgumentException() { final Quiz quiz = new Quiz("ru"); quiz.getQuestion(0); } @Test public void testThatWeCanGetRussianAnswerForQuestionByNumber() { final Quiz quiz = new Quiz("ru"); final String realAnswerNumber5 = quiz.getAnswer(5); final String expectedAnswerNumber5 = ResourceBundle. getBundle("answers", new Locale("ru")) .getString("answer5"); assertThat(realAnswerNumber5.equals(expectedAnswerNumber5), is(true)); } @Test public void testThatWeCanGetEnglishAnswerForQuestionByNumber() { final Quiz quiz = new Quiz("en"); final String realAnswerNumber5 = quiz.getAnswer(5); final String expectedAnswerNumber5 = ResourceBundle. getBundle("answers", new Locale("en")) .getString("answer5"); assertThat(realAnswerNumber5.equals(expectedAnswerNumber5), is(true)); } @Test(expected = IllegalArgumentException.class) public void testThatGettingNotExistingRussianAnswerThrowsIllegalArgumentException() { final Quiz quiz = new Quiz("ru"); quiz.getAnswer(0); } @Test(expected = IllegalArgumentException.class) public void testThatGettingNotExistingEnglishAnswerThrowsIllegalArgumentException() { final Quiz quiz = new Quiz("en"); quiz.getAnswer(15); } }
<script lang="ts"> import * as Form from '$lib/components/ui/form'; import { Input } from '$lib/components/ui/input'; import { Textarea } from '$lib/components/ui/textarea'; import * as Alert from '$lib/components/ui/alert'; import { experienceSchema, type ExperienceSchema } from '../schema'; import { zodClient } from 'sveltekit-superforms/adapters'; import { superForm, type Infer, type SuperValidated } from 'sveltekit-superforms/client'; import { AlertCircleIcon } from 'lucide-svelte'; export let data: SuperValidated<Infer<ExperienceSchema>>; const form = superForm(data, { validators: zodClient(experienceSchema), delayMs: 300, timeoutMs: 2000 }); const { form: formData, message, enhance } = form; </script> <form method="post" use:enhance> {#if $message} <Alert.Root class="bg-green-100"> <AlertCircleIcon class="h-5 w-5" /> <Alert.Title>Success!</Alert.Title> <Alert.Description>{$message}</Alert.Description> </Alert.Root> {/if} <Form.Field {form} name="name" class="mb-8"> <Form.Control let:attrs> <Form.Label>Name:</Form.Label> <Input {...attrs} bind:value={$formData.name} /> <Form.FieldErrors /> </Form.Control> </Form.Field> <Form.Field {form} name="imageUrl" class="mb-8"> <Form.Control let:attrs> <Form.Label>Image URL:</Form.Label> <Input {...attrs} type="url" bind:value={$formData.imageUrl} /> <Form.FieldErrors /> </Form.Control> </Form.Field> <Form.Field {form} name="price" class="mb-8"> <Form.Control let:attrs> <Form.Label>Price:</Form.Label> <Input {...attrs} type="number" bind:value={$formData.price} /> <Form.FieldErrors /> </Form.Control> </Form.Field> <Form.Field {form} name="description" class="mb-8"> <Form.Control let:attrs> <Form.Label>Description:</Form.Label> <Textarea {...attrs} bind:value={$formData.description} /> <Form.FieldErrors /> </Form.Control> </Form.Field> <Form.Button variant="default" class="block w-full">Create</Form.Button> </form>
"use client"; import { FC, FormEvent, useEffect, useRef, useState } from "react"; import emailjs from "@emailjs/browser"; import EmptyState from "@/components/EmptyState"; import Heading from "@/components/Heading"; import Container from "@/components/Container"; import { toast } from "react-hot-toast"; import { motion } from "framer-motion"; import Disclaimer from "./Disclaimer"; interface ContactFormProps {} const ContactForm: FC<ContactFormProps> = ({}) => { const formRef = useRef<HTMLFormElement | null>(null); const [isMessageSent, setIsMessageSent] = useState<boolean>(false); var now = new Date().getTime(); useEffect(() => { const sentMessageTime = localStorage.getItem("sentMessageTime"); if (sentMessageTime) { if (now - parseInt(sentMessageTime) > 3 * 60 * 60 * 1000) { // Delete the local storage after 3 hours localStorage.removeItem("sentMessageTime"); } else { setIsMessageSent(true); } } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); if (isMessageSent) { return ( <EmptyState title="Thanks for your submission!" subtitle="You'll be able to submit another message again after 3 hours." /> ); } const sendEmail = (e: FormEvent) => { e.preventDefault(); if (!formRef) { return; } //@ts-ignore if (formRef.current[2].value.length < 50) { toast.error("Message is too short!"); return; } emailjs .sendForm( "service_rafjm4f", "template_je7ya2a", formRef.current!, "FojtL_6mOjiB2gO7H" ) .then( () => { localStorage.setItem("sentMessageTime", "" + now); setIsMessageSent(true); }, (error) => { return; } ); }; return ( <Container> <motion.main initial={{ opacity: 0 }} whileInView={{ opacity: 1, transition: { duration: 0.5 } }} className="mx-auto my-12 max-w-[800px] space-y-4 rounded-lg border-2 p-4 shadow-lg" > <Heading title="Contact" /> <form ref={formRef} onSubmit={sendEmail} className="flex flex-col justify-center gap-4" > <div className="relative"> <input id="name" type="text" name="user_name" placeholder=" " required className={`peer w-full rounded-md border-2 px-4 py-3 outline-none focus:border-zinc-800`} /> <label className={`absolute left-3 top-3 origin-left -translate-y-6 scale-75 select-none rounded-md bg-bg px-2 text-neutral-500 transition peer-placeholder-shown:left-3 peer-placeholder-shown:-translate-y-0 peer-placeholder-shown:scale-100 peer-focus:-translate-y-6 peer-focus:text-neutral-800`} > Name </label> </div> <div className="relative"> <input id="email" type="email" name="user_email" placeholder=" " required className={`peer w-full rounded-md border-2 px-4 py-3 outline-none focus:border-zinc-800`} /> <label className={`absolute left-3 top-3 origin-left -translate-y-6 scale-75 select-none rounded-md bg-bg px-2 text-neutral-500 transition peer-placeholder-shown:left-3 peer-placeholder-shown:-translate-y-0 peer-placeholder-shown:scale-100 peer-focus:-translate-y-6 peer-focus:text-neutral-800`} > Email </label> </div> <div className="relative"> <textarea name="message" rows={5} placeholder=" " required className="peer w-full resize-none rounded-md border-2 px-2.5 py-1.5 outline-none focus:border-zinc-800" /> <label className={`absolute left-3 top-3 origin-left -translate-y-6 scale-75 select-none rounded-md bg-bg px-2 text-neutral-500 transition peer-placeholder-shown:left-3 peer-placeholder-shown:-translate-y-0 peer-placeholder-shown:scale-100 peer-focus:-translate-y-6 peer-focus:text-neutral-800`} > Message </label> </div> <button aria-label="submit button" type="submit" className="border-2 border-zinc-800 p-2 transition duration-300 hover:bg-zinc-800 hover:text-white md:text-lg" > Send Message </button> </form> <Disclaimer title="For Your Information" content={`> You'll only be able to send a message every few hours.\n> Feel free to report a bug or leave any feedback through this form!`} /> </motion.main> </Container> ); }; export default ContactForm;
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import { routes } from 'frontend/app/config/routes'; import { HttpClient, HttpEvent, HttpRequest, HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { ConfigService } from 'frontend/app/config/config.service'; import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { TranslateService } from '@ngx-translate/core'; import { environment } from 'frontend/environments/environment.staging'; import { TranslationModel } from '../../models/translation.model'; @Component({ selector: 'app-upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadComponent implements OnInit { @Output() uploadingEvent: EventEmitter<boolean> = new EventEmitter(); @Output() fileChangeEvent: EventEmitter<number> = new EventEmitter(); accept = '*'; files: File[] = []; config: any; progress: number; hasBaseDropZoneOver = false; httpEmitter: Subscription; httpEvent: HttpEvent<Event>; lastFileAt: Date; checkIcon: FaIconComponent; warningIcon: FaIconComponent; deleteIcon: FaIconComponent; uploadIcon: FaIconComponent; maxSize: number; lastInvalids: any; baseDropValid: any; dragFiles: any; translationFields: TranslationModel.Upload; constructor( public HttpClient: HttpClient, private configService: ConfigService, private translateService: TranslateService ) { console.log('test'); this.config = this.configService.getConfig(); this.checkIcon = this.config.icons.toggleOn; this.warningIcon = this.config.icons.warning; this.deleteIcon = this.config.icons.delete; this.uploadIcon = this.config.icons.upload; this.maxSize = environment.upload.maxSize; } cancel() { this.progress = 0; if (this.httpEmitter) { this.httpEmitter.unsubscribe(); } } uploadFilesToOrder(id: string, cb?: Function, shared?: boolean): Subscription { let url; if (shared) { url = `${routes.backendUrl}/${routes.paths.backend.orders.root}/` + `${routes.paths.backend.orders.shared}/${id}/${routes.paths.backend.orders.files}`; } else { url = `${routes.backendUrl}/${routes.paths.backend.orders.root}/${id}/${routes.paths.backend.orders.files}`; } const formData: FormData = new FormData(); this.files.forEach(file => { formData.append('file', file, file.name); }); const req = new HttpRequest<FormData>('POST', url, formData, { reportProgress: true// , responseType: 'text' }); this.emit(true); return this.httpEmitter = this.HttpClient.request(req) .subscribe( (event: HttpEvent<Event>) => { this.httpEvent = event; if (event instanceof HttpResponse) { delete this.httpEmitter; } }, error => console.log('Error Uploading', error), () => { this.emit(false); if (cb) { cb(); } } ); } getDate() { return new Date(); } ngOnInit() { this.translateService.onLangChange.subscribe(() => { this._translate(); }); this._translate(); } public emit(uploading) { this.uploadingEvent.emit(uploading); } public emitFileChange(files) { if (files && files.length) { this.fileChangeEvent.emit(files.length); } else { this.fileChangeEvent.emit(0); } } private _translate() { this.translateService.get(['upload']).subscribe((translations => { if (translations.hasOwnProperty('upload') && translations.upload.hasOwnProperty('labels')) { this.translationFields = TranslationModel.translationUnroll(translations); } })); } }
import axios from 'axios'; import { instance } from '../axios/index'; // Function for register user endpoint async function registerUser(username, email, password) { try { const response = await axios.post('http://localhost:3000/user/register', { username, email, password }); return response.data; } catch (error) { throw new Error(error.response.data.message || 'Something went wrong'); } } // Function for login user endpoint async function loginUser(username, password) { try { const response = await axios.post('http://localhost:3000/user/login', { username, password }); return response.data; } catch (error) { throw new Error(error.response.data.message || 'Something went wrong'); } } async function logoutUser() { try { await instance.post('/user/logout') } catch (error) { throw new Error(error.response.data.message || 'something went wrong') } } async function getSpecificUser() { try { const response = await instance.get(`/user/specific`); return response.data; } catch (error) { throw new Error(error.response.data.message || 'something went wrong') } } async function editProfile(user_id, formData) { try { const response = await instance.put(`/user/edit/${user_id}`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }) return response.data } catch (error) { throw new Error(error.response.data.message || 'Something went wrong'); } } export { registerUser, loginUser, logoutUser, getSpecificUser, editProfile };
import Layout from "../components/Layout/Layout"; import { Button, Label, TextInput } from "flowbite-react"; import { useMutation } from "@tanstack/react-query"; import { AxiosClient } from "../utils/AxiosClient"; import { useState } from "react"; const RegisterPage = () => { const [formData, setFormData] = useState({ fullName: "", cpf: "", dateOfBirth: "", }); function handleOnChange(evt) { setFormData({ ...formData, [evt.target.name]: evt.target.value, }); } const mutation = useMutation({ mutationFn: () => AxiosClient.post("http://127.0.0.1:5254/api/user", formData), onSuccess: () => { // Invalidate and refetch // queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }); function handleRegister(e) { e.preventDefault(); mutation.mutate(); } return ( <Layout> <form onSubmit={(e) => handleRegister(e)} method="POST" className="flex flex-col p-4 gap-4 w-1/3 bg-white rounded shadow text-center" > <h1 className="font-bold text-xl mb-2 mt-2 text-gray-900"> Cadastrar novo usuário </h1> <div> <div className="mb-2 block text-left"> <Label htmlFor="cpf" value="CPF: (somente números)" /> </div> <TextInput id="cpf" name="cpf" type="number" required={true} onChange={(e) => handleOnChange(e)} /> </div> <div> <div className="mb-2 block text-left"> <Label htmlFor="fullName" value="Nome Completo" /> </div> <TextInput id="fullName" name="fullName" type="text" required={true} onChange={(e) => handleOnChange(e)} /> </div> <div> <div className="mb-2 block text-left"> <Label htmlFor="dateOfBirth" value="Data de Nascimento:" /> </div> <TextInput id="dateOfBirth" name="dateOfBirth" type="date" required={true} onChange={(e) => handleOnChange(e)} /> </div> <Button className="bg-blue-500 text-white p-2 mt-6" type="submit"> Registrar </Button> <div className="mx-6 text-blue-500"> <a href="/login">Voltar ao login</a> </div> </form> </Layout> ); }; export default RegisterPage;
<form [formGroup]="registerForm" class="register-form"> <p-card header="Register" [style]="{ width: '360px' }" class="register-card"> <div class="field"> <label for="firstName">First Name</label> <input type="text" pInputText formControlName="firstName" class="w-full" name="firstName" placeholder="Enter your First Name" /> <small *ngIf="firstName.invalid && (firstName.dirty || firstName.touched)" class="block p-error" > <div *ngIf="firstName.errors?.['required']">First Name is required.</div> <div *ngIf="firstName.errors?.['pattern']">Enter a valid Name</div> </small> </div> <div class="field"> <label for="lastName">Last Name</label> <input type="text" pInputText formControlName="lastName" class="w-full" name="lastName" placeholder="Enter your Last Name" /> <small *ngIf="lastName.invalid && (lastName.dirty || lastName.touched)" class="block p-error" > <div *ngIf="lastName.errors?.['required']">Last Name is required.</div> <div *ngIf="lastName.errors?.['pattern']">Enter a valid Name</div> </small> </div> <div class="field"> <label for="email">Email</label> <input type="text" pInputText formControlName="email" class="w-full" name="email" placeholder="Enter your email" /> <small *ngIf="email.invalid && (email.dirty || email.touched)" class="block p-error" > <div *ngIf="email.errors?.['required']">Email is required.</div> <div *ngIf="email.errors?.['email']">Email should be valid</div> </small> </div> <div class="field"> <label for="password">Password</label> <input type="password" pInputText formControlName="password" class="w-full" name="password" placeholder="Enter your password" /> <small *ngIf="password.invalid && (password.dirty || password.touched)" class="block p-error" > <div *ngIf="password.errors?.['required']">Password is required.</div> </small> </div> <div class="field"> <label for="confirmPassword">Confirm Password</label> <input type="password" pInputText formControlName="confirmPassword" class="w-full" name="confirmPassword" placeholder="Confirm Password" /> <small *ngIf=" confirmPassword.invalid && (confirmPassword.dirty || confirmPassword.touched) " class="block p-error" > <div *ngIf="confirmPassword.errors?.['required']"> Confirm the password </div> </small> <small class="block p-error" *ngIf="registerForm.errors?.['passwordMismatch'] && confirmPassword.valid && password.valid" > Password should match </small> </div> <br/> <p-button label="Register" styleClass="w-full" [disabled]="registerForm.invalid" type="submit" ></p-button> <div class="mt-2">Already have an account? <a routerLink="/login">Login</a></div> </p-card> </form>
/******************************************************************************** * Copyright (c) 2023 Mercedes-Benz Group AG and BMW Group AG * Copyright (c) 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ import { PageBreadcrumb } from 'components/shared/frame/PageBreadcrumb/PageBreadcrumb' import { PageHeader, Typography, Button, ProcessList, } from '@catena-x/portal-shared-components' import { Box } from '@mui/material' import './ReleaseProcess.scss' type RequerementStepType = { neuButton: string marketplaceTitle: string marketplaceExplanation: string index: number } type StepListType = { description: string headline: string step: number } export enum ButtonLabelTypes { SAVE = 'save', SAVE_AND_PROCEED = 'saveAndProceed', } type ReleaseProcessProps = { onStartClick: () => void onOverviewButton: () => void stepsLists: StepListType[] headerTitle?: string descHeading?: string descMessage?: string startCreatingButton?: string overviewButton?: string stepHeading?: string dividerText?: string marketplaceHeading?: string requirements?: RequerementStepType[] elementNumbers: number registerButton?: string } export const ReleaseProcess = ({ onStartClick, onOverviewButton, stepsLists, headerTitle, descHeading, descMessage, overviewButton, stepHeading, dividerText, startCreatingButton, marketplaceHeading, requirements, elementNumbers, registerButton, }: ReleaseProcessProps) => { return ( <div className="appoverview-main"> <PageHeader title={headerTitle} topPage={true} headerHeight={200}> <PageBreadcrumb backButtonVariant="contained" /> </PageHeader> <div className="desc-section"> <div className="container"> <Typography variant="h3" className="desc-heading"> {descHeading} </Typography> <Typography variant="body2" className="desc-message"> {descMessage} </Typography> <div> <Button key="create" color="primary" size="small" className="create-btn" onClick={() => { onStartClick() }} > {registerButton} </Button> <Button key="overview" color="secondary" size="small" className="overview-btn" onClick={() => { onOverviewButton() }} > {overviewButton} </Button> </div> </div> </div> <div className="process-steps"> <div className="container"> <div className="steps-main"> <Typography variant="h3" className="step-heading"> {stepHeading} </Typography> <ProcessList elementNumbers={elementNumbers} list={stepsLists} stepsColor="#FFA600" stepsFontColor="#fff" /> <div className="lr-text-divider"> <Typography variant="body2" className="marketplace-title1"> {dividerText} </Typography> </div> <Box textAlign="center"> <Button color="primary" size="small" className="create-btn" onClick={() => { onStartClick() }} > {startCreatingButton} </Button> <Typography variant="h3" className="marketplace-heading"> {marketplaceHeading} </Typography> </Box> <div className="marketplace-requirements"> <ul> {requirements?.map((req: RequerementStepType) => ( <li key={req.index}> <Button color="secondary" size="small" className="neu-btn"> {req.neuButton} </Button> <span> <Typography variant="body2" className="marketplace-title1" > {req.marketplaceTitle} </Typography> <Typography variant="body2" className="marketplace-title1" > {req.marketplaceExplanation} </Typography> </span> </li> ))} </ul> </div> </div> </div> </div> </div> ) }
import { useState } from 'react'; import { useQuery } from '@tanstack/react-query'; import { PRODUCTS_PER_PAGE, SERVER_ERROR } from '@utils/constants'; import logo from '../../assets/sketch_6423309.svg'; import catalogAPI from './api/catalogAPI'; import List from './ui/List'; import Loader from './ui/Loader'; import Pagination from './ui/Pagination'; import Form from './ui/Form'; import styles from './styles.module.scss'; const Catalog = () => { const [error, setError] = useState(''); const [page, setPage] = useState(1); const [price, setPrice] = useState(''); const [brand, setBrand] = useState(''); const [product, setProduct] = useState(''); const isFilterApplied = Boolean(price || brand || product); const { isLoading: isProductIDsLoading, data: productIDs = [] } = useQuery({ queryKey: ['get-product-ids', page], queryFn: () => catalogAPI.getProductIDs( (page - 1) * PRODUCTS_PER_PAGE, PRODUCTS_PER_PAGE ) }); const { isLoading: isAllIDsLoading, data: allIDs = [] } = useQuery({ queryKey: ['get-product-ids'], queryFn: () => catalogAPI.getAllProductIDs() }); const { isLoading: isFilteredProductIDsLoading, data: filteredProductIDs = [] } = useQuery({ queryKey: ['get-filtered-product-ids', price, brand, product], queryFn: () => catalogAPI.getFilteredProductIDs(price, brand, product), enabled: isFilterApplied }); const isLoading = isProductIDsLoading || isFilteredProductIDsLoading || isAllIDsLoading; if (allIDs.isError) { setError(SERVER_ERROR); } if (productIDs.isError) { setError(SERVER_ERROR); } if (filteredProductIDs.isError) { setError(SERVER_ERROR); } const resetFilters = () => { setPage(1); setPrice(''); setBrand(''); setProduct(''); setError(''); }; const totalCount = Math.ceil(allIDs.length / PRODUCTS_PER_PAGE); return ( <> <header className={styles.header}> <a href="https://dannyohdanny.github.io/jewelry-store/"> <img src={logo} className={styles.icon} /> </a> <h1 className={styles.titleShop}>SHOP online</h1> </header> <div className={styles.root}> <Form price={price} brand={brand} product={product} setPrice={setPrice} setBrand={setBrand} setProduct={setProduct} resetFilters={resetFilters} isFilterApplied={isFilterApplied} /> {!isFilterApplied && ( <Pagination page={page} totalCount={totalCount} setPage={setPage} /> )} {isLoading ? ( <Loader /> ) : ( <List productIDs={isFilterApplied ? filteredProductIDs : productIDs} /> )} {error && <p>{error}</p>} </div> </> ); }; export default Catalog;
package _12_java_collection_framework.exercise.e1; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import _12_java_collection_framework.exercise.e1.AppConstant.Sort; public class Test { private static Scanner scanner= new Scanner(System.in); private static ProductService productService= new ProductService(); public static void main(String[] args) { displayMainMenu(); } private static void displayMainMenu(){ System.out.println("1. Create new product\n2. Edit a product\n3. Delete a product\n4. Display list product\n5. Search by name\n6. Sort by price"); int choice= 0; do{ System.out.print(choice==0? "Input your choice: ": "Please input value from 1 to 6: "); choice= Integer.parseInt(scanner.nextLine()); }while (choice<=0 || choice>6); switch (choice){ case 1: create(); break; case 2: edit(); break; case 3: delete(); break; case 4: show(productService.getAll()); break; case 5: search(); break; case 6: sort(); break; } backToMainMenu(); } private static void backToMainMenu(){ System.out.print("Do you back to main menu (Y/N): "); String answer= scanner.nextLine(); if(answer.equalsIgnoreCase("Y")) displayMainMenu(); else System.exit(0); } private static void create(){ inputAndSave(0); System.out.println("Created successful"); } private static void edit(){ productService.getAll().forEach(System.out::println); System.out.print("Please choice product id to edit: "); int id= Integer.parseInt(scanner.nextLine()); inputAndSave(id); System.out.println("Updated successful"); } private static void inputAndSave(int id){ System.out.print("Name: "); String name= scanner.nextLine(); System.out.print("Price: "); double price= Double.parseDouble(scanner.nextLine()); Product product= new Product(id, name, price); productService.save(product); } private static void delete(){ productService.getAll().forEach(System.out::println); System.out.print("Please choice product id to delete: "); int id= Integer.parseInt(scanner.nextLine()); productService.delete(id); System.out.println("Deleted sucessful"); } private static void sort(){ System.out.print("Do you want sort by ASC or DESC? "); String answer= scanner.nextLine(); // Sort sort= Sort.valueOf(answer.toUpperCase()); productService.sortByPrice(answer.equalsIgnoreCase("desc")); show(productService.getAll()); } private static void search(){ System.out.print("Input name to search: "); String name= scanner.nextLine(); show(productService.searchByName(name)); } private static void show(List<Product> products){ if(products.size()>0) products.forEach(System.out::println); else System.out.println("Empty list"); } }
package com.plannerapp.service.impl; import com.plannerapp.model.dto.LoginDTO; import com.plannerapp.model.dto.RegistrationDTO; import com.plannerapp.model.entity.User; import com.plannerapp.repo.UserRepository; import com.plannerapp.service.AuthService; import com.plannerapp.session.LoggedUser; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.BindingResult; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class AuthServiceImpl implements AuthService { private UserRepository userRepository; private ModelMapper modelMapper; private LoggedUser loggedUser; @Autowired public AuthServiceImpl(UserRepository userRepository, ModelMapper modelMapper, LoggedUser loggedUser) { this.userRepository = userRepository; this.modelMapper = modelMapper; this.loggedUser = loggedUser; } public List<String> validateRegister(RegistrationDTO registrationDTO){ Optional<User> findByEmail = this.userRepository.findByEmail(registrationDTO.getEmail()); Optional<User> findByUsername = this.userRepository.findByUsername(registrationDTO.getUsername()); List<String> invalidFields = new ArrayList<>(); if (findByEmail.isPresent()) { invalidFields.add("email"); } if (findByUsername.isPresent()) { invalidFields.add("username"); } if (!registrationDTO.getPassword().equals(registrationDTO.getConfirmPassword())) { invalidFields.add("password"); } return invalidFields; } public void registerInfo(RegistrationDTO registrationDTO){ this.userRepository.save(this.modelMapper.map(registrationDTO,User.class)); } public boolean logIn(LoginDTO loginDTO){ Optional<User>findByUsername = this.userRepository.findByUsername(loginDTO.getUsername()); if(findByUsername.isEmpty()){ return false; } if(!findByUsername.get().getPassword().equals(loginDTO.getPassword())){ return false; } User user = findByUsername.get(); this.loggedUser.logIn(user.getId(), user.getUsername()); return true; } public void logOut(){ this.loggedUser.logOut(); } }
// // ViewController.swift // AssignmentChalkboard // // Created by Angelos Staboulis on 19/1/22. // import UIKit import SwiftUI class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{ @IBOutlet var tableView: UITableView! var viewModel = BirthDayViewModel() var birthdayModelArray:[BirthDayModel]=[] var pages:Int!=0 override func viewDidLoad() { super.viewDidLoad() Loader.shared.loader(view: self.view, delay: 10) initialView() // Do any additional setup after loading the view. } } extension ViewController{ func initialView(){ tableView.delegate = self tableView.dataSource = self tableView.register(UINib(nibName: "MainCell", bundle: nil), forCellReuseIdentifier: "cell") self.navigationItem.title = "Birthday List" loadMore(records: 20) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 280.0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return birthdayModelArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:MainCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MainCell setupCell(cell: cell, indexPath: indexPath) return cell } func setupCell(cell:MainCell,indexPath:IndexPath) { if indexPath.row < self.birthdayModelArray.count{ cell.lblID.text = String(indexPath.row+1) cell.lblTitle.text = self.birthdayModelArray[indexPath.row].title cell.lblLastName.text = self.birthdayModelArray[indexPath.row].last cell.lblFirstName.text = self.birthdayModelArray[indexPath.row].first cell.lblDate.text = self.birthdayModelArray[indexPath.row].date cell.lblAge.text = String(self.birthdayModelArray[indexPath.row].age) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { showDetailPage(indexPath: indexPath) } func loadMore(records:Int){ viewModel.fetchList(records: records) { array in self.birthdayModelArray.removeAll() self.birthdayModelArray.append(contentsOf: array) self.tableView.reloadData() } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == birthdayModelArray.count - 1 { pages = pages + indexPath.row loadMore(records: pages) } } func showDetailPage(indexPath:IndexPath){ let storyboard = UIStoryboard(name: "Main", bundle: nil) let details:DetailPageViewController = storyboard.instantiateViewController(withIdentifier: "details") as! DetailPageViewController details.birthdayModel = birthdayModelArray[indexPath.row] self.navigationController?.pushViewController(details, animated: true) } }
import { NextResponse } from 'next/server'; import { auth } from '@clerk/nextjs'; import prismadb from '@/lib/prismadb'; export async function GET(request: Request, { params }: { params: { sizeId: string } }) { try { if(!params.sizeId) return NextResponse.json({ message: 'Size ID is required' }) const size = await prismadb.size.findUnique({ where: { id: params.sizeId } }) return NextResponse.json(size) } catch (error) { console.log('ERROR_GET_SIZE') return NextResponse.json({ message: 'Something went wrong' }, { status: 500 }) } } export async function PATCH(request: Request, { params }: { params: { sizeId: string, storeId: string } }) { try { const { userId } = auth() const body = await request.json() const { name, value } = body if(!userId) return NextResponse.json({ message: 'Unauthenticated' }, { status: 401 }) if(!name) return NextResponse.json({ message: 'Name is required' }, { status: 400 }) if(!value) return NextResponse.json({ message: 'Value is required' }, { status: 400 }) if(!params.sizeId) return NextResponse.json({ message: 'Size ID is required' }, { status: 400 }) const storeByUserId = await prismadb.store.findFirst({ where: { id: params.storeId, userId } }) if(!storeByUserId) return NextResponse.json({ message: 'Unauthorized' }, { status: 403 }) const size = await prismadb.size.update({ where: { id: params.sizeId }, data: { name, value } }) return NextResponse.json(size) } catch (error) { console.log('ERROR_UPDATING_SIZE', error) return NextResponse.json({ message: 'Something went wrong' }, { status: 500 }) } } export async function DELETE(request: Request, { params }: { params: { sizeId: string, storeId: string } }) { try { const { userId } = auth() if(!userId) return NextResponse.json({ message: 'Unauthenticated' }, { status: 401 }) if(!params.sizeId) return NextResponse.json({ message: 'Size ID is required' }, { status: 400 }) const storeByUserId = await prismadb.store.findFirst({ where: { id: params.storeId, userId } }) if(!storeByUserId) return NextResponse.json({ message: 'Unauthorized' }, { status: 403 }) const size = await prismadb.size.delete({ where: { id: params.sizeId }, }) return NextResponse.json(size) } catch (error) { console.log('ERROR_DELETING_SIZE', error) return NextResponse.json({ message: 'Something went wrong' }, { status: 500 }) } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author Dario */ //clase Rectangulo, hereda de Poligono public class Rectangulo extends Poligono{ int ladoA, ladoB; //Constructor public Rectangulo(int ladoA, int ladoB) { //Invocamos el constructor del padre (Clase Poligono) super(4); this.ladoA = ladoA; this.ladoB = ladoB; } // Funciones get y set para ladoA y ladoB public int getLadoA() { return ladoA; } public void setLadoA(int ladoA) { this.ladoA = ladoA; } public int getLadoB() { return ladoB; } public void setLadoB(int ladoB) { this.ladoB = ladoB; } //Metodo para obtener el Area @Override public float getArea() { return ladoA*ladoB; } //Metodo para obtener el perimetro @Override public float getPerimetro() { return (2*ladoA)+(2*ladoB); } }
import numpy as np import torch def get_calib_from_file(calib_file): with open(calib_file) as f: lines = f.readlines() obj = lines[2].strip().split(' ')[1:] P2 = np.array(obj, dtype=np.float32) obj = lines[3].strip().split(' ')[1:] P3 = np.array(obj, dtype=np.float32) obj = lines[4].strip().split(' ')[1:] R0 = np.array(obj, dtype=np.float32) obj = lines[5].strip().split(' ')[1:] Tr_velo_to_cam = np.array(obj, dtype=np.float32) return {'P2': P2.reshape(3, 4), 'P3': P3.reshape(3, 4), 'R0': R0.reshape(3, 3), 'Tr_velo2cam': Tr_velo_to_cam.reshape(3, 4)} class Calibration(object): def __init__(self, calib_file, is_cuda=False): if not isinstance(calib_file, dict): calib = get_calib_from_file(calib_file) else: calib = calib_file self.device = torch.device("cuda:0") if is_cuda else torch.device("cpu:0") if not is_cuda: self.P2 = calib['P2'] # 3 x 4 self.P3 = calib['P3'] # 3 x 4 self.R0 = calib['R0'] # 3 x 3 self.V2C = calib['Tr_velo2cam'] # 3 x 4 else: self.P2 = torch.from_numpy(calib['P2']).to(self.device) self.P3 = torch.from_numpy(calib['P3']).to(self.device) self.R0 = torch.from_numpy(calib['R0']).to(self.device) self.V2C = torch.from_numpy(calib['Tr_velo2cam']).to(self.device) # Camera intrinsics and extrinsics self.cu = self.P2[0, 2] self.cv = self.P2[1, 2] self.fu = self.P2[0, 0] self.fv = self.P2[1, 1] self.tx = self.P2[0, 3] / (-self.fu) self.ty = self.P2[1, 3] / (-self.fv) def cart_to_hom(self, pts): """ :param pts: (N, 3 or 2) :return pts_hom: (N, 4 or 3) """ if isinstance(pts, np.ndarray): pts_hom = np.hstack((pts, np.ones((pts.shape[0], 1), dtype=np.float32))) else: pts_hom = torch.hstack((pts, torch.ones((pts.shape[0], 1), device=self.device))) return pts_hom def rect_to_lidar(self, pts_rect): """ :param pts_lidar: (N, 3) :return pts_rect: (N, 3) """ pts_rect_hom = self.cart_to_hom(pts_rect) # (N, 4) if isinstance(pts_rect_hom, np.ndarray): R0_ext = np.hstack((self.R0, np.zeros((3, 1), dtype=np.float32))) # (3, 4) R0_ext = np.vstack((R0_ext, np.zeros((1, 4), dtype=np.float32))) # (4, 4) R0_ext[3, 3] = 1 V2C_ext = np.vstack((self.V2C, np.zeros((1, 4), dtype=np.float32))) # (4, 4) V2C_ext[3, 3] = 1 pts_lidar = np.dot(pts_rect_hom, np.linalg.inv(np.dot(R0_ext, V2C_ext).T)) else: R0_ext = torch.hstack((self.R0, torch.zeros((3, 1), device=self.device))) R0_ext = torch.vstack((R0_ext, torch.zeros((1, 4), device=self.device))) R0_ext[3, 3] = 1 V2C_ext = torch.vstack((self.V2C, torch.zeros((1, 4), device=self.device))) V2C_ext[3, 3] = 1 pts_lidar = torch.mm(pts_rect_hom, torch.linalg.inv(torch.mm(R0_ext, V2C_ext).t())) return pts_lidar[:, 0:3] def lidar_to_rect(self, pts_lidar): """ :param pts_lidar: (N, 3) :return pts_rect: (N, 3) """ pts_lidar_hom = self.cart_to_hom(pts_lidar) pts_rect = np.dot(pts_lidar_hom, np.dot(self.V2C.T, self.R0.T)) # pts_rect = reduce(np.dot, (pts_lidar_hom, self.V2C.T, self.R0.T)) return pts_rect def rect_to_img(self, pts_rect): """ :param pts_rect: (N, 3) :return pts_img: (N, 2) """ pts_rect_hom = self.cart_to_hom(pts_rect) pts_2d_hom = np.dot(pts_rect_hom, self.P2.T) pts_img = (pts_2d_hom[:, 0:2].T / pts_rect_hom[:, 2]).T # (N, 2) pts_rect_depth = pts_2d_hom[:, 2] - self.P2.T[3, 2] # depth in rect camera coord return pts_img, pts_rect_depth def lidar_to_img(self, pts_lidar): """ :param pts_lidar: (N, 3) :return pts_img: (N, 2) """ pts_rect = self.lidar_to_rect(pts_lidar) pts_img, pts_depth = self.rect_to_img(pts_rect) return pts_img, pts_depth def img_to_rect(self, u, v, depth_rect): """ :param u: (N) :param v: (N) :param depth_rect: (N) :return: """ x = ((u - self.cu) * depth_rect) / self.fu + self.tx y = ((v - self.cv) * depth_rect) / self.fv + self.ty if isinstance(depth_rect, np.ndarray): pts_rect = np.concatenate((x.reshape(-1, 1), y.reshape(-1, 1), depth_rect.reshape(-1, 1)), axis=1) else: pts_rect = torch.cat((x.reshape(-1, 1), y.reshape(-1, 1), depth_rect.reshape(-1, 1)), dim=1) return pts_rect def corners3d_to_img_boxes(self, corners3d): """ :param corners3d: (N, 8, 3) corners in rect coordinate :return: boxes: (None, 4) [x1, y1, x2, y2] in rgb coordinate :return: boxes_corner: (None, 8) [xi, yi] in rgb coordinate """ sample_num = corners3d.shape[0] corners3d_hom = np.concatenate((corners3d, np.ones((sample_num, 8, 1))), axis=2) # (N, 8, 4) img_pts = np.matmul(corners3d_hom, self.P2.T) # (N, 8, 3) x, y = img_pts[:, :, 0] / img_pts[:, :, 2], img_pts[:, :, 1] / img_pts[:, :, 2] x1, y1 = np.min(x, axis=1), np.min(y, axis=1) x2, y2 = np.max(x, axis=1), np.max(y, axis=1) boxes = np.concatenate((x1.reshape(-1, 1), y1.reshape(-1, 1), x2.reshape(-1, 1), y2.reshape(-1, 1)), axis=1) boxes_corner = np.concatenate((x.reshape(-1, 8, 1), y.reshape(-1, 8, 1)), axis=2) return boxes, boxes_corner if __name__ == '__main__': calib = Calibration('../kitti/calib/000008.txt')
import { ModalsService } from './../../shared/services/modals.service'; import { switchMap } from 'rxjs/operators'; import { AtaService } from './../../shared/services/ata.service'; import { ProfileService } from './../../shared/services/profile.service'; import { ActivatedRoute } from '@angular/router'; import { OnInit, Component } from '@angular/core'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; import { Ata } from 'src/app/shared/models/Ata.model'; import { Page } from 'src/app/shared/models/Page.model'; @Component({ templateUrl: './atas.component.html', styleUrls: ['./atas.component.scss'], }) export class AtasComponent implements OnInit { atasFormGroup: FormGroup; constructor( private formBuilder: FormBuilder, private activedRoute: ActivatedRoute, private profileService: ProfileService, private ataService: AtaService, private modalService: ModalsService ) {} atas: Ata[] = this.activedRoute.snapshot.data.atas; selectedAta: Ata; currentProfile = this.profileService.profile(); ngOnInit(): void { this.atasFormGroup = this.formBuilder.group({ title: [null, [Validators.required, Validators.maxLength(50)]], subject: [null, [Validators.required]], text: [null, [Validators.required]], }); } send() { const { id } = this.selectedAta; const ata: Ata = { ...this.atasFormGroup.value, requisicao: id }; this.ataService .salvarAta(ata) .pipe(switchMap(() => this.ataService.recuperarTodos())) .subscribe((atas) => { this.atas = atas; this.modalService.showMessage( 'Sucesso', 'Resposta enviada com sucesso!' ); }); } }
################################################################################################# ## Process the HAND rasters from GEE to match MODIS and Landsat ################################################################################################## library(raster) library(rgdal) library(gdalUtils) # base directory home <- "G:/My Drive/Chapter1_ET_Project/Data" source(paste0(home, "/Processing_scripts/helpers.R")) # HAND input fin <- paste0(home, "/Topography/HeightAboveNearestDrainage/hand30_100.tif") roi <- paste0(home, "/NA_CEC_Eco_Level3/blue_ridge.shp") roi_mask <- readOGR( paste0(home, "/NA_CEC_Eco_Level3/blue_ridge.shp")) # resample to match MODIS and mask to the ROI modis_template <- raster(paste0(home, "/MODIS_ET/clean/et_20000101.tif")) fout <- paste0(home,"/Topography/HeightAboveNearestDrainage/hand_modis.tif" ) warpMn(fin, modis_template, fout, 'bilinear') r <- raster(fout) r <- mask(r, roi_mask) writeRaster(r, fout, overwrite = T) # resample to match Landsat and mask to the ROI landsat_template <- raster(paste0(home, "/Landsat_ET/landsat_template/landsat_template_ROI.tif")) fout <- paste0(home,"/Topography/HeightAboveNearestDrainage/hand_landsat.tif" ) warpMn(fin, landsat_template, fout,'bilinear') r <- raster(fout) r <- mask(r, roi_mask) writeRaster(r, fout, overwrite = T)
--- import Layout from "src/layouts/Layout.astro"; import { Image } from "@astrojs/image/components"; import { getAllArticleSlugs, getArticleBySlug } from "src/utils/api/articles"; import formatDate from "src/utils/formatDate"; export async function getStaticPaths() { const blogSlugs = await getAllArticleSlugs(); return blogSlugs.map(({ slug }) => { return { params: { slug: slug, }, }; }); } const { slug } = Astro.params; const blog = await getArticleBySlug(slug); --- <Layout seo={{ title: `${blog.title} | 100 Million US`, description: blog.summary }} > <section class="bg-black px-edge py-10"> <div class="max-w-screen-lg mx-auto"> <div class="w-full relative pb-[40%]"> <Image class="absolute inset-0 w-full h-full object-cover" src={blog.featuredImage.node.sourceUrl} alt={blog.featuredImage.node.altText} format="jpeg" width={blog.featuredImage.node.mediaDetails.width} height={blog.featuredImage.node.mediaDetails.height} /> </div> <div class="mt-20 text-text-light"> <p class="font-bold text-xl text-primary">{formatDate(blog.date)}</p> <p class="mt-2">Written by: {blog.writer}</p> <h1 class="font-bebas text-6xl">{blog.title}</h1> <article class="prose prose-img:mx-auto prose-invert max-w-none" set:html={blog.body} /> </div> </div> </section> </Layout>
<template> <MyForm :model="formState" name="basic" autocomplete="off" ref="firAndSecRef" labelAlign="left"> <Row :gutter="24"> <Col :span="12"> <FormItem label="甲方" :labelCol="{ span: 6 }" name="partyAName" labelAlign="left"> <Input v-model:value="formState.partyAName" placeholder="请输入姓名" disabled /> </FormItem> </Col> <Col :span="12"> <FormItem label="乙方" name="partyBName" labelAlign="left" :labelCol="{ span: 6 }" :rules="[{ required: true, message: '请选择乙方' }]" > <Select v-model:value="formState.partyBName" showSearch label-in-value placeholder="请选择" style="width: 100%" :filter-option="false" :not-found-content="fetching ? undefined : null" :options="data" allowClear :maxlength="10" @search="onSearch" @select="selectCompany" :disabled="isEdit" > <template v-if="fetching" #notFoundContent> <Spin size="small" /> </template> </Select> </FormItem> </Col> </Row> <Row :gutter="24"> <Col :span="12"> <FormItem label="电话" name="partyAPhone" :labelCol="{ span: 6 }" :rules="[{ required: true, validator: validatorPhoneNum1 }]" > <Input v-model:value="formState.partyAPhone" placeholder="请输入电话" :maxlength="12" /> </FormItem> </Col> <Col :span="12"> <FormItem label="电话" name="partyBPhone" :labelCol="{ span: 6 }" :rules="[{ required: true, validator: validatorPhoneNum1 }]" > <Input v-model:value="formState.partyBPhone" placeholder="请输入电话" :maxlength="12" /> </FormItem> </Col> </Row> <Row :gutter="24"> <Col :span="12"> <FormItem label="省市" name="partyAAreaInfo" :labelCol="{ span: 6 }" :rules="[{ required: true, message: '请选择省市区' }]" > <Cascader :field-names="{ label: 'name', value: 'code' }" v-model:value="formState.partyAAreaInfo" :options="areas" @change="selectAAdress" placeholder="请选择省市区" /> </FormItem> </Col> <Col :span="12"> <FormItem label="省市" name="partyBAreaInfo" :labelCol="{ span: 6 }" :rules="[{ required: true, message: '请选择省市区' }]" > <Cascader :field-names="{ label: 'name', value: 'code' }" v-model:value="formState.partyBAreaInfo" :options="areas" @change="selectBAdress" placeholder="请选择省市区" /> </FormItem> </Col> </Row> <Row :gutter="24"> <Col :span="12"> <FormItem label="详细地址" name="partyAAddress" :labelCol="{ span: 6 }" :rules="[{ required: true, message: '请输入详细地址' }]" > <Input v-model:value="formState.partyAAddress" placeholder="请输入详细地址" :maxlength="11" /> </FormItem> </Col> <Col :span="12"> <FormItem label="详细地址" name="partyBAddress" :labelCol="{ span: 6 }" :rules="[{ required: true, message: '请输入详细地址' }]" > <Input v-model:value="formState.partyBAddress" placeholder="请输入详细地址" :maxlength="11" /> </FormItem> </Col> </Row> <Row :gutter="24"> <Col :span="12"> <FormItem label="经办人" name="partyAContact" :labelCol="{ span: 6 }" :rules="[{ required: true, message: '请输入经办人' }]" > <Input v-model:value="formState.partyAContact" placeholder="请输入经办人" :maxlength="100" /> </FormItem> </Col> <Col :span="12"> <FormItem label="经办人" name="partyBContact" :labelCol="{ span: 6 }" :rules="[{ required: true, message: '请输入经办人' }]" > <Input v-model:value="formState.partyBContact" placeholder="请输入经办人" :maxlength="100" /> </FormItem> </Col> </Row> <Row :gutter="24"> <Col :span="12"> <FormItem label="手机号" name="partyAMobile" :labelCol="{ span: 6 }" :rules="[{ required: true, validator: validatorPhoneNum }]" > <Input v-model:value="formState.partyAMobile" placeholder="请输入手机号" :maxlength="11" /> </FormItem> </Col> <Col :span="12"> <FormItem label="手机号" name="partyBMobile" :labelCol="{ span: 6 }" :rules="[{ required: true, validator: validatorPhoneNum }]" > <Input v-model:value="formState.partyBMobile" placeholder="请输入手机号" :maxlength="11" /> </FormItem> </Col> </Row> </MyForm> </template> <script lang="ts"> import { defineComponent, ref, reactive, onMounted, toRefs, watch } from 'vue'; import type { Dayjs } from 'dayjs'; import { Card, Form, FormItem, Row, Col, Select, DatePicker, Cascader, Input, RangePicker, Spin, } from 'ant-design-vue'; import { getBusinessInfoApi, findBusinessApi } from '/@/api/contractManage/contractManage'; import { getAreaApi } from '/@/api/common/dicts'; import { useRoute } from 'vue-router'; import { useUserStore } from '/@/store/modules/user'; import { debounce } from 'lodash-es'; import { validatorIdCard, validatorUploadImg, validatorChineseWord, validatorNumberAndEng, validatorUploadImgOnlyPng, validatorPhoneNum, validatorPhoneNum1, } from '/@/utils/validtor'; export default defineComponent({ name: 'FirAndSec', components: { [Card.name]: Card, MyForm: Form, FormItem, Row, Col, Select, Cascader, Input, Spin, }, props: { contractInfo: { default: () => {}, type: Object, }, }, emits: ['changeRegisterArea'], setup(props) { let formState = ref({ partyAName: '', partyBName: undefined, partyAMobile: '', partyBMobile: '', partyAAddress: '', partyBAddress: '', partyAContact: '', partyBContact: '', partyAPhone: '', partyBPhone: '', partyAProvince: '', partyACity: '', partyAArea: '', partyBProvince: '', partyBCity: '', partyBArea: '', partyAAreaInfo: [], partyBAreaInfo: [], }); const userStore = useUserStore(); const firAndSecRef = ref(); let route = useRoute(); let areas = ref(); let isEdit = ref(false); onMounted(async () => { let companyId = userStore.userInfo.companyId; let firCompanyInfo = await getBusinessInfoApi(companyId); initFormState(firCompanyInfo, 'A'); // 获取省市区 areas.value = (await getAreaApi())[0].children; if (route.query?.edit) { isEdit.value = true; } }); watch( () => props.contractInfo, () => { console.log(19993333, props.contractInfo.value); // formState.value.contractName = props.contractInfo.value?.contractInfo?.contractName; formState.value = { partyAName: props.contractInfo.value?.contractInfo?.partyAName, partyBName: props.contractInfo.value?.contractInfo?.partyBName, partyAMobile: props.contractInfo.value?.contractInfo?.partyAMobile, partyBMobile: props.contractInfo.value?.contractInfo?.partyBMobile, partyAAddress: props.contractInfo.value?.contractInfo?.partyAAddress, partyBAddress: props.contractInfo.value?.contractInfo?.partyBAddress, partyAContact: props.contractInfo.value?.contractInfo?.partyAContact, partyBContact: props.contractInfo.value?.contractInfo?.partyBContact, partyAPhone: props.contractInfo.value?.contractInfo?.partyAPhone, partyBPhone: props.contractInfo.value?.contractInfo?.partyBPhone, partyAProvince: props.contractInfo.value?.contractInfo?.partyAProvince, partyACity: props.contractInfo.value?.contractInfo?.partyACity, partyAArea: props.contractInfo.value?.contractInfo?.partyAArea, partyBProvince: props.contractInfo.value?.contractInfo?.partyBProvince, partyBCity: props.contractInfo.value?.contractInfo?.partyBCity, partyBArea: props.contractInfo.value?.contractInfo?.partyBArea, partyAAreaInfo: [ props.contractInfo.value?.contractInfo?.partyAProvince, props.contractInfo.value?.contractInfo?.partyACity, props.contractInfo.value?.contractInfo?.partyAArea, ], partyBAreaInfo: [ props.contractInfo.value?.contractInfo?.partyBProvince, props.contractInfo.value?.contractInfo?.partyBCity, props.contractInfo.value?.contractInfo?.partyBArea, ], }; }, { deep: true, }, ); const initFormState = ( { companyInfo, companyInvoiceInfo, companyLegalInfo }, companyName, ) => { formState.value[`party${companyName}Name`] = companyInfo.name; formState.value[`party${companyName}Phone`] = companyInfo.phone; formState.value[`party${companyName}Area`] = companyInfo.area; formState.value[`party${companyName}Province`] = companyInfo.province; formState.value[`party${companyName}City`] = companyInfo.city; formState.value[`party${companyName}Area`] = companyInfo.area; formState.value[`party${companyName}Address`] = companyInfo.detailedAddress; formState.value[`party${companyName}Contact`] = companyInfo.linkman; formState.value[`party${companyName}Mobile`] = companyInfo.phone; if (companyName == 'A') { if (companyInfo.province != '') { formState.value.partyAAreaInfo = [ companyInfo.province, companyInfo.city, companyInfo.area, ]; } } if (companyName == 'B') { if (companyInfo.province != '') { formState.value.partyBAreaInfo = [ companyInfo.province, companyInfo.city, companyInfo.area, ]; } } }; const searchData = reactive({ data: [], value: [], fetching: false, }); const onSearch = debounce(async (value) => { searchData.data = []; searchData.fetching = true; if (value != '') { let data = await findBusinessApi(value); searchData.data = data.map((ele) => { return { value: ele.id, label: ele.name }; }); searchData.fetching = false; } }, 500); const selectCompany = async (val) => { console.log(18888, val); let secCompanyInfo = await getBusinessInfoApi(val.key); initFormState(secCompanyInfo, 'B'); }; const selectAAdress = (val, selectedOptions) => { console.log(111, selectedOptions); formState.value.partyAProvince = selectedOptions[0].code; formState.value.partyACity = selectedOptions[1].code; formState.value.partyAArea = selectedOptions[2].code; }; const selectBAdress = (val, selectedOptions) => { console.log(111, selectedOptions); formState.value.partyBProvince = selectedOptions[0].code; formState.value.partyBCity = selectedOptions[1].code; formState.value.partyBArea = selectedOptions[2].code; }; return { formState, validatorIdCard, validatorUploadImg, validatorChineseWord, validatorNumberAndEng, validatorUploadImgOnlyPng, validatorPhoneNum, validatorPhoneNum1, firAndSecRef, onSearch, ...toRefs(searchData), selectCompany, areas, selectAAdress, selectBAdress, isEdit, }; }, }); </script> <style scoped></style>
// // Population.swift // FlowKit // // Created by Xiaodi Wu on 7/9/16. // Copyright © 2016 Xiaodi Wu. All rights reserved. // import Foundation import Accelerate /** A subset population of a `Sample`. */ public final class Population { /// The sample of which the population is a subset. public let root: Sample /** The mask that determines which of the sample's events are included (1) or excluded (0) from the subset population. If `mask == nil`, then all events are included in the population. */ public let mask: [Float]? /// The number of events included in the population. public let count: Int /** Initialize a new `Population` with the given sample and mask. - Precondition: If `mask != nil`, then `root.count` must equal `mask.count`. - Parameter root: The sample of which the population is to be a subset. - Parameter mask: The mask that determines which of the sample's events are to be included (1) or excluded (0) from the population subset. */ public init(_ root: Sample, mask: [Float]? = nil) { if let mask = mask { precondition(root.count == mask.count) } self.root = root self.mask = mask if let mask = mask { count = Int(cblas_sasum(Int32(mask.count), mask, 1)) } else { count = root.count } } /** Initialize a new `Population` with the given parent population and mask. - Precondition: If `mask != nil`, then `parent.root.count` (the number of events in the root sample) must equal `mask.count`. - Parameter parent: The parent population of which the population is to be a subset. - Parameter mask: The mask that is to be multiplied with the parent population mask to determine which of the sample's events are to be included (1) or excluded (0) from the population subset. */ public init(_ parent: Population, mask: [Float]? = nil) { if let mask = mask { precondition(parent.root.count == mask.count) } self.root = parent.root if var mask = mask { if let pm = parent.mask { // Compute `mask & pm` vDSP_vmul(mask, 1, pm, 1, &mask, 1, UInt(mask.count)) } self.mask = mask count = Int(cblas_sasum(Int32(mask.count), mask, 1)) } else { self.mask = parent.mask ?? nil count = parent.count } } }
// let abFilter = 25; const width = window.innerWidth; const height = window.innerHeight; let pieLeft = 800, pieTop = 700; let pieMargin = { top: 10, right: 30, bottom: 30, left: 60 }, pieWidth = 350, pieHeight = 350, pieRadius = Math.min(pieWidth, pieHeight)/2; let scatterLeft = 0, scatterTop = 550; let scatterMargin = { top: 10, right: 30, bottom: 30, left: 60 }, scatterWidth = 500 - scatterMargin.left - scatterMargin.right, scatterHeight = 350 - scatterMargin.top - scatterMargin.bottom; let barLeft = 100, barTop = 30; let barMargin = { top: 10, right: 30, bottom: 30, left: 60 }, barWidth = 500, barHeight = height - 500 - barMargin.top - barMargin.bottom; let dendrogramLeft = 0, dendrogramTop = 0; let dendroMargin = { top: 300, right: 600, bottom: -250, left: 700 }, dendrogramWidth = width - 100, dendrogramHeight = height - dendroMargin.bottom - dendroMargin.top; //loading the data d3.csv("pokemon.csv").then(rawData => { console.log("rawData", rawData); rawData.forEach(function (d) { d.Total = Number(d.Total); d.Attack = Number(d.Attack); d.Defense = Number(d.Defense); d.Height_m = Number(d.Height_m); d.Weight_kg = Number(d.Weight_kg); }); rawData = rawData.filter(d => d.Total > abFilter); rawData = rawData.map(d => { return { "Attack": d.Attack, "Defense": d.Defense, "Weight": d.Weight_kg, "Height": d.Height_m, "Type_1": d.Type_1, "Color": d.Color, "Name": d.Name, }; }); // Plot 1 const svg = d3.select("svg"); const g1 = svg.append("g") .attr("width", scatterWidth + scatterMargin.left + scatterMargin.right) .attr("height", scatterHeight + scatterMargin.top + scatterMargin.bottom) .attr("transform", `translate(${scatterMargin.left}, ${scatterTop})`); // X label g1.append("text") .attr("x", scatterWidth / 2) .attr("y", scatterHeight + 50) .attr("font-size", "20px") .attr("text-anchor", "middle") .text("Weight (kg)"); // Y label g1.append("text") .attr("x", -(scatterHeight / 2)) .attr("y", -40) .attr("font-size", "20px") .attr("text-anchor", "middle") .attr("transform", "rotate(-90)") .text("Height (m)"); // X ticks const x1 = d3.scaleLinear() .domain([0, d3.max(rawData, d => d.Weight)]) .range([0, scatterWidth]); const xAxisCall = d3.axisBottom(x1) .ticks(7); g1.append("g") .attr("transform", `translate(0, ${scatterHeight})`) .call(xAxisCall) .selectAll("text") .attr("y", "10") .attr("x", "-5") .attr("text-anchor", "end") .attr("transform", "rotate(-40)"); g1.append("text") .attr("x", scatterWidth / 2) .attr("y", -20) .attr("text-anchor", "middle") .style("font-size", "24px") .text("Height vs Weight of Pokemon"); // Y ticks const y1 = d3.scaleLinear() .domain([0, d3.max(rawData, d => d.Height)]) .range([scatterHeight, 0]); const yAxisCall = d3.axisLeft(y1) .ticks(13); g1.append("g").call(yAxisCall); const dots = g1.selectAll("circle").data(rawData); dots.enter().append("circle") .attr("cx", function (d) { return x1(d.Weight); }) .attr("cy", function (d) { return y1(d.Height); }) .attr("r", 2.5) .attr("fill", "#5A5AE2"); // Plot 2 Bar Chart const typeCounts = rawData.reduce((s, { Type_1 }) => (s[Type_1] = (s[Type_1] || 0) + 1, s), {}); const typeData = Object.keys(typeCounts).map((key) => ({ Type_1: key, count: typeCounts[key] })); console.log(typeData); const g3 = svg.append("g") .attr("width", barWidth + barMargin.left + barMargin.right) .attr("height", barHeight + barMargin.top + barMargin.bottom) .attr("transform", `translate(${barLeft}, ${barTop})`); // X label g3.append("text") .attr("x", barWidth / 2) .attr("y", barHeight + 50) .attr("font-size", "20px") .attr("text-anchor", "middle") .text("Number of Pokemon"); // Y label g3.append("text") .attr("x", -(barHeight / 2)) .attr("y", -60) .attr("font-size", "20px") .attr("text-anchor", "middle") .attr("transform", "rotate(-90)") .text("Types of Pokémon"); //title g3.append("text") .attr("x", barLeft + barWidth / 2 - 70) .attr("y", barTop - 35) .attr("font-size", "24px") .attr("text-anchor", "middle") .text("Number of Pokemon by Type"); // Y ticks const y2 = d3.scaleBand() .domain(typeData.map(d => d.Type_1)) .range([0, barHeight]) .paddingInner(0.1) .paddingOuter(0.2); const yAxisCall2 = d3.axisLeft(y2); g3.append("g") .call(yAxisCall2) .selectAll("text") .attr("x", "-5") .attr("text-anchor", "end"); // X ticks const x2 = d3.scaleLinear() .domain([0, d3.max(typeData, d => d.count)]) .range([0, barWidth]); const xAxisCall2 = d3.axisBottom(x2) .ticks(6); g3.append("g") .attr("transform", `translate(0, ${barHeight})`) .call(xAxisCall2); const bars = g3.selectAll("rect").data(typeData); //inserting bars bars.enter().append("rect") .attr("y", d => y2(d.Type_1)) .attr("x", 0) .attr("height", y2.bandwidth()) .attr("width", d => x2(d.count)) .attr("fill", "lightblue"); //pieChart plot 3 const colorCounts = rawData.reduce((s, { Color }) => (s[Color] = (s[Color] || 0) + 1, s), {}); const colorData = Object.keys(colorCounts).map((key) => ({ color: key, count: colorCounts[key] })); console.log(colorData); const pieSvg = d3.select("#pieChartContainer").append("svg") .attr("width", pieWidth*4) .attr("height", pieHeight*4) .append("g") .attr("transform", `translate(${pieLeft},${pieTop})`); // Create a pie chart const pie = d3.pie().value(d => d.count); // Define an arc for the pie chart const arc = d3.arc() .innerRadius(0) .outerRadius(pieRadius); // Create pie chart segments const arcs = pieSvg.selectAll("arc") .data(pie(colorData)) .enter() .append("g"); // Fill the pie chart with color arcs.append("path") .attr("d", arc) .attr("fill", d => d.data.color) .attr("stroke", "black") .style("stroke-width", "3px") .style("opacity", 0.7); // Add labels for each color segment arcs.append("text") .attr("transform", d => { const [x, y] = arc.centroid(d); const angle = Math.atan2(y, x); const radius = pieRadius * 1.24; const xPos = Math.cos(angle) * radius; const yPos = Math.sin(angle) * radius; return `translate(${xPos},${yPos})`; }) .attr("text-anchor", "middle") .attr("fill", "black") .attr("font-size", 15) .text(d => { const percentage = (d.data.count / d3.sum(colorData, d => d.count) * 100).toFixed(1); return `${d.data.color}: ${percentage}%`; }); //pie chart title pieSvg.append("text") .attr("x", 0) .attr("y", -pieRadius * 1.5) .attr("text-anchor", "middle") .style("font-size", "24px") .text("Pokemon Color Percentage"); //dendrogram plot 4 dendroSvg = svg.append("g") .attr("width", dendrogramWidth * 5) .attr("height", dendrogramHeight * 5) .attr("transform", `translate(${width - 900}, ${height - 800})`); //parsed data for Dendrogram const dendroData = { name: "Pokemon", children: [ {name: "Grass", children:[ {name: "Venusaur", children: [{name: "Ivysaur", children: [{name: "Bulbasaur"}]}]}, {name: "Vileplume", children: [{name: "Gloom", children: [{name: "Oddish"}]}]}, ] }, {name: "Water", children:[ {name: "Blastoise", children: [{name: "Wartortle", children: [{name: "Squirtle"}]}]}, {name: "Poliwrath", children: [{name: "Polywhirl", children: [{name: "Poliwag"}]}]}, ] }, {name: "Bug", children:[ {name: "Butterfree", children: [{name: "Metapod", children: [{name: "Caterpie"}]}]}, {name: "Beedrill", children: [{name: "Kakuna", children: [{name: "Weedle"}]}]}, ] }, {name: "Fire", children:[ {name: "Charizard", children: [{name: "Charmeleon", children: [{name: "Charmander"}]}]}, {name: "Typhlosion", children: [{name: "Quilava", children: [{name: "Cynaquil"}]}]}, ] }, {name: "Electric", children:[ {name: "Raichu", children: [{name: "Pikachu"}]}, {name: "Magnemite", children: [{name: "Magneton"}]}, ] }, ] }; //creating the tree cluster = d3.cluster().size([dendrogramHeight - 200, dendrogramWidth - 1500]); //adding the root root = d3.hierarchy(dendroData, function(d) { return d.children; }); cluster(root); //creating the lines or paths for each node dendroSvg.selectAll('path') .data(root.descendants().slice(1)) .enter() .append('path') .attr("d", function(d){ return "M" + d.x + "," + d.y + "C" + (d.parent.x + (d.x - d.parent.x)) + "," + d.y + " " + (d.parent.x + (d.x - d.parent.x)) + "," + d.parent.y + " " + d.parent.x + "," + d.parent.y; }) .style("fill", 'none') .attr("stroke", '#007eff') .attr("stroke-size", "2px"); //creating the circles for each node dendroSvg.selectAll("g.node") .data(root.descendants()) .enter() .append("g") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) .append("circle") .attr("r", 5) .style("fill", "#69b3a2") .attr("stroke", "black") .style("stroke-width", 2); //labels for each node dendroSvg.selectAll("g.node") .data(root.descendants()) .enter() .append("text") .attr("x", function(d) { return d.x;}) .attr("y", function(d) { return d.y - 20; }) .text(function(d) { return d.data.name; }) .attr("text-anchor", "middle") .attr("font-size", "15px") .attr("fill", "black"); //title for dendrogram svg.append("text") .attr("x", (dendrogramWidth / 2) + 455) .attr("y", dendrogramHeight - 800) .attr("font-size", "24px") .attr("text-anchor", "middle") .text("Evolution of Pokemon"); }).catch(function (error) { console.log(error); });
package com.example.testeapp.presentation.viewmodels import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.testeapp.domain.entities.TrainingPresentation import com.example.testeapp.domain.usecases.TrainingUseCase import com.example.testeapp.utils.TAG import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import javax.inject.Inject sealed class TrainingUiState { object Loading : TrainingUiState() data class Success(val trainings: List<TrainingPresentation>) : TrainingUiState() data class Error(val message: String) : TrainingUiState() } @HiltViewModel class TrainingViewModel @Inject constructor( private val useCase: TrainingUseCase ) : ViewModel() { private val _uiState = MutableStateFlow<TrainingUiState>(TrainingUiState.Loading) val uiState = _uiState fun getTrainings() = viewModelScope.launch { _uiState.value = TrainingUiState.Loading try { useCase.getTrainings().collect { trainings -> _uiState.value = TrainingUiState.Success(trainings) } } catch (e: Exception) { _uiState.value = TrainingUiState.Error(e.message.toString()) } } init { getTrainings() } fun getTrainingById(id: String, callback: (TrainingPresentation) -> Unit) { viewModelScope.launch { try { val training = useCase.getTrainingById(id) callback(training) } catch (e: Exception) { Log.e(TAG, e.message.toString()) } } } fun deleteTraining(id: String) { _uiState.value = TrainingUiState.Loading viewModelScope.launch { try { useCase.deleteTraining(id) _uiState.value = TrainingUiState.Success(useCase.getTrainings().first()) } catch (e: Exception) { _uiState.value = TrainingUiState.Error(e.message.toString()) } } } }
#pragma once #ifndef LAB471_PROGRAM_H_INCLUDED #define LAB471_PROGRAM_H_INCLUDED #include <map> #include <string> #include <glad/glad.h> std::string readFileAsString(const std::string &fileName); class Program { public: void setVerbose(const bool v) { verbose = v; } bool isVerbose() const { return verbose; } void setShaderNames(std::string const &v, std::string const &f, std::string tc = "", std::string te = ""); void setProgramName(const std::string &name); std::string getProgramName(); virtual bool init(); virtual void bind(); virtual void unbind(); void addAttribute(const std::string &name); void addUniform(const std::string &name); GLint getAttribute(const std::string &name) const; GLint getUniform(const std::string &name) const; GLuint pid = 0; protected: std::string vShaderName; std::string fShaderName; std::string teShaderName; std::string tcShaderName; std::string programName; private: std::map<std::string, GLint> attributes; std::map<std::string, GLint> uniforms; bool verbose = true; }; #endif // LAB471_PROGRAM_H_INCLUDED
<?php if (!defined("ABSPATH")) exit; /** * Return all global product tabs * * @return array */ function wptp_get_all_global_tabs() { $tabs = array(); $tab_query = new WP_Query(array( 'post_type' => \WPTP\GlobalTabs::get_posttype(), 'posts_per_page' => -1, 'post_status' => 'publish' )); // Gather data what's required foreach($tab_query->posts as $post) { $fieldID = get_post_meta($post->ID, '_wptp_field', true); $tab_data = (object) array( 'ID' => $post->ID, 'fieldID' => $fieldID, 'title' => $post->post_title, 'content' => $post->post_content, 'global' => true, 'hide' => false ); $tabs[$fieldID] = $tab_data; } return $tabs; } /** * Return all products tabs * * @return array */ function wptp_get_all_tabs() { global $post; // Retrieve global tabs $global_tabs = wptp_get_all_global_tabs(); // Retrieve product specific tabs $product_tabs = get_post_meta($post->ID, '_wptp', true); // Override global tab property: "hide, content" from product tab return wptp_merge_tabs($global_tabs, $product_tabs); } /** * Merge global/custom tab * @param array $global_tabs * @param array $product_tabs * @return array */ function wptp_merge_tabs($global_tabs, $product_tabs) { // If both empty return nothing if (empty($global_tabs) && empty($product_tabs)) { return array(); } // If product have no specific tabs return globals if (empty($product_tabs)) { wptp_apply_html($global_tabs); \WPTP\Tabs::set($global_tabs); return $global_tabs; } /** * Override global tabs content */ foreach ($product_tabs as $fieldID => &$product_tab) { // Assuming that global tab ($global_tabs[$fieldID]) is deleted, so skip... if ($product_tab->global && !isset($global_tabs[$fieldID])) { unset($product_tabs[$fieldID]); continue; } // If it's not a global tab, don't bother, we skip if (!$product_tab->global) continue; // Single product tab $global_tab = $global_tabs[$fieldID]; // Temporarily save hide value for later override $hide = $product_tab->hide; // Assign all properties from global tab $product_tab = $global_tab; /** * Assign back the original hide value to product tab */ $product_tab->hide = $hide; } // Let's append newly created global tabs afterwards foreach ($global_tabs as $global_tab) { // Skip if fieldID is not set if (!isset($global_tab->fieldID)) continue; // Skip if existing global fieldID is already in product_tabs[] if (isset($product_tabs[$global_tab->fieldID])) continue; $product_tabs[$global_tab->fieldID] = $global_tab; } wptp_apply_html($product_tabs); \WPTP\Tabs::set($product_tabs); return $product_tabs; } /** * Check whether the tab is global or not * @param string $tab_field * @return bool */ function wptp_is_global($tab_field) { $global_tabs = wptp_get_all_global_tabs(); $is_global = false; // Loop through each global tab foreach ($global_tabs as $global_tab) { // fieldID is same, which means the tab is global if ($tab_field === $global_tab->fieldID) { $is_global = true; break; } } return $is_global; } /** * Render tab html content on admin * * @param object $tab * @return void */ function wptp_render_block($tab) { \WPTP\Tabs::setCurrentTab($tab); include \WPTP\TEMPLATES . 'product-tab.php'; ?> <?php } /** * Upgrade function */ function wptp_upgrade() { // upgrade process } /** * Apply shortcode to tabs content * @param $tabs array * @since 1.0.1 * @return void */ function wptp_apply_html( &$tabs) { /** * Parsing shortcode on frontend only, because this function is used * cross side, so we don't want to parse shortcode on the backend editor */ if (is_admin()) return; array_walk($tabs, function($tab) { $tab->content = wptp_get_the_content(do_shortcode($tab->content)); }); } /** * Return html format custom tab contents * * @param $content string * @since 1.0.1 * @return string */ function wptp_get_the_content( $content ) { $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); return $content; }
@import "__var.scss"; @import "__mixings.scss"; @import "__classes.scss"; @import "__header.scss"; *, ::before, ::after { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 62.5%; scroll-behavior: smooth; } body { font-family: 'Poppins', sans-serif; font-size: 1.6rem; &.no-scroll { overflow: hidden; } } a, a:active, a:visited { text-decoration: none; } li { list-style: none; } h1, h2, h3, h4 { color: $black-color; margin-bottom: 1.3rem; } //hero .hero { @include section; &__container { @include display-flex; &>div { flex-basis: 50%; @include breakpoint-down(medium) { flex-basis: 100%; } } } &__text { @include breakpoint-down(medium) { order: 2; } } &__large { font-size: 5rem; line-height: 3rem; position: relative; @include breakpoint-down(medium) { font-size: 3rem; } &::after { height: .3rem; background-color: $black-color; width: 50%; content: ""; position: absolute; right: 14rem; top: 2rem; @include breakpoint-down(medium) { right: 5rem; } } } &__md { font-size: 2.4rem; margin-bottom: 2rem; @include breakpoint-down(medium) { font-size: 1.8rem; margin-bottom: 1rem; } &+a.btn { margin-right: 2rem; } } &__banner { @include breakpoint-down(medium) { order: 1; } .banner__img { @include img-style; } } } //about .about { @include section; padding: 2rem 0; &__container { @include display-flex; &>div { flex-basis: 50%; } } &__text { & .about__font { letter-spacing: 1.2rem; font-size: 4.9rem; text-transform: uppercase; line-height: 6.5rem; @include breakpoint-down(medium) { font-size: 3rem; line-height: 4rem; } } } &__banner img { @include img-style; } } //exper .exper { @include section; &__container { display: grid; grid-template-columns: 2fr 1fr; gap: 11rem; @include breakpoint-down(medium) { gap: 2rem; grid-template-columns: 1fr; } } &__company { .company__container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 2rem; @include breakpoint-down(medium) { grid-template-columns: repeat(2, 1fr); gap: 1rem; } // comapny img div style &>div { border: 1px solid #ddd; display: flex; align-items: center; justify-content: center; height: 100px; width: 190px; transition: transform 0.5s ease-in-out; @include breakpoint-down(medium) { height: 60px; width: 125px; } &:hover { transform: scale(1.1); box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); } &>.company__img { width: 80px; } } } } // right section style &__call { position: relative; background-color: #FEF6F6; & .experi__info { position: absolute; left: -20%; top: 10%; width: 200px; height: 170px; @include breakpoint-down(medium) { width: 150px; height: 100px; left: 0; } } } &__call { height: 35rem; } &__info__container { padding: 2rem; flex-direction: column; display: flex; justify-content: space-between; & .info__heading { font-size: 7.4rem; margin-bottom: 0; @include color-trans; margin-right: .7rem; @include breakpoint-down(medium) { font-size: 5rem; } } & .info__first { & .info__heading { &+span { font-size: 2.2rem; font-weight: 600; } } } } } // service .service { &__heading { padding: 3rem; } &__item__container { margin-bottom: 5rem; display: grid; grid-template-columns: repeat(4, 1fr); background-color: #F8FCFD; @include breakpoint-down(large) { grid-template-columns: repeat(2, 1fr); } @include breakpoint-down(medium) { grid-template-columns: repeat(1, 1fr); } } &__item { padding: 5rem 1rem 3rem; transition: all 0.5s ease-in-out; text-align: center; &:hover { transform: scale(1); background-color: #fff; box-shadow: .1rem .1rem .7rem rgba(0, 0, 0, 0.5); } & .service__img { margin-bottom: 2rem; } } } //subscribe .subscribe { padding: 3rem 0; &__container { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 0 2rem; background: url(../img/subscribe-bg.png) no-repeat center center; height: 50rem; @include breakpoint-down(medium){ height: 100vh; text-align: center; } & h1, p { color: $white-color; } } &__form { margin-top: 2rem; ::placeholder{ font-family: Poppins; font-weight: 500; } & input { padding: .8rem; width: 40rem; height: 5rem; border: 3px solid #ddd; margin: 0 2rem 2rem 0 ; &:focus{ outline: none; } @include breakpoint-down(medium){ width: 20rem; } } & button.btn{ border: 2px solid $white-color; padding: 1.5rem 3rem; } } }
[//]: # (title: Data structure constraints) Some data structures may require a part of operations not to be executed concurrently, such as single-producer single-consumer queues. Lincheck provides out-of-the-box support for such contracts, generating concurrent scenarios according to the restrictions. Consider the [single-consumer queue](https://github.com/JCTools/JCTools/blob/66e6cbc9b88e1440a597c803b7df9bd1d60219f6/jctools-core/src/main/java/org/jctools/queues/atomic/MpscLinkedAtomicQueue.java) from the [JCTools library](https://github.com/JCTools/JCTools). Let's write a test to check correctness of its `poll()`, `peek()`, and `offer(x)` operations. In your `build.gradle(.kts)` file, add the JCTools dependency: <tabs group="build-script"> <tab title="Kotlin" group-key="kotlin"> ```kotlin dependencies { // jctools dependency testImplementation("org.jctools:jctools-core:%jctoolsVersion%") } ``` </tab> <tab title="Groovy" group-key="groovy"> ```groovy dependencies { // jctools dependency testImplementation "org.jctools:jctools-core:%jctoolsVersion%" } ``` </tab> </tabs> To meet the single-consumer restriction, ensure that all `poll()` and `peek()` consuming operations are called from a single thread. For that, we can set the `nonParallelGroup` parameter of the corresponding `@Operation` annotations to the same value, e.g. `"consumers"`. Here is the resulting test: ```kotlin import org.jctools.queues.atomic.* import org.jetbrains.kotlinx.lincheck.annotations.* import org.jetbrains.kotlinx.lincheck.check import org.jetbrains.kotlinx.lincheck.strategy.managed.modelchecking.* import org.jetbrains.kotlinx.lincheck.strategy.stress.* import org.junit.* class MPSCQueueTest { private val queue = MpscLinkedAtomicQueue<Int>() @Operation fun offer(x: Int) = queue.offer(x) @Operation(nonParallelGroup = "consumers") fun poll(): Int? = queue.poll() @Operation(nonParallelGroup = "consumers") fun peek(): Int? = queue.peek() @Test fun stressTest() = StressOptions().check(this::class) @Test fun modelCheckingTest() = ModelCheckingOptions().check(this::class) } ``` Here is an example of the scenario generated for this test: ```text = Iteration 15 / 100 = | --------------------- | | Thread 1 | Thread 2 | | --------------------- | | poll() | | | poll() | | | peek() | | | peek() | | | peek() | | | --------------------- | | offer(-1) | offer(0) | | offer(0) | offer(-1) | | peek() | offer(-1) | | offer(1) | offer(1) | | peek() | offer(1) | | --------------------- | | peek() | | | offer(-2) | | | offer(-2) | | | offer(2) | | | offer(-2) | | | --------------------- | ``` Note that all consuming `poll()` and `peek()` invocations are performed from a single thread, thus satisfying the "single-consumer" restriction. > [Get the full code](https://github.com/Kotlin/kotlinx-lincheck/blob/guide/src/jvm/test/org/jetbrains/kotlinx/lincheck/test/guide/MPSCQueueTest.kt). > {type="note"} ## Next step Learn how to [check your algorithm for progress guarantees](progress-guarantees.md) with the model checking strategy.
import React, { useState } from "react"; import { useEffect } from "react"; import { Link,useNavigate } from "react-router-dom" import {useDispatch} from "react-redux" import "./BasicInfo.css" import { addData } from "../Store/Slice/PropertySlice"; const BasicInfo = () => { const navigate=useNavigate() const dispatch=useDispatch() const [formData,setFormdata]=useState({}) let blueColorUrl = window.location.href useEffect(() => { // console.log( blueColorUrl); },[blueColorUrl]); const handleChange=(e)=>{ const {name,value}=e.target setFormdata((prevFormData)=>({...prevFormData,[name]:value})) } const handleClick=(e)=>{ e.preventDefault() console.log(formData) dispatch(addData({key:"basicInfo",value:formData})) navigate("/details") } return ( <> <form className="formContainer" > <section className="column"> <section className="inputSection"> <label className="WideLabel" htmlFor="PropertyType">Property Type</label> <select className="WideInput" type="text" id="PropertyType" name="PropertyType" placeholder="Select Property Type" onChange={handleChange} > <option value="option1" className="WideInput" >Select Property Type</option> <option value="Plot">Plot</option> <option value="flat">Flat</option> <option value="House">House</option> <option value="Other">Other</option> </select> </section> <section className="inputSection"> <label className="WideLabel" htmlFor="Price">Price</label> <input className="WideInput" type="text" id="Price" name="Price" value={formData.Price || ""} onChange={handleChange} placeholder="Example: 10000" /></section> <section className="inputSection"> <label className="WideLabel" htmlFor="PropertyAge">Property Age</label> <input className="WideInput" type="text" id="PropertyAge" name="PropertyAge" value={formData.PropertyAge || ""} onChange={handleChange} placeholder="Select Property Age" /></section> <section className="inputSection"> <label className="WideLabel" htmlFor="PropertyDescription">Property Description</label> <input className="WideInput" type="text" id="PropertyDescription" name="PropertyDescription" value={formData.PropertyDescription ||""} onChange={handleChange} /> </section> </section> <section className="column"> <section className="inputSection"> <label className="WideLabel" htmlFor="Negotable">Negotable</label> <select className="WideInput" type="text" id="Negotable" name="Negotable" placeholder="Select Negotable" > <option value="option1" className="SelectNegotable" >Select Negotable</option> <option value="option2">yes </option> <option value="option3">no </option> </select> </section> <section className="inputSection"><label className="WideLabel" htmlFor="Ownership">Ownership</label> <select className="WideInput" type="text" id="Ownership" name="Ownership" onChange={handleChange} placeholder="Ownership" > <option value="Ownership" className="Ownership" >Ownership</option> <option value="partnership">partnership</option> <option value="sole proprietorship">sole proprietorship</option> </select> </section> <section className="inputSection"> <label className="WideLabel" htmlFor="PropertyApproved">Property Approved</label> <select className="WideInput" type="text" id="PropertyApproved" name="PropertyApproved" placeholder="PropertyApproved" > <option value="option1" className="PropertyApproved" >Property Approved</option> <option value="option2">Done</option> <option value="option3">not Done</option> </select> </section> <section className="inputSection"> <label className="WideLabel" htmlFor="BankLoan">Bank Loan</label> <select className="WideInput" type="text" id="BankLoan" name="BankLoan" placeholder="BankLoan" > <option value="option1" className="BankLoan" >Bank Loan</option> <option value="option2">Available</option> <option value="option3">not Available </option> </select> </section> </section> </form> <section className="buttons"> <Link to='/properties'> <button className="button1" >Cancel</button></Link> <Link > <button className="button2" onClick={handleClick} >Save & Continue</button></Link> </section> </> ) } export default BasicInfo;
@extends('layouts.app') @section('content') <div class="container "> <div class="row justify-content-center"> <div class="card"style="width: 30rem;"> <img src="/images/{{ $post->photo }}" class="card-img" alt="{{ $post->photo }}"> <div class="card-body"> <h4 class="card-title">{{ $post->title }}</h4> <p class="card-text">{{ $post->content }}</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Created at :{{ $post->created_at }}</li> <li class="list-group-item">Updated at :{{ $post->updated_at }}</li> <li class="list-group-item"> @foreach ($tags as $item) @foreach ($post->tags as $item2) @if ($item->id == $item2->id) {{ $item->name }}&nbsp; &nbsp; &nbsp;&nbsp; @endif @endforeach @endforeach </li> </ul> <div class="card-body"> <h4 class="card-title">Comments</h4> <div class="card-text"> @include('posts.comments',['comments'=>$post->comments,'post_id'=>$post->id]) <hr> <form class="row g-3" action="{{ route('comments.store') }}" method="POST"> @csrf <input type="hidden" name="user_id" value="{{ $item->user_id }}"> <input type="hidden" name="post_id" value="{{ $post->id }}"> <textarea class="form-control" name='content' rows="1"></textarea> <div class="col-12"> <button type="submit" class="btn btn-primary">Comment</button> </div> </form> </div> </div> </div> <br> @if ($errors->any()) <div class="alert alert-danger" role="alert"> <ul> @foreach ($errors->all() as $item) <li>{{ $item }}</li> @endforeach </ul> </div> @endif </div> </div> @endsection
import { color, textFont } from "@styles/theme"; import styled from "styled-components"; export enum CheckboxSize { small = "small", medium = "medium", } export enum CheckboxState { unchecked = "unchecked", indeterminate = "indeterminate", checked = "checked", } export const StyledCheckbox = styled.input.attrs({ type: "checkbox" })<{ state: CheckboxState; cbSize: CheckboxSize; }>` appearance: none; + label { display: grid; place-items: center; white-space: pre; line-height: 1; content: " "; content: ${(props) => { switch (props.state) { case CheckboxState.checked: return props.cbSize === CheckboxSize.small ? "url(/icons/check-small.png)" : "url(/icons/check-medium.png)"; case CheckboxState.indeterminate: return props.cbSize === CheckboxSize.small ? "url(/icons/minus-small.png)" : "url(/icons/minus-medium.png)"; default: return " "; } }}; :focus { background: crimson; border-color: red; outline: 4px solid ${color("primary", 300)}; } :hover { border: 1px solid ${color("primary", 400)}; } background: ${color("primary", 50)}; color: ${color("primary", 600)}; height: ${(props) => props.cbSize === CheckboxSize.small ? "16px" : "20px"}; width: ${(props) => props.cbSize === CheckboxSize.small ? "16px" : "20px"}; border: 1px solid ${color("gray", 300)}; border-radius: 4px; cursor: pointer; } :disabled ~ label { content: ${(props) => { switch (props.state) { case CheckboxState.checked: return "url(/icons/check-disabled.png)"; case CheckboxState.indeterminate: return "url(/icons/minus-disabled.png)"; default: return " "; } }}; background: ${color("gray", 100)}; border: 1px solid ${color("gray", 200)}; } :disabled ~ p { color: ${color("gray", 300)}; } `; const CheckboxContainer = styled.div<{ cbSize: CheckboxSize }>` position: relative; display: flex; align-items: center; gap: ${(props) => (props.cbSize === CheckboxSize.small ? "8px" : "12px")}; ${(props) => { const size = props.cbSize === CheckboxSize.small ? "sm" : "md"; return textFont(size, "medium"); }}; `; type CheckboxProps = { state: CheckboxState; cbSize: CheckboxSize; label?: string; disabled?: boolean; }; const Checkbox = ({ cbSize = CheckboxSize.small, state = CheckboxState.unchecked, label, disabled = false, }: CheckboxProps) => { const id = crypto.randomUUID(); if (label) { const id = crypto.randomUUID(); return ( <CheckboxContainer cbSize={cbSize}> <StyledCheckbox cbSize={cbSize} state={state} id={id} checked={state === "checked" ? true : false} disabled={disabled} /> <label htmlFor={id}></label> <p>{label}</p> </CheckboxContainer> ); } return ( <CheckboxContainer cbSize={cbSize}> <StyledCheckbox cbSize={cbSize} state={state} checked={state === "checked" ? true : false} id={id} disabled={disabled} /> <label htmlFor={id}></label> </CheckboxContainer> ); }; export { Checkbox };
qld === linear quadratic programming solver Calling Sequence ~~~~~~~~~~~~~~~~ :: [x, lagr] = qld(Q, p, C, b, ci, cs, me [,tol]) [x, lagr, info] = qld(Q, p, C, b, ci, cs, me [,tol]) Arguments ~~~~~~~~~ :Q real positive definite symmetric matrix (dimension `n x n` ). : :p real (column) vector (dimension `n`) : :C real matrix (dimension `(me + md) x n` ) : :b RHS column vector (dimension `(me + md)` ) : :ci column vector of lower-bounds (dimension `n`). If there are no lower bound constraints, put `ci = []`. If some components of `x` are bounded from below, set the other (unconstrained) values of `ci` to a very large negative number (e.g. `ci(j) = -number_properties('huge')` . : :cs column vector of upper-bounds. (Same remarks as above). : :me number of equality constraints (i.e. `C(1:me,:)*x = b(1:me)` ) : :tol Floatting point number, required precision. : :x optimal solution found. : :lagr vector of Lagrange multipliers. If lower and upper-bounds `ci, cs` are provided, `lagr` has `me + md + 2* n` components. The components `lagr(1:me + md)` are associated with the linear constraints and `lagr (me + md + 1 : 2 * n)` are associated with the lower and upper bounds constraints. If an upper-bound (resp. lower- bound) constraint `i` is active `lagr(i)` is > 0 (resp. <0). If no bounds are provided, `lagr` has only `me + md` components. On successful termination, all values of `lagr` with respect to inequalities and bounds should be greater or equal to zero. : :info integer, return the execution status instead of sending errors. info==1 : Too many iterations needed info==2 : Accuracy insufficient to statisfy convergence criterion info==5 : Length of working array is too short info==10: The constraints are inconsistent : Description ~~~~~~~~~~~ This function requires `Q` to be positive definite, if it is not the case, one may use the contributed toolbox " **quapro**". Examples ~~~~~~~~ :: //Find x in R^6 such that: //C1*x = b1 (3 equality constraints i.e me=3) C1= [1,-1,1,0,3,1; -1,0,-3,-4,5,6; 2,5,3,0,1,0]; b1=[1;2;3]; //C2*x <= b2 (2 inequality constraints) C2=[0,1,0,1,2,-1; -1,0,2,1,1,0]; b2=[-1;2.5]; //with x between ci and cs: ci=[-1000;-10000;0;-1000;-1000;-1000];cs=[10000;100;1.5;100;100;1000]; //and minimize 0.5*x'*Q*x + p'*x with p=[1;2;3;4;5;6]; Q=`eye`_(6,6); //No initial point is given; C=[C1;C2]; b=[b1;b2]; me=3; [x,lagr]=qld(Q,p,C,b,ci,cs,me) //Only linear constraints (1 to 4) are active (lagr(1:6)=0): See Also ~~~~~~~~ + `qpsolve`_ linear quadratic programming solver + `optim`_ non-linear optimization routine The contributed toolbox "quapro" may also be of interest, in particular for singular `Q`. Used Functions ~~~~~~~~~~~~~~ `ql0001.f` in `modules/optimization/src/fortran/ql0001.f` .. _optim: optim.html .. _qpsolve: qpsolve.html
<div class="card"> <div class="card-header"> <h5><i class="fa fa-phone"></i> <%= mt(:call_record) %></h5> <%= link_to fa_icon_tag('close'), 'javascript:history.go(-1);', :class => 'card-header-close' %> </div> <div class="card-body"> <div class="row"> <div class="col-12 d-flex flex-column flex-lg-row justify-content-between"> <h6> <span class="text-gray mr-3"><%= "# #{@candidate.uid}" %></span> <span><%= @candidate.last_name %> <%= @candidate.first_name %></span> </h6> <div class="btn-group btn-group-sm"> <%= link_to new_candidate_comment_path(candidate_id: @candidate.id), :class => 'btn btn-primary' do %> <%= fa_icon_tag('plus') %> <%= t('action.add_model', :model => mt(:candidate_comment)) %> <% end if false # can?(:new, CandidateComment) %> </div> </div> </div> <!-- Nav tabs --> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#call_records"> <%= mt(:call_record) %> <%= count_badge(@call_records.count) %> </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#comments"> <%= mt(:candidate_comment) %> <%= count_badge(@candidate_comments.count) %> </a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane active" id="call_records"> <div class="candidate-comment-group mt-3"> <% @call_records.each do |call_record| %> <div class="candidate-comment-unit"> <span class="badge badge-light"><%= show_creator(call_record) %></span> <span class="badge badge-light"><%= show_timestamps(call_record) %></span> <p class="content"><%= call_record.memo %></p> </div> <% end %> </div> </div> <div class="tab-pane" id="comments"> <div class="candidate-comment-group mt-3"> <% @candidate_comments.each do |comment| %> <div class="candidate-comment-unit"> <span class="badge badge-light"><%= show_creator(comment) %></span> <span class="badge badge-light"><%= show_timestamps(comment) %></span> <p class="content"><%= content_tag(:i, nil, class: 'fa fa-flag text-red') if comment.is_top? %><%= comment.content %></p> </div> <% end%> </div> </div> </div> </div> </div>
--@Autor(es): Aguilera Valderrama Alexis Fernando, -- Pereda Ceballos Jorge Francisco --@Fecha creación: 09/01/2022 --@Descripción: procedimiento encargado de cargar las fotos de los empleados connect sys / system as sysdba create or replace directory fotos_dir as '/tmp/bases/emp-img'; grant read, write on directory fotos_dir to agpe_proy_admin; prompt Creando procedimiento con usuario agpe_proy_admin connect agpe_proy_admin / agpe set serveroutput on create or replace procedure p_actualiza_foto_empleado is v_bfile bfile; v_src_offset number; v_dest_offset number; v_blob blob; v_src_length number; v_dest_length number; v_nombre_archivo varchar2(50); v_contador number; begin select count (*) into v_contador from empleado; for v_index in 1..v_contador loop v_nombre_archivo:='emp-'||v_index||'.jpg'; dbms_output.put_line('Cargando foto para '||v_nombre_archivo); --Validando si el archivo existe v_bfile:=bfilename('FOTOS_DIR',v_nombre_archivo); if dbms_lob.fileexists(v_bfile)=0 then raise_application_error(-20001,'El archivo '||v_nombre_archivo||' no existe.'); end if; --abrir archivo if dbms_lob.isopen(v_bfile)=1 then raise_application_error(-20001,'El archivo '||v_nombre_archivo||' está abierto. No se puede usar'); end if; --abriendo archivo dbms_lob.open(v_bfile,dbms_lob.lob_readonly); --Actualizando blob en la tabla --Asegurarse que la tabla auto contenga datos y la columna foto debe tener un blob vacío. --Asignar v_blob select foto into v_blob from empleado where empleado_id=v_index for update; --Escribiendo bytes v_src_offset:=1; v_dest_offset:=1; dbms_lob.loadblobfromfile( dest_lob => v_blob, src_bfile => v_bfile, amount => dbms_lob.getlength(v_bfile), dest_offset => v_dest_offset, src_offset => v_src_offset ); --Cerrando archivo dbms_lob.close(v_bfile); --Validando carga v_src_length:=dbms_lob.getlength(v_bfile); v_dest_length:=dbms_lob.getlength(v_blob); if v_dest_length<>v_src_length then raise_application_error(-20001,'El archivo '||v_nombre_archivo||' no se cargó correctamente'); end if; end loop; end; / show errors
package com.projetofinal.ninjatask.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.projetofinal.ninjatask.dto.PaginaDTO; import com.projetofinal.ninjatask.dto.TarefaDTO; import com.projetofinal.ninjatask.entity.TarefaEntity; import com.projetofinal.ninjatask.entity.UsuarioEntity; import com.projetofinal.ninjatask.exceptions.BusinessException; import com.projetofinal.ninjatask.service.TarefaService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import lombok.RequiredArgsConstructor; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.sql.SQLException; import java.util.List; @RestController @RequestMapping("/tarefa") @RequiredArgsConstructor @Validated public class TarefaController { private final TarefaService tarefaService; @Operation(summary = "inserir nova tarefa", description = "este processo cria uma nova tarefa na base de dados") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deu certo"), @ApiResponse(responseCode = "400", description = "Erro na validação dos dados"), @ApiResponse(responseCode = "500", description = "deu erro no servidor") }) @PostMapping public TarefaDTO inserirTarefa(@RequestBody TarefaDTO dto) throws Exception{ return tarefaService.salvarTarefa(dto); // return tarefaSalva; } //listar tarefas @GetMapping public List<TarefaDTO> listarTarefas() throws SQLException { return tarefaService.listarTarefas(); // return lista; } @GetMapping("/listar-por-id") public List<TarefaDTO> listarTarefasPorId(Integer id) throws SQLException, JsonProcessingException { return tarefaService.listarPorId(id); } @Operation(summary = "editar tarefa", description = "este processo edita a tarefa da base de dados") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deu certo"), @ApiResponse(responseCode = "400", description = "Erro na validação dos dados"), @ApiResponse(responseCode = "500", description = "deu erro no servidor") }) @PutMapping public TarefaDTO atualizarTarefa(@RequestBody TarefaDTO dto) throws Exception { return tarefaService.editarTarefa(dto); } @Operation(summary = "excluir tarefa", description = "este processo exclui a tarefa da base de dados") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deu certo"), @ApiResponse(responseCode = "400", description = "Erro na validação dos dados"), @ApiResponse(responseCode = "500", description = "deu erro no servidor") }) @DeleteMapping("/{id_tarefa}") public void removerTarefa(@PathVariable("id_tarefa") Integer id) throws BusinessException, JsonProcessingException { tarefaService.excluirTarefa(id); } @GetMapping("/listarPaginado") public PaginaDTO<TarefaDTO> listarPaginado(Integer paginaSolicitada, Integer tamanhoPorPagina){ return tarefaService.listarPaginado(paginaSolicitada, tamanhoPorPagina); } }
pragma solidity ^0.5.0; contract Software { // Model the software licence offerings struct Licence { uint id; string userID; // added for tracking the UserID string option; uint licenceCount; } // Store accounts that have used options mapping(address => bool) public users; // Store Options // Fetch Option mapping(uint => Licence) public licences; // Store Licence Count uint public licenceCount; // Store Licence Count string public userID; // added for tracking the UserID // use event event useEvent(uint indexed _licenceId); constructor () public { addLicence("Read-Only Access (FREE)"); addLicence("Read-WRITE One-Time Access"); addLicence("Read-WRITE Unlimited Subscription"); } function addLicence (string memory _name) private { licenceCount ++; licences[licenceCount] = Licence(licenceCount, userID, _name, 0); } function use (uint _licenceId) public { // require that they haven't used before require(!users[msg.sender]); // require a valid licence require(_licenceId > 0 && _licenceId <= licenceCount); // record that user has used the licence users[msg.sender] = true; // update licence use Count licences[_licenceId].licenceCount ++; // trigger use event emit useEvent(_licenceId); } function test() public view returns (string memory) { uint256 randomNumber; // uint randomNumber = uint(keccak256(abi.encodePacked(_addr))) % MAX_INT; return addressToString(); } function addressToString() public pure returns(string memory) { uint256 MIN_INT = - 1**256; uint256 MAX_INT = 2**256 - 1; uint randomNumber = uint(keccak256(abi.encodePacked(MIN_INT))) % MAX_INT; bytes32 value = bytes32(uint256(randomNumber)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(51); str[0] = '0'; str[1] = 'x'; for (uint256 i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint8(value[i + 12] >> 4)]; str[3+i*2] = alphabet[uint8(value[i + 12] & 0x0f)]; } return string(str); } }
#ifndef FILE_DOG #define FILE_DOG /** * struct dog - structure dog * @name: atribute name's dog * @age: atribute age's dog * @owner: atribute owner's dog */ struct dog { char *name; float age; char *owner; }; typedef struct dog dog_t; void init_dog(struct dog *d, char *name, float age, char *owner); void print_dog(struct dog *d); dog_t *new_dog(char *name, float age, char *owner); void free_dog(dog_t *d); #endif