text
stringlengths
184
4.48M
import React from 'react'; import { useCart } from 'react-use-cart'; import './Cart.css'; import Navbar from '../Navbar/Navbar22'; function Cart() { const { isEmpty, totalUniqueItems, items, totalItems, cartTotal, updateItemQuantity, removeItem, emptyCart } = useCart(); if (isEmpty) return <h1>your cart is Empty</h1> return ( <> <Navbar /> <div> <h4 className="total-items"> Cart({totalUniqueItems}) total Items: ({totalItems})</h4> <table className="table"> <tbody> {items.map((item, index) => { return( <tr key={index}> <td className="td-items"> {item.title}&nbsp;&nbsp; </td> <td> {item.price}&nbsp;&nbsp; </td> <td>Quantity: {item.quantity}&nbsp;&nbsp; </td> <td> <button className="btn-incredecre" onClick={() => updateItemQuantity(item.id, item.quantity-1)}>-</button> <button className="btn-incredecre" onClick={() => updateItemQuantity(item.id, item.quantity+1)}>+</button> <button className="btn-incredecre" onClick={() => removeItem(item.id)}>Remove item</button> </td> </tr> ) })} </tbody> </table> <div> <h2 className="total-items">Total price:{cartTotal}</h2> </div> <div> <button onClick={() => emptyCart()}> Clear Cart </button> <button>Buy Now</button> </div> </div> </> ) } export default Cart;
# coding=utf-8 from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from general.models import UserSettings class UserSettingsForm(forms.ModelForm): class Meta: model = UserSettings fields = ['two_factor_auth_enabled', 'language', 'alias'] # Form de Django class SignupForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] # Form del programa class LoginForm(forms.Form): username = forms.CharField(label=_('User name')) # label='Nombre de usuario' password = forms.CharField(label=_('Password'), widget=forms.PasswordInput) # label='Contraseña' # class TwoFactorAuthForm(forms.Form): # activate_2fa = forms.BooleanField(label='Activate 2FA', required=False)
import { QlikSaaSClient } from "qlik-rest-api"; export interface IAPIKey { id: string; tenantId: string; description: string; sub: string; subType: string; status: string; expiry: string; createdByUser: string; created: string; lastUpdated: string; } export class APIKey { #id: string; #saasClient: QlikSaaSClient; details: IAPIKey; constructor(saasClient: QlikSaaSClient, id: string, details?: IAPIKey) { if (!id) throw new Error(`apiKeys.get: "id" parameter is required`); this.details = details ?? ({} as IAPIKey); this.#id = id; this.#saasClient = saasClient; } async init(arg?: { force: true }) { if (Object.keys(this.details).length == 0 || arg?.force == true) { this.details = await this.#saasClient .Get<IAPIKey>(`api-keys/${this.#id}`) .then((res) => res.data); } } async remove() { return await this.#saasClient .Delete(`api-keys/${this.#id}`) .then((res) => res.status); } async update(arg: { description: string }) { if (!arg.description) throw new Error(`apiKey.update: "description" parameter is required`); const data = [{ op: "replace", path: `/description`, value: arg.description, }]; let updateStatus = 0; return await this.#saasClient .Patch(`api-keys/${this.#id}`, data) .then((res) => { updateStatus = res.status; return this.init({ force: true }); }) .then(() => updateStatus); } }
--- title: Creating a new page with Hugo date: 2024-05-31 author: Hugo Toyin image: /images/blog/creating-a-hugo-theme-from-scratch.jpg type: blog --- Hello and welcome back to my blog. This blog post is about creating a new page using Hugo. Hugo is one of the most popular open-source static site generators (straight from their website) and I’ve been having great fun learning to use it. If you’re a fan of Hugo or looking to get into it, then you’re in the right place. Hugo has great documentation in general (find it [here](https://gohugo.io/)) but I found that the way Hugo works, being based on hierarchy, can be confusing at times. So here is a very simple explanation of how page content and layouts work and how to create your own single page with a custom layout. Of course I'm assuming you have a basic working knowledge of Hugo. If anything is confusing please feel free to get in touch and maybe I can explain things a bit better. Your directory structure could look something like this: ``` content ├── _index.md └── contact ├── _index.md ├── page-one.md └── page-two.md └── about.md ``` Firstly, just to talk about what the the relative paths for these files. In Hugo, a `.md` file is treated as a web page and is accessible via a URL. So, every markdown file you have in your /content directory, will be their own page. The below codeblock shows the directory structure with the URL paths you can expect as a result. ``` content ├── _index.md // <- https://example.com (optional) └── contact ├── _index.md // <- https://example.com/contact/ ├── page-one.md // <- https://example.com/contact/page-one/ └── page-two.md // <- https://example.com/contact/page-two/ └── about.md // <- https://example.com/about/ ``` * `_index.md` is the default markdown content used for the root - this is optional * There are 2 ways to create a new standalone page as above. Either create it directly in inside`/content` or create a subfolder where you can use `_index.md` as the relative root and so on. Now that you have your web pages, you will want to use a template to render the content. Everything in Hugo is a hierarchy of specificity. This is no different. When Hugo renders content, it looks for templates in the following order of specificity (always inside the `/layouts` directory): 1. **Specific content type templates**: Hugo looks for templates named after the content type first. For example, if your content type is `contact`, it will look for a template named `contact.html`. 2. **Section templates**: If Hugo doesn't find a specific content type template, it looks for a template named after the section in which the content resides. For example, if your content is in a section named `contact`, it will look for a template named `section/contact.html`. 3. **`_default` templates**: If Hugo doesn't find a specific content type or section template, it falls back to the `_default` templates. These templates apply to all content types unless overridden by more specific templates. Important here is `single.html` which is the template used for single pages as a default. So if you were creating a standalone contact page, you can create the HTML file in a few ways and see which is most comfortable and intuitive for you. ``` layouts └── _default ├── single.html └── contact.html └── contact └── single.html └── contact.html ``` 1. Place `contact.html` inside `/layouts` 2. Place `single.html` inside `/layouts/contact/` 3. Place `contact.html` inside`/layouts/_default/` If none of these templates are added, Hugo will default and use `/_default/single.html` and apply it. Now go forth and create some pages with custom template renders. **N.B: I have personally found that placing html files directly in the layouts folder does not apply them in which case use 2 or 3 instead.** **Note:** When creating a new page by using method 2, you may find a file call `list.html` which is used as the template file for any subpages of the new page. E.g., Your new blog page at `/blog` could have many blog posts sitting in subpages and they would use all use the html template at `list.html`.
/** * Performs a binary search on a sorted array and returns the index of the target element if found, otherwise -1. * @param arr The sorted array to search in. * @param target The target element to search for. * @returns The index of the target element if found, otherwise -1. */ export function binarySearch<T>( arr: T[], target: T, compareFn: (a: T, b: T) => number ): number { let left = 0 let right = arr.length - 1 while (left <= right) { const mid = Math.floor((left + right) / 2) const cmp = compareFn(arr[mid], target) if (cmp === 0) { //相同 return mid } else if (cmp < 0) { //中间的值小于目标值,查找的范围移动到中间至末尾区间 left = mid + 1 } else { //中间的值大于目标值,查找的范围移动到开始区间至中间 right = mid - 1 } } return -1 } /** * Performs a binary search on a sorted array and returns the index of the closest element to the target if not found, otherwise the index of the target element. * @param arr The sorted array to search in. * @param target The target element to search for. * @param compareFn The function to compare elements in the array. * @returns The index of the closest element to the target if not found, otherwise the index of the target element. */ export function binarySearchClosest<T>( arr: T[], target: T, compareFn: (a: T, b: T) => number ): number { let left = 0 let right = arr.length - 1 while (left <= right) { const mid = Math.floor((left + right) / 2) const cmp = compareFn(arr[mid], target) if (cmp === 0) { //相同 return mid } else if (cmp < 0) { //中间的值小于目标值,查找的范围移动到中间至末尾区间 left = mid + 1 } else { //中间的值大于目标值,查找的范围移动到开始区间至中间 right = mid - 1 } } // If target is not found, return the index of the closest element if (right < 0) { return 0 } else if (left >= arr.length) { return arr.length - 1 } else { const leftDiff = Math.abs(compareFn(arr[right], target)) const rightDiff = Math.abs(compareFn(arr[left], target)) return leftDiff <= rightDiff ? right : left } }
/* 10) Crie uma função para uma "mini" calculadora (somente de inteiros), ou seja, passe como argumento: ➢ Dois (2) números inteiros: Número1 e Número2 e ➢ Um (1) Operador: Soma ( + ) ou Subtração ( ̶) ou Multiplicação ( * ) ou Divisão ( / ) ou MOD ( % ) Retorne desta função a operação matemática solicitada pelo usuário. Na main, use a função em 100 operações matemáticas com valores de Número1, Número2 e Operador lidos do usuário. FEITO! */ #include <stdio.h> // Biblioteca I/O // PROTÓTIPO: int calculadora(int Numero1, int Numero2, char operador); // FUNÇÃO: int calculadora(int Numero1, int Numero2, char operador) { int resultado; if (operador == '+') { resultado = Numero1 + Numero2; } else if (operador == '-') { resultado = Numero1 - Numero2; } else if (operador == '*') { resultado = Numero1 * Numero2; } else if (operador == '/') { if (Numero2 != 0) { resultado = Numero1 / Numero2; } else { printf("Erro: Divisão por zero!\n"); resultado = 0; } } else if (operador == '%') { if (Numero2 != 0) { resultado = Numero1 % Numero2; } else { printf("Erro: Divisão por zero!\n"); resultado = 0; } } else { printf("Operador inválido! Tente novamente.\n"); resultado = 0; } return resultado; } // MAIN int main() { int Numero1, Numero2, index; char operador; int resultado; for (index = 0; index < 100; index++) { printf("Digite o primeiro número: "); scanf("%i", &Numero1); // LOOP PARA DEFINIR O OPERADOR int operadorValido = 0; do { printf("Digite o operador ( +, -, *, /, %% ): "); scanf(" %c", &operador); if (operador == '+' || operador == '-' || operador == '*' || operador == '/' || operador == '%') { operadorValido = 1; } else { printf("Operador inválido! Tente novamente.\n"); } } while (!operadorValido); printf("Digite o segundo número: "); scanf("%i", &Numero2); resultado = calculadora(Numero1, Numero2, operador); printf("Resultado: %i\n", resultado); } return 0; }
import {FC, ReactPortal, useEffect, useState} from "react"; import PopupMenu from "../../index"; import "./index.scss"; import MenuButton from "../../items/button"; import PopupDialog from "../../../popup-dialog"; import {useChangePasswordMutation, useEditProfileMutation, useGetAvatarMutation} from "../../../../services/users.api"; import {useTypedSelector} from "../../../../redux/store"; import {getUser} from "../../../../redux/reducers/authSlice"; import {useSendExceptionMutation} from "../../../../services/debug.api"; import HttpError from "../../../../common/http-error"; import MenuDivider from "../../items/divider"; import UserAvatar from "../../../user-avatar"; import {getAvatar, isAvatarLoading} from "../../../../redux/reducers/usersSlice"; import {createPortal} from "react-dom"; type ProfileSettingsProps = { close: () => void } const ProfileSettings: FC<ProfileSettingsProps> = ({close}) => { const [portal, setPortal] = useState<ReactPortal | null>(null); const [editProfile, editProfileStatus] = useEditProfileMutation(); const [changePassword, changePasswordStatus] = useChangePasswordMutation(); const [fetchAvatar, fetchAvatarStatus] = useGetAvatarMutation(); const user = useTypedSelector(getUser)!; const avatar = useTypedSelector(getAvatar(user.id)); const _isAvatarLoading = useTypedSelector(isAvatarLoading(user.id)); const [sendException] = useSendExceptionMutation(); useEffect(() => { !_isAvatarLoading && !avatar && fetchAvatar(user!.id); }, []); const onEditProfile = () => { setPortal(createPortal(<PopupDialog title={"Edit profile"} fields={[ {title: "Avatar", type: "image", name: "avatar", options: {initialImage: avatar}}, {title: "Firstname", type: "text", name: "firstname"}, {title: "Lastname", type: "text", name: "lastname"}, ]} actions={[ { title: "Confirm", cb: async fields => { try { !editProfileStatus.isLoading && await editProfile({ firstname: fields.find(e => e.name === "firstname")?.value, lastname: fields.find(e => e.name === "lastname")?.value, avatar: fields.find(e => e.name === "avatar")?.value, }).unwrap(); } catch (e) { sendException(e); return "Error while trying to change profile."; } fields.find(e => e.name === "avatar") && fetchAvatar(user!.id); return undefined; }, validate: async fields => { const firstname: string = fields.find(e => e.name === "firstname")?.value; const lastname: string = fields.find(e => e.name === "lastname")?.value; if (firstname && (firstname.length < 3 || firstname.length > 20)) return "Firstname must be 3-20 symbols"; if (lastname && (lastname.length < 3 || lastname.length > 20)) return "Lastname must be 3-20 symbols"; return undefined; } }, {title: "Cancel"} ]} closeCb={() => setPortal(null)}/>, document.body)); } const onChangePassword = () => { setPortal(createPortal(<PopupDialog title={"Change password"} fields={[ { title: "Current password", type: "password", name: "currentPassword", options: {placeholder: "Current password"} }, {title: "New password", type: "password", name: "newPassword", options: {placeholder: "New password"}}, { title: "Repeat new password", type: "password", name: "repeatNewPassword", options: {placeholder: "Repeat new password"} }, ]} actions={[ { title: "Confirm", cb: async fields => { try { !changePasswordStatus.isLoading && await changePassword({ oldPassword: fields.find(e => e.name === "currentPassword")?.value, newPassword: fields.find(e => e.name === "newPassword")?.value, }).unwrap(); } catch (e) { sendException(e); console.error(e); if ((e as HttpError).status === 400) return "Invalid current or new password."; return "Error while trying to change password."; } return undefined; }, validate: async (fields) => { const currentPassword: string = fields.find(e => e.name === "currentPassword")?.value; const newPassword: string = fields.find(e => e.name === "newPassword")?.value; const repeatNewPassword: string = fields.find(e => e.name === "repeatNewPassword")?.value; if (!currentPassword || currentPassword.length <= 0) return "Enter current password"; if (!newPassword || newPassword.length < 8 || newPassword.length > 32) return "New password must be 8-32 symbols"; if (newPassword && repeatNewPassword && newPassword !== repeatNewPassword) return "New password does not match."; return undefined; } }, {title: "Cancel"} ]} closeCb={() => setPortal(null)}/>, document.body)); } return ( <PopupMenu title={"Profile settings"} className={"profile-settings"} close={close}> {portal} <div className={"profile-info"}> <UserAvatar userId={user.id}/> <div className={"profile-details"}> <span className={"profile-name"}>{user.firstname + " " + user.lastname}</span> <span className={"profile-id"}>{user.id}</span> </div> </div> <MenuDivider/> <MenuButton title={"Edit profile"} onClick={onEditProfile}/> <MenuButton title={"Change password"} onClick={onChangePassword}/> </PopupMenu> ) } export default ProfileSettings;
--- title: Cache description: Cache Overview hide_table_of_contents: true --- import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; <Tabs queryString="primary"> <TabItem value="cache-overview" label="Overview"> Temporary data store, typically in RAM, that holds frequently accessed data for faster retrieval. ### Core Concepts - Cache Operations - **Cache Lookup**: Application checks the cache for requested data - **Cache Hit**: Data is found in the cache and returned directly - **Cache Miss**: Data is not found in the cache. The application fetches it from the primary source, updates the cache, and returns the data ### Benefits - Reduced database load - Faster data access (commonly retrieval from RAM) - Scalability - Cost-Effectiveness </TabItem> <TabItem value="cache-operations" label="Operations"> - `GET`: Retrieve the value of a key - `PUT`: Create a new key-value pair or update an existing key - `DELETE`: Delete a key-value pair </TabItem> <TabItem value="cache-key-value-mappings" label="Key-Value Mappings"> ### Keys - Unique identifier - Can be only a string ### Values <table> <thead> <tr> <th>Redis Data Structures</th> <th>Underlying Implementation</th> </tr> </thead> <tbody> <tr> <td><b>String</b></td> <td>SDS (Simple Dynamic String)</td> </tr> <tr> <td><b>Lists</b></td> <td> <ul> <li>Bi-Directional LinkedList → QuickList in Redis 7 - `O(n)`</li> <li>ZipList → ListPack in Redis 7 - `O(n)`</li> </ul> </td> </tr> <tr> <td><b>Hashes</b></td> <td> <ul> <li>ZipList → ListPack in Redis 7 - `O(n)`</li> <li>HashTable `O(1)`</li> </ul> </td> </tr> <tr> <td><b>Sets</b></td> <td> <ul> <li>HashTable `O(1)`</li> <li>IntSet `O(n)`</li> </ul> </td> </tr> <tr> <td><b>Sorted Sets</b></td> <td> <ul> <li>ZipList → ListPack in Redis 7 - `O(n)`</li> <li>SkipList `O(log(n))`</li> </ul> </td> </tr> </tbody> </table> </TabItem> <TabItem value="cache-persistence" label="Persistence"> ### Levels - **1ns (L1 cache)** - **10ns (L2 cache)** - **100ns (RAM access)**: Redis read - **10µs (send data over network)**: Memcached send data over 1 Gbps network - **100µs (read from SSD)**: RocksDB read - **1ms (database insert)**: PostgreSQL insert - **10ms (HDD disk seek)**: PostgreSQL read - **100ms (packet CA → NL → CA)**: Remote Zoom call - **10s (retry/refresh interval)**: Grafana refresh interval Options: - **AOF (Append Only File)**: Acts like a log, continuously recording every write operation. This allows replaying them on restart to rebuild the data - **RDB (Redis Database)**: Creates point-in-time snapshots of your entire dataset at regular intervals - **No Persistence**: Disables data persistence entirely, suitable for caching temporary data </TabItem> <TabItem value="cache-eviction-policies" label="Eviction Policies"> <table> <thead> <tr> <th>Eviction Policy</th> <th>Description</th> <th>Pros</th> <th>Cons</th> <th>Use Cases</th> </tr> </thead> <tbody> <tr> <td><b>Least Frequently Used (LFU)</b></td> <td>Evicts the least frequently accessed items from the cache. It counts how often an item is accessed</td> <td> <ul> <li>Ideal for scenarios where access frequency varies widely</li> <li>Ensures that frequently accessed items stay in the cache</li> </ul> </td> <td> <ul> <li>Complexity in implementation due to the need for tracking access frequency</li> <li>Can be less effective in scenarios with sudden spikes in access frequency</li> </ul> </td> <td> <ul> <li>Caching of user profiles, session data, and user preferences</li> </ul> </td> </tr> <tr> <td><b>Least Recently Used (LRU)</b></td> <td>Evicts the least recently accessed items from the cache. It tracks the time of the last access for each item</td> <td> <ul> <li>Effective in scenarios where recently accessed items are more likely to be accessed again</li> </ul> </td> <td> <ul> <li>May not be optimal for scenarios with varying access patterns</li> <li>Requires frequent updates to access timestamps</li> </ul> </td> <td> <ul> <li>Web page caching, API response caching, and frequently accessed database records</li> </ul> </td> </tr> <tr> <td><b>Size-Based</b></td> <td>Evicts items based on the size of the cache. It ensures that the cache does not exceed a predefined size limit</td> <td> <ul> <li>Guarantees that the cache size remains within predefined limits</li> </ul> </td> <td> <ul> <li>May lead to eviction of useful items if not carefully tuned</li> <li>May not consider access patterns, leading to suboptimal cache utilization</li> </ul> </td> <td> <ul> <li>Image caching, file caching, and multimedia content caching</li> </ul> </td> </tr> <tr> <td><b>Time-to-Live (TTL)</b></td> <td>Evicts items based on their time since creation or last access. Items are evicted once their predefined lifespan expires</td> <td> <ul> <li>Provides control over the freshness of cached data</li> <li>Useful for scenarios where data validity is time-bound</li> </ul> </td> <td> <ul> <li>May lead to eviction of frequently accessed but still valid items</li> <li>Requires careful consideration of TTL values to balance between freshness and cache utilization</li> </ul> </td> <td> <ul> <li>News articles, stock prices, and time-sensitive data feeds</li> </ul> </td> </tr> </tbody> </table> </TabItem> <TabItem value="cache-invalidation-strategies" label="Invalidation Strategies"> - **Time-Based** - **Absolute Timeout**: Cached data is invalidated after a fixed period from the time of caching - **Relative Timeout**: Cached data is invalidated after a fixed period from the time of last access or update - **Sliding Timeout**: Timeout period is extended every time the data is accessed or updated - **Event-Based Invalidation** - **Publish/Subscribe Model**: Invalidate cache based on events published by the data source or other relevant services - **Webhooks**: Trigger cache invalidation based on HTTP callbacks from the data source - **Message Queue Integration**: Invalidate cache in response to messages received from a message queue - **Manual Invalidation** - **Programmatic Invalidation**: Invalidate cache entries programmatically through API calls or direct cache manipulation - **Admin Console**: Provide a user interface for administrators to manually invalidate cache entries </TabItem> <TabItem value="cache-redis-vs-memcached" label="Redis vs Memcached"> <table class="text_vertical"> <thead> <tr> <th>Aspect</th> <th>Redis</th> <th>Memcached</th> </tr> </thead> <tbody> <tr> <td><b>Data Structure</b></td> <td> <ul> <li>List</li> <li>Set/Sorted Set</li> <li>Hash</li> <li>Bit Array</li> <li>HyperLogLog</li> </ul> </td> <td>Plain string value</td> </tr> <tr> <td><b>Architecture</b></td> <td>Single-thread for read/write keys</td> <td>Multi-threaded</td> </tr> <tr> <td><b>Transactions</b></td> <td>Support atomic operations</td> <td>❌</td> </tr> <tr> <td><b>Snapshots/Persistence</b></td> <td> <ul> <li>Keep data on disks</li> <li>Support RDB/AOF persistence</li> </ul> </td> <td>❌</td> </tr> <tr> <td><b>Pub-Sub Messaging</b></td> <td>Support Pub-Sub messaging with pattern matching</td> <td>❌</td> </tr> <tr> <td><b>Geo-Spatial Support</b></td> <td>Geospatial indexes that stores the longitude and latitude data of the location</td> <td>❌</td> </tr> <tr> <td><b>Server-Side Script</b></td> <td>Support Lua script to perform operations inside Redis</td> <td>❌</td> </tr> <tr> <td><b>Support Cache Eviction</b></td> <td> <ul> <li>noeviction</li> <li>allkeys-lru/allkeys-lfu/allkeys-random</li> <li>volatile-lru/volatile-lfu/volatile-random/volatile-ttl</li> </ul> </td> <td>LRU</td> </tr> <tr> <td><b>Replication</b></td> <td>Leader-Follower replication</td> <td>❌</td> </tr> </tbody> </table> </TabItem> </Tabs> ## Security <Tabs queryString="primary"> <TabItem value="security-overview" label="Overview"> <Tabs queryString="secondary"> <TabItem value="security-overview-cache-miss" label="Cache Miss" attributes={{ className: "tabs__vertical" }}> Cache Miss Attack exploits weaknesses in how data is stored to steal information or overload systems. It targets situations where a web application doesn't consider all input data when storing data in a cache. This lets attackers trick the cache into revealing sensitive information or causing performance issues. Solutions: - Cache keys with null value. Set a short TTL (Time to Live) for keys with null value - Bloom filter to quickly check if key exists before hitting cache/database ```mermaid graph TB subgraph attack [Cache Miss Attack] direction LR attack_app(Application) attack_cache[[Cache]] attack_db[(DB)] attack_app --> |1. read<br/>cache miss| attack_cache attack_app --> |2. read<br/>no data| attack_db attack_db ~~~| hackers can overload the DB<br/>by initiating a lot of<br/>such queries| attack_db end subgraph solution1 [Cache non-existent keys] direction LR solution1_app(Application) solution1_cache[[Cache]] solution1_db[(DB)] solution1_app --> |1. read k3<br/>cache miss| solution1_cache solution1_app --> |2. read<br/>no data| solution1_db solution1_app --> |3. write k3=NULL| solution1_cache solution1_db ~~~|next time the key can be found in cache and DB is not hit| solution1_db solution1_cache ~~~|<table><thead><tr><th>Key</th><th>Value</th></tr></thead><tbody><tr><td>k1</td><td>1</td></tr><tr><td>k2</td><td>2</td></tr><tr><td>k3</td><td>NULL</td></tr></tbody></table>| solution1_cache end subgraph solution2 [Bloom Filter] direction TB subgraph key [key exists] direction LR key_app(Application) key_cache[[Cache]] key_db[(DB)] key_filter{{Bloom Filter}} key_app --> |1. read k1<br/>found k1| key_filter key_app --> |2. read k1| key_cache key_filter ~~~|<table><tr><td>1</td><td>0</td><td>0</td><td>1</td><td>1</td></tr></table>| key_filter key_cache ~~~|<table><thead><tr><th>Key</th><th>Value</th></tr></thead><tbody><tr><td>k1</td><td>1</td></tr><tr><td>k2</td><td>2</td></tr></tbody></table>| key_cache end subgraph noKey [key doesn't exist] direction LR noKey_cache[[Cache]] noKey_app(Application) noKey_db[(DB)] noKey_filter{{Bloom Filter}} noKey_app --> |1. read k3<br/>not found| noKey_filter noKey_filter ~~~|<table><tr><td>1</td><td>0</td><td>0</td><td>1</td><td>1</td></tr></table>| noKey_filter noKey_cache ~~~|<table><thead><tr><th>Key</th><th>Value</th></tr></thead><tbody><tr><td>k1</td><td>1</td></tr><tr><td>k2</td><td>2</td></tr></tbody></table>| noKey_cache noKey_db ~~~|cache and DB are not hit if the key doesn't exist| noKey_db end end attack --> |solution| solution1 & solution2 ``` </TabItem> </Tabs> </TabItem> </Tabs>
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ToolbarComponent } from './components/toolbar/toolbar.component'; import {MatIconModule} from "@angular/material/icon"; import {MatToolbarModule} from "@angular/material/toolbar"; import {MatButtonModule} from "@angular/material/button"; import { ProjectsComponent } from './components/projects/projects.component'; import {MatInputModule} from "@angular/material/input"; import {MatTableModule} from "@angular/material/table"; import {MatPaginatorModule} from "@angular/material/paginator"; import { ProjectsTableComponent } from './components/projects/projects-table/projects-table.component'; import {NoopAnimationsModule} from "@angular/platform-browser/animations"; import { PopupComponent } from './components/ui/popup/popup.component'; import {MatDialogModule} from "@angular/material/dialog"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {MatSortModule} from "@angular/material/sort"; import { ProjectsEditComponent } from './components/projects/projects-edit/projects-edit.component'; import {MatTabsModule} from "@angular/material/tabs"; import {MatSelectModule} from "@angular/material/select"; import {MatSidenavModule} from "@angular/material/sidenav"; import {MatGridListModule} from "@angular/material/grid-list"; import { TreeComponent } from './components/ui/tree/tree.component'; import {MatTreeModule} from "@angular/material/tree"; import {MatListModule} from "@angular/material/list"; import { EditableTableComponent } from './components/ui/editable-table/editable-table.component'; import { PropertyTableComponent } from './components/ui/property-table/property-table.component'; import { IndTableComponent } from './components/ui/ind-table/ind-table.component'; import {MatDatepickerModule} from "@angular/material/datepicker"; import {MatNativeDateModule} from "@angular/material/core"; @NgModule({ declarations: [ AppComponent, ToolbarComponent, ProjectsComponent, ProjectsTableComponent, PopupComponent, ProjectsEditComponent, TreeComponent, EditableTableComponent, PropertyTableComponent, IndTableComponent ], imports: [ BrowserModule, AppRoutingModule, MatToolbarModule, MatIconModule, MatButtonModule, MatInputModule, MatTableModule, MatPaginatorModule, NoopAnimationsModule, MatDialogModule, ReactiveFormsModule, MatSortModule, MatTabsModule, MatSelectModule, MatSidenavModule, MatGridListModule, MatTreeModule, MatListModule, FormsModule, MatDatepickerModule, MatNativeDateModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>刮刮卡</title> </head> <body> <canvas id="canvas" width="500" height="500" style="border: 1px solid #000"></canvas> <script> const canvas = document.getElementById('canvas') const ctx = canvas.getContext('2d') const textArr = ['未中奖', '一等奖', '二等奖'] //随机生成一个中奖信息 const msg = textArr[Math.floor(Math.random() * textArr.length)] ctx.font = '48px serif' ctx.textAlign = 'center' ctx.textBaseline = 'middle' ctx.fillStyle = 'red' ctx.fillText(msg, canvas.width / 2, canvas.height / 2) //中奖信息作为画布的背景图片 const img = canvas.toDataURL('image/png', 1) canvas.style.background = `url(${img})` //覆盖层 ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = '#eee' ctx.fillRect(0, 0, 500, 500) //鼠标划擦 //鼠标移动时,不断绘制正方形 let isDraw = false canvas.addEventListener('mousedown', (e) => { isDraw = true //将绘制后的目标区域设置为透明 ctx.globalCompositeOperation = 'destination-out' }) canvas.addEventListener('mousemove', (e) => { if (!isDraw) return const x = e.clientX const y = e.clientY ctx.fillStyle = '#000' ctx.fillRect(x + 2, y + 2, 20, 20) }) canvas.addEventListener('mouseup', (e) => { isDraw = false }) </script> </body> </html>
import { useMemo, useEffect, useRef } from 'react'; import isDev from '../utils/isDev'; import { isFunction } from '../utils'; import { debounce } from 'lodash-es'; type noop = (...args: any[]) => any; export interface DebounceOptions { wait?: number; leading?: boolean; trailing?: boolean; maxWait?: number; } function useDebounceFn<T extends noop>(fn: T, options?: DebounceOptions) { if (isDev) { if (!isFunction(fn)) { console.error(`useDebounceFn expected parameter is a function, got ${typeof fn}`); } } const wait = options?.wait ?? 1000; const ref = useRef(fn); ref.current = fn; const debounced = useMemo( () => // 注意 debounce 返回一个函数 debounce( (...args: Parameters<T>): ReturnType<T> => { // 注意,如果这里直接是用 fn(...args) 则每次都是同一个 fn,所以需要借助 useRef,表示引用对象,会指向同一个 fn,所以 // 通过将新的 fn 赋值给 current, 引用对象是可以感知的 return ref.current(...args); }, wait, options, ), [], ); useEffect(() => { return () => { debounced.cancel(); }; }, []); return { run: debounced, cancel: debounced.cancel, flush: debounced.flush, }; } export default useDebounceFn;
# CS416 Programming Assignment 1 This assignment consists of several parts. Each part includes an implementation component and several questions to answer. Modify this README file with your answers. Only modify the specified files in the specified way. Other changes will break the programs and/or testing infrastructure. You are encouraged to develop and perform correctness testing on the platform of your choice, but you should answer the questions below based on your testing on the *ada* cluster, and specifically the compute nodes of the cluster (which have more cores than the head node). Recall that you don't access the compute nodes directly, instead you submit jobs to the queueing system (SLURM) which executes jobs on your behalf. Thus you will test your program by submitting cluster jobs and reviewing the output. ## Getting Started 1. Connect to *ada* via `ssh username@ada.middlebury.edu` (if you are off-campus you will need to use the VPN), logging in with your regular Middlebury username and password (i.e. replace `username` with your username). When you connect to *ada* you are logging into the cluster "head" node. You should use this node for compilation, interacting with GitHub, and other "administrative" tasks, but all testing will occur via submitting jobs to the cluster's queueing system. 2. Clone the assignment skeleton from GitHub to *ada* or copy from the files from your local computer. 3. Load the CS416 environment by executing the following: ``` module use /home/mlinderman/modules/modulefiles module load cs416/s23 ``` These commands configure the environment so that you can access the tools we use in class. You will need to execute these commands every time you log in. Doing so is tedious, so instead you can add the two lines your `.bash_profile` file (at `~/.bash_profile`) so they execute every time you login. 4. Prepare the skeleton for compilation In the root directory of the skeleton, prepare for compilation by invoking `cmake3 .`. Note the *3*. You will need to explicitly invoke `cmake3` on *ada* to get the correct version, on other computers it will just be `cmake`. You only need to do this once. 5. Change to the assignment directory and compile the assignment programs ``` cd pa1 make ``` 6. Submit a job to the cluster to test your programs The assignment directory includes `ada-submit`, a starter submission script. Modify this BASH script to invoke your assignment programs for testing. In the following example I submitted the script with the `sbatch` command. SLURM (the cluster job queueing system) responded that it created job 4238. ``` [mlinderman@ada pa1]$ sbatch ada-submit Submitted batch job 4238 ``` I then checked the cluster status to see if that job is running (or pending). If you don't see your job listed, it has already completed. ``` [mlinderman@ada pa1]$ squeue JOBID PARTITION NAME USER ST TIME NODES NODELIST(REASON) 4238 short pa1 mlinderm R 0:09 1 node004 ``` And when it is done, I reviewed the results by examining the output file `pa1-4238.out` created by SLURM (i.e. `pa1-<JOB ID>.out`). Review the guide on Canvas for more details on working with *ada*. Each subsequent time you work on the assignment you will need start with steps 1 and 3 above, then recompile the test program(s) and resubmit your cluster job each time you change your program. ## Part 1: Mandelbrot images or 2-D parallelism ### Introduction The `mandlebrot-main` program will generate `mandelbrot-serial.ppm`, a fractal image visualizing the Mandelbrot set. Most platforms should have a PPM viewer. When using *ada* you will need to copy the images back to your local computer to view them. Each pixel corresponds to a point in the complex plane, with the brightness proportional to the difficulty (computational cost) of determining whether that point is contained in the Mandelbrot set. ![Mandelbrot Image](mandelbrot-example.png) Assuming you have run CMake in the root directory, you can compile your programs with `make mandelbrot-main`. The main program will automatically check the correctness of each implementation, printing out the first indexes (and values) where your implementation is not sufficiently close to the reference implementation. You will not be able to run the "next" function until the preceding is correct. ### Implementation #### Using C++ threads In the `MandelbrotThreads` function in <mandelbrot.cc>, implement the Mandelbrot image generation using exactly `num_threads` [C++ threads](http://www.cplusplus.com/reference/thread/thread/), including the "master" thread (i.e. the caller should be able set `num_threads` to any value and your code should work correctly). Do not re-implement the Mandelbrot computation itself, instead your threaded implementation should ultimately call `MandelbrotSerial` in each thread. Recall that you launch a C++ thread by constructing a `std::thread` object with a function you want to execute in that thread and any arguments to be provided to that function. `MandelbrotThreads` should be fully self-contained, i.e. it should launch and join all threads before returning. Your solution should use a static work allocation and not require any synchronization. The following example, adapted from the `[cplusplus.com](http://www.cplusplus.com/reference/thread/thread/) shows an example creating two threads in addition to the "master" thread. ```cpp #include <thread> void Foo() { // do stuff... } void Bar(int x) { // do stuff... } int main() { std::thread threads[2]; threads[0] = std::thread(foo); // Spawn new thread that calls foo() threads[1] = std::thread(bar, 0); // Spawn new thread that calls bar(0) // Foo, Bar and this function are now executing concurrently // Synchronize threads: threads[0].join(); // Pauses until "Foo" thread finishes threads[1].join(); // pauses until "Bar" thread finishes return 0; } ``` The skeleton contains an implementation with two threads where each thread computes half the image (i.e. the bottom or the top half). Start by extending this implementation to work with any number of threads (as described above), partitioning the image accordingly. After you have successfully implemented `MandelbrotThreads`, test it with different numbers of threads by changing the `--threads` command line option, e.g. ``` ./mandelbrot-main --threads 2 ``` then answer the questions below. #### Using ISPC to target the SIMD execution units and processor cores While your threaded program could exploit multiple cores, it does not take advantage of the processor's SIMD execution units. And in fact, for several programs we use a compiler `#pragma` to prevent the compiler from automatically generating vectorized code for the serial implementation (to a have a truly serial baseline for benchmarking purposes). Our goal is to use IPSC, the [Intel SPMD Program Compiler](https://ispc.github.io), to simultaneously exploit the SIMD execution unit and multiple cores! Above you explicitly created threads and assigned work to those threads (an *imperative* approach). With ISPC you will instead describe what computations are independent; ISPC will be responsible for mapping those computations to the available computational resources (a *declarative* approach). The `mandelbrot.ispc` file includes an implementation, `MandelbrotISPC` for generating the Mandelbrot image in the IPSC language. While this looks like C/C++ code, it is not. This file is compiled by ipsc to generate executable code that can be called from a C++ program. The `export` keyword indicates that this function should be callable from the C++ application code. Recall that the IPSC execution model is very different. In the SPMD model, multiple instances of a program are executed in parallel on different data. Here multiple instances of the ISPC program are executed in parallel on the processor's SIMD execution units. ISPC calls this group of concurrently running program instances a "gang". The number of these instances is determined at compiler time (and is chosen to match the vector width of the SIMD unit, e.g. 8). You can access the number of instances in the gang with the special `programCount` variable and each instance's unique index in the gang via the `programIndex` variable. You can think of the call from C++ to the ISPC as spawning `programCount` concurrent program instances. The gang of instances run the program to completion and then control returns back to the calling C++ code. The ISPC code below (from the ISPC documentation) interleaves computing each array element across the program instances. ```cpp for (uniform int i = 0; i < count; i += programCount) { float d = data[i + programIndex]; float r = .... result[i + programIndex] = r; } ``` The code above explicitly maps the iteration space to specific program instances. Instead it is more concise, and more powerful, to declaratively express what computations are independent and thus could be executed concurrently. And then let the compiler decide how to map the iteration space to specific program instances. The `foreach` loop used in the skeleton does the latter. Before proceeding, review the ISPC language constructs by reading through the [documentation](https://ispc.github.io/documentation.html) and particularly the [example walkthrough](https://ispc.github.io/example.html), which is similar to the problem we are working on here. Run the benchmark program. What do you observe about the ISPC implementation? Make sure to answer the questions below. So far the ISPC implementation is only using one core. We can use ISPC tasks to take advantage of multiple cores. The `MandelbrotISPCTasks` function uses the `launch[1]` keyword to launch a single Mandelbrot task that computes the entire image. Adapt this function to launch an arbitrary number of tasks, each of which computes a different region of the image. Just as `foreach` specifies which computations are independent and can be performed by different program instances, `launch` specifies which tasks are independent and can executed on different cores. After you have re-implemented the `MandelbrotISPCTasks` function successfully, experiment with different values for the `--tasks` command line option, i.e. ``` ./mandelbrot-main --tasks 8 ``` to run the program. By thoughtfully setting the number of tasks you should be able to achieve a many fold speedup! As above, make sure to answer the questions below. ### What to turn in for this part You should have modified the `MandelbrotThreads` function in `mandelbrot.cc` and the `MandelbrotISPCTasks` function in `mandelbrot.ispc`. The test program should run to completion without reporting any errors. Answer the following questions by editing this README (i.e. place your answer after the question, update any tables, etc.). Your answers should be on the order of several sentences. Some questions may require you to revisit your implementation. 1. Fill in the following table with the speedup you observed on *ada* for your threaded implementation. Do you observe effectively linear speedup? In your answer hypothesize why you observe the speedups that you do, especially for small numbers of cores. As a hint, the data point for 3 cores can be particularly informative. ``` ANSWER This is a not a linear speedup, it is more of a logarithmic speedup (when graphing the points (x = cores, y = speedup) it looked to resemble a 4.5*log(x) line). This occurs because the Mandelbrot set has different color complexities (in our case white or black) based on their computatinal cost. Since this image is not symetrical once it is split into more planes than two, the time that it takes to compute each thread will be different. This is exposed by the 3, because the middle of the Mandlebrot set is more difficult to compute than the edges, so the x3 speedup is actually larger than the x2. ``` *** Seen in pa1-111892.out *** | Cores | Speedup | | ----- | ------- | | 1 | 1.000X | | 2 | 1.959X | | 3 | 1.610X | | 4 | 2.356X | | 8 | 3.832X | | 18 | 5.624X | | 36 | 6.404X | 2. To investigate your hypothesis, measure the amount of time each thread spends to compute its portion of the image. You can do so by inserting timing code at the beginning and end of your worker function, e.g. ```cpp double startTime = CycleTimer::currentSeconds(); ... double endTime = CycleTimer::currentSeconds(); ``` How do your measurements explain your speedup results? ``` ANSWER ** Note, the manelbrot-main runs each 3 times, so had to insert ID to figure out which were apart of the same run ** *** Time Output seen in pa1-111895.out *** When adding the timing, it was evident that for the 2 threads, the amount of work was fairly even (because symmetrical), but when the three threads were computing, the middle image thread took way longer to complete (~0.3 for middle, ~0.1 for edges). This fact confirms our initial hypothesis that the work on each thread is not evenly distributed so it takes longer for 3 threads than 2. ``` 3. You should be able to achieve a speedup **>7X** with 8 threads on a single *ada* node. If your implementation already does so you are done. If not, revise your static work decomposition (which should work for any number of threads) to achieve the specified performance level. How did you change your work decomposition? Report your final speedup for 8 threads. *** Seen in pa1-111901.out *** | Cores | Speedup | | ----- | ------- | | 8 | 7.022X | ``` *** ANSWER *** The orginal decomposition was to break the work into chunks based on num_threads, however after an analysis in question 1&2 we saw that this didn't work because of an uneven work distribution. So, instead of breaking into chunks, instead we would do line by line computation such that the total number of lines assigned to each thread is even, however it is more evenly distributed throughout the image. So instead of the image being split like 111,222,333 it is 123,123,123 (lines) ``` 4. The ISPC compiler is configured for 8-wide AVX2 instructions. What is the ideal speedup would you expect for the ISPC code (without tasks). Why might your results be less than ideal? Consider what characteristics of this computation might limit SIMD performance. ``` *** ANSWER *** The ideal speedup for an ISPC compiler configured for 8-wide AVX2 instruction would be x8 because you could divide the work into 8 different processors. However, it is difficult to speed up to the full maount because there are micro load imblances in the SIMD performace. When executing, the vector being computed is only as fast as its slowest operation, so it must wait until all computations are finished to move to the next vector. Therefore, it is not perfectly vecotrizable and will not reach the full x8 speedup expected. ``` 5. Experiment with different numbers of tasks. Report the best speedup you achieved and the number of tasks. Why do you think that number of tasks was best? ``` *** ANSWER *** I experimented with values in increments from 36 to 256 and foudn that the maxium value being around 210 tasks and 81.851X speedup. This can be seen in the pa1-111985.out file. I think that this number (or around this number) is the best because it is using all the computational power it can with 36 cores and using a vectorized computational appraoch because of the ISCP implementation ``` ## Part 2: Sqrt ### Introduction The `sqrt.cc` file contains an iterative implementation for `sqrt`. To avoid division (which can be very slow), we actually compute the reciprocal square root of $$S$$ by solving the equation $$\frac{1}{x^2}-S=0$$ using [Newton's method for root-finding method](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Iterative_methods_for_reciprocal_square_roots). The iterative relation is $$x_{i+1}=\frac{x_i}{2}(3-Sx_{i}^{2})$$. The figure below shows the number of iterations required to converge to a specific accuracy for inputs in the range 0-3 (this implementation does not converge for inputs outside of that range) with an initial guess of 1.0. Notice that the number of iterations required grows when the initial guess is less accurate. ![sqrt Iterations](sqrt-iterations.png) You can compile this part with `make sqrt-main`. ### Implementation #### Good and Bad Inputs The skeleton provides a serial implementation as well ISPC implementations with and without tasks. Experiment with these implementations and then answer the questions below. #### Intel SIMD intrinsics Now that you have some experience targeting the processor's SIMD execution units using ISPC, we are going to do the same but with the compiler's SIMD intrinsics. Recall that compiler intrinsics are treated like functions but directly map to processor instructions. In the `SqrtIntrinsics` function in `sqrt.cc`, implement the `sqrt` computation using Intel SIMD intrinsics. We are targeting the AVX2 extensions, which provide 256-bit vectors (i.e. 8 32-bit `float`s). The `__m256` represents 8-wide vector of floats. Add the `--intrinsics` argument so that the `main` function will benchmark your function and test it for correctness, i.e., `./sqrt-main --intrinsics`. You should not use the AVX-512 extensions. **You are not permitted to use any of the sqrt intrinsics, e.g. `_mm256_rsqrt_ps`.** Check out the [Intel Instrinsics Guide](https://software.intel.com/sites/landingpage/IntrinsicsGuide/) for a searchable list of intrinsic functions you can use in your code. The skeleton includes some helper functions that may useful to you. There are many possible solutions, but as a starting point attempt to directly translate the serial code into the corresponding intrinsic functions. Your solution will still need to include C++ control flow, e.g. a `while` loop. Make sure to answer the questions below. ### What to turn in for this part You should have modified the `SqrtIntrinsics` function in `sqrt.cc`. The test program should run to completion without reporting any errors. Answer the following questions by editing this README (i.e. place your answer after the question, update any tables, etc.). Your answers should be on the order of several sentences. Some questions may require you to revisit your implementation. 1. Report speedups vs. the sequential implementation you obtain for both ISPC implementations when using all the cores for the random input. | Implementation | Speedup | | --------------- | ------- | | ISPC | | | ISPC with tasks | | 2. Modify the inputs generated in the `sqrt-main.cc` test program (look for the TODO) to obtain the **best** possible speedup for the ISPC implementation (without tasks). Report the speedups you obtained. Describe the input you identified and briefly explain why the ISPC implementations are faster for that input. | Implementation | Speedup | | --------------- | ------- | | ISPC | | 3. Modify the inputs generated in the `sqrt-main.cc` test program (look for the TODO) to obtain the **worst** possible speedup for the ISPC implementation (with tasks). Report the speedups you obtained. Describe the input you identified and briefly explain why the ISPC implementations are less efficient for that input. | Implementation | Speedup | | --------------- | ------- | | ISPC | | 4. Report the speedup for your intrinsic implementation compared to the serial implementation for the random input. To get full credit your implementation should have similar or better performance than the ISPC implementation. | Implementation | Speedup | | --------------- | ------- | | ISPC | | | Intrinsics | | 5. *Bonus competition* Recall that SIMD control flow is implemented with masking. ISPC masks the computations in the inner "while" loop once the specified tolerance is reached. Is that masking needed? Attempt to improve the performance of the ISPC implementation by optimizing the masking. As a hint, investigate the [`unmasked` block`](https://ispc.github.io/ispc.html#re-establishing-the-execution-mask) in the ISPC language. Gradescope will record the execution time for the your ISPC implementation and the performance will be subsequently evaluated on Ada. The fastest implementation will win a prize! ## Part 3: SAXPY ### Introduction SAXPY is a level-1 routine in the widely used and heavily optimized BLAS (Basic Linear Algebra Subproblems) library. BLAS provides functions for a variety of linear algebra operations. SAXPY implements "Single precision A*X+Y" where A is a scalar and X and Y are arrays. Our implementation performs SAXPY on 20 million elements. You can compile this part with `make saxpy-main`. ### Implementation #### Using ISPC to target the SIMD execution units and processor cores In `saxpy.ispc` implement the `SaxpyISPCTask` and `SaxpyISPCTasks` functions to create an ISPC implementation with tasks. Your implementations will look similar to our previous ISPC implementations. Your task-based implementation should use the specified number of tasks. After you have implemented these functions successfully, experiment with different values for the `--tasks` command line option, e.g. ``` ./saxpy-main --tasks 8 ``` ### What to turn in for this part You should have modified the he `SaxpyISPCTask` and `SaxpyISPCTasks` functions in `saxpy.ispc`. The test program should run to completion without reporting any errors. Answer the following questions by editing this README (i.e. place your answer after the question, update any tables, etc.). Your answers should be on the order of several sentences. 1. Run SAXPY with different number of tasks. What kind of speedups relative to the serial implementation do you observe? Do you think it would be possible to re-implement SAXPY to get (near) linear speedup? As a hint, think about what might be the limiting aspect of this computation? Is the limit the arithmetic throughput (how many arithmetic operations the processor can perform), memory bandwidth of something else? 2. We implement SAXPY to overwrite one of the inputs with the result values (this is the interface used by the optimized BLAS library). If we changed the interface to have a distinct result array, do you think speedups would increase or decrease? Make you answer quantitative by comparing the FLOP/byte, i.e. the "arithmetic intensity" of the two implementations. As a hint, the distinct result array implementation will load from or store to memory a total of `4 * n * sizeof(float)` bytes or `4 * sizeof(float)` bytes per iteration (the 4 is not a typo, think about how caches work under a write-allocate model). ## Grading Assessment | Requirements -------|-------- **N**eeds revision | Some but not all components compile. Some but not all components are correct, or some but not all questions are answered *except* the intrinsic implementation for Sqrt. **M**eets Expectations | All components (Mandelbot, Sqrt and Saxpy) are correct, you meet the specified performance targets and your answers to the embedded questions meet expectations *except* the intrinsic implementation for Sqrt. **E**emplary | All requirements for *Meets Expectations* and the intrinsic implementation for Sqrt is correct and meets specified performance targets. ### Acknowledgements This assignment was adapted from a course taught by Kayvon Fatahalian and Kunle Olukotun.
function resizeTest(plugin) %writeTests(plugin) % Checks to see if automatic resizing of images is working properly for a % given videoReader/videoWriter plugin using some quick heuristics. % %Examples: % resizeTest % resizeTest ffmpegPopen2 % linux & similar % resizeTest ffmpegDirect % ...if system's gcc is compatible w/ Matlab's % resizeTest DirectShow % Windows ienter if nargin < 1, plugin = defaultVideoIOPlugin; end W = 640; H = 480; fname = [tempname '.avi']; try vw = videoWriter(fname, plugin, 'width',W, 'height',H); widths = 4:40:640; for i=1:length(widths) w = widths(i); frame = psychedelicFrame(w,w,i); addframe(vw, frame); end vw = close(vw); vr = videoReader(fname, plugin); info = get(vr); %#ok<NASGU> vrassert W == info.width; vrassert H == info.height; vr = close(vr); %#ok<NASGU> delete(fname); catch e = lasterror; try close(vw); catch end delete(fname); rethrow(e); end iexit
#!/usr/bin/env python3 ## Coding: UTF-8 ## Author: mjanez@tragsa.es ## Institution: - ## Project: - # inbuilt libraries import logging import os # Logging def log_file(log_folder): ''' Starts the logger --log_folder parameter entered Parameters ---------- - log_folder: Folder where log is stored Return ---------- Logger object ''' logger = logging.getLogger() for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) if not os.path.exists(log_folder): os.makedirs(log_folder) logging.basicConfig( handlers=[logging.FileHandler(filename=log_folder + "/geopostgis-manager.log", encoding='utf-8', mode='a+')], format="%(asctime)s %(levelname)s::%(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO ) return logger
# Copyright (C) 2019 Greenbone Networks GmbH # Text descriptions are largely excerpted from the referenced # advisory, and are Copyright (C) the respective author(s) # # SPDX-License-Identifier: GPL-2.0-or-later # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. if(description) { script_oid("1.3.6.1.4.1.25623.1.0.704542"); script_version("2019-10-07T02:00:11+0000"); script_cve_id("CVE-2019-12384", "CVE-2019-14439", "CVE-2019-14540", "CVE-2019-16335", "CVE-2019-16942", "CVE-2019-16943"); script_tag(name:"cvss_base", value:"7.5"); script_tag(name:"cvss_base_vector", value:"AV:N/AC:L/Au:N/C:P/I:P/A:P"); script_tag(name:"last_modification", value:"2019-10-07 02:00:11 +0000 (Mon, 07 Oct 2019)"); script_tag(name:"creation_date", value:"2019-10-07 02:00:11 +0000 (Mon, 07 Oct 2019)"); script_name("Debian Security Advisory DSA 4542-1 (jackson-databind - security update)"); script_category(ACT_GATHER_INFO); script_copyright("Copyright (C) 2019 Greenbone Networks GmbH"); script_family("Debian Local Security Checks"); script_dependencies("gather-package-list.nasl"); script_mandatory_keys("ssh/login/debian_linux", "ssh/login/packages", re:"ssh/login/release=DEB(10|9)"); script_xref(name:"URL", value:"https://www.debian.org/security/2019/dsa-4542.html"); script_xref(name:"URL", value:"https://security-tracker.debian.org/tracker/DSA-4542-1"); script_tag(name:"summary", value:"The remote host is missing an update for the 'jackson-databind' package(s) announced via the DSA-4542-1 advisory."); script_tag(name:"vuldetect", value:"Checks if a vulnerable package version is present on the target host."); script_tag(name:"insight", value:"It was discovered that jackson-databind, a Java library used to parse JSON and other data formats, did not properly validate user input before attempting deserialization. This allowed an attacker providing maliciously crafted input to perform code execution, or read arbitrary files on the server."); script_tag(name:"affected", value:"'jackson-databind' package(s) on Debian Linux."); script_tag(name:"solution", value:"For the oldstable distribution (stretch), these problems have been fixed in version 2.8.6-1+deb9u6. For the stable distribution (buster), these problems have been fixed in version 2.9.8-3+deb10u1. We recommend that you upgrade your jackson-databind packages."); script_tag(name:"solution_type", value:"VendorFix"); script_tag(name:"qod_type", value:"package"); exit(0); } include("revisions-lib.inc"); include("pkg-lib-deb.inc"); res = ""; report = ""; if(!isnull(res = isdpkgvuln(pkg:"libjackson2-databind-java", ver:"2.9.8-3+deb10u1", rls:"DEB10"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libjackson2-databind-java-doc", ver:"2.9.8-3+deb10u1", rls:"DEB10"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libjackson2-databind-java", ver:"2.8.6-1+deb9u6", rls:"DEB9"))) { report += res; } if(!isnull(res = isdpkgvuln(pkg:"libjackson2-databind-java-doc", ver:"2.8.6-1+deb9u6", rls:"DEB9"))) { report += res; } if(report != "") { security_message(data:report); } else if(__pkg_match) { exit(99); } exit(0);
use std::{fs::File, io::{BufReader, BufRead, Read}, path::PathBuf}; #[tauri::command] pub async fn read_text_file(file_path: &str) -> Result<Option<Vec<String>>, ()> { let file = match File::open(file_path) { Ok(f) => f, Err(e) => { eprintln!("{:?}", e); return Ok(None); }, }; let reader = BufReader::new(file); let mut lines = Vec::<String>::new(); for line in reader.lines() { if line.is_err() { unsafe { eprintln!("{:?}", line.unwrap_err_unchecked()); } return Ok(None); } let line = line.unwrap(); lines.push(line); } return Ok(Some(lines)); } #[tauri::command] pub fn is_file_openable_as_text(file_path: &str) -> bool { match File::open(file_path) { Ok(mut f) => { let mut buffer = String::new(); match f.read_to_string(&mut buffer) { Ok(_) => true, Err(_) => false, } }, Err(_) => false, } } #[tauri::command] pub async fn get_file_name(file_path: &str) -> Result<Option<String>, ()> { let path = PathBuf::from(file_path); match path.file_name() { Some(name) => Ok(Some(name.to_string_lossy().into_owned())), None => Ok(None), } }
// // LoadNewsFromRemoteUseCaseTest.swift // CryptoListTests // // Created by Ihwan on 13/02/22. // import XCTest @testable import CryptoList class LoadNewsFromRemoteUseCaseTest: XCTestCase { func test_init_doesNotRequestDataFromURL() { let (_, client) = makeSUT() XCTAssertTrue(client.requestedURLs.isEmpty) } func test_loadTwice_requestsDataFromURLTwice() { let url = URL(string: "https://a-given-url.com")! let (sut, client) = makeSUT(url: url) sut.load { _ in } sut.load { _ in } XCTAssertEqual(client.requestedURLs, [url, url]) } func test_load_deliversConnectivityErrorOnClientError() { let (sut, client) = makeSUT() expect(sut, toCompleteWith: .failure(.connectivity), when: { let clientError = NSError(domain: "Test", code: 0) client.complete(with: clientError) }) } func test_load_deliversInvalidDataErrorOnNon200HTTPResponse() { let (sut, client) = makeSUT() let samples = [199, 201, 300, 400, 500] samples.enumerated().forEach { index, code in expect(sut, toCompleteWith: .failure(.invalidData), when: { let json = makeDataJSON([]) client.complete(withStatusCode: code, data: json, at: index) }) } } func test_load_deliversInvalidDataErrorOn200HTTPResponseWithInvalidJSON() { let (sut, client) = makeSUT() expect(sut, toCompleteWith: .failure(.invalidData), when: { let invalidJSON = Data("invalid json".utf8) client.complete(withStatusCode: 200, data: invalidJSON) }) } private func makeSUT(url: URL = URL(string: "https://a-url.com")!, file: StaticString = #filePath, line: UInt = #line) -> (sut: NewsService, client: HTTPClientSpy) { let client = HTTPClientSpy() let sut = NewsServiceAPI(url: url, client: client) trackForMemoryLeaks(sut, file: file, line: line) trackForMemoryLeaks(client, file: file, line: line) return (sut, client) } private func makeDataJSON(_ data: [[String: Any]]) -> Data { let json = ["Data": data] return try! JSONSerialization.data(withJSONObject: json) } } extension LoadNewsFromRemoteUseCaseTest { func expect(_ sut: NewsService, toCompleteWith expectedResult: Result<[News], NewsServiceAPI.Error>, when action: () -> Void, file: StaticString = #filePath, line: UInt = #line) { let exp = expectation(description: "Wait for load completion") sut.load { receivedResult in switch (receivedResult, expectedResult) { case let (.success(receivedItems), .success(expectedItems)): XCTAssertEqual(receivedItems, expectedItems, file: file, line: line) case let (.failure(receivedError as NewsServiceAPI.Error), .failure(expectedError)): XCTAssertEqual(receivedError, expectedError, file: file, line: line) default: XCTFail("Expected result \(expectedResult) got \(receivedResult) instead", file: file, line: line) } exp.fulfill() } action() waitForExpectations(timeout: 0.1) } }
import { createApp } from "vue" import App from "./App.vue" import router from "./router" import { initSocket } from "./socket" import { Button, Input, setConfig, frappeRequest, resourcesPlugin, FormControl, } from "frappe-ui" import EmptyState from "@/components/EmptyState.vue" import { IonicVue } from "@ionic/vue" import { session } from "@/data/session" import { userResource } from "@/data/user" import { employeeResource } from "@/data/employee" import dayjs from "@/utils/dayjs" import getIonicConfig from "@/utils/ionicConfig" import FrappePushNotification from "../public/frappe-push-notification" /* Core CSS required for Ionic components to work properly */ import "@ionic/vue/css/core.css" /* Theme variables */ import "./theme/variables.css" import "./main.css" const app = createApp(App) const socket = initSocket() setConfig("resourceFetcher", frappeRequest) app.use(resourcesPlugin) app.component("Button", Button) app.component("Input", Input) app.component("FormControl", FormControl) app.component("EmptyState", EmptyState) app.use(router) app.use(IonicVue, getIonicConfig()) if (session?.isLoggedIn && !employeeResource?.data) { employeeResource.reload() } app.provide("$session", session) app.provide("$user", userResource) app.provide("$employee", employeeResource) app.provide("$socket", socket) app.provide("$dayjs", dayjs) const registerServiceWorker = async () => { window.frappePushNotification = new FrappePushNotification("hrms") if ("serviceWorker" in navigator) { let serviceWorkerURL = "/assets/hrms/frontend/sw.js" let config = "" try { config = await window.frappePushNotification.fetchWebConfig() serviceWorkerURL = `${serviceWorkerURL}?config=${encodeURIComponent( JSON.stringify(config) )}` } catch (err) { console.error("Failed to fetch FCM config", err) } navigator.serviceWorker .register(serviceWorkerURL, { type: "classic", }) .then((registration) => { if (config) { window.frappePushNotification.initialize(registration).then(() => { console.log("Frappe Push Notification initialized") }) } }) .catch((err) => { console.error("Failed to register service worker", err) }) } else { console.error("Service worker not enabled/supported by the browser") } } router.isReady().then(() => { if (import.meta.env.DEV) { frappeRequest({ url: "/api/method/hrms.www.hrms.get_context_for_dev", }).then((values) => { if (!window.frappe) window.frappe = {} window.frappe.boot = values registerServiceWorker() app.mount("#app") }) } else { registerServiceWorker() app.mount("#app") } }) router.beforeEach(async (to, from, next) => { let isLoggedIn = session.isLoggedIn try { if (isLoggedIn) await userResource.reload() } catch (error) { isLoggedIn = false } if (!isLoggedIn && to.name !== "Login") { next({ name: "Login" }) } else if (isLoggedIn && to.name !== "InvalidEmployee") { await employeeResource.promise // user should be an employee to access the app // since all views are employee specific if ( !employeeResource?.data || employeeResource?.data?.user_id !== userResource.data.name ) { next({ name: "InvalidEmployee" }) } else if (to.name === "Login") { next({ name: "Home" }) } else { next() } } else { next() } })
/******************************************************************** * \file RendererManager.h * \brief Renderer Manager, manage renderer(s) and render targets * * \author Lancelot 'Robin' Chen * \date June 2022 *********************************************************************/ #ifndef RENDERER_MANAGER_H #define RENDERER_MANAGER_H #include "RenderTarget.h" #include "Frameworks/SystemService.h" #include "Frameworks/Rtti.h" #include "GameEngine/IRenderer.h" #include "GameEngine/RenderBufferRepository.h" #include <system_error> #include <memory> #include <unordered_map> #include <functional> namespace Enigma::Renderer { class RenderElementBuilder; using error = std::error_code; using CustomRendererFactoryFunc = std::function<Engine::IRendererPtr(const std::string&)>; /** Renderer Manager Service */ class RendererManager : public Frameworks::ISystemService { DECLARE_EN_RTTI; public: RendererManager(Frameworks::ServiceManager* srv_mngr); RendererManager(const RendererManager&) = delete; RendererManager(RendererManager&&) = delete; virtual ~RendererManager() override; RendererManager& operator=(const RendererManager&) = delete; RendererManager& operator=(RendererManager&&) = delete; /// On Init virtual Frameworks::ServiceResult onInit() override; /// On Term virtual Frameworks::ServiceResult onTerm() override; /** register renderer factory */ static void RegisterCustomRendererFactory(const std::string& type_name, const CustomRendererFactoryFunc& fn); /** create renderer */ error CreateRenderer(const std::string& name); /** create custom renderer */ error CreateCustomRenderer(const std::string& type_name, const std::string& name); /** insert renderer */ error InsertRenderer(const std::string& name, const Engine::IRendererPtr& renderer); /** destroy renderer by name : remove from map, & destroy */ error DestroyRenderer(const std::string& name); /** get renderer */ Engine::IRendererPtr GetRenderer(const std::string& name) const; /** create render target */ error CreateRenderTarget(const std::string& name, RenderTarget::PrimaryType primary, const std::vector<Graphics::RenderTextureUsage>& usages); /** destroy render target by name : remove from map, & destroy */ error DestroyRenderTarget(const std::string& name); /** get render target */ RenderTargetPtr GetRenderTarget(const std::string& name) const; /** get primary render target */ RenderTargetPtr GetPrimaryRenderTarget() const; protected: void ClearAllRenderer(); void ClearAllRenderTarget(); void DoCreatingRenderer(const Frameworks::ICommandPtr& c); void DoDestroyingRenderer(const Frameworks::ICommandPtr& c); void DoCreatingRenderTarget(const Frameworks::ICommandPtr& c); void DoDestroyingRenderTarget(const Frameworks::ICommandPtr& c); void DoResizingPrimaryTarget(const Frameworks::ICommandPtr& c) const; void DoChangingViewPort(const Frameworks::ICommandPtr& c) const; void DoChangingClearingProperty(const Frameworks::ICommandPtr& c) const; protected: Frameworks::CommandSubscriberPtr m_doCreatingRenderer; Frameworks::CommandSubscriberPtr m_doDestroyingRenderer; Frameworks::CommandSubscriberPtr m_doCreatingRenderTarget; Frameworks::CommandSubscriberPtr m_doDestroyingRenderTarget; Frameworks::CommandSubscriberPtr m_doResizingPrimaryTarget; Frameworks::CommandSubscriberPtr m_doChangingViewPort; Frameworks::CommandSubscriberPtr m_doChangingClearingProperty; using RendererMap = std::unordered_map<std::string, Engine::IRendererPtr>; using RenderTargetMap = std::unordered_map<std::string, RenderTargetPtr>; RendererMap m_renderers; RenderTargetMap m_renderTargets; std::string m_primaryRenderTargetName; unsigned int m_accumulateRendererStamp; ///< 記錄哪些stamp bit已經被使用過 using CustomRendererFactoryTable = std::unordered_map<std::string, CustomRendererFactoryFunc>; static CustomRendererFactoryTable m_customRendererFactoryTable; }; }; #endif // RENDERER_MANAGER_H
import React, { useContext, useEffect } from "react"; import { useState } from "react"; import { auth, database } from "../firebase"; const AuthContext = React.createContext(); export function useAuth() { return useContext(AuthContext); } export function AuthProvider({ children }) { const [currentUser, setCurrentUser] = useState(); const [loading, setLoading] = useState(true); function signup(email, password, data) { return auth.createUserWithEmailAndPassword(email, password).then((doc) => { database.collection("users").doc(doc.user.uid).set(data); }); } function login(email, password) { return auth.signInWithEmailAndPassword(email, password); } function logout() { return auth.signOut(); } useEffect(() => { const unsubscribe = auth.onAuthStateChanged((user) => { setCurrentUser(user); setLoading(false); }); return unsubscribe; }, []); const value = { currentUser, login, signup, logout, }; return ( <AuthContext.Provider value={value}> {!loading && children} </AuthContext.Provider> ); }
import PropTypes from 'prop-types'; import React, { PureComponent } from 'react'; import { routerRedux } from 'dva/router'; import { connect } from 'dva'; import { Row, Col, Card } from 'antd'; import BinLocationList from './List'; import BinLocationSearch from './Search'; import BinLocationModal from './Modal'; @connect(({ binLocations, loading }) => ({ binLocations, loading: loading.effects['binLocations/query'], })) class BinLocationsView extends PureComponent { static defaultProps = { binLocations: {}, }; static propTypes = { binLocations: PropTypes.object, }; componentDidMount() { const { dispatch } = this.props; dispatch({ type: 'binLocations/query' }); } render() { const { dispatch, binLocations } = this.props; const { loading, list, pagination, currentItem, modalVisible, modalType, } = binLocations; const binLocationModalProps = { item: modalType === 'create' ? {} : currentItem, type: modalType, visible: modalVisible, onOk(data) { dispatch({ type: `binLocations/${modalType}`, payload: Object.assign({}, currentItem, data), }); }, onCancel() { dispatch({ type: 'binLocations/hideModal' }); }, }; const binLocationListProps = { dataSource: list, loading, pagination, onPageChange(page) { dispatch({ type: 'binLocations/query', payload: { page: page.current, size: page.pageSize, }, }); }, onDeleteItem(id) { dispatch({ type: 'binLocations/delete', payload: id }); }, onEditItem(item) { dispatch({ type: 'binLocations/showModal', payload: { modalType: 'update', currentItem: item, }, }); }, }; const binLocationSearchProps = { onSearch(fieldsValue) { const payload = {}; if (fieldsValue.keyword.length > 0) { if (fieldsValue.field === 'name') { payload.name = fieldsValue.keyword; } } dispatch({ type: 'binLocations/query', payload, }); }, onAdd() { dispatch({ type: 'binLocations/showModal', payload: { modalType: 'create', }, }); }, }; const BinLocationModalGen = () => <BinLocationModal {...binLocationModalProps} />; return ( <div className="content-inner"> <BinLocationSearch {...binLocationSearchProps} /> <BinLocationList {...binLocationListProps} /> <BinLocationModalGen /> </div> ); } } export default BinLocationsView;
export class Employee { constructor(name, typeCode) { this._name = name; this._typeCode = typeCode; } get name() { return this._name; } get type() { return Employee.legalTypeCodes[this._typeCode]; } static get legalTypeCodes() { return { E: 'Engineer', M: 'Manager', S: 'Salesman' }; } static createSeniorEngineer(name) { return new Employee(name, 'SE'); } static createEngineer(name) { return new Employee(name, 'E'); } } const employee = Employee.createEngineer('Elli'); console.log(employee)
import React from 'react' import { ActivityIndicator, View, StyleSheet } from 'react-native' import type { ViewProps as RNViewProps } from 'react-native' import colors from '~/theme/colors' const styles = StyleSheet.create({ container: { display: 'flex', height: '100%', paddingHorizontal: 12, width: '100%', }, loadingWrapper: { alignItems: 'center', bottom: 0, justifyContent: 'center', left: 0, position: 'absolute', right: 0, top: 0, }, }) interface ViewProps extends RNViewProps { children: React.ReactNode isLoading?: boolean } const ContainerView = ({ children, isLoading, style }: ViewProps) => ( <View style={[styles.container, style]}> {isLoading ? ( <View style={styles.loadingWrapper}> <ActivityIndicator size="large" color={colors.secondary} /> </View> ) : ( children )} </View> ) export default ContainerView
"""Python Module in which we define all the need classes for our machine-learning routine. """ # Libraries import torch import polars as pl from pathlib import Path from torch import optim, nn import lightning.pytorch as lg from model import LogisticRegression from torch.utils.data import Dataset, DataLoader from torch.utils.data.dataset import random_split from torchmetrics.classification import BinaryAccuracy # Classes class CustomDataSet(Dataset): def __init__(self, dataframe: pl.DataFrame, columns: list[str], target: str): self.columns = columns self.target = target self.dataframe = dataframe.select(self.columns+[self.target]) def __len__(self): return len(self.dataframe) def __getitem__(self, idx): row = self.dataframe.row(idx, named=True) input_tokens = [row[col] for col in self.columns] label = row[self.target] return torch.tensor(input_tokens), torch.tensor(label, dtype=torch.float) class DataModule(lg.LightningDataModule): def __init__(self, data_path: Path, id_client: int = None, batch_size: int = 64, num_workers: int = 0): super().__init__() self.id_client = id_client self.data_path = data_path self.batch_size = batch_size self.num_workers = num_workers self.features = [] self.n_features = 0 self.obs = 0 def prepare_data(self) -> None: pass def setup(self, stage = None, seed: int = None) -> None: """In this function we setup the dataset. Args: - seed (int): The random seed for the torch.Generator. Default None. Returns: - None """ csv_path = self.data_path/f'hospital_{self.id_client}.csv' if seed: generator = torch.Generator().manual_seed(seed) else: generator = None data = pl.read_csv(csv_path).drop(['encounter_id', 'icu_d', 'icu_stay_type', 'patient_id', 'hospital_id']) numerical_cat = [ 'elective_surgery', 'apache_post_operative', 'arf_apache', 'gcs_unable_apache', 'intubated_apache', 'ventilated_apache', 'aids', 'cirrhosis', 'diabetes_mellitus', 'hepatic_failure', 'immunosuppression', 'leukemia', 'lymphoma', 'solid_tumor_with_metastasis'] categorical = [ 'ethnicity', 'gender', 'icu_admit_source', 'icu_type', 'apache_3j_bodysystem', 'apache_2_bodysystem'] numeric_only = list(set(data.columns)-set(numerical_cat + categorical+['hospital_death'])) # Subsitute the missing values: # - numerical_cat & categorical: mode # - numerical: median data = data.with_columns( [pl.col(col).fill_null(data.get_column(col).mode().item()) for col in numerical_cat + categorical] + [pl.col(col).fill_null(pl.median(col)) for col in numeric_only] ) data = data.with_columns( pl.col('gender').map_dict({'M':0, 'F':1}) ) categorical.remove('gender') data = data.to_dummies(columns=categorical, separator=':') columns = data.columns columns.remove('hospital_death') self.features = columns self.obs, self.n_features = data.shape self.n_features -= 1 dataset = CustomDataSet(data, columns, 'hospital_death') self.training_data, self.test_data, self.validation_data = random_split(dataset, [0.8, 0.1, 0.1], generator) def train_dataloader(self) -> DataLoader: """The function used to return the train DataLoader. Returns: - DataLoader : the train DataLoader. """ return DataLoader(self.training_data, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers) def val_dataloader(self) -> DataLoader: """The function used to return the validation DataLoader. Returns: - DataLoader : the validation DataLoader. """ return DataLoader(self.validation_data, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers) def test_dataloader(self) -> DataLoader: """The function used to return the test DataLoader. Returns: - DataLoader : the test DataLoader. """ return DataLoader(self.test_data, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers) class Classifier(lg.LightningModule): def __init__(self, model: nn.Module, lr: float = 1e-3): super().__init__() self.model = model self.lr = lr def training_step(self, batch, batch_idx: int): x, y = batch y_hat = self.model(x).squeeze(dim=1) criterion = nn.BCEWithLogitsLoss() accuracy_function = BinaryAccuracy() loss = criterion(y_hat, y) acc = accuracy_function(y_hat, y)#(y_hat == y).sum().item() / y.size(0) self.log("training_loss", loss) self.log("training_acc", acc) return loss def test_step(self, batch, batch_idx: int): x, y = batch y_hat = self.model(x).squeeze(dim=1) criterion = nn.BCEWithLogitsLoss() accuracy_function = BinaryAccuracy() test_loss = criterion(y_hat, y) test_acc = accuracy_function(y_hat, y)#(y_hat == y).sum().item() / y.size(0) self.log("test_loss", test_loss) self.log("test_acc", test_acc) return test_loss def validation_step(self, batch, batch_idx: int): x, y = batch y_hat = self.model(x).squeeze(dim=1) criterion = nn.BCEWithLogitsLoss() accuracy_function = BinaryAccuracy() val_loss = criterion(y_hat, y) val_acc = accuracy_function(y_hat, y)#(y_hat == y).sum().item() / y.size(0) self.log("val_loss", val_loss, prog_bar=True, on_step=False, on_epoch=True) self.log("val_lacc", val_acc, prog_bar=True, on_step=False, on_epoch=True) return val_loss def configure_optimizers(self): """Function in which we configure the optimizer. We decided to use the Adam optimizer. """ return optim.Adam(self.parameters(), lr=self.lr) if __name__ == "__main__": seed = 42 current = Path('.') data_path = current/'data' datamodule = DataModule(data_path, num_workers=12) datamodule.prepare_data() datamodule.setup(seed=seed) model = LogisticRegression(datamodule.n_features) clf = Classifier(model, lr=1e-1) trainer = lg.Trainer(max_epochs=30) trainer.fit(clf, datamodule=datamodule) trainer.test(ckpt_path='best', datamodule=datamodule)
<?php namespace App\Http\Controllers; use App\Models\Branch; use App\Models\Coach; use App\Models\Customer; use App\Models\Employee; use App\Models\Expense; use App\Models\Installment; use App\Models\Product; use App\Models\Salary; use App\Models\Subscription; use Carbon\Carbon; use Illuminate\Http\Request; class DashboardController extends Controller { public function getInsights(Request $request) { $customersCount = Customer::count(); $productsCount = Product::count(); $maleCustomersCount = Customer::where('gender' , 'male')->count(); $femaleCustomersCount = Customer::where('gender' , 'female')->count(); $activeCustomers = Customer::whereHas('subscriptions', function ($query) { $query->where('state', 'active'); })->count(); $activeSubscriptions = Subscription::where('state' , 'active')->count(); $inactiveSubscriptions = Subscription::where('state' , 'inactive')->count(); $frozenSubscriptions = Subscription::where('state' , 'frozen')->count(); $unpaidInstallments = Installment::where('paid' , 'false')->count(); $coachesCount = Coach::count(); $employeesCount = Employee::count(); $branchesCount = Branch::count(); return response()->json(['customersCount'=> $customersCount, 'activeCustomers'=> $activeCustomers, 'activeSubscriptions' => $activeSubscriptions , 'frozenSubscriptions' => $frozenSubscriptions , 'unpaidInstallments' => $unpaidInstallments , 'inactiveSubscriptions' => $inactiveSubscriptions , 'coachesCount' => $coachesCount , 'femaleCustomersCount' => $femaleCustomersCount , 'maleCustomersCount' => $maleCustomersCount , 'productsCount' => $productsCount , 'employeesCount' => $employeesCount , 'branchesCount' => $branchesCount ],200); } public function annualProfitsChart(Request $request) { // Initialize an array to store the monthly revenues and expenses $monthlyData = []; // Define an array of month names $monthNames = [ 1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December', ]; // Get the current year $currentYear = Carbon::now()->year; // Loop through each month in the year for ($month = 1; $month <= 12; $month++) { // Calculate the start and end dates of the month $startDate = Carbon::createFromDate($currentYear, $month, 1)->startOfMonth(); $endDate = Carbon::createFromDate($currentYear, $month, 1)->endOfMonth(); // Retrieve the revenues for the month $cashSubscriptions = Subscription::where('subscription_type', '!=', 'installments')->whereBetween('subscription_date', [$startDate, $endDate])->get(['price','sale',]); $installments = Installment::where('paid', true)->whereBetween('updated_at', [$startDate, $endDate])->get(); // Calculate the sum of cash subscription prices $cashRevenue = $cashSubscriptions->sum(function ($subscription) { return $subscription->price - ($subscription->sale ?? 0); }); // Calculate the sum of installment amounts $installmentsRevenue = $installments->sum('amount'); // Calculate the total revenue (cash + installments) $totalRevenue = $cashRevenue + $installmentsRevenue; // Retrieve the expenses for the month $constantExpenses = Expense::where('expense_type' , 'constant')->where('created_at' , '<' , $endDate)->get(); // $constantExpenses = Expense::where('expense_type' , 'constant')->get(); $variableExpenses = Expense::where('expense_type' , 'variable')->whereBetween('created_at',[$startDate, $endDate])->get(); $salaries = Salary::whereBetween('paid_date',[$startDate, $endDate])->get(); // Calculate the sum of constant expenses amounts $constantExpensesTotal = $constantExpenses->sum('expense_cost'); // Calculate the sum of variable expenses amounts $variableExpensesTotal = $variableExpenses->sum('expense_cost'); // Calculate the sum of variable expenses amounts $salariesTotal = $salaries->sum('amount'); // Calculate the total expenses $totalExpense = $constantExpensesTotal + $variableExpensesTotal + $salariesTotal; $monthName = $monthNames[$month]; // Store the monthly revenues and expenses in the array $monthlyData[$monthName] = [ 'revenue' => $totalRevenue, 'expense' => $totalExpense, ]; } // Return the monthly revenues and expenses data return response()->json(['annualProfits' => $monthlyData],200); } }
;; @see https://bitbucket.org/lyro/evil/issue/360/possible-evil-search-symbol-forward ;; evil 1.0.8 search word instead of symbol (setq evil-symbol-word-search t) ;; load undo-tree and ert (add-to-list 'load-path "~/.emacs.d/site-lisp/evil/lib") ;; @see https://bitbucket.org/lyro/evil/issue/511/let-certain-minor-modes-key-bindings (defmacro adjust-major-mode-keymap-with-evil (m &optional r) `(eval-after-load (quote ,(if r r m)) '(progn (evil-make-overriding-map ,(intern (concat m "-mode-map")) 'normal) ;; force update evil keymaps after git-timemachine-mode loaded (add-hook (quote ,(intern (concat m "-mode-hook"))) #'evil-normalize-keymaps)))) (adjust-major-mode-keymap-with-evil "git-timemachine") (adjust-major-mode-keymap-with-evil "browse-kill-ring") (adjust-major-mode-keymap-with-evil "etags-select") (require 'evil) ;; @see https://bitbucket.org/lyro/evil/issue/342/evil-default-cursor-setting-should-default ;; cursor is alway black because of evil ;; here is the workaround (setq evil-default-cursor t) ;; enable evil-mode (evil-mode 1) ;; {{ @see https://github.com/timcharper/evil-surround for tutorial (require 'evil-surround) (global-evil-surround-mode 1) (defun evil-surround-prog-mode-hook-setup () (push '(40 . ("(" . ")")) evil-surround-pairs-alist) (push '(41 . ("(" . ")")) evil-surround-pairs-alist)) (add-hook 'prog-mode-hook 'evil-surround-prog-mode-hook-setup) (defun evil-surround-emacs-lisp-mode-hook-setup () (push '(?` . ("`" . "'")) evil-surround-pairs-alist)) (add-hook 'emacs-lisp-mode-hook 'evil-surround-emacs-lisp-mode-hook-setup) ;; }} ;; {{ For example, press `viW*` (require 'evil-visualstar) (setq evil-visualstar/persistent t) (global-evil-visualstar-mode t) ;; }} ;; {{ https://github.com/gabesoft/evil-mc ;; `grm' create cursor for all matching selected ;; `gru' undo all cursors ;; `grs' pause cursor ;; `grr' resume cursor ;; `grh' make cursor here ;; `C-p', `C-n' previous cursor, next cursor (require 'evil-mc) (global-evil-mc-mode 1) ;; }} (require 'evil-mark-replace) ;; {{ define my own text objects, works on evil v1.0.9 using older method ;; @see http://stackoverflow.com/questions/18102004/emacs-evil-mode-how-to-create-a-new-text-object-to-select-words-with-any-non-sp (defmacro define-and-bind-text-object (key start-regex end-regex) (let ((inner-name (make-symbol "inner-name")) (outer-name (make-symbol "outer-name"))) `(progn (evil-define-text-object ,inner-name (count &optional beg end type) (evil-select-paren ,start-regex ,end-regex beg end type count nil)) (evil-define-text-object ,outer-name (count &optional beg end type) (evil-select-paren ,start-regex ,end-regex beg end type count t)) (define-key evil-inner-text-objects-map ,key (quote ,inner-name)) (define-key evil-outer-text-objects-map ,key (quote ,outer-name))))) ;; between dollar signs: (define-and-bind-text-object "$" "\\$" "\\$") ;; between pipe characters: (define-and-bind-text-object "|" "|" "|") ;; trimmed line (define-and-bind-text-object "l" "^ *" " *$") ;; angular template (define-and-bind-text-object "r" "\{\{" "\}\}") ;; }} ;; {{ nearby file path as text object, ;; - "vif" to select only basename ;; - "vaf" to select the full path ;; ;; example: "/hello/world" "/test/back.exe" ;; "C:hello\\hello\\world\\test.exe" "D:blah\\hello\\world\\base.exe" ;; ;; tweak evil-filepath-is-nonname to re-define a path (defun evil-filepath-is-separator-char (ch) "Check ascii table that CH is slash characters. If the character before and after CH is space or tab, CH is NOT slash" (let (rlt prefix-ch postfix-ch) (when (and (> (point) (point-min)) (< (point) (point-max))) (save-excursion (backward-char) (setq prefix-ch (following-char))) (save-excursion (forward-char) (setq postfix-ch (following-char)))) (if (and (not (or (= prefix-ch 32) (= postfix-ch 32))) (or (= ch 47) (= ch 92)) ) (setq rlt t)) rlt)) (defun evil-filepath-not-path-char (ch) "Check ascii table for charctater " (let (rlt) (if (or (and (<= 0 ch) (<= ch 32)) (= ch 34) ; double quotes (= ch 39) ; single quote (= ch 40) ; ( (= ch 41) ; ) (= ch 60) ; < (= ch 62) ; > (= ch 91) ; [ (= ch 93) ; ] (= ch 96) ; ` (= ch 123) ; { (= ch 125) ; } (= 127 ch)) (setq rlt t)) rlt)) (defun evil-filepath-char-not-placed-at-end-of-path (ch) (or (= 44 ch) ; , (= 46 ch) ; . )) (defun evil-filepath-calculate-path (b e) (let (rlt f) (when (and b e) (setq b (+ 1 b)) (when (save-excursion (goto-char e) (setq f (evil-filepath-search-forward-char 'evil-filepath-is-separator-char t)) (and f (>= f b))) (setq rlt (list b (+ 1 f) (- e 1))))) rlt)) (defun evil-filepath-get-path-already-inside () (let (b e) (save-excursion (setq b (evil-filepath-search-forward-char 'evil-filepath-not-path-char t))) (save-excursion (setq e (evil-filepath-search-forward-char 'evil-filepath-not-path-char)) (when e (goto-char (- e 1)) ;; example: hello/world, (if (evil-filepath-char-not-placed-at-end-of-path (following-char)) (setq e (- e 1))) )) (evil-filepath-calculate-path b e))) (defun evil-filepath-search-forward-char (fn &optional backward) (let (found rlt (limit (if backward (point-min) (point-max))) out-of-loop) (save-excursion (while (not out-of-loop) ;; for the char, exit (if (setq found (apply fn (list (following-char)))) (setq out-of-loop t) ;; reach the limit, exit (if (= (point) limit) (setq out-of-loop t) ;; keep moving (if backward (backward-char) (forward-char))))) (if found (setq rlt (point)))) rlt)) (defun evil-filepath-extract-region () "Find the closest file path" (let (rlt b f1 f2) (if (and (not (evil-filepath-not-path-char (following-char))) (setq rlt (evil-filepath-get-path-already-inside))) ;; maybe (point) is in the middle of the path t ;; need search forward AND backward to find the right path (save-excursion ;; path in backward direction (when (setq b (evil-filepath-search-forward-char 'evil-filepath-is-separator-char t)) (goto-char b) (setq f1 (evil-filepath-get-path-already-inside)))) (save-excursion ;; path in forward direction (when (setq b (evil-filepath-search-forward-char 'evil-filepath-is-separator-char)) (goto-char b) (setq f2 (evil-filepath-get-path-already-inside)))) ;; pick one path as the final result (cond ((and f1 f2) (if (> (- (point) (nth 2 f1)) (- (nth 0 f2) (point))) (setq rlt f2) (setq rlt f1))) (f1 (setq rlt f1)) (f2 (setq rlt f2)))) rlt)) (evil-define-text-object evil-filepath-inner-text-object (&optional count begin end type) "File name of nearby path" (let ((selected-region (evil-filepath-extract-region))) (if selected-region (evil-range (nth 1 selected-region) (nth 2 selected-region) :expanded t)))) (evil-define-text-object evil-filepath-outer-text-object (&optional NUM begin end type) "Nearby path" (let ((selected-region (evil-filepath-extract-region))) (if selected-region (evil-range (car selected-region) (+ 1 (nth 2 selected-region)) type :expanded t)))) (define-key evil-inner-text-objects-map "f" 'evil-filepath-inner-text-object) (define-key evil-outer-text-objects-map "f" 'evil-filepath-outer-text-object) ;; }} ;; {{ https://github.com/syl20bnr/evil-escape (require 'evil-escape) (setq-default evil-escape-delay 0.5) (setq evil-escape-excluded-major-modes '(dired-mode)) (setq-default evil-escape-key-sequence "kj") (evil-escape-mode 1) ;; }} ;; {{ evil-space (require 'evil-space) (evil-space-mode) ;; }} ;; Move back the cursor one position when exiting insert mode (setq evil-move-cursor-back t) (defun toggle-org-or-message-mode () (interactive) (if (eq major-mode 'message-mode) (org-mode) (if (eq major-mode 'org-mode) (message-mode)) )) ;; (evil-set-initial-state 'org-mode 'emacs) ;; As a general RULE, mode specific evil leader keys started ;; with uppercased character or 'g' or special character except "=" and "-" (evil-declare-key 'normal org-mode-map "gh" 'outline-up-heading "gl" 'outline-next-visible-heading "$" 'org-end-of-line ; smarter behaviour on headlines etc. "^" 'org-beginning-of-line ; ditto "<" 'org-metaleft ; out-dent ">" 'org-metaright ; indent (kbd "TAB") 'org-cycle) (loop for (mode . state) in '((minibuffer-inactive-mode . emacs) (ggtags-global-mode . emacs) (grep-mode . emacs) (Info-mode . emacs) (term-mode . emacs) (sdcv-mode . emacs) (anaconda-nav-mode . emacs) (log-edit-mode . emacs) (vc-log-edit-mode . emacs) (magit-log-edit-mode . emacs) (inf-ruby-mode . emacs) (direx:direx-mode . emacs) (yari-mode . emacs) (erc-mode . emacs) (neotree-mode . emacs) (w3m-mode . emacs) (gud-mode . emacs) (help-mode . emacs) (eshell-mode . emacs) (shell-mode . emacs) ;;(message-mode . emacs) (fundamental-mode . emacs) (weibo-timeline-mode . emacs) (weibo-post-mode . emacs) (sr-mode . emacs) (dired-mode . emacs) (compilation-mode . emacs) (speedbar-mode . emacs) (messages-buffer-mode . normal) (magit-commit-mode . normal) (magit-diff-mode . normal) (browse-kill-ring-mode . normal) (etags-select-mode . normal) (js2-error-buffer-mode . emacs) ) do (evil-set-initial-state mode state)) ;; I prefer Emacs way after pressing ":" in evil-mode (define-key evil-ex-completion-map (kbd "C-a") 'move-beginning-of-line) (define-key evil-ex-completion-map (kbd "C-b") 'backward-char) (define-key evil-ex-completion-map (kbd "M-p") 'previous-complete-history-element) (define-key evil-ex-completion-map (kbd "M-n") 'next-complete-history-element) (define-key evil-normal-state-map "Y" (kbd "y$")) (define-key evil-normal-state-map "go" 'goto-char) (define-key evil-normal-state-map (kbd "M-y") 'browse-kill-ring) (define-key evil-normal-state-map (kbd "j") 'evil-next-visual-line) (define-key evil-normal-state-map (kbd "k") 'evil-previous-visual-line) (define-key evil-normal-state-map (kbd "C-]") 'etags-select-find-tag-at-point) (define-key evil-visual-state-map (kbd "C-]") 'etags-select-find-tag-at-point) (require 'evil-numbers) (define-key evil-normal-state-map "+" 'evil-numbers/inc-at-pt) (define-key evil-normal-state-map "-" 'evil-numbers/dec-at-pt) (require 'evil-matchit) (global-evil-matchit-mode 1) ;; press ",xx" to expand region ;; then press "z" to contract, "x" to expand (eval-after-load "evil" '(progn (setq expand-region-contract-fast-key "z") )) ;; I learn this trick from ReneFroger, need latest expand-region ;; @see https://github.com/redguardtoo/evil-matchit/issues/38 (define-key evil-visual-state-map (kbd "v") 'er/expand-region) (define-key evil-insert-state-map (kbd "C-e") 'move-end-of-line) (define-key evil-insert-state-map (kbd "C-k") 'kill-line) (define-key evil-insert-state-map (kbd "M-j") 'yas-expand) (define-key evil-emacs-state-map (kbd "M-j") 'yas-expand) (global-set-key (kbd "C-r") 'undo-tree-redo) ;; My frequently used commands are listed here ;; For example, for line like `"ef" 'end-of-defun` ;; You can either press `,ef` or `M-x end-of-defun` to execute it (require 'general) (general-evil-setup t) ;; {{ use `,` as leader key (nvmap :prefix "," "=" 'increase-default-font-height ; GUI emacs only "-" 'decrease-default-font-height ; GUI emacs only "bf" 'beginning-of-defun "bu" 'backward-up-list "bb" 'back-to-previous-buffer "ef" 'end-of-defun "mf" 'mark-defun "em" 'erase-message-buffer "eb" 'eval-buffer "sd" 'sudo-edit "sc" 'shell-command "ee" 'eval-expression "aa" 'copy-to-x-clipboard ; used frequently "aw" 'ace-swap-window "af" 'ace-maximize-window "zz" 'paste-from-x-clipboard ; used frequently "cy" 'strip-convert-lines-into-one-big-string "bs" '(lambda () (interactive) (goto-edge-by-comparing-font-face -1)) "es" 'goto-edge-by-comparing-font-face "ntt" 'neotree-toggle "ntf" 'neotree-find ; open file in current buffer in neotree "ntd" 'neotree-project-dir "nth" 'neotree-hide "nts" 'neotree-show "fl" 'cp-filename-line-number-of-current-buffer "fn" 'cp-filename-of-current-buffer "fp" 'cp-fullpath-of-current-buffer "dj" 'dired-jump ;; open the dired from current file "ff" 'toggle-full-window ;; I use WIN+F in i3 "ip" 'find-file-in-project "kk" 'find-file-in-project-by-selected "fd" 'find-directory-in-project-by-selected "trm" 'get-term "tff" 'toggle-frame-fullscreen "tfm" 'toggle-frame-maximized "ti" 'fastdef-insert "th" 'fastdef-insert-from-history ;; "ci" 'evilnc-comment-or-uncomment-lines ;; "cl" 'evilnc-comment-or-uncomment-to-the-line ;; "cc" 'evilnc-copy-and-comment-lines ;; "cp" 'evilnc-comment-or-uncomment-paragraphs "epy" 'emmet-expand-yas "epl" 'emmet-expand-line "rd" 'evilmr-replace-in-defun "rb" 'evilmr-replace-in-buffer "tt" 'evilmr-tag-selected-region ;; recommended "rt" 'evilmr-replace-in-tagged-region ;; recommended "tua" 'artbollocks-mode "cby" 'cb-switch-between-controller-and-view "cbu" 'cb-get-url-from-controller "ht" 'etags-select-find-tag-at-point ; better than find-tag C-] "hp" 'etags-select-find-tag "mm" 'counsel-bookmark-goto "mk" 'bookmark-set "yy" 'browse-kill-ring "gf" 'counsel-git-find-file "gc" 'counsel-git-find-file-committed-with-line-at-point "gl" 'counsel-git-grep-yank-line "gg" 'counsel-git-grep ; quickest grep should be easy to press "ga" 'counsel-git-grep-by-author "gm" 'counsel-git-find-my-file "gs" 'counsel-git-show-commit "sf" 'counsel-git-show-file "df" 'counsel-git-diff-file "rjs" 'run-js "jsr" 'js-send-region "rmz" 'run-mozilla "rpy" 'run-python "rlu" 'run-lua "tci" 'toggle-company-ispell "kb" 'kill-buffer-and-window ;; "k" is preserved to replace "C-g" "it" 'issue-tracker-increment-issue-id-under-cursor "ls" 'highlight-symbol "lq" 'highlight-symbol-query-replace "ln" 'highlight-symbol-nav-mode ; use M-n/M-p to navigation between symbols "bm" 'pomodoro-start ;; beat myself "ii" 'counsel-imenu-goto "im" 'ido-imenu "ij" 'rimenu-jump "." 'evil-ex ;; @see https://github.com/pidu/git-timemachine ;; p: previous; n: next; w:hash; W:complete hash; g:nth version; q:quit "tmt" 'git-timemachine-toggle "tdb" 'tidy-buffer "tdl" 'tidy-current-line ;; toggle overview, @see http://emacs.wordpress.com/2007/01/16/quick-and-dirty-code-folding/ "ov" 'my-overview-of-current-buffer "or" 'open-readme-in-git-root-directory "oo" 'compile "c$" 'org-archive-subtree ; `C-c $' ;; org-do-demote/org-do-premote support selected region "c<" 'org-do-promote ; `C-c C-<' "c>" 'org-do-demote ; `C-c C->' "cam" 'org-tags-view ; `C-c a m': search items in org-file-apps by tag "cxi" 'org-clock-in ; `C-c C-x C-i' "cxo" 'org-clock-out ; `C-c C-x C-o' "cxr" 'org-clock-report ; `C-c C-x C-r' "qq" 'my-grep "xc" 'save-buffers-kill-terminal "rr" 'counsel-recentf-goto "rh" 'counsel-yank-bash-history ; bash history command => yank-ring "rf" 'counsel-goto-recent-directory "da" 'diff-region-tag-selected-as-a "db" 'diff-region-compare-with-b "di" 'evilmi-delete-items "si" 'evilmi-select-items "jb" 'js-beautify "jp" 'js2-print-json-path "sep" 'string-edit-at-point "sec" 'string-edit-conclude "sea" 'string-edit-abort "xe" 'eval-last-sexp "x0" 'delete-window "x1" 'delete-other-windows "x2" 'split-window-vertically "x3" 'split-window-horizontally "rw" 'rotate-windows "ru" 'undo-tree-save-state-to-register ; C-x r u "rU" 'undo-tree-restore-state-from-register ; C-x r U "xt" 'toggle-window-split "uu" 'winner-undo "UU" 'winner-redo "to" 'toggle-web-js-offset "sl" 'sort-lines "ulr" 'uniquify-all-lines-region "ulb" 'uniquify-all-lines-buffer "lj" 'moz-load-js-file-and-send-it "mr" 'moz-console-clear "rnr" 'rinari-web-server-restart "rnc" 'rinari-find-controller "rnv" 'rinari-find-view "rna" 'rinari-find-application "rnk" 'rinari-rake "rnm" 'rinari-find-model "rnl" 'rinari-find-log "rno" 'rinari-console "rnt" 'rinari-find-test "ss" 'swiper-the-thing ; http://oremacs.com/2015/03/25/swiper-0.2.0/ for guide "hst" 'hs-toggle-fold "hsa" 'hs-toggle-fold-all "hsh" 'hs-hide-block "hss" 'hs-show-block "hd" 'describe-function "hf" 'find-function "hk" 'describe-key "hv" 'describe-variable "gt" 'ggtags-find-tag-dwim "gr" 'ggtags-find-reference "fb" 'flyspell-buffer "fe" 'flyspell-goto-next-error "fa" 'flyspell-auto-correct-word "pe" 'flymake-goto-prev-error "ne" 'flymake-goto-next-error "fw" 'ispell-word "bc" '(lambda () (interactive) (wxhelp-browse-class-or-api (thing-at-point 'symbol))) "ma" 'mc/mark-all-like-this-in-defun "mw" 'mc/mark-all-words-like-this-in-defun "ms" 'mc/mark-all-symbols-like-this-in-defun ;; "opt" is occupied by my-open-project-todo ;; recommended in html "md" 'mc/mark-all-like-this-dwim "me" 'mc/edit-lines "oag" 'org-agenda "otl" 'org-toggle-link-display "om" 'toggle-org-or-message-mode "ut" 'undo-tree-visualize "ar" 'align-regexp "wrn" 'httpd-restart-now "wrd" 'httpd-restart-at-default-directory "bk" 'buf-move-up "bj" 'buf-move-down "bh" 'buf-move-left "bl" 'buf-move-right "so" 'sos "0" 'select-window-0 "1" 'select-window-1 "2" 'select-window-2 "3" 'select-window-3 "4" 'select-window-4 "5" 'select-window-5 "6" 'select-window-6 "7" 'select-window-7 "8" 'select-window-8 "9" 'select-window-9 "xm" 'smex "xx" 'er/expand-region "xf" 'ido-find-file "xb" 'ido-switch-buffer "xh" 'mark-whole-buffer "xk" 'ido-kill-buffer "xs" 'save-buffer "xz" 'suspend-frame "vm" 'vc-rename-file-and-buffer "vc" 'vc-copy-file-and-rename-buffer "xvv" 'vc-next-action "va" 'git-add-current-file "xvp" 'git-push-remote-origin "xvu" 'git-add-option-update "xvg" 'vc-annotate "vs" 'git-gutter:stage-hunk "vr" 'git-gutter:revert-hunk "vl" 'vc-print-log "vv" 'git-messenger:popup-message "v=" 'git-gutter:popup-hunk "hh" 'cliphist-paste-item "yu" 'cliphist-select-item "nn" 'my-goto-next-hunk "pp" 'my-goto-previous-hunk "ww" 'narrow-or-widen-dwim "xnw" 'widen "xnd" 'narrow-to-defun "xnr" 'narrow-to-region "ycr" 'my-yas-reload-all "wf" 'popup-which-function) ;; }} ;; {{ Use `SPC` as leader key ;; all keywords arguments are still supported (nvmap :prefix "SPC" "ss" 'wg-create-workgroup ; save windows layout "ll" 'my-wg-switch-workgroup ; load windows layout "kk" 'scroll-other-window "jj" 'scroll-other-window-up "yy" 'hydra-launcher/body "gs" 'git-gutter:set-start-revision "gh" 'git-gutter-reset-to-head-parent "gr" 'git-gutter-reset-to-default "ud" 'my-gud-gdb "uk" 'gud-kill-yes "ur" 'gud-remove "ub" 'gud-break "uu" 'gud-run "up" 'gud-print "ue" 'gud-cls "un" 'gud-next "us" 'gud-step "ui" 'gud-stepi "uc" 'gud-cont "uf" 'gud-finish) ;; per-major-mode leader setup (general-define-key :states '(normal motion insert emacs) :keymaps 'js2-mode-map :prefix "SPC" :non-normal-prefix "M-SPC" "de" 'js2-display-error-list "nn" 'js2-next-error "te" 'js2-mode-toggle-element "tf" 'js2-mode-toggle-hide-functions "jeo" 'js2r-expand-object "jco" 'js2r-contract-object "jeu" 'js2r-expand-function "jcu" 'js2r-contract-function "jea" 'js2r-expand-array "jca" 'js2r-contract-array "jwi" 'js2r-wrap-buffer-in-iife "jig" 'js2r-inject-global-in-iife "jev" 'js2r-extract-var "jiv" 'js2r-inline-var "jrv" 'js2r-rename-var "jvt" 'js2r-var-to-this "jag" 'js2r-add-to-globals-annotation "jsv" 'js2r-split-var-declaration "jss" 'js2r-split-string "jef" 'js2r-extract-function "jem" 'js2r-extract-method "jip" 'js2r-introduce-parameter "jlp" 'js2r-localize-parameter "jtf" 'js2r-toggle-function-expression-and-declaration "jao" 'js2r-arguments-to-object "juw" 'js2r-unwrap "jwl" 'js2r-wrap-in-for-loop "j3i" 'js2r-ternary-to-if "jlt" 'js2r-log-this "jsl" 'js2r-forward-slurp "jba" 'js2r-forward-barf "jk" 'js2r-kill) ;; }} ;; {{ Use `;` as leader key, for searching something (nvmap :prefix ";" ";" 'avy-goto-subword-1 "db" 'sdcv-search-pointer ; in buffer "dt" 'sdcv-search-input+ ;; in tip "dd" 'my-lookup-dict-org "dw" 'define-word "dp" 'define-word-at-point "mm" 'lookup-doc-in-man "gg" 'w3m-google-search "gf" 'w3m-google-by-filetype "gd" 'w3m-search-financial-dictionary "gj" 'w3m-search-js-api-mdn "ga" 'w3m-java-search "gh" 'w3mext-hacker-search ; code search in all engines with firefox "gq" 'w3m-stackoverflow-search "mm" 'mpc-which-song "mn" 'mpc-next-prev-song "mp" '(lambda () (interactive) (mpc-next-prev-song t))) ;; }} ;; change mode-line color by evil state (lexical-let ((default-color (cons (face-background 'mode-line) (face-foreground 'mode-line)))) (add-hook 'post-command-hook (lambda () (let ((color (cond ((minibufferp) default-color) ((evil-insert-state-p) '("#e80000" . "#ffffff")) ((evil-emacs-state-p) '("#444488" . "#ffffff")) ((buffer-modified-p) '("#006fa0" . "#ffffff")) (t default-color)))) (set-face-background 'mode-line (car color)) (set-face-foreground 'mode-line (cdr color)))))) (require 'evil-nerd-commenter) (evilnc-default-hotkeys) (provide 'init-evil)
export type Json = | string | number | boolean | null | { [key: string]: Json | undefined } | Json[] export interface Database { public: { Tables: { ends: { Row: { created_at: string | null end_number: number game_id: number hammer_team_id: number | null id: number points_scored: number | null scoring_team_id: number | null } Insert: { created_at?: string | null end_number?: number game_id: number hammer_team_id?: number | null id?: number points_scored?: number | null scoring_team_id?: number | null } Update: { created_at?: string | null end_number?: number game_id?: number hammer_team_id?: number | null id?: number points_scored?: number | null scoring_team_id?: number | null } Relationships: [ { foreignKeyName: "ends_game_id_fkey" columns: ["game_id"] referencedRelation: "games" referencedColumns: ["id"] }, { foreignKeyName: "ends_hammer_team_id_fkey" columns: ["hammer_team_id"] referencedRelation: "teams" referencedColumns: ["id"] }, { foreignKeyName: "ends_scoring_team_id_fkey" columns: ["scoring_team_id"] referencedRelation: "teams" referencedColumns: ["id"] } ] } events: { Row: { created_at: string | null id: number name: string | null profile_id: string | null rink_id: number | null } Insert: { created_at?: string | null id?: number name?: string | null profile_id?: string | null rink_id?: number | null } Update: { created_at?: string | null id?: number name?: string | null profile_id?: string | null rink_id?: number | null } Relationships: [ { foreignKeyName: "events_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "events_rink_id_fkey" columns: ["rink_id"] referencedRelation: "rinks" referencedColumns: ["id"] } ] } games: { Row: { away: number | null away_color: string | null completed: boolean | null created_at: string | null hammer_first_end: number | null home: number | null home_color: string | null id: number name: string | null profile_id: string | null rink_id: number | null sheet_id: number | null start_time: string | null } Insert: { away?: number | null away_color?: string | null completed?: boolean | null created_at?: string | null hammer_first_end?: number | null home?: number | null home_color?: string | null id?: number name?: string | null profile_id?: string | null rink_id?: number | null sheet_id?: number | null start_time?: string | null } Update: { away?: number | null away_color?: string | null completed?: boolean | null created_at?: string | null hammer_first_end?: number | null home?: number | null home_color?: string | null id?: number name?: string | null profile_id?: string | null rink_id?: number | null sheet_id?: number | null start_time?: string | null } Relationships: [ { foreignKeyName: "games_away_fkey" columns: ["away"] referencedRelation: "teams" referencedColumns: ["id"] }, { foreignKeyName: "games_hammer_first_end_fkey" columns: ["hammer_first_end"] referencedRelation: "teams" referencedColumns: ["id"] }, { foreignKeyName: "games_home_fkey" columns: ["home"] referencedRelation: "teams" referencedColumns: ["id"] }, { foreignKeyName: "games_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "games_rink_id_fkey" columns: ["rink_id"] referencedRelation: "rinks" referencedColumns: ["id"] }, { foreignKeyName: "games_sheet_id_fkey" columns: ["sheet_id"] referencedRelation: "sheets" referencedColumns: ["id"] } ] } player_game_junction: { Row: { away_fourth_id: number | null away_lead_id: number | null away_second_id: number | null away_skip_id: number | null away_third_id: number | null created_at: string | null game_id: number | null home_fourth_id: number | null home_lead_id: number | null home_second_id: number | null home_skip_id: number | null home_third_id: number | null id: number } Insert: { away_fourth_id?: number | null away_lead_id?: number | null away_second_id?: number | null away_skip_id?: number | null away_third_id?: number | null created_at?: string | null game_id?: number | null home_fourth_id?: number | null home_lead_id?: number | null home_second_id?: number | null home_skip_id?: number | null home_third_id?: number | null id?: number } Update: { away_fourth_id?: number | null away_lead_id?: number | null away_second_id?: number | null away_skip_id?: number | null away_third_id?: number | null created_at?: string | null game_id?: number | null home_fourth_id?: number | null home_lead_id?: number | null home_second_id?: number | null home_skip_id?: number | null home_third_id?: number | null id?: number } Relationships: [ { foreignKeyName: "player_game_junction_away_fourth_id_fkey" columns: ["away_fourth_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_away_lead_id_fkey" columns: ["away_lead_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_away_second_id_fkey" columns: ["away_second_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_away_skip_id_fkey" columns: ["away_skip_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_away_third_id_fkey" columns: ["away_third_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_game_id_fkey" columns: ["game_id"] referencedRelation: "games" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_home_fourth_id_fkey" columns: ["home_fourth_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_home_lead_id_fkey" columns: ["home_lead_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_home_second_id_fkey" columns: ["home_second_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_home_skip_id_fkey" columns: ["home_skip_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "player_game_junction_home_third_id_fkey" columns: ["home_third_id"] referencedRelation: "players" referencedColumns: ["id"] } ] } players: { Row: { avatar: Json | null created_at: string | null id: number name: string | null profile_id: string | null profile_id_for_player: string | null } Insert: { avatar?: Json | null created_at?: string | null id?: number name?: string | null profile_id?: string | null profile_id_for_player?: string | null } Update: { avatar?: Json | null created_at?: string | null id?: number name?: string | null profile_id?: string | null profile_id_for_player?: string | null } Relationships: [ { foreignKeyName: "players_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "players_profile_id_for_player_fkey" columns: ["profile_id_for_player"] referencedRelation: "profiles" referencedColumns: ["id"] } ] } profiles: { Row: { avatar_url: string | null created_at: string | null first_name: string | null id: string last_name: string | null player_id: number | null timezone: string | null username: string profile_search: string | null } Insert: { avatar_url?: string | null created_at?: string | null first_name?: string | null id: string last_name?: string | null player_id?: number | null timezone?: string | null username?: string } Update: { avatar_url?: string | null created_at?: string | null first_name?: string | null id?: string last_name?: string | null player_id?: number | null timezone?: string | null username?: string } Relationships: [ { foreignKeyName: "profiles_id_fkey" columns: ["id"] referencedRelation: "users" referencedColumns: ["id"] }, { foreignKeyName: "profiles_player_id_fkey" columns: ["player_id"] referencedRelation: "players" referencedColumns: ["id"] } ] } rinks: { Row: { created_at: string | null id: number name: string | null profile_id: string | null } Insert: { created_at?: string | null id?: number name?: string | null profile_id?: string | null } Update: { created_at?: string | null id?: number name?: string | null profile_id?: string | null } Relationships: [ { foreignKeyName: "rinks_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] } ] } rocks: { Row: { color: string | null created_at: string | null id: number notes: string | null number: number | null profile_id: string | null sheet_id: number | null } Insert: { color?: string | null created_at?: string | null id?: number notes?: string | null number?: number | null profile_id?: string | null sheet_id?: number | null } Update: { color?: string | null created_at?: string | null id?: number notes?: string | null number?: number | null profile_id?: string | null sheet_id?: number | null } Relationships: [ { foreignKeyName: "rocks_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "rocks_sheet_id_fkey" columns: ["sheet_id"] referencedRelation: "sheets" referencedColumns: ["id"] } ] } sheets: { Row: { created_at: string | null id: number name: string | null profile_id: string | null rink_id: number | null } Insert: { created_at?: string | null id?: number name?: string | null profile_id?: string | null rink_id?: number | null } Update: { created_at?: string | null id?: number name?: string | null profile_id?: string | null rink_id?: number | null } Relationships: [ { foreignKeyName: "sheets_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "sheets_rink_id_fkey" columns: ["rink_id"] referencedRelation: "rinks" referencedColumns: ["id"] } ] } shots: { Row: { created_at: string | null end_id: number id: number line: number | null notes: string | null player_id: number | null rock_positions: Json score: number | null shot_no: number | null turn: number | null type_id: number | null } Insert: { created_at?: string | null end_id: number id?: number line?: number | null notes?: string | null player_id?: number | null rock_positions?: Json score?: number | null shot_no?: number | null turn?: number | null type_id?: number | null } Update: { created_at?: string | null end_id?: number id?: number line?: number | null notes?: string | null player_id?: number | null rock_positions?: Json score?: number | null shot_no?: number | null turn?: number | null type_id?: number | null } Relationships: [ { foreignKeyName: "shots_end_id_fkey" columns: ["end_id"] referencedRelation: "ends" referencedColumns: ["id"] }, { foreignKeyName: "shots_player_id_fkey" columns: ["player_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "shots_type_id_fkey" columns: ["type_id"] referencedRelation: "shottypes" referencedColumns: ["id"] } ] } team_profile_junction: { Row: { created_at: string | null id: number profile_id: string team_id: number } Insert: { created_at?: string | null id?: number profile_id: string team_id: number } Update: { created_at?: string | null id?: number profile_id?: string team_id?: number } Relationships: [ { foreignKeyName: "team_profile_junction_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "team_profile_junction_team_id_fkey" columns: ["team_id"] referencedRelation: "teams" referencedColumns: ["id"] } ] } team_requests: { Row: { created_at: string | null id: number requestee_profile_id: string | null requester_profile_id: string | null status: string | null team_id: number | null updated_at: string | null } Insert: { created_at?: string | null id?: number requestee_profile_id?: string | null requester_profile_id?: string | null status?: string | null team_id?: number | null updated_at?: string | null } Update: { created_at?: string | null id?: number requestee_profile_id?: string | null requester_profile_id?: string | null status?: string | null team_id?: number | null updated_at?: string | null } Relationships: [ { foreignKeyName: "team_requests_requestee_profile_id_fkey" columns: ["requestee_profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "team_requests_requester_profile_id_fkey" columns: ["requester_profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "team_requests_team_id_fkey" columns: ["team_id"] referencedRelation: "teams" referencedColumns: ["id"] } ] } teams: { Row: { created_at: string | null fifth_player_id: number | null fourth_player_id: number | null id: number lead_player_id: number | null name: string | null profile_id: string | null second_player_id: number | null seventh_player_id: number | null sixth_player_id: number | null skip_id: number | null third_player_id: number | null } Insert: { created_at?: string | null fifth_player_id?: number | null fourth_player_id?: number | null id?: number lead_player_id?: number | null name?: string | null profile_id?: string | null second_player_id?: number | null seventh_player_id?: number | null sixth_player_id?: number | null skip_id?: number | null third_player_id?: number | null } Update: { created_at?: string | null fifth_player_id?: number | null fourth_player_id?: number | null id?: number lead_player_id?: number | null name?: string | null profile_id?: string | null second_player_id?: number | null seventh_player_id?: number | null sixth_player_id?: number | null skip_id?: number | null third_player_id?: number | null } Relationships: [ { foreignKeyName: "teams_fifth_player_id_fkey" columns: ["fifth_player_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "teams_fourth_player_id_fkey" columns: ["fourth_player_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "teams_lead_player_id_fkey" columns: ["lead_player_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "teams_profile_id_fkey" columns: ["profile_id"] referencedRelation: "profiles" referencedColumns: ["id"] }, { foreignKeyName: "teams_second_player_id_fkey" columns: ["second_player_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "teams_seventh_player_id_fkey" columns: ["seventh_player_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "teams_sixth_player_id_fkey" columns: ["sixth_player_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "teams_skip_id_fkey" columns: ["skip_id"] referencedRelation: "players" referencedColumns: ["id"] }, { foreignKeyName: "teams_third_player_id_fkey" columns: ["third_player_id"] referencedRelation: "players" referencedColumns: ["id"] } ] } } Views: { [_ in never]: never } Functions: { calculate_averages: { Args: { player_id_param: number } Returns: { avg_score: number avg_inturn: number avg_outturn: number avg_draw: number avg_hit: number }[] } delete_avatar: { Args: { avatar_url: string } Returns: Record<string, unknown> } delete_storage_object: { Args: { bucket: string object: string } Returns: Record<string, unknown> } gen_random_text: { Args: { length: number } Returns: string } get_columns: { Args: { tablename: string } Returns: { column_name: string data_type: string }[] } get_game_stats: { Args: { game_id_param: number } Returns: Record<string, unknown>[] } get_games: { Args: Record<PropertyKey, never> Returns: Record<string, unknown>[] } get_profile: | { Args: Record<PropertyKey, never> Returns: Record<string, unknown> } | { Args: { profile_id_param: string } Returns: Record<string, unknown> } get_shot_averages_player: { Args: { player_id_param: number } Returns: { avg_score: number avg_inturn: number avg_outturn: number avg_draw: number avg_hit: number avg_inside: number avg_onbroom: number avg_outside: number avg_inside_inturn: number avg_onbroom_inturn: number avg_outside_inturn: number avg_inside_outturn: number avg_onbroom_outturn: number avg_outside_outturn: number avg_inside_draw: number avg_onbroom_draw: number avg_outside_draw: number avg_inside_hit: number avg_onbroom_hit: number avg_outside_hit: number }[] } get_shot_averages_player_for_game: { Args: { team_id_param: number game_id_param: number } Returns: { avg_score: number avg_inturn: number avg_outturn: number avg_draw: number avg_hit: number avg_inside: number avg_onbroom: number avg_outside: number avg_inside_inturn: number avg_onbroom_inturn: number avg_outside_inturn: number avg_inside_outturn: number avg_onbroom_outturn: number avg_outside_outturn: number avg_inside_draw: number avg_onbroom_draw: number avg_outside_draw: number avg_inside_hit: number avg_onbroom_hit: number avg_outside_hit: number }[] } get_shot_averages_team: { Args: { team_id_param: number } Returns: { avg_score: number avg_inturn: number avg_outturn: number avg_draw: number avg_hit: number avg_inside: number avg_onbroom: number avg_outside: number avg_inside_inturn: number avg_onbroom_inturn: number avg_outside_inturn: number avg_inside_outturn: number avg_onbroom_outturn: number avg_outside_outturn: number avg_inside_draw: number avg_onbroom_draw: number avg_outside_draw: number avg_inside_hit: number avg_onbroom_hit: number avg_outside_hit: number }[] } get_shot_averages_team_for_game: { Args: { team_id_param: number game_id_param: number } Returns: { avg_score: number avg_inturn: number avg_outturn: number avg_draw: number avg_hit: number avg_inside: number avg_onbroom: number avg_outside: number avg_inside_inturn: number avg_onbroom_inturn: number avg_outside_inturn: number avg_inside_outturn: number avg_onbroom_outturn: number avg_outside_outturn: number avg_inside_draw: number avg_onbroom_draw: number avg_outside_draw: number avg_inside_hit: number avg_onbroom_hit: number avg_outside_hit: number }[] } get_table_info: { Args: { tablename: string } Returns: { column_name: string data_type: string foreign_key: string }[] } get_team_averages: { Args: { team_id_param: number } Returns: { average_score: number average_score_inturn: number average_score_outturn: number average_score_draw: number average_score_hit: number }[] } get_team_detailed: { Args: { team_id_param: number } Returns: { id: number name: string profile_id: string wins: number losses: number ties: number total_points: number total_ends_played: number hammer_ends_count: number hammer_steal_count: number hammer_blank_count: number hammer_1_point_count: number hammer_2_point_count: number hammer_3_point_count: number hammer_4_point_count: number hammer_5_point_count: number hammer_6_point_count: number hammer_7_point_count: number hammer_8_point_count: number stolen_end_count: number forced_end_count: number avg_points_conceded: number lead_player_id: number lead_player_name: string lead_player_avatar: Json second_player_id: number second_player_name: string second_player_avatar: Json third_player_id: number third_player_name: string third_player_avatar: Json fourth_player_id: number fourth_player_name: string fourth_player_avatar: Json fifth_player_id: number fifth_player_name: string fifth_player_avatar: Json sixth_player_id: number sixth_player_name: string sixth_player_avatar: Json seventh_player_id: number seventh_player_name: string seventh_player_avatar: Json team_avg: number }[] } get_team_request_count_to_respond: { Args: Record<PropertyKey, never> Returns: number } get_team_requests: { Args: Record<PropertyKey, never> Returns: { team_name: string status: string created_at: string role: string requestee_username: string requestee_avatar: Json requester_username: string requester_avatar: Json }[] } get_team_stats: { Args: { team_id_param: number } Returns: Record<string, unknown>[] } get_team_wins: { Args: { team_id_param: number } Returns: Record<string, unknown> } get_teams_basic: { Args: Record<PropertyKey, never> Returns: { id: number created_at: string profile_id: string skip_id: number name: string lead_player_id: Json second_player_id: Json third_player_id: Json fourth_player_id: Json fifth_player_id: Json sixth_player_id: Json seventh_player_id: Json status: string subject: string requester_id: string }[] } get_teams_detailed: { Args: Record<PropertyKey, never> Returns: { id: number name: string profile_id: string wins: number losses: number ties: number total_points: number total_ends_played: number hammer_ends_count: number hammer_steal_count: number hammer_blank_count: number hammer_1_point_count: number hammer_2_point_count: number hammer_3_point_count: number hammer_4_point_count: number hammer_5_point_count: number hammer_6_point_count: number hammer_7_point_count: number hammer_8_point_count: number stolen_end_count: number forced_end_count: number avg_points_conceded: number lead_player_id: number lead_player_name: string lead_player_avatar: Json second_player_id: number second_player_name: string second_player_avatar: Json third_player_id: number third_player_name: string third_player_avatar: Json fourth_player_id: number fourth_player_name: string fourth_player_avatar: Json fifth_player_id: number fifth_player_name: string fifth_player_avatar: Json sixth_player_id: number sixth_player_name: string sixth_player_avatar: Json seventh_player_id: number seventh_player_name: string seventh_player_avatar: Json team_avg: number }[] } get_teams_details: { Args: Record<PropertyKey, never> Returns: { team_id: number name: string wins: number losses: number ties: number total_points: number total_ends_played: number hammer_ends_count: number hammer_steal_count: number hammer_blank_count: number hammer_1_point_count: number hammer_2_point_count: number hammer_3_point_count: number hammer_4_point_count: number hammer_5_point_count: number hammer_6_point_count: number hammer_7_point_count: number hammer_8_point_count: number stolen_end_count: number forced_end_count: number avg_points_conceded: number }[] } has_access_to_resource: { Args: { current_profile_id: string player_profile_id: string } Returns: boolean } profile_search: { Args: { "": unknown } Returns: string } } Enums: { shot_type_enum: "Draw" | "Hit" } CompositeTypes: { team_info: { id: number name: string } } } }
/*! * \file CBinTreeRB.hpp Template red-black balanced binary tree container * class. * \brief Template red-black balanced binary tree container class. * \author Ivan Shynkarenka aka 4ekucT * \version 1.0 * \date 29.08.2006 */ /* FILE DESCRIPTION: Template red-balck balanced binary tree container class. AUTHOR: Ivan Shynkarenka aka 4ekucT GROUP: The NULL workgroup PROJECT: The Depth PART: Template common containers VERSION: 1.0 CREATED: 29.08.2006 00:00:26 EMAIL: chronoxor@gmail.com WWW: http://code.google.com/p/depth COPYRIGHT: (C) 2005-2010 The NULL workgroup. All Rights Reserved. */ /*--------------------------------------------------------------------------*/ /* Copyright (C) 2005-2010 The NULL workgroup. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*--------------------------------------------------------------------------*/ /* FILE ID: $Id$ CHANGE LOG: $Log$ */ #ifndef __CBINTREERB_HPP__ #define __CBINTREERB_HPP__ #include <Depth/include/containers/CBinTree.hpp> /* NAMESPACE DECLARATIONS */ namespace NDepth { /*--------------------------------------------------------------------------*/ namespace NContainers { /* CLASS DECLARATIONS */ //! Template red-black balanced binary tree container class. /*! <b>Overview.</b>\n A red-black tree is a type of self-balancing binary search tree, a data structure used in computer science, typically used to implement associative arrays. The original structure was invented in 1972 by Rudolf Bayer who called them "symmetric binary B-trees", but acquired its modern name in a paper in 1978 by Leo J. Guibas and Robert Sedgewick. It is complex, but has good worst-case running time for its operations and is efficient in practice: it can search, insert, and delete in O(log n) time, where n is the number of elements in the tree. <b>Background and terminology.</b>\n A red-black tree is a special type of binary tree, which is a structure used in computer science to organize pieces of comparable data, such as numbers. Each piece of data is stored in a node. One of the nodes always functions as our starting place, and is not the child of any node; we call this the root node or root. It has up to two "children", other nodes to which it connects. Each of these children can have up to two children of its own, and so on. The root node thus has a path connecting it to any other node in the tree. If a node has no children, we call it a leaf node, since intuitively it is at the periphery of the tree. A subtree is the portion of the tree that can be reached from a certain node, considered as a tree itself. In red-black trees, the leaves are assumed to be null, that is, they do not contain any data. As red-black trees are also binary search trees, they satisfy the constraint that every node contains a value less than or equal to all nodes in its right subtree, and greater than or equal to all nodes in its left subtree. This makes it quick to search the tree for a given value, and allows efficient in-order traversal of elements. <b>Uses and advantages.</b>\n Red-black trees, along with AVL trees, offer the best possible worst-case guarantees for insertion time, deletion time, and search time. Not only does this make them valuable in time-sensitive applications such as real-time applications, but it makes them valuable building blocks in other data structures which provide worst-case guarantees; for example, many data structures used in computational geometry can be based on red-black trees. Red-black trees are also particularly valuable in functional programming, where they are one of the most common persistent data structures, used to construct associative arrays and sets which can retain previous versions after mutations. The persistent version of red-black trees requires O(log n) space for each insertion or deletion, in addition to time. Red-black trees are an isometry of 2-3-4 trees. In other words, for every 2-3-4 tree, there exists at least one red-black tree with data elements in the same order. The insertion and deletion operations on 2-3-4 trees are also equivalent to color-flipping and rotations in red-black trees. This makes 2-3-4 trees an important tool for understanding the logic behind red-black trees, and this is why many introductory algorithm texts introduce 2-3-4 trees just before red-black trees, even though 2-3-4 trees are not often used in practice. <b>Properties.</b>\n \image html BinTree-Red-Black.png "Red-Black binary tree." A red-black tree is a binary search tree where each node has a color attribute, the value of which is either red or black. In addition to the ordinary requirements imposed on binary search trees, we make the following additional requirements of any valid red-black tree: \li 1. A node is either red or black. \li 2. The root is black. \li 3. All leaves are black. (This includes the NIL children) \li 4. Both children of every red node are black. (i.e. Every red node must have a black parent.) \li 5. All paths from any given node to its leaf nodes contain the same number of black nodes. These constraints enforce a critical property of red-black trees: that the longest possible path from the root to a leaf is no more than twice as long as the shortest possible path. The result is that the tree is roughly balanced. Since operations such as inserting, deleting, and finding values requires worst-case time proportional to the height of the tree, this theoretical upper bound on the height allows red-black trees to be efficient in the worst-case, unlike ordinary binary search trees. To see why these properties guarantee this, it suffices to note that no path can have two red nodes in a row, due to property 4. The shortest possible path has all black nodes, and the longest possible path alternates between red and black nodes. Since all maximal paths have the same number of black nodes, by property 5, this shows that no path is more than twice as long as any other path. In many presentations of tree data structures, it is possible for a node to have only one child, and leaf nodes contain data. It is possible to present red-black trees in this paradigm, but it changes several of the properties and complicates the algorithms. For this reason, in this article we use "nil leaves" or "null leaves", which contain no data and merely serve to indicate where the tree ends, as shown above. These nodes are often omitted in drawings, resulting in a tree which seems to contradict the above principles, but which in fact does not. A consequence of this is that all internal (non-leaf) nodes have two children, although one or more of those children may be a null leaf. Some explain a red-black tree as a binary search tree whose edges, instead of nodes, are colored in red or black, but this does not make any difference. The color of a node in our terminology corresponds to the color of the edge connecting the node to its parent, except that the root node is always black in our terminology (property 2) whereas the corresponding edge does not exist. <b>Operations.</b>\n Read-only operations on a red-black tree require no modification from those used for binary search trees, because every red-black tree is a specialization of a simple binary search tree. However, the immediate result of an insertion or removal may violate the properties of a red-black tree. Restoring the red-black properties requires a small number (O(log n) or amortized O(1)) of color changes (which are very quick in practice) and no more than three tree rotations (two for insertion). Although insert and delete operations are complicated, their times remain O(log n). <b>Proof of asymptotic bounds.</b>\n A red black tree which contains n internal nodes has a height of O(log(n)). Definitions: \li h(v) = height of subtree rooted at node v \li bh(v) = the number of black nodes (not counting v if it is black) from v to any leaf in the subtree (called the black-height). <b>Lemma:</b> A subtree rooted at node v has at least 2bh(v) ? 1 internal nodes. Proof of Lemma (by induction height): Basis: h(v) = 0 If v has a height of zero then it must be nil, therefore bh(v) = 0. So: \f$2^{bh(v)} - 1 = 20 - 1 = 1 - 1 = 0\f$ Inductive Hypothesis: v such that h(v) = k, has \f$2^{bh(v)} - 1\f$ internal nodes implies that v' such that h(v') = k+1 has \f$2^{bh(v')} - 1\f$ internal nodes. Since v' has h(v') > 0 it is an internal node. As such it has two children which have a black-height of either bh(v') or bh(v')-1 (depending on whether v' is red or black). By the inductive hypothesis each child has at least \f$2^{bh(v)} - 1 - 1\f$ internal nodes, so v' has: \f[2^{bh(v)} - 1 - 1 + 2^{bh(v')} - 1 - 1 + 1 = 2^{bh(v')} - 1\f] internal nodes. Using this lemma we can now show that the height of the tree is logarithmic. Since at least half of the nodes on any path from the root to a leaf are black (property 4 of a red black tree), the black- height of the root is at least \f$h(root) \over 2\f$. By the lemma we get: \f[n \geq 2^{{h(root) \over 2}} - 1 \leftrightarrow \; \log{(n+1)} \geq {h(root) \over 2} \leftrightarrow \; h(root) \leq 2\log{(n+1)}\f] Therefore the height of the root is O(log(n)). <b>References.</b>\n \li Mathworld: Red-Black Tree \li San Diego State University: CS 660: Red-Black tree notes, by Roger Whitney \li Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, Second Edition. MIT Press and McGraw-Hill, 2001. ISBN 0-262-03293-7 . Chapter 13: Red-Black Trees, pp.273-301. <b>Taken from:</b>\n Red-black tree from Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/Red-black_tree */ template <typename T_Type, typename T_BinaryPredicate = NAlgorithms::NFunctions::FBoolLessThan<const T_Type&>, class T_Allocator = NMemory::NAllocators::CAllocatorMemory> class CBinTreeRB : public CBinTree<T_Type, T_BinaryPredicate, T_Allocator> { //! Type for MConceptDepthType constraint checking. typedef CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator> TDepthCheckType; // Check CBinTreeRB class constraint to be a real Depth type. REQUIRES_CONCEPT1(NConcept::NTypes, MConceptDepthType, TDepthCheckType); public: //! Container associative key type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TKey TKey; //! Container associative value type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TValue TValue; //! Container value type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TType TType; //! Container type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TContainer TContainer; //! Non constant binary tree iterator type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TIterator TIterator; //! Constant binary tree iterator type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TIteratorConst TIteratorConst; //! Container binary predicate type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TLessThanPredicate TLessThanPredicate; //! Container allocator type. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::TAllocator TAllocator; //! Default class constructor. /*! Create an empty red-black balanced binary tree. \param a_fLessThan - 'LessThan' binary comparator function (default is T_BinaryPredicate()). \param a_crAllocator - Constant reference to the memory allocator (default is T_Allocator()). */ CBinTreeRB(T_BinaryPredicate a_fLessThan = T_BinaryPredicate(), const T_Allocator& a_crAllocator = T_Allocator()); //! Initialize red-black balanced binary tree with one item. /*! Create an empty red-black balanced binary tree, then insert item into it as a root node. \param a_crItem - Constant reference to the item to insert. \param a_fLessThan - 'LessThan' binary comparator function (default is T_BinaryPredicate()). \param a_crAllocator - Constant reference to the memory allocator (default is T_Allocator()). */ CBinTreeRB(const T_Type& a_crItem, T_BinaryPredicate a_fLessThan = T_BinaryPredicate(), const T_Allocator& a_crAllocator = T_Allocator()); //! Class copy constructor. /*! \param a_crInstance - Constant reference to another instance of the CBinTreeRB class. \param a_fLessThan - 'LessThan' binary comparator function (default is T_BinaryPredicate()). \param a_crAllocator - Constant reference to the memory allocator (default is T_Allocator()). */ CBinTreeRB(const CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator>& a_crInstance, T_BinaryPredicate a_fLessThan = T_BinaryPredicate(), const T_Allocator& a_crAllocator = T_Allocator()); //! Class virtual destructor. virtual ~CBinTreeRB(); //! Serialize CBinTreeRB class instance. /*! \param a_rArchive - Reference to the serialization archive. \return true - if serialization has been successfully done. \n false - if serialization has not been successfully done. \n */ template <class T_Archive> Tbool serialize(T_Archive& a_rArchive); //! Swap two CBinTreeRB class instances. /*! \param a_rInstance - Reference to another CBinTreeRB class instance. */ void swap(CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator>& a_rInstance); protected: //! Binary tree node structure. typedef typename CBinTree<T_Type, T_BinaryPredicate, T_Allocator>::SBinTreeNode SBinTreeNode; // CBinTree class overriding methods. virtual Tbool insertAndBalance(SBinTreeNode* a_pNode); virtual Tbool removeAndBalance(SBinTreeNode* a_pNode); private: //! Unlink red-black balanced binary tree node. /*! \param a_pNode - Pointer to the red-black balanced binary tree node. \param a_pParentNode - Pointer to the parent red-black balanced binary tree node. */ void unlink(SBinTreeNode* a_pNode, SBinTreeNode* a_pParentNode); //! Rotate red-black balanced binary tree node to the left. /*! \param a_pNode - Pointer to the red-black balanced binary tree node. */ void rotateLeft(SBinTreeNode* a_pNode); //! Rotate red-black balanced binary tree node to the right. /*! \param a_pNode - Pointer to the red-black balanced binary tree node. */ void rotateRight(SBinTreeNode* a_pNode); //! Check if given red-black balanced binary tree node has black color. /*! \param a_crNode - Constant reference to the red-black balanced binary tree node. \return true - if red-black balanced binary tree node has black color. \n false - if red-black balanced binary tree node has red color. \n */ static Tbool isBlack(const SBinTreeNode& a_crNode); //! Check if given red-black balanced binary tree node has red color. /*! \param a_crNode - Constant reference to the red-black balanced binary tree node. \return true - if red-black balanced binary tree node has red color. \n false - if red-black balanced binary tree node has black color. \n */ static Tbool isRed(const SBinTreeNode& a_crNode); //! Set black color for given red-black balanced binary tree node. /*! \param a_rNode - Reference to the red-black balanced binary tree node. */ static void setBlack(SBinTreeNode& a_rNode); //! Set red color for given red-black balanced binary tree node. /*! \param a_rNode - Reference to the red-black balanced binary tree node. */ static void setRed(SBinTreeNode& a_rNode); }; } /*--------------------------------------------------------------------------*/ } /* CONTAINER TRAITS SPECIALIZATION DECLARATIONS */ namespace NDepth { /*--------------------------------------------------------------------------*/ namespace NTraits { /*--------------------------------------------------------------------------*/ //! Traits meta-class: red-black balanced binary tree container traits specialization. template <typename T_Type, typename T_BinaryPredicate, class T_Allocator> class MTraitsContainer<NContainers::CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator> > : public MType<NContainers::CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator> > { public: //! Container value type. typedef typename NContainers::CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator>::TType value; //! Container type. typedef typename NContainers::CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator>::TContainer container; //! Container non constant iterator type. typedef typename NContainers::CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator>::TIterator iterator; //! Container constant iterator type. typedef typename NContainers::CBinTreeRB<T_Type, T_BinaryPredicate, T_Allocator>::TIteratorConst citerator; static const Tbool isConst = false; //!< Is container constant? static const Tbool isCircleSL = false; //!< Is container non constant single linked circle? static const Tbool isCircleSLConst = false; //!< Is container constant single linked circle? static const Tbool isCircleDL = false; //!< Is container non constant double linked circle? static const Tbool isCircleDLConst = false; //!< Is container constant double linked circle? static const Tbool isStack = false; //!< Is container non constant stack? static const Tbool isStackConst = false; //!< Is container constant stack? static const Tbool isQueue = false; //!< Is container non constant queue? static const Tbool isQueueConst = true; //!< Is container constant queue? static const Tbool isDeque = false; //!< Is container non constant deque? static const Tbool isDequeConst = true; //!< Is container constant deque? static const Tbool isRandom = false; //!< Is container non constant random? static const Tbool isRandomConst = false; //!< Is container constant random? static const Tbool isAssociative = true; //!< Is container non constant associative? static const Tbool isAssociativeConst = true; //!< Is container constant associative? static const Tbool isTree = false; //!< Is container non constant tree? static const Tbool isTreeConst = true; //!< Is container constant tree? static const Tbool isGraph = false; //!< Is container non constant graph? static const Tbool isGraphConst = false; //!< Is container constant graph? }; /*--------------------------------------------------------------------------*/ } /*--------------------------------------------------------------------------*/ } #include <Depth/include/containers/CBinTreeRB.inl> //! \example example-containers-CBinTreeRB.cpp /*--------------------------------------------------------------------------*/ //! \test test-containers-CBinTreeRB.cpp #endif
import React, { useMemo, useState } from "react"; import { Box, useTheme } from "@mui/material"; import Header from "components/Header"; import { ResponsiveLine } from "@nivo/line"; // import { useGetSalesQuery } from "state/api"; import { useGetProductStatsQuery } from "state/api"; import DatePicker from "react-datepicker"; import "react-datepicker/dist/react-datepicker.css"; const Daily = ({ isDashboard = false }) => { // adjust date const [startDate, setStartDate] = useState(new Date("2021-01-01")); const [endDate, setEndDate] = useState(new Date("2021-12-01")); const { data } = useGetProductStatsQuery(); const theme = useTheme(); const [formattedData] = useMemo(() => { if (!data) return []; const { dailyData } = data; const totalPurchaseLine = { id: "totalPurchase", color: theme.palette.secondary.main, data: [], }; const totalUnitsLine = { id: "totalUnits", color: theme.palette.secondary[600], data: [], }; Object.values(dailyData).forEach(({ date, totalPurchase, totalUnits }) => { const dateFormatted = new Date(date); if (dateFormatted >= startDate && dateFormatted <= endDate) { const splitDate = date.substring(date.indexOf("-") + 1); totalPurchaseLine.data = [ ...totalPurchaseLine.data, { x: splitDate, y: totalPurchase }, ]; totalUnitsLine.data = [ ...totalUnitsLine.data, { x: splitDate, y: totalUnits }, ]; } }); const formattedData = [totalPurchaseLine, totalUnitsLine]; return [formattedData]; }, [data, startDate, endDate]); // eslint-disable-line react-hooks/exhaustive-deps return ( <Box height={isDashboard ? "400px" : "100%"} width={undefined} minHeight={isDashboard ? "325px" : undefined} minWidth={isDashboard ? "325px" : undefined} position="relative" > <Header title="DAILY SALES" subtitle="Chart of daily sales" /> <Box height="75vh"> <Box display="flex" justifyContent="flex-end"> <Box> <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} selectsStart startDate={startDate} endDate={endDate} /> </Box> <Box> <DatePicker selected={endDate} onChange={(date) => setEndDate(date)} selectsEnd startDate={startDate} endDate={endDate} minDate={startDate} /> </Box> </Box> {data ? ( <ResponsiveLine data={formattedData} theme={{ axis: { domain: { line: { stroke: theme.palette.secondary[200], }, }, legend: { text: { fill: theme.palette.secondary[200], }, }, ticks: { line: { stroke: theme.palette.secondary[200], strokeWidth: 1, }, text: { fill: theme.palette.secondary[200], }, }, }, legends: { text: { fill: theme.palette.secondary[200], }, }, tooltip: { container: { color: theme.palette.primary.main, }, }, }} colors={{ datum: "color" }} margin={{ top: 50, right: 50, bottom: 70, left: 60 }} xScale={{ type: "point" }} yScale={{ type: "linear", min: "auto", max: "auto", stacked: false, reverse: false, }} yFormat=" >-.2f" curve="catmullRom" axisTop={null} axisRight={null} axisBottom={{ orient: "bottom", tickSize: 5, tickPadding: 5, tickRotation: 90, legend: "Month", legendOffset: 60, legendPosition: "middle", }} axisLeft={{ orient: "left", tickSize: 5, tickPadding: 5, tickRotation: 0, legend: "Total", legendOffset: -50, legendPosition: "middle", }} enableArcLinkLabels={!isDashboard} enableGridX={false} enableGridY={false} pointSize={10} pointColor={{ theme: "background" }} pointBorderWidth={2} pointBorderColor={{ from: "serieColor" }} pointLabelYOffset={-12} useMesh={true} legends={[ { anchor: "top-right", direction: "column", justify: false, translateX: isDashboard ? 50 : 0, translateY: isDashboard ? 0 : 56, // translateX: 50, // translateY: 0, itemsSpacing: 0, itemDirection: "left-to-right", itemWidth: 80, itemHeight: 20, itemOpacity: 0.75, symbolSize: 12, symbolShape: "circle", symbolBorderColor: "rgba(0, 0, 0, .5)", effects: [ { on: "hover", style: { itemBackground: "rgba(0, 0, 0, .03)", itemOpacity: 1, }, }, ], }, ]} /> ) : ( <>Loading...</> )} </Box> </Box> ); }; export default Daily; // import React, { useMemo, useState } from "react"; // import { Box, useTheme } from "@mui/material"; // import Header from "components/Header"; // import { ResponsiveLine } from "@nivo/line"; // // import { useGetSalesQuery } from "state/api"; // import { useGetProductStatsQuery } from "state/api"; // import DatePicker from "react-datepicker"; // import "react-datepicker/dist/react-datepicker.css"; // const Daily = ({ isDashboard = false }) => { // // adjust date // const [startDate, setStartDate] = useState(new Date("2021-01-01")); // const [endDate, setEndDate] = useState(new Date("2021-12-01")); // const { data } = useGetProductStatsQuery(); // const theme = useTheme(); // const [formattedData] = useMemo(() => { // if (!data) return []; // const { dailyData } = data; // const totalPurchaseLine = { // id: "totalPurchase", // color: theme.palette.secondary.main, // data: [], // }; // const totalUnitsLine = { // id: "totalUnits", // color: theme.palette.secondary[600], // data: [], // }; // Object.values(dailyData).forEach(({ date, totalPurchase, totalUnits }) => { // const dateFormatted = new Date(date); // if (dateFormatted >= startDate && dateFormatted <= endDate) { // const splitDate = date.substring(date.indexOf("-") + 1); // totalPurchaseLine.data = [ // ...totalPurchaseLine.data, // { x: splitDate, y: totalPurchase }, // ]; // totalUnitsLine.data = [ // ...totalUnitsLine.data, // { x: splitDate, y: totalUnits }, // ]; // } // }); // const formattedData = [totalPurchaseLine, totalUnitsLine]; // return [formattedData]; // }, [data, startDate, endDate]); // eslint-disable-line react-hooks/exhaustive-deps // return ( // <Box m="1.5rem 2.5rem"> // <Header title="DAILY SALES" subtitle="Chart of daily sales" /> // <Box height="75vh"> // <Box display="flex" justifyContent="flex-end"> // <Box> // <DatePicker // selected={startDate} // onChange={(date) => setStartDate(date)} // selectsStart // startDate={startDate} // endDate={endDate} // /> // </Box> // <Box> // <DatePicker // selected={endDate} // onChange={(date) => setEndDate(date)} // selectsEnd // startDate={startDate} // endDate={endDate} // minDate={startDate} // /> // </Box> // </Box> // {data ? ( // <ResponsiveLine // data={formattedData} // theme={{ // axis: { // domain: { // line: { // stroke: theme.palette.secondary[200], // }, // }, // legend: { // text: { // fill: theme.palette.secondary[200], // }, // }, // ticks: { // line: { // stroke: theme.palette.secondary[200], // strokeWidth: 1, // }, // text: { // fill: theme.palette.secondary[200], // }, // }, // }, // legends: { // text: { // fill: theme.palette.secondary[200], // }, // }, // tooltip: { // container: { // color: theme.palette.primary.main, // }, // }, // }} // colors={{ datum: "color" }} // margin={{ top: 50, right: 50, bottom: 70, left: 60 }} // xScale={{ type: "point" }} // yScale={{ // type: "linear", // min: "auto", // max: "auto", // stacked: false, // reverse: false, // }} // yFormat=" >-.2f" // curve="catmullRom" // axisTop={null} // axisRight={null} // axisBottom={{ // orient: "bottom", // tickSize: 5, // tickPadding: 5, // tickRotation: 90, // legend: "Month", // legendOffset: 60, // legendPosition: "middle", // }} // axisLeft={{ // orient: "left", // tickSize: 5, // tickPadding: 5, // tickRotation: 0, // legend: "Total", // legendOffset: -50, // legendPosition: "middle", // }} // enableGridX={false} // enableGridY={false} // pointSize={10} // pointColor={{ theme: "background" }} // pointBorderWidth={2} // pointBorderColor={{ from: "serieColor" }} // pointLabelYOffset={-12} // useMesh={true} // legends={[ // { // anchor: "top-right", // direction: "column", // justify: false, // translateX: 50, // translateY: 0, // itemsSpacing: 0, // itemDirection: "left-to-right", // itemWidth: 80, // itemHeight: 20, // itemOpacity: 0.75, // symbolSize: 12, // symbolShape: "circle", // symbolBorderColor: "rgba(0, 0, 0, .5)", // effects: [ // { // on: "hover", // style: { // itemBackground: "rgba(0, 0, 0, .03)", // itemOpacity: 1, // }, // }, // ], // }, // ]} // /> // ) : ( // <>Loading...</> // )} // </Box> // </Box> // ); // }; // export default Daily;
#!/software/hgi/installs/anaconda3/envs/hgi_base/bin/Rscript --vanilla ## Note! It is not intended that you use this file directly as it is adapted to Sanger's LSF submission ## system (See callouts for LSB_JOBINDEX). It is intended that you modify this script to fit your job ## submission sytem. library(data.table) library(tidyr) library(dplyr) library(broom) library(meta) args <- commandArgs(trailingOnly = T) input.icd <- args[1] variant.maf <- as.integer(args[2]) age.cutoff <- as.integer(args[3]) fi.only <- as.logical(args[4]) outdir <- args[5] disease.data.long <- readRDS(input.icd) disease.data.long <- disease.data.long[age.at.incidence < age.cutoff] icd.codes <- fread("rawdata/phewas/icd10_tree.tsv", header = T) variant.counts <- readRDS("rawdata/phewas/variant_counts.rdat") UKBB.phenotype.data <- readRDS("rawdata/phewas/UKBB.phenotype.rdat") if (fi.only == T) { UKBB.phenotype.data <- UKBB.phenotype.data[has.first.incidence.data == T] } current.code <- as.integer(Sys.getenv("LSB_JOBINDEX")) current.code.line <- icd.codes[current.code] outfile <- paste("glm",current.code,"out",sep=".") outfile <- paste(outdir,outfile,sep="/") get.participants <- function(code, node, ids = c()) { ids <- c(ids, unique(disease.data.long[icd.code %in% code,eid])) curr.children <- icd.codes[parent_id == node] if (nrow(curr.children) != 0) { for (i in 1:nrow(curr.children)) { ids <- c(get.participants(curr.children[i, coding], curr.children[i, node_id], ids)) } return(ids) } else { return(ids) } } run.lm <- function(code, node, sex, variant.type) { ## Some individuals have multiple codes in the same category when dealing with blocks indv.with.code <- unique(get.participants(code, node)) lm.table <- merge(UKBB.phenotype.data,variant.counts[allele.freq == variant.maf & type == variant.type],by.x="eid",by.y="sample_id") lm.table[,has.disorder:=if_else(eid %in% indv.with.code,1,0)] # Set Covariates: covariates <- c("product_sHET","has.disorder","sexPulse","agePulse","agePulse.squared","birth.year.cut",paste0("PC",seq(1,40)), paste0("scaled.rare.PC",seq(1,100))) ## Remove WES individuals from CNV analyses for meta-analysis purposes if (variant.type == "DEL") { lm.table <- lm.table[has.wes == 0] } else { covariates <- c(covariates,"has.wes") } if (sex == "MALE") { lm.table <- lm.table[sexPulse == 1 & !is.na(children.fathered)] lm.table[,has.children:=if_else(children.fathered > 0,1,0)] } else if (sex == "FEMALE") { lm.table <- lm.table[sexPulse == 2 & !is.na(live.births)] lm.table[,has.children:=if_else(live.births > 0,1,0)] } if (nrow(lm.table[has.disorder == 1]) < 2) { return(list(NaN, NaN, NaN, NaN, NaN, NaN, nrow(lm.table[has.disorder == 1]), nrow(lm.table[has.disorder == 1 & product_sHET > 0]))) } else { lm.formula <- as.formula(paste("has.children",paste(covariates,collapse = "+"),sep="~")) lm.model <- glm(lm.formula, data = lm.table, family = "binomial") lm.out <- data.table(tidy(lm.model)) return(list(lm.out[term=="product_sHET",estimate], lm.out[term=="product_sHET",std.error], lm.out[term=="product_sHET",p.value], lm.out[term=="has.disorder",estimate], lm.out[term=="has.disorder",std.error], lm.out[term=="has.disorder",p.value], nrow(lm.table[has.disorder == 1]), nrow(lm.table[has.disorder == 1 & product_sHET > 0]))) } } analysis.table <- data.table(crossing(current.code.line[,c("coding","meaning","node_id")],sex=c("MALE","FEMALE"),variant.type = c("DEL","LOF_HC"))) analysis.table[,c("var.est","var.err","var.p","icd.est","icd.err","icd.p","n","n.cases"):=run.lm(coding,node_id,sex,variant.type),by=1:nrow(analysis.table)] get.meta.val <- function(s) { meta.table <- analysis.table[sex == s] result <- list() if (nrow(meta.table[is.na(var.est)]) > 0) { result <- append(result, list(NaN,NaN,NaN)) } else { meta.analy.var <- metagen(var.est, var.err, studlab = variant.type, method.tau = "SJ", sm = "OR", data = meta.table) result <- append(result, list(meta.analy.var$TE.fixed, meta.analy.var$seTE.fixed, meta.analy.var$pval.fixed)) } if (nrow(meta.table[is.na(icd.est)]) > 0) { result <- append(result, list(NaN,NaN,NaN)) } else { meta.analy.icd <- metagen(icd.est, icd.err, studlab = variant.type, method.tau = "SJ", sm = "OR", data = meta.table) result <- append(result, list(meta.analy.icd$TE.fixed, meta.analy.icd$seTE.fixed, meta.analy.icd$pval.fixed)) } result <- append(result, list(meta.table[,sum(n)],meta.table[,sum(n.cases)])) return(result) } meta.table <- data.table(current.code.line[,c("coding","meaning","node_id")], sex = c("MALE","FEMALE"), variant.type = "META") meta.table[,c("var.est","var.err","var.p","icd.est","icd.err","icd.p","n","n.cases"):=get.meta.val(sex),by=1:nrow(meta.table)] analysis.table <- rbind(analysis.table, meta.table) get.chapter <- function(code) { curr.code <- icd.codes[node_id == code,coding] curr.par <- icd.codes[node_id == code,parent_id] if (grepl("Chapter",curr.code) == T) { return(curr.code) } else if (grepl("-1",curr.code) == T) { return(NA) } else { get.chapter(curr.par) } } analysis.table[,chapter:=get.chapter(node_id),by=1:nrow(analysis.table)] tree.climb <- function(code, level = 1) { curr.par <- icd.codes[node_id == code,parent_id] if (curr.par == 0) { return(level) } else { level <- tree.climb(curr.par, level + 1) } } analysis.table[,level:=tree.climb(node_id),by=1:nrow(analysis.table)] write.table(analysis.table,outfile,col.names = F,row.names = F,sep = "\t", quote = F)
import torch from torch import Tensor import deepinv as dinv class MultispectralUtils: """Utility class to obtain lrms, hrms and pan images from concatenated volumes. We assume that all volumes are passed around as (B,C+1,H,W) where the extra channel is the pan band, and H,W are the HR dimensions. LRMS is stored by upsampling and zero-filling. The RGB and NIR utilities assume that the RGB are the first 3 channels followed by NIR. """ def lrms_from_volume(self, volume: Tensor, scale_factor: int = 4) -> Tensor: return volume[:, :-1, ::scale_factor, ::scale_factor] def pan_from_volume(self, volume: Tensor) -> Tensor: return volume[:, [-1], :, :] def hrms_from_volume(self, volume: Tensor) -> Tensor: return volume[:, :-1, :, :] def rgb_from_ms(self, ms: Tensor) -> Tensor: return ms[:, :3, :, :] def nir_from_ms(self, ms: Tensor) -> Tensor: assert ms.shape[1] == 4 return ms[:, 3, :, :] def rgb_nir_from_ms(self, ms: Tensor) -> tuple: return self.rgb_from_ms(ms), self.nir_from_ms(ms) def hrms_pan_to_volume(self, hrms: Tensor, pan: Tensor) -> Tensor: return torch.cat([hrms, pan], dim=1) def lrms_pan_to_volume(self, lrms: Tensor, pan: Tensor, scale_factor: int = 4) -> Tensor: lrms_up = torch.zeros(( lrms.shape[0], lrms.shape[1], lrms.shape[2] * scale_factor, lrms.shape[3] * scale_factor ), device=lrms.device) lrms_up[:, :, :: scale_factor, :: scale_factor] = lrms return self.hrms_pan_to_volume(lrms_up, pan) def plot_multispectral(x: torch.Tensor | list, y: torch.Tensor=None): """Plot HRMS, LRMS and PAN images from x and y volumes. :param torch.Tensor x: _description_ :param torch.Tensor y: _description_, defaults to None :return _type_: _description_ """ msu = MultispectralUtils() if isinstance(x, (tuple, list)): return dinv.utils.plot([msu.rgb_from_ms(msu.hrms_from_volume(_x)) for _x in x]) elif y is None: return dinv.utils.plot(msu.rgb_from_ms(msu.hrms_from_volume(x))) else: return dinv.utils.plot([ msu.rgb_from_ms(msu.hrms_from_volume(x)), msu.rgb_from_ms(msu.lrms_from_volume(y)), msu.rgb_from_ms(msu.pan_from_volume(y)) ], titles=["HRMS", "LRMS", "PAN"])
/* eslint-disable @typescript-eslint/no-unused-vars */ import { Card, Space, Typography, Divider, } from 'antd'; import TextArea from 'antd/lib/input/TextArea'; import React, { forwardRef, useEffect, useImperativeHandle, useState, } from 'react'; import { useForm, FormProvider, Controller, } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import BrowserPreviewModal from './BrowserPreviewModal'; import MediaSocialForm from './MediaSocialForm'; import MetaDataForm from './MetaDataForm'; import SeoDataForm from './SeoDataForm'; import SocialPreviewModal from './SocialPreviewModal'; import { SeoFormTypes } from './types'; import mapModifiers from 'common/utils/functions'; export type OthersFormType = CommentFormType; export interface PreviewSeoModalType { open: boolean; data?: SeoFormTypes; } type CommentFormType = { comment: string; }; export interface SeoSectionActionProps { handleOpenBrowserPreview: () => void; handleOpenSocialPreview: () => void; handleForm: () => Promise<SeoFormTypes | undefined>; isFormDirty: () => boolean; handleOthersForm: () => OthersFormType | undefined; clearOthersForm: (fieldName?: keyof OthersFormType) => void; reset: (data?: SeoFormTypes) => void; } interface SeoSectionProps { defaultValues?: SeoFormTypes; socialList?: OptionType[]; children?: React.ReactNode; noLabel?: boolean; canCreateComment?: boolean; } const SeoSection = forwardRef<SeoSectionActionProps, SeoSectionProps>(({ defaultValues, socialList, noLabel, children, canCreateComment }, ref) => { const { t } = useTranslation(); /* States */ const [browserPreview, setBrowserPreview] = useState<PreviewSeoModalType>({ open: false, data: undefined, }); const [socialPreview, setSocialPreview] = useState<PreviewSeoModalType>({ open: false, data: undefined, }); /* React-hook-form */ const method = useForm<CommentFormType>({ mode: 'onSubmit', defaultValues: { comment: '', } }); const seoMethod = useForm<SeoFormTypes>({ mode: 'onChange', defaultValues: defaultValues || { seoTitle: '', seoIntro: '', seoKeyword: '', ogImage: '', mediaSocial: [] } }); const { isDirty } = seoMethod.formState; useEffect(() => { if (defaultValues) { seoMethod.reset(defaultValues); } }, [defaultValues, seoMethod]); /* Functions */ const handleCloseBrowserPreview = () => { setBrowserPreview({ open: false, data: undefined, }); }; const handleCloseSocialPreview = () => { setSocialPreview({ open: false, data: undefined, }); }; /* Imperative Handler */ useImperativeHandle(ref, () => ({ handleOpenBrowserPreview: () => { setBrowserPreview({ open: true, data: seoMethod.getValues(), }); }, handleOpenSocialPreview: () => { setSocialPreview({ open: true, data: seoMethod.getValues(), }); }, handleForm: async () => { const isValid = await seoMethod.trigger(); if (isValid) { return seoMethod.getValues(); } return undefined; }, isFormDirty: () => isDirty, handleOthersForm: () => method.getValues(), clearOthersForm: ( fieldName?: keyof OthersFormType ) => { if (fieldName) { method.resetField(fieldName); } else { method.reset(); } }, reset: (data?: SeoFormTypes) => seoMethod.reset(data), })); return ( <div className="seoSection"> {!noLabel && ( <div className="seoSection_label"> {t('dashboard.others')} </div> )} {children} {canCreateComment && ( <FormProvider {...method}> <form noValidate> <Card> <Space direction="vertical" size={12} style={{ width: '100%' }}> <div className="seoSection_comment"> <Typography.Text strong> {t('system.comments')} </Typography.Text> <Controller name="comment" render={({ field }) => ( <TextArea {...field} className="u-mt-8" value={field.value} onChange={field.onChange} size="large" rows={2} style={{ minHeight: 50 }} /> )} /> </div> </Space> </Card> </form> </FormProvider> )} <div className="u-mt-16"> <FormProvider<SeoFormTypes> {...seoMethod}> <form noValidate> <div className="site-card-border-less-wrapper"> <Card type="inner" title={( <Typography.Title level={5} className={mapModifiers('seoSection_title', !!(Object.keys(seoMethod.formState.errors).length) && 'error')} > SEO </Typography.Title> )} > <Space direction="vertical" size={12} style={{ width: '100%' }}> <SeoDataForm /> {/* <Divider /> */} <div className="seoSection_social"> {/* <MediaSocialForm method={seoMethod} socialList={socialList} /> <Divider /> */} <MetaDataForm /> </div> </Space> </Card> </div> </form> </FormProvider> </div> {/* Modals */} <BrowserPreviewModal href="https://onecms-spa.3forcom.net" isOpen={browserPreview.open} handleIsOpen={handleCloseBrowserPreview} seoData={browserPreview.data} /> <SocialPreviewModal isOpen={socialPreview.open} href="https://onecms-spa.3forcom.net" handleIsOpen={handleCloseSocialPreview} seoData={socialPreview.data} socialList={socialList} /> </div> ); }); export default SeoSection;
from django import forms from django.contrib.auth.models import User from .models import Profile class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput) class Meta: model = User fields = ["username", "email"] def clean_password2(self): cd = self.cleaned_data if cd["password"] != cd["password2"]: raise forms.ValidationError("Passwords don't match.") return cd["password2"] def clean_email(self): email = self.cleaned_data["email"] if not email: return email if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email already in use by another user.") return email class UserEditForm(forms.ModelForm): class Meta: model = User fields = ["username", "email"] def clean_email(self): email = self.cleaned_data["email"] if not email: return email email_exists = ( User.objects.exclude(id=self.instance.id).filter(email=email).exists() ) if email_exists: raise forms.ValidationError("Email already in use by another user.") return email class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = ["title", "photo", "facebook_profile_link", "twitter_profile_link"] def clean_facebook_profile_link(self): fb_link = self.cleaned_data["facebook_profile_link"] if fb_link == "" or fb_link.startswith("https://web.facebook.com"): return fb_link else: raise forms.ValidationError("Not a valid facebook link.") def clean_twitter_profile_link(self): twitter_link = self.cleaned_data["twitter_profile_link"] if twitter_link == "" or twitter_link.startswith("https://twitter.com"): return twitter_link else: raise forms.ValidationError("Not a valid twitter link.") def clean_photo(self): photo = self.cleaned_data["photo"] if not photo or (photo.size / 2**10) <= 100: return photo else: raise forms.ValidationError( "Image size should not be larger than 100 kilobytes." )
import React, { useContext, useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import { Context } from "../store/appContext"; const Login = () => { const { store, actions } = useContext(Context); const [formValue, setFormValue] = useState({ email: "", password: "" }); const navigate = useNavigate(); function onChange(e) { const id = e.target.id; const value = e.target.value; setFormValue({ ...formValue, [id]: value }); } return ( <div className="container login-container mt-5"> <form className="row g-3 border border-lightgray bg-light"> <div className="py-2 bg-light border-bottom border-lightgray mt-0 text-center"> <h2>Login</h2> </div> <div className="col-md-12"> <label htmlFor="email" className="form-label"> Email </label> <input onChange={onChange} value={formValue.email} type="email" className="form-control" placeholder="Enter email" id="email" /> </div> <div className="col-md-12"> <label htmlFor="password" className="form-label"> Password </label> <input onChange={onChange} value={formValue.password} type="password" className="form-control" placeholder="Enter password" id="password" /> </div> <div className="col-md-12"> {/* Link to the forgotpassword page */} <Link to="/forgotpassword">Forgot Password?</Link> </div> <br /> <br /> <button type="button" // Assuming 'actions' is defined elsewhere in your code // and contains the 'login' function onClick={() => actions.login(formValue, navigate)} className="btn btn-primary" > Login </button> </form> </div> ); }; export default Login;
package br.com.capsistema.view.jetpackcomposepermissions import android.Manifest import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Settings import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import br.com.capsistema.view.jetpackcomposepermissions.ui.theme.JetpackComposePermissionsTheme class MainActivity : ComponentActivity() { private val permissionRequired = Manifest.permission.CAMERA override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposePermissionsTheme { var showPermissionDialog by remember { mutableStateOf(false) } val storagePermissionResultLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission(), onResult = { isGranted -> if (isGranted) { Toast .makeText(this, "Permission granted", Toast.LENGTH_SHORT) .show() } showPermissionDialog = !isGranted } ) Scaffold { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Button(onClick = { storagePermissionResultLauncher.launch(permissionRequired) }) { Text(text = "Request permission") } } } if (showPermissionDialog) { PermissionDialog(StoragePermissionDialogTextProvider(), isPermanentlyDeclined = !shouldShowRequestPermissionRationale(permissionRequired), onDismiss = { showPermissionDialog = false }, onOkClick = { storagePermissionResultLauncher.launch(permissionRequired) showPermissionDialog = false }, onGoToAppSettingsClick = { openAppSettings() showPermissionDialog = false } ) } } } } private fun openAppSettings() { val intent = Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null) ) startActivity(intent) } }
import { useState } from "react"; export interface IuseObjBoolFns { [key: string]: (newValue: boolean) => void; } export const useObjectBool = ( initialKeys: Array<[string, boolean]> ): [Record<string, boolean>, IuseObjBoolFns, (key: string) => boolean] => { // useState const [value, setValue] = useState<Record<string, boolean>>(() => { const initialObj: Record<string, boolean> = {}; initialKeys.forEach(([key, value]): void => { initialObj[key] = value; }); // console.log("[initialObj]", initialObj); return { ...initialObj }; }); const setBool = (key: string) => (newValue: boolean) => { setValue((oldValue) => { return { ...oldValue, [key]: newValue, }; }); }; const valueObjBoolFn = () => { const result: Record<string, (newValue: boolean) => void> = {}; for (const [key] of initialKeys) { result[key] = setBool(key); } return result; }; const toggle = (key: string) => { const oppositeValue = !value[key]; setValue((oldValue) => { return { ...oldValue, [key]: !oldValue[key] } }) return oppositeValue } return [value, valueObjBoolFn(), toggle]; };
"""microauth URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^admin/', admin.site.urls), # django-oauth-toolkit url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^', include('apps.authentication.urls', namespace='microauth_authentication')), url(r'^api/', include('apps.api.urls', namespace='microauth_api')), url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}), ] urlpatterns += staticfiles_urlpatterns()
import json import requests from config import currencies import os from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) class APIException(Exception): """ Класс исключений ошибок пользователя. ... """ pass class CurrencyConverter: """ Класс конвертера валют. ... Methods ------- @staticmethod get_price(base: str, quote: str, amount: str) -> float: Метод, конвертирующий валюту. """ @staticmethod def get_price(base: str, quote: str, amount: str) -> float: """ Метод, конвертирующий валюту. Parameters ---------- quote : str валюта из которой конвертируем base : str валюта в которую конвертируем amount : int количество конвертируемой валюты Returns ------- total_quote : float итоговое количество конвертируемой валюты """ if quote == base: raise APIException(f'Невозможно перевести одинаковые валюты: {base}.') try: quote_ticker = currencies[quote] except KeyError: raise APIException(f'Не удалось обработать валюту: {quote}') try: base_ticker = currencies[base] except KeyError: raise APIException(f'Не удалось обработать валюту: {base}') try: amount = float(amount) except ValueError: raise APIException(f'Не удалось обработать количество: {amount}') main_request = requests.get( f'https://v6.exchangerate-api.com/v6/{os.getenv('api_token')}/pair/{base_ticker}/{quote_ticker}') total_quote = float(json.loads(main_request.content)['conversion_rate'] * amount) return total_quote
import React, { useEffect, useState } from 'react' import { getDeck, getFirstNPokemon, IsGameOver, } from '../../Utils/functionUtils' import { CardComponent } from '../CardComponent/CardComponent' import style from './GameComponent.module.scss' export type Card = { pokemonName: string isVisible: boolean isMatched: boolean } type CardWithIndex = Card & { cardIndex: number } type GameProps = { pokemonArray: Card[] } const Game: React.FunctionComponent<GameProps> = ({ pokemonArray }) => { const [allCards, setAllCards] = useState<Card[]>(pokemonArray) const [victoryState, setVictoryState] = useState(false) const [cardToCheck, setCardToCheck] = useState<CardWithIndex | null>(null) const [isClicked, setIsClicked] = useState(false) const [score, setScore] = useState(0) const [isPlayAgain, setIsPlayAgain] = useState(false) useEffect(() => { if (IsGameOver(allCards)) { setVictoryState(true) } }, [allCards, victoryState]) useEffect(() => { if (isPlayAgain) { setIsPlayAgain(false) const numPokemon = pokemonArray.length / 2 const newFirstNPokemon = getFirstNPokemon(numPokemon) const newPokemonDeck = getDeck(newFirstNPokemon) setAllCards(newPokemonDeck) setVictoryState(false) setCardToCheck(null) setIsClicked(false) setScore(0) } }, [ pokemonArray, isPlayAgain, allCards, victoryState, cardToCheck, isClicked, score, ]) const toggleCard = (index: number) => { setAllCards((prevState) => { const localState = [...prevState] const currentCard = localState[index] const newCard: Card = { ...currentCard, isVisible: !currentCard.isVisible, } localState[index] = newCard return localState }) } const setMatch = (first: number, second: number) => setAllCards((prevCardState) => { return prevCardState.map((card, index) => { if (index === first || index === second) { return { ...card, isMatched: true, } } return card }) }) const incrementScore = () => { setScore(score + 5) } const decrementScore = () => { if (score < 1) { setScore(0) return } setScore(score - 1) } const checkIfCardsMatched = (currentCard: Card, currentCardIndex: number) => { if (allCards[currentCardIndex].isMatched) return if (isClicked) return toggleCard(currentCardIndex) if (cardToCheck === null) { setCardToCheck({ ...currentCard, cardIndex: currentCardIndex }) return } if (cardToCheck.cardIndex === currentCardIndex) { return } setIsClicked(true) setTimeout(() => { if (cardToCheck.pokemonName !== currentCard.pokemonName) { const storedCardIndex = cardToCheck.cardIndex toggleCard(storedCardIndex) toggleCard(currentCardIndex) setCardToCheck(null) decrementScore() } else { setCardToCheck(null) setMatch(cardToCheck.cardIndex, currentCardIndex) incrementScore() } setIsClicked(false) console.log(`Now you can click it`) }, 300) } return ( <div> <div className={style.game}> <div className={style.gameInfo}> <div className={style.gameInfoForItems}>Score: {score}</div> {victoryState && ( <div className={style.gameInfoForItems}>You win!</div> )} <button className={`${style.gameInfoForItems} ${style.playAgainButton}`} onClick={() => { setIsPlayAgain(true) }} > Play again </button> </div> <div className={style.deck}> {allCards.map((card, indexCard) => { return ( <div key={indexCard} className="card" onClick={() => checkIfCardsMatched(card, indexCard)} > <CardComponent card={card} /> </div> ) })} </div> </div> </div> ) } export { Game }
import { useCallback } from "react"; import CartGoodCard from "./CartGoodCard"; import { AddToCart, CartReducer, ClearCart, RemoveFromCart, SetCartItem, } from "./cart"; import { API_URL } from "./constants"; import { useLocalStorage } from "./useLocalStorage"; export interface CartPageProps { reducer: CartReducer; } const CartPage: React.FC<CartPageProps> = ({ reducer }) => { const [cart, dispatch] = reducer; const [name, setName] = useLocalStorage("name"); const [email, setEmail] = useLocalStorage("email"); const [phone, setPhone] = useLocalStorage("phone"); const [address, setAddress] = useLocalStorage("address"); const makeOrder: React.FormEventHandler<HTMLFormElement> = useCallback( async (e) => { e.preventDefault(); if (cart.items.length === 0) { alert("Cart is empty"); return; } const form = e.target as HTMLFormElement; const formData = new FormData(form); const obj = Object.fromEntries(formData.entries()); fetch(`${API_URL}/order`, { method: "post", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...obj, items: cart.items.map((item) => ({ good: item.good.id, count: item.count, })), }), }).then((res) => { if (res.ok) { alert("Order has been made"); dispatch(ClearCart()); } }); }, [cart], ); return ( <div className="flex flex-row p-2"> <form className="w-1/2" onSubmit={makeOrder}> <label className="block border my-2 p-1"> Name: <input className="border w-full p-0.5" type="text" name="name" required value={name} onChange={(e) => setName(e.target.value)} /> </label> <label className="block border my-2 p-1"> Email: <input className="border w-full p-0.5" type="text" name="email" required value={email} onChange={(e) => setEmail(e.target.value)} /> </label> <label className="block border my-2 p-1"> Phone: <input className="border w-full p-0.5" type="text" name="phone" required value={phone} onChange={(e) => setPhone(e.target.value)} /> </label> <label className="block border my-2 p-1"> Address: <input className="border w-full p-0.5" type="text" name="address" required value={address} onChange={(e) => setAddress(e.target.value)} /> </label> <button type="submit" className="border rounded p-2 bg-blue-100 hover:bg-blue-200 w-full my-2" > Order </button> </form> <div className="grid grid-cols-1 w-full"> {cart.items.map((item) => ( <div key={item.good.id} className="flex"> <CartGoodCard {...item.good} count={item.count} onAddToCart={dispatch.bind(null, AddToCart(item.good))} onRemoveFromCart={dispatch.bind( null, RemoveFromCart(item.good.id), )} onCountChange={(count) => dispatch( SetCartItem({ good: item.good, count: Math.max(1, count), }), ) } /> </div> ))} </div> </div> ); }; export default CartPage;
package com.lollypop.runtime.instructions.invocables import com.lollypop.language._ import com.lollypop.runtime.errors.ScenarioNotFoundError import com.lollypop.runtime.instructions.VerificationTools import com.lollypop.runtime.instructions.conditions.Verify import com.lollypop.runtime.instructions.expressions.{Dictionary, Infix, WWW} import com.lollypop.runtime.{LollypopCompiler, LollypopVM, Scope} import org.scalatest.funspec.AnyFunSpec /** * Scenario Test Suite */ class ScenarioTest extends AnyFunSpec with VerificationTools { implicit val compiler: LollypopCompiler = LollypopCompiler() describe(classOf[Scenario].getSimpleName) { it("should compile a simple scenario") { val model = compiler.compile( """|scenario 'Create a new contest' { | val response = www post 'http://{{host}}:{{port}}/api/shocktrade/contests' <~ { name: "Winter is coming" } | verify response.statusCode is 200 |} |""".stripMargin) assert(model == Scenario( title = "Create a new contest".v, verifications = Seq( ValVar(ref = "response", `type` = None, initialValue = Some( WWW(method = "post", url = "http://{{host}}:{{port}}/api/shocktrade/contests".v, body = Some( Dictionary(Map("name" -> "Winter is coming".v)) )) ), isReadOnly = true), Verify(Infix("response".f, "statusCode".f) is 200.v) ) )) } it("should compile a scenario that \"extends\" a parent scenario") { val model = compiler.compile( """|scenario 'Retrieve the previously created contest' extends 'Create a new contest' { | val response = www get 'http://{{host}}:{{port}}/api/shocktrade/contests?id={{contest_id}}' | verify response.statusCode is 200 |} |""".stripMargin) assert(model == Scenario( title = "Retrieve the previously created contest".v, inherits = Some("Create a new contest".v), verifications = Seq( ValVar(ref = "response", `type` = None, initialValue = Some( WWW(method = "get", url = "http://{{host}}:{{port}}/api/shocktrade/contests?id={{contest_id}}".v) ), isReadOnly = true), Verify(Infix("response".f, "statusCode".f) is 200.v) ) )) } it("should execute a scenario that \"extends\" its state from a peer scenario") { val (_, _, result) = LollypopVM.executeSQL(Scope(), """|feature "State Inheritance" { | scenario 'Create a contest' { | val contest_id = "40d1857b-474c-4400-8f07-5e04cbacc021" | var counter = 1 | stdout <=== "contest_id = {{contest_id}}, counter = {{counter}}" | verify contest_id is "40d1857b-474c-4400-8f07-5e04cbacc021" | and counter is 1 | } | | scenario 'Create a member' { | val member_id = "4264f8a5-6fa3-4a38-b3bb-30e2e0b826d1" | stdout <=== "member_id = {{member_id}}" | verify member_id is "4264f8a5-6fa3-4a38-b3bb-30e2e0b826d1" | } | | scenario 'Inherit contest state' extends 'Create a contest' { | counter = counter + 1 | stdout <=== "contest_id = {{contest_id}}, counter = {{counter}}" | verify contest_id is "40d1857b-474c-4400-8f07-5e04cbacc021" | and counter is 2 | } | | scenario 'Inherit contest and member state' extends ['Create a contest', 'Create a member'] { | counter = counter + 1 | stdout <=== "contest_id = {{contest_id}}, member_id = {{member_id}}, counter = {{counter}}" | verify contest_id is "40d1857b-474c-4400-8f07-5e04cbacc021" | and member_id is "4264f8a5-6fa3-4a38-b3bb-30e2e0b826d1" | and counter is 3 | } |} |""".stripMargin) assert(result == Map("passed" -> 4, "failed" -> 0)) } it("should fail if the state inherited from a peer scenario does not exist") { assertThrows[ScenarioNotFoundError] { LollypopVM.executeSQL(Scope(), """|feature "Shared state between tests" { | scenario 'Create some state' { | contest_id = "40d1857b-474c-4400-8f07-5e04cbacc021" | counter = 1 | stdout <=== "contest_id = {{contest_id}}, counter = {{counter}}" | verify contest_id is "40d1857b-474c-4400-8f07-5e04cbacc021" | and counter is 1 | } | | scenario 'Pass state from a parent' extends 'Create XXX state' { | counter = counter + 1 | stdout <=== "contest_id = {{contest_id}}, counter = {{counter}}" | verify contest_id is "40d1857b-474c-4400-8f07-5e04cbacc021" | and counter is 2 | } |} |""".stripMargin) } } } }
/************************************************************************* * Copyright 2009-2016 Ent. Services Development Corporation LP * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ************************************************************************/ package com.eucalyptus.autoscaling.common.internal.groups; import static com.eucalyptus.autoscaling.common.AutoScalingMetadata.AutoScalingGroupMetadata; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Example; import org.hibernate.criterion.Junction; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Property; import org.hibernate.criterion.Restrictions; import com.eucalyptus.autoscaling.common.AutoScalingResourceName; import com.eucalyptus.autoscaling.common.internal.instances.AutoScalingInstance; import com.eucalyptus.autoscaling.common.internal.instances.HealthStatus; import com.eucalyptus.autoscaling.common.internal.metadata.AbstractOwnedPersistents; import com.eucalyptus.autoscaling.common.internal.metadata.AbstractOwnedPersistentsWithResourceNameSupport; import com.eucalyptus.autoscaling.common.internal.metadata.AutoScalingMetadataException; import com.eucalyptus.component.annotation.ComponentNamed; import com.eucalyptus.util.Callback; import com.eucalyptus.auth.principal.OwnerFullName; import com.eucalyptus.util.FUtils; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Sets; /** * */ @ComponentNamed public class PersistenceAutoScalingGroups extends AutoScalingGroups { private PersistenceSupport persistenceSupport = new PersistenceSupport(); @Override public <T> List<T> list( final OwnerFullName ownerFullName, final Predicate<? super AutoScalingGroup> filter, final Function<? super AutoScalingGroup,T> transform ) throws AutoScalingMetadataException { return persistenceSupport.list( ownerFullName, filter, transform ); } @Override public <T> List<T> listRequiringScaling( final Function<? super AutoScalingGroup,T> transform ) throws AutoScalingMetadataException { return persistenceSupport.listByExample( AutoScalingGroup.requiringScaling(), Predicates.alwaysTrue(), transform ); } @Override public <T> List<T> listRequiringInstanceReplacement( final Function<? super AutoScalingGroup,T> transform ) throws AutoScalingMetadataException { final DetachedCriteria criteria = DetachedCriteria.forClass( AutoScalingInstance.class ) .add( Example.create( AutoScalingInstance.withHealthStatus( HealthStatus.Unhealthy ) ) ) .setProjection( Projections.property( "autoScalingGroup" ) ); return persistenceSupport.listByExample( AutoScalingGroup.withOwner( null ), Predicates.alwaysTrue(), Property.forName( "id" ).in( criteria ), Collections.<String, String>emptyMap(), transform ); } @Override public <T> List<T> listRequiringMonitoring( final Set<MonitoringSelector> selectors, final Function<? super AutoScalingGroup,T> transform ) throws AutoScalingMetadataException { final Collection<String> suffixes = selectors.stream( ) .flatMap( FUtils.chain( MonitoringSelector::suffixes, Collection::stream ) ) .collect( Collectors.toSet( ) ); final Junction likeAnyOf = Restrictions.disjunction(); for ( final String suffix : suffixes ) { likeAnyOf.add( Restrictions.ilike( "id", "%" + suffix ) ); } return persistenceSupport.listByExample( AutoScalingGroup.withOwner( null ), Predicates.alwaysTrue(), likeAnyOf, Collections.<String,String>emptyMap(), transform ); } @Override public <T> T lookup( final OwnerFullName ownerFullName, final String autoScalingGroupName, final Function<? super AutoScalingGroup,T> transform ) throws AutoScalingMetadataException { return persistenceSupport.lookup( ownerFullName, autoScalingGroupName, transform ); } @Override public void update( final OwnerFullName ownerFullName, final String autoScalingGroupName, final Callback<AutoScalingGroup> groupUpdateCallback ) throws AutoScalingMetadataException { persistenceSupport.updateWithRetries( ownerFullName, autoScalingGroupName, groupUpdateCallback ); } @Override public void markScalingRequiredForZones( final Set<String> availabilityZones ) throws AutoScalingMetadataException { if ( !availabilityZones.isEmpty() ) { persistenceSupport.transactionWithRetry( AutoScalingGroup.class, new AbstractOwnedPersistents.WorkCallback<Void>() { @Override public Void doWork() throws AutoScalingMetadataException { final List<AutoScalingGroup> groups = persistenceSupport.listByExample( AutoScalingGroup.withOwner( null ), Predicates.alwaysTrue(), Functions.<AutoScalingGroup>identity() ); for ( final AutoScalingGroup group : groups ) { if ( !Sets.union( Sets.newHashSet( group.getAvailabilityZones() ), availabilityZones ).isEmpty() ) { group.setScalingRequired( true ); } } return null; } } ); } } @Override public boolean delete( final AutoScalingGroupMetadata autoScalingGroup ) throws AutoScalingMetadataException { return persistenceSupport.delete( autoScalingGroup ); } @Override public AutoScalingGroup save( final AutoScalingGroup autoScalingGroup ) throws AutoScalingMetadataException { return persistenceSupport.save( autoScalingGroup ); } private static class PersistenceSupport extends AbstractOwnedPersistentsWithResourceNameSupport<AutoScalingGroup> { private PersistenceSupport() { super( AutoScalingResourceName.Type.autoScalingGroup ); } @Override protected AutoScalingGroup exampleWithOwner( final OwnerFullName ownerFullName ) { return AutoScalingGroup.withOwner( ownerFullName ); } @Override protected AutoScalingGroup exampleWithName( final OwnerFullName ownerFullName, final String name ) { return AutoScalingGroup.named( ownerFullName, name ); } @Override protected AutoScalingGroup exampleWithUuid( final String uuid ) { return AutoScalingGroup.withUuid( uuid ); } } }
------------------------------------------------------------------------ -- The Agda standard library -- -- The basic code for equational reasoning with a non-reflexive relation ------------------------------------------------------------------------ {-# OPTIONS --cubical-compatible --safe #-} open import Function using (case_of_) open import Level using (_⊔_) open import Relation.Binary.Core open import Relation.Binary.Definitions open import Relation.Nullary.Decidable using (Dec; yes; no) open import Relation.Binary.PropositionalEquality.Core as P using (_≡_) open import Relation.Binary.Reasoning.Syntax module Relation.Binary.Reasoning.Base.Partial {a ℓ} {A : Set a} (_∼_ : Rel A ℓ) (trans : Transitive _∼_) where ------------------------------------------------------------------------ -- Definition of "related to" -- This seemingly unnecessary type is used to make it possible to -- infer arguments even if the underlying equality evaluates. infix 4 _IsRelatedTo_ data _IsRelatedTo_ : A → A → Set (a ⊔ ℓ) where singleStep : ∀ x → x IsRelatedTo x multiStep : ∀ {x y} (x∼y : x ∼ y) → x IsRelatedTo y ∼-go : Trans _∼_ _IsRelatedTo_ _IsRelatedTo_ ∼-go x∼y (singleStep y) = multiStep x∼y ∼-go x∼y (multiStep y∼z) = multiStep (trans x∼y y∼z) stop : Reflexive _IsRelatedTo_ stop = singleStep _ ------------------------------------------------------------------------ -- Types that are used to ensure that the final relation proved by the -- chain of reasoning can be converted into the required relation. data IsMultiStep {x y} : x IsRelatedTo y → Set (a ⊔ ℓ) where isMultiStep : ∀ x∼y → IsMultiStep (multiStep x∼y) IsMultiStep? : ∀ {x y} (x∼y : x IsRelatedTo y) → Dec (IsMultiStep x∼y) IsMultiStep? (multiStep x<y) = yes (isMultiStep x<y) IsMultiStep? (singleStep _) = no λ() extractMultiStep : ∀ {x y} {x∼y : x IsRelatedTo y} → IsMultiStep x∼y → x ∼ y extractMultiStep (isMultiStep x≈y) = x≈y multiStepSubRelation : SubRelation _IsRelatedTo_ _ _ multiStepSubRelation = record { IsS = IsMultiStep ; IsS? = IsMultiStep? ; extract = extractMultiStep } ------------------------------------------------------------------------ -- Reasoning combinators open begin-subrelation-syntax _IsRelatedTo_ multiStepSubRelation public open ≡-noncomputing-syntax _IsRelatedTo_ public open ∼-syntax _IsRelatedTo_ _IsRelatedTo_ ∼-go public open end-syntax _IsRelatedTo_ stop public ------------------------------------------------------------------------ -- DEPRECATED NAMES ------------------------------------------------------------------------ -- Please use the new names as continuing support for the old names is -- not guaranteed. -- Version 1.6 infix 3 _∎⟨_⟩ _∎⟨_⟩ : ∀ x → x ∼ x → x IsRelatedTo x _ ∎⟨ x∼x ⟩ = multiStep x∼x {-# WARNING_ON_USAGE _∎⟨_⟩ "Warning: _∎⟨_⟩ was deprecated in v1.6. Please use _∎ instead if used in a chain, otherwise simply provide the proof of reflexivity directly without using these combinators." #-}
#include <stdio.h> /** * main - Entry point * * Description: prints all possible different combinations of two digits * * Return: 0 (End Program) */ int main(void) { int first = 0; int second = 0; while (first <= 98) { second = first; while (second <= 99) { if (first != second) { putchar((first / 10) + 48); putchar((first % 10) + 48); putchar(' '); putchar((second / 10) + 48); putchar((second % 10) + 48); if (first != 98 || second != 99) { putchar(','); putchar(' '); } } second++; } first++; } putchar('\n'); return (0); }
/* * phobj.h * * Copyright (c) 2009 Ismael Gomez-Miguelez, UPC <ismael.gomez at tsc.upc.edu>. All rights reserved. * * * This file is part of ALOE. * * ALOE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ALOE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ALOE. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef PHOBJ_INCLUDED #define PHOBJ_INCLUDED #define T phobj_o #define phobj_sizeof sizeof(struct phobj_o) /** @defgroup phobj ALOE Object * @ingroup common_obj * * This object is used by several Daemons and is used to define Object in the ALOE environment. * * It does not implement any complex functionality at all, it is inteded to use it to store object information * and access it. * * @{ */ typedef struct T *T; struct T { /* public members */ objid_t obj_id; /**< Id of the objiect */ peid_t pe_id; /**< Id of the processor where object is running */ status_t status; /**< Execution status of the object */ appid_t app_id; unsigned short exec_position; peid_t core_idx; int force_pe; str_o appname; /**< Application where object is running */ str_o objname; /**< Name of the object instance */ str_o exename; /**< Executable name for the object */ Set_o itfs; /**< Set of interfaces for the object */ Set_o stats; /**< Set of stats */ Set_o params; /**< Initialization Parameters */ rtcobj_o rtc; /**< RTC Information or requirements */ Set_o logs; /**< Set of logs */ }; T phobj_new(void); void phobj_delete(T *o); T phobj_dup(T o); int phobj_topkt(void *x, char **start, char *end); void * phobj_newfrompkt(char **start, char *end); int phobj_findid(const void *x, const void *member); int phobj_cmpid(const void *x, const void *member); int phobj_findobjname(const void *x, const void *member); int phobj_findappname(const void *x, const void *member); int phobj_finddiffstatus(const void *x, const void *member); int phobj_xsizeof(const void *x); void phobj_xdelete(void **x); void * phobj_xdup(const void *x); /** @} */ #undef T #endif /* */
{% extends "base.html" %} {% block content %} <div class="flex flex-col items-center justify-center px-6 py-8"> <!-- Challenge information --> <div class="mb-24 w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <div class="p-6 space-y-4 md:space-y-6 sm:p-8"> <p class="text-3xl font-bold text-white"><span class="underline decoration-sky-500">Challenge:</span> {{ title }}</p> <p class="text-lg text-white">{{ description }}</p> <p class="text-s italic text-white">Created by {{ created_by }}</p> <!-- Only let owner of a post end it. --> {% if user_owns_challenge and ongoing %} <form method="post" action="/export-challenge/{{ challenge_id }}"> <button type="submit" class="text-white bg-gradient-to-br from-pink-500 to-orange-400 hover:bg-gradient-to-bl focus:ring-4 focus:outline-none focus:ring-pink-200 dark:focus:ring-pink-800 font-medium rounded-lg text-l px-5 py-2.5 text-center mr-2 mb-2 mt-5"> Export challenge submissions to CSV </button> </form> {% endif %} </div> </div> {% if submissions|length != 0 %} {% for submission in submissions %} <div class="p-10 bg-white border border-gray-200 rounded-lg shadow dark:bg-gray-800 dark:border-gray-700 mb-10 w-8/12"> <!-- Basic post information--> <p class="text-2xl font-bold text-white">{{ submission.title }}</p> <p class="text-lg text-white">{{ submission.description }}</p> <img src="/static/user-content/{{ submission.link_id }}"> <p class="text-s italic text-gray-400">Created by {{ submission.created_by_username }}</p> <hr class="h-px my-8 bg-gray-200 border-0 dark:bg-gray-700"> <!-- Interactions with post--> {% if submission.already_liked %} <form method="post" action="/remove_like/{{submission.id}}"> <input type="hidden" name="like" value="true"> <button type="submit" class="text-2xl text-white underline decoration-pink-500 ">Unlike</button> </form> {% else %} <form method="post" action="/like/{{submission.id}}"> <input type="hidden" name="like" value="true"> <button type="submit" class="text-2xl text-white underline decoration-indigo-500">Like</button> </form> {% endif %} <p class="text-lg text-white">{{ submission.number_of_likes }} Likes</p> <hr class="h-px my-8 bg-gray-200 border-0 dark:bg-gray-700"> <!-- Comments --> <p class="text-white text-2xl">Comments:</p> <ul> {% for comment in submission.comments %} <li> <p class="text-white text-s"> {{ comment.message }} </p> </li> <br> {% endfor %} </ul> <p class="text-white text-2xl">Add a comment:</p> <form method="post" action="/add-comment/{{submission.id}}"> <input type="text" placeholder="A heartwarming response to their art!" name="message" class="block w-full p-4 text-gray-900 border border-gray-300 rounded-lg bg-gray-50 sm:text-md focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"> <button type="submit" class="mt-3 bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded shadow"> Comment! </button> </form> </div> {% endfor %} {% endif %} <!-- Submissions --> <div class="mb-24 w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <div class="p-6 space-y-4 md:space-y-6 sm:p-8"> <p class="text-3xl text-white">Submit your own work!</p> <form method="post" action="/add-submission/{{ challenge_id }}" enctype="multipart/form-data"> <div> <label for="title" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Title</label> <input type="text" name="title" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="A creative title your your stunning piece..." required> </div> <div> <label for="last_name" class="block mt-4 mb-2 text-sm font-medium text-gray-900 dark:text-white">Description</label> <input type="text" name="description" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="A short but apt description..." required> </div> <label class="block mt-5 mb-0 text-sm font-medium text-gray-900 dark:text-white" for="file_input">Upload file</label> <input type="file" name="file" class="block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400"> <p class="mt-1 text-sm text-gray-500 dark:text-gray-300" id="file_input_help">SVG, PNG, JPG, or JPEG</p> <input type="submit" value="Upload" class="mt-3 bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded shadow"> </form> </div> {% endblock %} {% block script %} {% endblock %}
const sinon = require('sinon'); const { expect } = require('chai'); const connection = require('../../../models/connection'); const modelProducts = require('../../../models/productsModel'); describe('Testa ao chamar a função getById da camada de modelo', () => { describe('Quando existe o produto no banco de dados', () => { const executeProduct = [{ "id": 1, "name": "Martelo de Thor", "quantity": 10 }] before(async () => { sinon.stub(connection, 'execute').resolves([executeProduct]); }); after(async () => { connection.execute.restore(); }); it('se existe um array', async () => { const dataProduct = await modelProducts.getById(1); expect(dataProduct).to.be.an('array'); }); it('se no array contém objetos', async () => { const [dataProduct] = await modelProducts.getById(1); expect(dataProduct).to.be.an('object'); }); it('que o array contem objetos com as chaves id, name e quantity', async () => { const [dataProduct] = await modelProducts.getById(1); expect(dataProduct).to.have.all.keys('id', 'name', 'quantity'); }); }); describe('Quando não existe o produto no banco de dados', () => { const executeProduct = []; before(async () => { sinon.stub(connection, 'execute').resolves([executeProduct]); }); after(async () => { connection.execute.restore(); }); it('se existe um array', async () => { const dataProduct = await modelProducts.getById(9); expect(dataProduct).to.be.an('array'); }); it('o array está vazio', async () => { const dataProduct = await modelProducts.getById(9); expect(dataProduct).to.be.empty; }); }); });
--- layout: default title: En hel webbplats subtitle: Steget från en bunt webbsidor till en sammanhängande webbplats desc: Hur webbsidor länkas samman för att bli en webbplats. Pseudoklasser för länkar. Att inkludera dokument i andra dokument idag <em>alltid</em> innebär serverskript, exempel i PHP. category: grunderna --- <p>I detta kapitel tar vi upp hur du kan gå tillväga för att skapa en sammanhängande webbplats utav en samling webbsidor. Även hur du skapar länkar mellan dessa egna webbsidor, och så klart även till andras webbplatser. Det finns många olika sätt att hantera problemet med hur grunden för en webbplats ska se ut, så det vi går igenom här är inte det enda och bästa sättet i alla möjliga fall; men det är en simpel och fungerande lösning. <p>Till skillnad mot tidigare kapitel behövs här en webbserver, av anledningar vi kommer till snart. Förut, ”förr i tiden”, användes något som kallas för ramar. Vilket är det HTML erbjuder som lösning på webbplatsstrukturproblemet. Kort och gott så är det en förlegad teknik och används inte mer (eller snarare, bör inte användas mer). Designdelen av boken går in lite mer på detta då det samtidigt erbjuder ett sätt att bygga en grundläggande layout. Här nöjer vi oss med att säga att vi inte längre vill använda ramar och att det idag finns bättre alternativ; den största nackdelen med ramlösningen är att det blir onödigt svårt för oerfarna användare att få tag i adressen till aktuell sida, något som du idag troligen tar för givet. <h2>Länkar, det webben är gjort av och för</h2> <p>För att bygga en användbar webbplats så krävs det nästan att man använder sig utav länkar, för att länka ihop sin webbplats och länka till andra webbplatser. För att skapa länkar används <code>a</code>-elementet. Ett <code>a</code>-element har två delar, en <strong>länktext</strong> och en <strong>destinationsdel</strong>. <ul> <li>Länktexten är den besökaren klickar på, eller på vilket sätt nu webbläsaren används, t.ex. med tangentbordet. Se till att länktexten är informativ och lättförstådd. Det värsta exemplet är länktexter så som ”klicka här”, använd istället något som visar var besökaren kommer till om denna skulle klicka på länken. <li>Destinationen är det dokument webbläsaren går till efter ”klicket”. </ul> <h3><code>href</code>-attributet, länkdestinationen</h3> <p>Ett fullständigt <code>a</code>-element kan se ut såhär:</p> <figure><pre><code>&lt;p&gt;Länk till &lt;a href="http://exempel.net"&gt;exempel.net&lt;/a&gt;.&lt;/p&gt;</code></pre></figure> <p>Det är alltså i <code>href="http://exempel.net"</code> destinationen bestäms.</p> <ul> <li>Som du märker så står det <code>http://</code> i början av <code>href</code>-värdet. Detta betyder att det är en <strong>extern länk</strong>, med andra ord en länk som går till en annan sida. Att vi skriver HTTP i början beror på att det helt enkelt är det protokollet som ska användas. Det är nästan alltid <code>http://</code> som du ska använda här. Som vi nämnde i inledningen (som var ett tag sedan nu) så är det HTTP som används vid transport av information på Internet. <li>Det andra är helt enkelt <strong>värdnamnet</strong>, som t.ex. <code>google.com</code>, <code>example.com</code> och så vidare. <li>Om du sedan vill länka till en speciell fil kan du lägga till filnamnet efter, t.ex. <code>http://example.org/om_oss.html</code>. </ul> <h3><code>target</code>-attributet, främst för att öppna länkar i nya fönster</h3> <p>Attributet <code>target</code> används för att ange var destinationsdelen ska dyka upp, t.ex. ett nytt fönster. Det finns en rad olika fördefinierade nyckelord att använda, t.ex. för att länken ska öppnas i ett nytt fönster finns <code>target="_blank"</code>. Detta är inte rekommenderat då vi ännu en gång använder HTML för något det inte är tänkt för. Attributet skriver om standardbeteendet för beteendelagret, och detta är inget HTML ska göra. Det är upp till beteendelagret att göra det. <p>Det går att göra önskad förändring i beteendelagret istället, men det är inte att vi är i fel lager för att göra denna förändring som är problemet. Det är först och främst att det blir förvirrande för användaren. Genom att bara kolla på länken är det omöjligt att tala om huruvida den kommer att öppnas i ett nytt fönster eller ej. Om användaren vill öppna länken i ett nytt fönster kan denna <em>bestämma detta själv</em> genom att t.ex. använda mittenmusknappen eller hålla in <kbd>Ctrl</kbd>-tangenten och vänsterklicka på länken för att öppna den i ett nytt fönster eller tabb/flik. Om <em>vi</em> bestämmer att länken <em>alltid</em> ska öppnas i nytt fönster (genom att lägga till <code>target="_blank"</code>) har användaren inte längre något val, den öppnas alltid i ett nytt fönster, oberoende av vad användaren vill. Så om vi låter standardbeteendet vara kvar kan användaren förutsätta att länkar alltid öppnas i aktuellt fönster, och om det inte är önskat så kan användaren själv välja att öppna länken i ett nytt fönster. <p>Ursprungligen används detta attribut för att specificera hur, de tidigare nämnda, ramarna skulle fungera tillsammans med varandra. Ramar är som sagt en förlegad teknik som vi inte längre använder, så vi går inte in på hur <code>tagret</code> används till ramar. <p>Sammanfattning blir alltså: använd inte <code>target</code>-attributet, och speciellt inte för att öppna nya fönster. Gör inte på något annat sätt för att webbläsaren ska öppna nya fönster för den delen heller. Låt användaren bestämma över <em>sin</em> webbläsare! <h3><code>title</code>-attributet, en föklarande text</h3> <p><code>title</code>-attribut kan ge en liten hänvisning till var länken går, en förklaring eller liknande. Bra för bl.a. förkortade länktexter, t.ex. tidningar gillar att använda ”Läs mer …”-länkar för sina artiklar, då kan ett mellanalternativ mot dessa ”Klicka här”-länkar vara:</p> <figure><pre><code>&lt;a href="http://example.org" title="Läs mera om hunden Göran och hans äventyr"&gt;Läs mer …&lt;/a&gt;</code></pre></figure> <p>Om du själv tycker att länken är något otydlig och det är svårt att förstå var länken går kan det vara en bra idé att lägga till ett <code>title</code>-attribut. <h3>Ankare</h3> <p>Det är möjligt att med <code>id</code>-attributet (samma som ibland används för att koppla CSS till dokumentet) länka till en speciell position på sidan, eller en annan webbsida för den delen. Genom att lägga till <code>#</code> följt av <code>id</code>-namnet i slutet av adressen:</p> <figure><pre><code>&lt;p&gt;&lt;a href="#example"&gt;Hoppa till rubriken ”Exempel”&lt;/a&gt;&lt;/p&gt; […] &lt;h2 id="example"&gt;Exempel&lt;/h2&gt;</code></pre></figure> <p>När besökaren klickar på länken så kommer webbläsaren skrolla ner till ”Exempel”-rubriken. <p>Eller om det skulle vara till en position på <code>example.org</code>:</p> <figure><pre><code>&lt;p&gt;Vilket är dokumenterat under &lt;a href="http://example.org#example"&gt;”exempel” hos example.org&lt;/a&gt;&lt;/p&gt;</code></pre></figure> <p>En gammal variant på ankare är använda ett <code>a</code>-element utan varken länktext eller destinationsdel, vilket innebär att det blir ”osynligt”. Då används <code>name</code>-attributet istället för <code>id</code> på valfritt ”vanligt” element. Detta bör inte användas då <code>a</code>-elementet inte används till vad det ursprungligen var tänkt för, samt att koden har en tendens att bli rörig. Vi tog bara upp detta om du någon gång skulle tvingas att länka till en sidan som använder denna teknik. <h3>Länkars utseende</h3> <p>Oberoende av hur genomtänkta länkarna så spelar det ingen roll om man inte ser dem, otroligt nog … Vad menar vi nu med detta? Jo, vi ska gå tillbaka hur man ändrar utseende på länkar med hjälp av CSS. Ännu en del när vi nu kombinerar våra nya kunskaper med tidigare bemästrade sådana alltså. Vi har tidigare gått igenom pseudoklasser och pseudoelement, och sade där att pseudoklasserna från CSS2 främst används för att ändra utseendet på länkar. Dessa pseudoklasser är: <ul> <li><code>:link</code>, icke-besökt länk (ja, det är ett ganska olyckligt namnval) <li><code>:visited</code>, besökt länk <li><code>:hover</code>, markerad länk (t.ex. att musmarkören hålls över den, brukar även kallas att man ”hovrar”). <li><code>:active</code>, har en ganska luddig definition; något förenklat kan vi säga att från det ögonblicket när musknappen tryckts ner tills det den släppts. (Vilket inte är den riktiga definitionen men används nästan alltid endast till det.) </ul> <p>När dessa används är det för enkelhetsens skull bäst att ange reglerna i ovanstående ordning. För att komma ihåg ordning var det någon (vem det var har vi glömt bort) för länge sedan som skapade denna minnesregel: <em>LoVe HAte</em>. Där versalerna står för respektive pseudoklass. <p>Varför ”LoVe HAte”-ordningen, varför spelar det någon roll? Jo, som du förhoppningsvis minns så är kaskad ett centralt koncept när det kommer till CSS. Alla selektorer kommer ju här få samma specifitetsvärde! Så det skulle finnas risk för att de skulle skriva över varandra om de kom i olämplig ordning, eftersom att en länk kan befinnas sig i mer än ett tillstånd samtidigt, t.ex. kan en länk både vara obesökt och aktiv. <p>Så med all denna nya information skapar vi följande CSS-kod:</p> <figure><pre><code>a:link { color:green; font-weight:bold; } a:visited { color:red; } a:hover { color:yellow; } a:active { text-decoration:line-through; }</code></pre></figure> <p>Ibland kan det även vara en bra idé att utelämna <code>:link</code> från första selektorn om du t.ex. vill att länkar alltid ska vara feta, oberoende av tillstånd. Nu är den bara fet så länge den inte är besökt. Innan du går vidare rekommenderar vi att du skapar ett testdokument där du experimenterar omkring med dessa selektorer och några länkar (t.ex. en länk som är besökt och en som inte är det brevid varandra så att du ser vilka selektorer som matchar vad). <p>Det finns en <a href="http://meyerweb.com/eric/css/link-specificity.html">känd artikel om detta problem</a> där Eric Meyer svarar på frågan: ”I tried to apply CSS to my hyperlinks and the hovering didn't work. How come? Is this another case of browsers being stupid?” Där går Meyers igenom problemet mer grundligt om du fortfarande har problem att förstå vad som händer. <h4>Några avslutande riktlinjer</h4> <p>Följande är bra att fundera över när du ändrar länkars utseende: <ul> <li>Först och främst ska länkarna vara lätta att urskilja från resten av texten <li>Även om länkarna ska vara lätta att urskilja får de inte vara så utstickande att de gör det svårt att läsa närliggande text <li>Det ska lätt att se vilka länkar som besökts innan, med hjälp av <code>:visited</code> <li>Tänka på att det finns en möjlighet att en besökare med nedsatt syn och/eller färgseende kan trilla in på webbplatsen och det är därför bra att ha något mer än färgen som skiljer länkarna från resten av texten; t.ex. en understrykning, fetstil eller något annat uppfinningsrikt </ul> <h2>DRY-principen återigen</h2> <p>Låt säga att du har följande tre sidor på din webbplats:</p> <figure> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Startsidan | Anonym webbplats&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="menu"&gt; &lt;li&gt;&lt;a href="start.html"&gt;Hem&lt;/a&gt; &lt;li&gt;&lt;a href="dikter.html"&gt;Dikter&lt;/a&gt; &lt;li&gt;&lt;a href="kontakt.html"&gt;Kontakt&lt;/a&gt; &lt;/ul&gt; &lt;h1&gt;Välkommen till den ananyma webbplatsen&lt;/h1&gt; &lt;p&gt;Detta är min första riktiga webbplats, då den består utav mer än en webbsida.&lt;/p&gt; &lt;p&gt;Är den inte snygg?&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <figcaption><code>start.html</code></figcaption> </figure> <figure> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Dikter | Anonym webbplats&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="menu"&gt; &lt;li&gt;&lt;a href="start.html"&gt;Hem&lt;/a&gt; &lt;li&gt;&lt;a href="dikter.html"&gt;Dikter&lt;/a&gt; &lt;li&gt;&lt;a href="kontakt.html"&gt;Kontakt&lt;/a&gt; &lt;/ul&gt; &lt;h1&gt;Dikter på den ananyma webbplatsen&lt;/h1&gt; &lt;p&gt;Här skulle jag publicera mina bästa dikter, men jag kom inte på några så det är istället tomt.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <figcaption><code>dikter.html</code></figcaption> </figure> <figure> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Kontakt | Anonym webbplats&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="menu"&gt; &lt;li&gt;&lt;a href="start.html"&gt;Hem&lt;/a&gt; &lt;li&gt;&lt;a href="dikter.html"&gt;Dikter&lt;/a&gt; &lt;li&gt;&lt;a href="kontakt.html"&gt;Kontakt&lt;/a&gt; &lt;/ul&gt; &lt;h1&gt;Kontakta ansvarig för den ananyma webbplatsen&lt;/h1&gt; &lt;p&gt;Jag tänkte lägga ut min mejladress här så du kunde nå mig, men sedan ångrade jag mig. Inte mycket blev som planerat på min första webbplats.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <figcaption><code>kontakt.html</code></figcaption> </figure> <p>När du hållit på med utveckling (inte nödvändigtvis bara för webben) skriker hela din kropp av plåga och djup smärta när du ser ett så uppenbart brott mot DRY-principen. När du vill ändra i menyn måste du ju ändra i alla filer på hela webbplatsen och så vidare och allt annat som följer av att bryta mot DRY. <p>Utöver ramar erbjuder HTML inte någon lösning på detta. Det är nu webbservern kommer in. Vi kan med den inkludera (alt. infoga) en bit HTML-kod i en annan bit HTML-kod, där HTML-koden som den förstnämnda HTML-koden inkluderas i är genensam för alla webbsidor på webbplatsen. Det är inte så svårt att se vilka delar som är gemensamma för alla sidor på vår nuvarande webbplats:</p> <figure> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;%Här skriver vi titlen på sidan% | Anonym webbplats&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="menu"&gt; &lt;li&gt;&lt;a href="start.html"&gt;Hem&lt;/a&gt; &lt;li&gt;&lt;a href="dikter.html"&gt;Dikter&lt;/a&gt; &lt;li&gt;&lt;a href="kontakt.html"&gt;Kontakt&lt;/a&gt; &lt;/ul&gt; &lt;h1&gt;%Titeln på sidan igen%&lt;/h1&gt; &lt;p&gt;%Här är själva innehållet på sidan sedan, några textstycken troligen.%&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <figcaption>Mallen för alla webbsidor på vår webbplats</figcaption> </figure> <h2>Installation av webbservern</h2> <p>Så, var får vi tag i en webbserver? Och först och främst vad ska vi använda för webbserver? Vi ska först nämna att det inte räcker med en webbserver, det behövs även att serverskriptspråk som utför själva inkluderingen. Till webbserver har vi valt Apache och serverskriptspråk PHP. Det finns många val här, just dessa val motiveras av att båda är mycket välanvända och gratis. <p>Om du använder Windows så finns ett färdigt paket som installerar Apache och PHP åt dig och gör alla nödvändiga konfigurationer åt dig. Detta paket heter <a href="http://wampserver.com">WAMP</a> och står för ”Apache, MySQL, PHP on Windows”. Följ instruktionerna på webbplatsen och installationsprogrammet så kommer det lösa sig. <p>Om du använder GNU/Linux finns det troligen något färdigt paket att använda för din distribution, t.ex. för Ubuntu finns det dokumenterat för hur du <a href="https://help.ubuntu.com/10.04/serverguide/C/web-servers.html">installerar och konfigurerar både Apache och PHP</a> (notera att länken kan vara utdaterad, i skrivande stund är 10.04 den nyaste stabila versionen). Kortfattat bör följande räcka:</p> <figure><pre><code>sudo apt-get install apache2 php5 libapache2-mod-php5 && sudo /etc/init.d/apache2 restart</code></pre></figure> <p>Om du använder något annat operativsystem får du tyvärr lösa problemet själv, vi kan inte enumerera alla operativsystem av uppenbara anledningar. Alternativt kan du köpa en plats på något billigare webbhotell, då slipper du att installera någon programvara.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./Base64.sol"; contract PewNFT is ERC721 { using Strings for uint256; // Store data about the contributions made by a user holding the token struct Contribution { string ipfsHash; uint256 upvotes; uint256 downvotes; } mapping(uint256 => Contribution[]) contributions; mapping(uint256 => uint256) mintedTime; address public PEW_CORE; string public baseURI; // The tokenId of the next token to be minted. uint128 internal _currentIndex; event ContributionAdded( address indexed contributor, uint256 indexed tokenId, string ipfsHash ); constructor( string memory name_, string memory symbol_, address _pewCore ) ERC721(name_, symbol_) { PEW_CORE = address(_pewCore); } modifier onlyPew() { require(msg.sender == address(PEW_CORE)); _; } function mint(address _to) external onlyPew { _safeMint(_to, _currentIndex); mintedTime[_currentIndex] = block.timestamp; _currentIndex++; } /** * R@notice Add Contribution to the token. */ function addContribution(string memory ipfsHash, uint256 tokenId) external onlyPew { require( tx.origin == ownerOf(tokenId), "Only the owner can add a contribution" ); Contribution memory contribution = Contribution(ipfsHash, 0, 0); contributions[tokenId].push(contribution); emit ContributionAdded(msg.sender, tokenId, ipfsHash); } /** * @notice Upvote a contribution. */ function upvote(uint256 tokenId, uint256 contributionIndex) external onlyPew { Contribution storage contribution = contributions[tokenId][ contributionIndex ]; contribution.upvotes++; } /** * @notice Downvote a contribution. */ function downvote(uint256 tokenId, uint256 contributionIndex) external onlyPew { Contribution storage contribution = contributions[tokenId][ contributionIndex ]; contribution.downvotes++; } /** * Get Total Supply of Tokens Minted * @return Current Total Supply */ function totalSupply() public view returns (uint256) { return _currentIndex; } /** * @dev See {IERC721Metadata-tokenURI}. * @dev gets baseURI from contract state variable */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return buildMetadata(tokenId); } /// @notice Builds the metadata required in accordance ot Opensea requirements /// @param _tokenId Policy ID which will also be the NFT token ID /// @dev Can change public to internal function buildMetadata(uint256 _tokenId) public view returns (string memory) { uint256 _governanceScore = getGovernanceScore(_tokenId); string memory image; // NFTS that level up based on the governance score of the token. // Storj is used to host the images. Storj enables fast and secure cloud storage and it is built ontop of IPFS. if (_governanceScore > 1) { image = "ipfs://QmPmcwZTXWovxB1VY5Bu7jXHw4YND3hR8G8CzWr8zb5rB6"; } else if (_governanceScore > 2) { image = "ipfs://QmQSVwpjT43GUS9YySzQ7SiWQRsmKUzqaSoaKZ322GD8wf"; } else if (_governanceScore > 3) { image = "ipfs://Qme5NcRM227hMLjLftJexB9RyYgw8qyGzijiXoX7qiWe2o"; } else if (_governanceScore > 4) { image = "ipfs://QmPGY273SFsczt2n7NUWYeTKcoQChhR72vGSbW3Fnm4HxT"; } else { image = "ipfs://QmcLGFwJKNskZNLN2o3s8oXQrnMnW3wtbYu2ei6YZDviYE"; } bytes memory m1 = abi.encodePacked( '{"name":"', name(), " Membership", '", "description":"', name(), " Membership", '", "image": "', image, // adding policyHolder '", "attributes": [{"trait_type":"Governance Score",', '"value":"', Strings.toString(_governanceScore), '"}]}' ); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(bytes.concat(m1)) ) ); } function getUpvotes(uint256 tokenId, uint256 index) public view returns (uint256) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return contributions[tokenId][index].upvotes; } function getDownvotes(uint256 tokenId, uint256 index) public view returns (uint256) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return contributions[tokenId][index].downvotes; } function getTotalUpvotes(uint256 tokenId) public view returns (uint256 _totalUpvotes) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); for (uint256 i = 0; i < contributions[tokenId].length; i++) { _totalUpvotes += contributions[tokenId][i].upvotes; } return _totalUpvotes; } function getTotalDownvotes(uint256 tokenId) public view returns (uint256 _totalDownvotes) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); for (uint256 i = 0; i < contributions[tokenId].length; i++) { _totalDownvotes += contributions[tokenId][i].downvotes; } return _totalDownvotes; } function getContribution(uint256 tokenId, uint256 index) public view returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return string( abi.encodePacked( "https://ipfs.io/ipfs/", contributions[tokenId][index].ipfsHash ) ); } function getAllContributions(uint256 tokenId) public view returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory contributionsString = ""; for (uint256 i = 0; i < contributions[tokenId].length; i++) { if (i + 1 < contributions[tokenId].length) { string( abi.encodePacked( contributionsString, "https://ipfs.io/ipfs/", contributions[tokenId][i].ipfsHash, "," ) ); } else { string( abi.encodePacked( contributionsString, "https://ipfs.io/ipfs/", contributions[tokenId][i].ipfsHash ) ); } } return contributionsString; } function getContributionCount(uint256 tokenId) public view returns (uint256 _contributionCount) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return contributions[tokenId].length; } function getTimeScore(uint256 tokenId) public view returns (uint256) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return (block.timestamp - mintedTime[tokenId]) / 1 days; } function getGovernanceScore(uint256 tokenId) public view returns (uint256 _governanceScore) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); uint256 _totalUpvotes = getTotalUpvotes(tokenId); uint256 _totalDownvotes = getTotalDownvotes(tokenId); uint256 _timeScore = getTimeScore(tokenId); if (_totalDownvotes > _totalUpvotes) { _governanceScore = 0; } else { _governanceScore = _totalUpvotes - _totalDownvotes + _timeScore; } return _governanceScore; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal pure override { // Prevent Future Transfer of token require(from == address(0), "ERC721: transfer from non-zero address"); } }
import { Box, Button, CloseButton, Flex, Image, Input, Text, } from "@chakra-ui/react"; import { ChangeEvent, FC, useEffect, useRef, useState } from "react"; import { AnimatePresence, motion } from "framer-motion"; import { ReplyIconLg } from "@/components/svg/ReplyIconLg"; import { useDevice } from "@/hooks/useDevice"; import { useCommentReply } from "@/libs/dtl/comment"; import { useMyUserProfile } from "@/libs/dtl"; interface IReplyingCommentProps { isFocused?: boolean; isLoading?: boolean; disabled?: boolean; onCancelReply?: () => void; isUnfocused?: () => void; onSubmitComment?: (value: string) => void; } const MAX_COMMENT_LENGTH = 2000; const CommentField: FC<IReplyingCommentProps> = ({ isFocused, isLoading, disabled, isUnfocused, onSubmitComment, }) => { const myUserProfile = useMyUserProfile() const commentReply = useCommentReply(); const { isMobile } = useDevice(); const inputRef = useRef<HTMLInputElement>(null); const [inputValue, setInputValue] = useState(""); const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => { setInputValue(e.target.value); }; const handleSubmitComment = async () => { if (onSubmitComment) await onSubmitComment(inputValue); commentReply.clear(); setInputValue(""); }; useEffect(() => { if (isFocused) { inputRef.current?.focus(); } }, [isFocused]); return ( <Box bg="white" position={{ base: "fixed", lg: "sticky" }} w={{ base: "100vw", lg: "100%" }} alignSelf="center" bottom={0} zIndex={10} left={0} > <Box position="relative"> <AnimatePresence> {commentReply.comment && ( <motion.div initial={{ opacity: 0.8, top: isMobile ? -32 : -56 }} animate={{ opacity: 1, top: isMobile ? -52 : -68 }} exit={{ opacity: 0, top: isMobile ? -32 : -56 }} transition={{ duration: 0.2 }} style={{ position: "absolute", width: "100%", left: 0, }} > <Flex bg="grey.0" width="100%" rounded={{ lg: "md" }} justifyContent="space-between" py="10px" px="22px" alignItems="center" shadow="md" > {myUserProfile.data && <Flex alignItems="center"> <ReplyIconLg role="button" /> <Box ml={{ base: "7px", lg: "17px" }}> <Text color="accent.2" fontWeight="extrabold" fontSize={{ base: "10px", lg: "16px" }} > {myUserProfile.data.firstName + " " + myUserProfile.data.lastName} </Text> <Text fontWeight="bold" fontSize={{ base: "10px", lg: "16px" }} width="12ch" textOverflow="ellipsis" whiteSpace="nowrap" overflow="hidden" color="primary" > {commentReply.comment.content} </Text> </Box> </Flex>} <CloseButton color="primary" onClick={commentReply.clear} /> </Flex> </motion.div> )} </AnimatePresence> <Flex alignItems="center" gap={4} justifySelf="end" pt="10px" pb="15px" px={{ base: "20px", lg: "0" }} > <Image w={{ base: "30px", lg: "50px" }} h={{ base: "30px", lg: "50px" }} src={myUserProfile.data?.avatar} alt="avatar" rounded="full" objectFit="cover" fallbackSrc="/images/DefaultAvaCircle.png" /> <Input flex={1} ref={inputRef} value={inputValue} onChange={handleInputChange} placeholder="Say something" color="primary" _placeholder={{ color: "grey.300", opacity: 0.5 }} _focus={{ borderColor: "primary" }} borderColor="primary" variant="flushed" isDisabled={disabled} fontSize={{ base: "16px", lg: "xl" }} onBlur={isUnfocused} maxLength={MAX_COMMENT_LENGTH} onKeyUp={(e) => { if (e.key === "Enter" && !!inputValue) { handleSubmitComment(); } }} /> <Button variant="link" color={inputValue ? "secondary" : "gray"} fontSize={{ base: "sm", lg: "xl" }} textDecoration="unset" textTransform="unset" isDisabled={disabled} onClick={() => { if (!inputValue) return; handleSubmitComment(); }} isLoading={isLoading} > Send </Button> </Flex> </Box> </Box> ); }; export default CommentField;
/* 3. আমরা for লুপ ব্যাবহার করে ১ থেকে ১০ এর যোগফল বের করেছি। নিচের ৫টি ধারা গুলোর যোগফল বের করার জন্য প্রোগ্রাম লিখ। ===A) 1+2+3+.....50 === var sum = 0; for (var i = 1; i <=50; i++) { sum = sum + i; } console.log(sum); === B. 1+3+5+...+39 ( প্রথম ২০টি পদ) === var sum = 0; for (var i = 1; i <=39; i+=2){ sum = sum + i; } console.log(sum); === C. 50 + 49 + 48 + 47 + …… ( প্রথম ১০টি পদ) === var sum = 0; for (var i = 50; i >=41; i--){ sum = sum + i; } console.log(sum); ===== D. 2 + 5 + 8 + 11 + 14 + ….. (প্রথম ১০টি পদ) var sum = 0; for (var i = 2; i <=29; i+=3){ sum = sum + i; } console.log(sum); === E. 100 + 97 + 94 + 91 + …. (0 এর চেয়ে বড় পর্যন্ত) === var sum = 0; for (var i = 100; i >=0; i-=3) { sum = sum + i; } console.log(sum); */
% Analise dataset % Alessandro Antonucci @AlexRookie % Placido Falqueto % University of Trento close all; clear all; clc; options.save = false; % save results options.plot = false; % show plot options.show = false; % show statistics % Folder tree addpath(genpath('../functions/')); addpath(genpath('../Clothoids/')); colors = customColors; % Dataset file files = dir(fullfile('*.mat')); load('edinburgh_10Sep.mat'); f=1; files(f).name = 'edinburgh_10Sep.mat'; totalMeanL = []; totalMinL = []; totalMaxL = []; totalRMSE = []; totalERR = []; totalRMSE_seg = []; totalERR_seg = []; %for f = 1:numel(files) disp(['Processing ', files(f).name, ' set...']); % Load data load(files(f).name); Humans = Data.Humans; % Plot dataset %{ figure(2); hold on, grid on, box on, axis equal; axis(Data.AxisLim); xlabel('x (m)'); xlabel('y (m)'); title(files(f).name, 'interpreter', 'latex'); %cellfun(@(X) plot(X(:,1), X(:,2)), Humans); drawnow; %} LVEC = 0.5; L = []; RMSE = NaN(1,numel(Humans)); ERR = NaN(1,numel(Humans)); RMSE_seg = NaN(1,numel(Humans)); ERR_seg = NaN(1,numel(Humans)); for i = 1:numel(Humans) if mod(i,100)==0 fprintf("%d/%d\n", i, numel(Humans)); end if options.plot clf(figure(1)); hold on, grid on, box on, axis equal; axis(Data.AxisLim); xlabel('x (m)'); xlabel('y (m)'); title(files(f).name, 'interpreter', 'latex'); end HS = [smooth(Humans{i}(:,1),100), smooth(Humans{i}(:,2),100)]; HSdx = smooth(diff(HS(:,1)),10); HSdy = smooth(diff(HS(:,2)),10); if options.plot plot(Humans{i}(:,1), Humans{i}(:,2), 'LineWidth', 2); plot(HS(:,1), HS(:,2), 'LineWidth', 2, 'Color', 'red'); end %{ figure(2) subplot(2,2,1) plot(Humans{i}(:,1)) hold on; grid on; box on; plot(HS(:,1)) subplot(2,2,2) plot(Humans{i}(:,2)) hold on; grid on; box on; plot(HS(:,2)) subplot(2,2,3) plot(HSdx) hold on; grid on; box on; subplot(2,2,4) plot(HSdy) hold on; grid on; box on; figure(1) %} smoothangle = 10; P1 = [Humans{i}(1,1), Humans{i}(1,2)]; a1 = atan2(mean(HS(1:smoothangle,2))-P1(2), mean(HS(1:smoothangle,1))-P1(1)); P2 = [Humans{i}(end,1), Humans{i}(end,2)]; a2 = atan2(P2(2)-mean(HS(end-smoothangle:end,2)), P2(1)-mean(HS(end-smoothangle:end,1))); if options.plot plot(P1(1), P1(2), 'ro', ... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',5); plot(P2(1), P2(2), 'bo', ... 'MarkerEdgeColor','k',... 'MarkerFaceColor','y',... 'MarkerSize',5); quiver( P1(1), P1(2), LVEC*cos(a1), LVEC*sin(a1), 'Color', 'black' ); quiver( P2(1), P2(2), LVEC*cos(a2), LVEC*sin(a2), 'Color', 'black' ); end zerocrossing = 0.01; K = dsearchn(HS, [(max(HS(:,1))+min(HS(:,1)))/2, (max(HS(:,2))+min(HS(:,2)))/2]); KK1 = find(HSdx<zerocrossing & HSdx>-zerocrossing); KK1d = []; if length(KK1)>0 check = KK1(1); for z = 2:length(KK1) if KK1(z)-1 == KK1(z-1) check = [check KK1(z)]; end if KK1(z)-1 ~= KK1(z-1) | z==length(KK1) minimo = [abs(HSdx(check(1))), check(1)]; for j = 2:length(check) if abs(HSdx(check(j))) < minimo(1) minimo = [abs(HSdx(check(j))), check(j)]; end end KK1d = [KK1d; minimo(2)]; check = KK1(z); end end end KK1d(KK1d<6|KK1d>length(HS)-5) = []; KK2 = find(HSdy<zerocrossing & HSdy>-zerocrossing); KK2d = []; if length(KK2)>0 check = KK2(1); for z = 2:length(KK2) if KK2(z)-1 == KK2(z-1) check = [check KK2(z)]; end if KK2(z)-1 ~= KK2(z-1) | z==length(KK2) minimo = [abs(HSdy(check(1))), check(1)]; for j = 2:length(check) if abs(HSdy(check(j))) < minimo(1) minimo = [abs(HSdy(check(j))), check(j)]; end end KK2d = [KK2d; minimo(2)]; check = KK2(z); end end end KK2d(KK2d<6|KK2d>length(HS)-5) = []; KKd = unique([K; KK1d; KK2d]); MM = HS(KKd,:); [C,IA,IC] = unique(MM,'rows'); MM = MM(sort(IA),:); if options.plot plot(MM(:,1), MM(:,2), 'ro', ... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',5); end M12 = HS(K,:); if options.plot plot(M12(1), M12(2), 'ro', ... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',5); end d1 = sqrt((MM(1,1)-P1(1))^2+(MM(1,2)-P1(2))^2); d2 = sqrt((MM(end,1)-P1(1))^2+(MM(end,2)-P1(2))^2); if(d1<d2) path = [P1; MM; P2]; else path = [P1; flipud(MM); P2]; end %------------------------------------------------------------------ % Segment seg = []; num_of_points = [0; KKd; size(HS,1)]; for j = size(path,1):-1:2 nop = num_of_points(j)-num_of_points(j-1); seg = [seg; [linspace(path(j,1),path(j-1,1),nop); linspace(path(j,2),path(j-1,2),nop)]']; end seg = flipud(seg); if options.plot plot(seg(:,1), seg(:,2), '.', 'LineWidth', 2, 'Color', 'm'); end dist = []; for s = 1:length(HS) d = norm(HS(s,:) - seg(s,:)); dist = [dist; d]; end RMSE_seg(i) = sqrt(mean(dist.^2)); ERR_seg(i) = max(dist); %------------------------------------------------------------------ to_del = []; for j = 2:size(path,1)-1 if norm(path(j-1,:)-path(j,:)) < 0.1 to_del = [to_del, j]; end end path(to_del,:) = []; % Clothoid npts = 100; CL = ClothoidSplineG2(); CL.verbose(false); SL = CL.buildP1(path(:,1), path(:,2), a1, a2); if options.plot SL.plot(npts, {'Color','#77AC30','LineWidth',2}, {'Color','#77AC30','LineWidth',2}); end l = SL.length(); n = size(HS,1); SL_sampled = NaN(n,2); for k = 1:n sl = (k-1)*l/(n-1); [SL_sampled(k,1), SL_sampled(k,2), ~] = SL.evaluate(sl); end dist = []; for s = 1:length(HS) d = norm(HS(s,:) - SL_sampled(s,:)); %d = SL.distance(HS(s,1),HS(s,2)); dist = [dist; d]; % plot(HS(s,1), HS(s,2), '*', 'markersize', 20, 'linestyle', 'none') % plot(SL_sampled(s,1), SL_sampled(s,2), '*', 'markersize', 12, 'linestyle', 'none') end RMSE(i) = sqrt(mean(dist.^2)); ERR(i) = max(dist); for k = 1:SL.numSegments() L = [L, SL.get(k).length()]; end if options.show [RMSE(i), RMSE_seg(i), ERR(i), ERR_seg(i)] end end pause(); totalRMSE = [totalRMSE, nanmean(RMSE)]; totalERR = [totalERR, nanmean(ERR)]; totalMeanL = [totalMeanL, nanmean(L)]; totalMinL = [totalMinL, nanmin(L)]; totalMaxL = [totalMaxL, nanmax(L)]; totalRMSE_seg = [totalRMSE_seg, nanmean(RMSE_seg)]; totalERR_seg = [totalERR_seg, nanmean(ERR_seg)]; %end if options.show [totalRMSE, totalRMSE_seg, totalERR, totalERR_seg] options figure(3); hold on; plot(RMSE); plot(RMSE_seg, '--'); plot(ERR); plot(ERR_seg, '--'); end disp('Done!');
import { useState } from "react"; import { useDispatch } from "react-redux"; import InputText from "../../../components/Input/InputText"; import ErrorText from "../../../components/Typography/ErrorText"; import { showNotification } from "../../common/headerSlice"; import { useCreateMentalHealth } from "../../../hooks/mentalHealth.hook"; const INITIAL_LEAD_OBJ = { name: "", description: "", status: "ACTIVE", }; function AddMentalHealthModalBody({ closeModal }) { const dispatch = useDispatch(); const [loading, setLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(""); const [leadObj, setLeadObj] = useState(INITIAL_LEAD_OBJ); const { mutate } = useCreateMentalHealth(); const saveNewLead = async () => { if (leadObj.name.trim() === "") { return setErrorMessage("Name is required!"); } else if (leadObj.description.trim() === "") { return setErrorMessage("Description is required!"); } else { try { const payload = { name: leadObj.name, description: leadObj.description, status: leadObj.status, }; await mutate(payload); dispatch( showNotification({ message: "New Mental Health Added!", status: 1 }) ); closeModal(); setTimeout(() => { window.location.reload(); }, 1000); } catch (error) { console.error("Error adding new Mental Health:", error); setErrorMessage("Error adding new Mental Health. Please try again."); } finally { setLoading(false); } } }; const updateFormValue = ({ updateType, value }) => { setErrorMessage(""); setLeadObj((prevLeadObj) => ({ ...prevLeadObj, [updateType]: value, })); }; return ( <> <InputText type="text" defaultValue={leadObj.name} updateType="name" containerStyle="mt-4" labelTitle="Name" updateFormValue={updateFormValue} /> <InputText type="text" defaultValue={leadObj.description} updateType="description" containerStyle="mt-4" labelTitle="Description" updateFormValue={updateFormValue} /> <ErrorText styleClass="mt-16">{errorMessage}</ErrorText> <div className="modal-action"> <button className="btn btn-ghost" onClick={() => closeModal()}> Cancel </button> <button className="btn btn-primary px-6" onClick={() => { saveNewLead(); }} > Save </button> </div> </> ); } export default AddMentalHealthModalBody;
import logging from web3 import Web3 from ....general.enums import rewarderType from ..gamma.rewarder import gamma_rewarder class zyberswap_masterchef_rewarder(gamma_rewarder): def __init__( self, address: str, network: str, abi_filename: str = "", abi_path: str = "", block: int = 0, timestamp: int = 0, custom_web3: Web3 | None = None, custom_web3Url: str | None = None, ): self._abi_filename = abi_filename or "zyberchef_rewarder" self._abi_path = abi_path or f"{self.abi_root_path}/zyberswap/masterchef" super().__init__( address=address, network=network, abi_filename=self._abi_filename, abi_path=self._abi_path, block=block, timestamp=timestamp, custom_web3=custom_web3, custom_web3Url=custom_web3Url, ) def _getTimeElapsed(self, _from: int, _to: int, _endTimestamp: int) -> int: return self.call_function_autoRpc( "_getTimeElapsed", None, _from, _to, _endTimestamp ) def currentTimestamp(self, pid: int) -> int: return self.call_function_autoRpc("currentTimestamp", None, pid) @property def distributorV2(self) -> str: return self.call_function_autoRpc("distributorV2") @property def isNative(self) -> bool: return self.call_function_autoRpc("isNative") @property def owner(self) -> str: return self.call_function_autoRpc("owner") def pendingTokens(self, pid: int, user: str) -> int: return self.call_function_autoRpc( "pendingTokens", None, pid, Web3.toChecksumAddress(user) ) def poolIds(self, input: int) -> int: return self.call_function_autoRpc("poolIds", None, input) def poolInfo(self, pid: int) -> tuple[int, int, int, int, int]: """ Args: pid (int): pool index Returns: tuple[int, int, int, int, int]: accTokenPerShare uint256 startTimestamp unit256 lastRewardTimestamp uint256 allocPoint uint256 — allocation points assigned to the pool. totalRewards uint256 — total rewards for the pool """ return self.call_function_autoRpc("poolInfo", None, pid) def poolRewardInfo(self, input1: int, input2: int) -> tuple[int, int, int]: """_summary_ Args: input1 (int): _description_ input2 (int): _description_ Returns: tuple[int,int,int]: startTimestamp uint256, endTimestamp uint256, rewardPerSec uint256 """ return self.call_function_autoRpc("poolRewardInfo", None, input1, input2) def poolRewardsPerSec(self, pid: int) -> int: return self.call_function_autoRpc("poolRewardsPerSec", None, pid) @property def rewardInfoLimit(self) -> int: return self.call_function_autoRpc("rewardInfoLimit") @property def rewardToken(self) -> str: return self.call_function_autoRpc("rewardToken") @property def totalAllocPoint(self) -> int: """Sum of the allocation points of all pools Returns: int: totalAllocPoint """ return self.call_function_autoRpc("totalAllocPoint") def userInfo(self, pid: int, user: str) -> tuple[int, int]: """_summary_ Args: pid (int): pool index user (str): user address Returns: tuple[int, int]: amount uint256, rewardDebt uint256 amount — how many Liquid Provider (LP) tokens the user has supplied rewardDebt — the amount of SUSHI entitled to the user """ return self.call_function_autoRpc("userInfo", None, pid, user) # CUSTOM def as_dict(self, convert_bint=False, static_mode: bool = False) -> dict: """as_dict _summary_ Args: convert_bint (bool, optional): Convert big integers to string. Defaults to False. static_mode (bool, optional): only general static fields are returned. Defaults to False. Returns: dict: """ result = super().as_dict(convert_bint=convert_bint) result["type"] = "zyberswap" # result["token_precision"] = ( # str(self.acc_token_precision) if convert_bint else self.acc_token_precision # ) result["masterchef_address"] = (self.distributorV2).lower() result["owner"] = (self.owner).lower() # result["pendingOwner"] = "" # result["poolLength"] = self.poolLength # result["rewardPerSecond"] = ( # str(self.rewardPerSecond) if convert_bint else self.rewardPerSecond # ) result["rewardToken"] = (self.rewardToken).lower() result["totalAllocPoint"] = ( str(self.totalAllocPoint) if convert_bint else self.totalAllocPoint ) # only return when static mode is off if not static_mode: pass return result # get all rewards def get_rewards( self, pids: list[int] | None = None, convert_bint: bool = False, ) -> list[dict]: """Search for rewards data Args: pids (list[int] | None, optional): pool ids linked to hypervisor. One pool id normally convert_bint (bool, optional): Convert big integers to string. Defaults to False. Returns: list[dict]: network: str block: int timestamp: int rewarder_address: str rewarder_type: str rewarder_refIds: list[str] rewardToken: str rewards_perSecond: int """ result = [] for pid in pids: try: poolRewardsPerSec = self.poolRewardsPerSec(pid) # get rewards data result.append( { # "network": self._network, "block": self.block, "timestamp": self._timestamp, # "hypervisor_address": pinfo[0].lower(), # there is no hype address in this contract "rewarder_address": self.address.lower(), "rewarder_type": rewarderType.ZYBERSWAP_masterchef_v1_rewarder, "rewarder_refIds": [pid], "rewarder_registry": self.address.lower(), "rewardToken": self.rewardToken.lower(), # "rewardToken_symbol": symbol, # "rewardToken_decimals": decimals, "rewards_perSecond": str(poolRewardsPerSec) if convert_bint else poolRewardsPerSec, # "total_hypervisorToken_qtty": str(pinfo[6]) # if convert_bint # else pinfo[6], } ) except Exception as e: logging.getLogger(__name__).exception( f" Error encountered while constructing zyberswap rewards -> {e}" ) return result class zyberswap_masterchef_v1(gamma_rewarder): # https://arbiscan.io/address/0x9ba666165867e916ee7ed3a3ae6c19415c2fbddd#readContract def __init__( self, address: str, network: str, abi_filename: str = "", abi_path: str = "", block: int = 0, timestamp: int = 0, custom_web3: Web3 | None = None, custom_web3Url: str | None = None, ): self._abi_filename = abi_filename or "zyberchef_v1" self._abi_path = abi_path or f"{self.abi_root_path}/zyberswap/masterchef" super().__init__( address=address, network=network, abi_filename=self._abi_filename, abi_path=self._abi_path, block=block, timestamp=timestamp, custom_web3=custom_web3, custom_web3Url=custom_web3Url, ) @property def maximum_deposit_fee_rate(self) -> int: """maximum deposit fee rate Returns: int: unit16 """ return self.call_function_autoRpc("MAXIMUM_DEPOSIT_FEE_RATE") @property def maximum_harvest_interval(self) -> int: """maximum harvest interval Returns: int: unit256 """ return self.call_function_autoRpc("MAXIMUM_HARVEST_INTERVAL") def canHarvest(self, pid: int, user: str) -> bool: """can harvest Args: pid (int): pool id user (str): user address Returns: bool: _description_ """ return self.call_function_autoRpc("canHarvest", None, pid, user) @property def feeAddress(self) -> str: """fee address Returns: str: address """ return self.call_function_autoRpc("feeAddress") @property def getZyberPerSec(self) -> int: """zyber per sec Returns: int: unit256 """ return self.call_function_autoRpc("getZyberPerSec") @property def marketingAddress(self) -> str: """marketing address Returns: str: address """ return self.call_function_autoRpc("marketingAddress") @property def marketingPercent(self) -> int: """marketing percent Returns: int: unit256 """ return self.call_function_autoRpc("marketingPercent") @property def owner(self) -> str: """owner Returns: str: address """ return self.call_function_autoRpc("owner") def pendingTokens( self, pid: int, user: str ) -> tuple[list[str], list[str], list[int], list[int]]: """pending tokens Args: pid (int): pool id user (str): user address Returns: tuple: addresses address[], symbols string[], decimals uint256[], amounts uint256[] """ return self.call_function_autoRpc("pendingTokens", None, pid, user) def poolInfo(self, pid: int) -> tuple[str, int, int, int, int, int, int, int]: """pool info Args: pid (int): pool id Returns: tuple: lpToken address, allocPoint uint256, lastRewardTimestamp uint256, accZyberPerShare uint256, depositFeeBP uint16, harvestInterval uint256, totalLp uint256 """ return self.call_function_autoRpc("poolInfo", None, pid) @property def poolLength(self) -> int: """pool length Returns: int: unit256 """ return self.call_function_autoRpc("poolLength") def poolRewarders(self, pid: int) -> list[str]: """pool rewarders Args: pid (int): pool id Returns: list[str]: address[] """ return self.call_function_autoRpc("poolRewarders", None, pid) def poolRewardsPerSec( self, pid: int ) -> tuple[list[str], list[str], list[int], list[int]]: """pool rewards per sec first item is always ZYB ( without pool rewarder bc it is directly rewarded by the masterchef) subsequent items have pool rewarder ( when calling poolRewarders(pid)) Args: pid (int): pool id Returns: tuple: addresses address[], symbols string[], decimals uint256[], rewardsPerSec uint256[] """ return self.call_function_autoRpc("poolRewardsPerSec", None, pid) def poolTotalLp(self, pid: int) -> int: """pool total lp Args: pid (int): pool id Returns: int: unit256 """ return self.call_function_autoRpc("poolTotalLp", None, pid) @property def startTimestamp(self) -> int: """start timestamp Returns: int: unit256 """ return self.call_function_autoRpc("startTimestamp") @property def teamAddress(self) -> str: """team address Returns: str: address """ return self.call_function_autoRpc("teamAddress") @property def teamPercent(self) -> int: """team percent Returns: int: unit256 """ return self.call_function_autoRpc("teamPercent") @property def totalAllocPoint(self) -> int: """total alloc point Returns: int: unit256 """ return self.call_function_autoRpc("totalAllocPoint") @property def totalLockedUpRewards(self) -> int: """total locked up rewards Returns: int: unit256 """ return self.call_function_autoRpc("totalLockedUpRewards") @property def totalZyberInPools(self) -> int: """total zyber in pools Returns: int: unit256 """ return self.call_function_autoRpc("totalZyberInPools") def userInfo(self, pid: int, user: str) -> tuple[int, int, int, int]: """user info Args: pid (int): pool id user (str): user address Returns: tuple: amount uint256, rewardDebt uint256, rewardLockedUp uint256, nextHarvestUntil uint256 """ return self.call_function_autoRpc("userInfo", None, pid, user) @property def zyber(self) -> str: """zyber Returns: str: address """ return self.call_function_autoRpc("zyber") @property def zyberPerSec(self) -> int: """zyber per sec Returns: int: unit256 """ return self.call_function_autoRpc("zyberPerSec") # get all rewards def get_rewards( self, hypervisor_addresses: list[str] | None = None, pids: list[int] | None = None, convert_bint: bool = False, ) -> list[dict]: """Search for rewards data Args: hypervisor_addresses (list[str] | None, optional): list of lower case hypervisor addresses. When defaults to None, all rewarded hypes ( gamma or non gamma) will be returned. pids (list[int] | None, optional): pool ids linked to hypervisor. When defaults to None, all pools will be returned. convert_bint (bool, optional): Convert big integers to string. Defaults to False. Returns: list[dict]: network: str block: int timestamp: int hypervisor_address: str rewarder_address: str rewarder_type: str rewarder_refIds: list[str] rewardToken: str rewardToken_symbol: str rewardToken_decimals: int rewards_perSecond: int total_hypervisorToken_qtty: int """ result = [] for pid in pids or range(self.poolLength): # lpToken address, allocPoint uint256, lastRewardTimestamp uint256, accZyberPerShare uint256, depositFeeBP uint16, harvestInterval uint256, totalLp uint256 ( lpToken_address, allocPoint, lastRewardTimestamp, accZyberPerShare, depositFeeBP, harvestInterval, totalLp, ) = self.poolInfo(pid) if pinfo := self.poolInfo(pid): if ( not hypervisor_addresses or lpToken_address.lower() in hypervisor_addresses ): # addresses address[], symbols string[], decimals uint256[], rewardsPerSec uint256[] poolRewardsPerSec = self.poolRewardsPerSec(pid) poolRewarders = self.poolRewarders(pid) # get rewards data first_time = True for address, symbol, decimals, rewardsPerSec in zip( poolRewardsPerSec[0], poolRewardsPerSec[1], poolRewardsPerSec[2], poolRewardsPerSec[3], ): rewarder_type = rewarderType.ZYBERSWAP_masterchef_v1_rewarder rewarder_address = self.address.lower() if first_time: # first item is always ZYB ( without pool rewarder bc it is directly rewarded by the masterchef) # subsequent items have pool rewarder rewarder_address = self.address.lower() first_time = False rewarder_type = rewarderType.ZYBERSWAP_masterchef_v1 else: rewarder_address = poolRewarders.pop(0).lower() # if rewardsPerSec: # do not uncomment bc it leads to unknown result ( error or no result) result.append( { # "network": self._network, "block": self.block, "timestamp": self._timestamp, "hypervisor_address": lpToken_address.lower(), "rewarder_address": rewarder_address, "rewarder_type": rewarder_type, "rewarder_refIds": [pid], "rewarder_registry": self.address.lower(), "rewardToken": address.lower(), "rewardToken_symbol": symbol, "rewardToken_decimals": decimals, "rewards_perSecond": str(rewardsPerSec) if convert_bint else rewardsPerSec, "total_hypervisorToken_qtty": str(totalLp) if convert_bint else totalLp, "raw_data": { "allocPoint": allocPoint, "lastRewardTimestamp": lastRewardTimestamp, "accZyberPerShare": str(accZyberPerShare) if convert_bint else accZyberPerShare, "depositFeeBP": depositFeeBP, "harvestInterval": harvestInterval, }, } ) return result
import 'dart:io'; import 'package:dukan/provider/product_provider.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; import 'package:uuid/uuid.dart'; class ImagesScreen extends StatefulWidget { const ImagesScreen({super.key}); @override State<ImagesScreen> createState() => _ImagesScreenState(); } class _ImagesScreenState extends State<ImagesScreen> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; final FirebaseStorage _storage = FirebaseStorage.instance; final ImagePicker picker = ImagePicker(); final List<File> _image = []; final List<String> _imageUrlList = []; chooseImage() async { final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile == null) { print('no Image Picked'); } else { setState(() { _image.add(File(pickedFile.path)); }); } } @override Widget build(BuildContext context) { super.build(context); final ProductProvider productProvider = Provider.of(context); return Scaffold( body: Padding( padding: const EdgeInsets.all(15.0), child: Column( children: [ GridView.builder( shrinkWrap: true, itemCount: _image.length + 1, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, mainAxisSpacing: 8, childAspectRatio: 3 / 3, crossAxisSpacing: 8), itemBuilder: (context, index) { return index == 0 ? Center( child: IconButton( onPressed: () { chooseImage(); }, icon: const Icon( Icons.add, ), ), ) : Container( decoration: BoxDecoration( image: DecorationImage( image: FileImage( _image[index - 1], ), ), ), ); }), if (_image.isNotEmpty) ElevatedButton( onPressed: () async { EasyLoading.show(status: 'PLEASE WAIT'); for (var img in _image) { Reference ref = _storage .ref() .child('productImages') .child(const Uuid().v4()); await ref.putFile(img).whenComplete(() async { await ref.getDownloadURL().then((value) { setState(() { _imageUrlList.add(value); }); }); EasyLoading.dismiss(); }); productProvider.getFormData(imageUrlList: _imageUrlList); } }, child: const Text('Upload Images'), ), ], ), )); } }
"use client" import { useState, useEffect } from "react"; import Link from "next/link"; import jwt from "jsonwebtoken"; import { useRouter } from "next/navigation"; export default function Navbar() { // Step 1: Check if a token exists in the localStorage const token = localStorage.getItem("token"); const isLoggedIn = !!token; const router = useRouter // Step 2: Create a state variable to hold the user's username const [username, setUsername] = useState(""); // Step 3: Set the username when the component mounts useEffect(() => { // Step 4: Decode the token and extract the username if (token) { try { const decodedToken = jwt.decode(token); // Assuming the token contains a field "username" with the username if (decodedToken && decodedToken.userId.username) { setUsername(decodedToken.userId.username); } } catch (error) { // Handle any decoding errors here (e.g., invalid token) console.error("Error decoding token:", error); } } }, [token]); const handleLogout = () => { localStorage.clear(); router.push('/login'); }; return ( <nav className="flex items-center justify-between flex-wrap bg-teal-500 p-6"> {isLoggedIn && ( <Link href={"/add"}> <div className="flex items-center flex-shrink-0 text-white mr-6"> <span className="font-semibold text-xl tracking-tight">Add Topic</span> </div> </Link> )} <div> {/* Step 5: Conditionally render the elements */} {isLoggedIn ? ( <> <span className="text-white mr-4">Hello, {username}</span> <button onClick={handleLogout} > <div className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-teal-500 hover:bg-white mt-4 lg:mt-0"> Logout </div> </button> </> ) : ( <div className="space-x-2"> <Link href="/login"> <div className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-teal-500 hover:bg-white mt-4 lg:mt-0"> Login </div> </Link> <Link href="/register"> <div className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-teal-500 hover:bg-white mt-4 lg:mt-0"> Register </div> </Link> </div> )} </div> </nav> ); }
<?php declare(strict_types=1); namespace App\Jobs; use App\Events\DealChanged; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; /** * Class DealCreated * * @author Milica Mihajlovic <milica@forwardslashny.com> */ class JobDealSendEmail implements ShouldQueue { use Dispatchable; use InteractsWithQueue; use Queueable; use SerializesModels; public $deal; public function __construct($deal) { $this->deal = $deal; } public function handle() { event(new DealChanged($this->deal, 'createdPublished')); } }
package StackAndQueue; // 35 https://leetcode.cn/problems/top-k-frequent-elements/description/ /** * 使用map记录每个元素出现的频次 * 使用优先级队列完成排序,保留频次最高的K个元素,具体过程是: * 1. 优先级队列存储元素和频次,且以频次升序排序,这样构造的优先级队列是小顶堆,即堆顶是频次最低的元素 * 2. 遍历map:当队列大小小于K时,直接添加元素;否则比较当前元素频次和队列中最小频次元素的频次,如果当前元素频次较大,则替换队列中最小频次元素 * 3. 遍历结束后,队列中剩下的元素即为频次最高的K个元素 */ import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; public class Top_K_FrequentElements { public int[] topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); } PriorityQueue<int[]> priorityQueue = new PriorityQueue<>( // 实现排序接口,这是是升序排序,则构造的优先队列是小顶堆,符合我们的需要 // 如果排序规则是(a, b) -> b[1] - a[1] ,则是大顶堆 Comparator.comparingInt(a -> a[1]) ); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (priorityQueue.size() < k) { priorityQueue.add(new int[]{entry.getKey(), entry.getValue()}); } else if (priorityQueue.peek() != null && priorityQueue.peek()[1] < entry.getValue()) { priorityQueue.poll(); priorityQueue.add(new int[]{entry.getKey(), entry.getValue()}); } } int index = 0; int[] result = new int[k]; while (!priorityQueue.isEmpty()) { result[index++] = priorityQueue.poll()[0]; } return result; } }
#include "SuperHeroGame.h" SuperHeroGame::SuperHeroGame() { _system = &(_system->getInstance()); std::ifstream ofsGame(FileConstants::GAME_FILE_NAME, std::ios::out | std::ios::binary); if (!ofsGame.is_open()) throw std::logic_error("Can not open the file!"); ofsGame.read((char*)&turnsCounter, sizeof(size_t)); size_t counter = currentTurnPlayers.size(); ofsGame.read((char*)&counter, sizeof(size_t)); for (size_t i = 0; i < counter; i++) { String currentUsername; currentUsername.readFromBinary(ofsGame); currentTurnPlayers.push_back(_system->userWith(currentUsername)); } ofsGame.close(); } void SuperHeroGame::run() { while (true) { try { if (!_system->isLogged()) { login(); clearConsole(); continue; } menu(); if (command()) return; } catch (const std::exception& ex) { std::cout << ex.what() << std::endl; continue; } } } void SuperHeroGame::menu() { std::cout << std::endl << "+----------------+" << std::endl; if (_system->isAdmin()) { std::cout <<"| ADMIN MENU: |" << std::endl <<"|PRINT: |" << std::endl <<"| --Users |" << std::endl <<"| --Market |" << std::endl <<"| --Results |" << std::endl <<"| --ViewUser |" << std::endl <<"|MODIFY: |" << std::endl <<"| --AddAdmin |" << std::endl <<"| --AddPlayer |" << std::endl <<"| --DeletePlayer |" << std::endl <<"| --AddToMarket |" << std::endl <<"| --Resurrect |" << std::endl; } else { std::cout << "| PLAYER MENU: |" << std::endl << "|PRINT: |" << std::endl << "| --Users |" << std::endl << "| --Market |" << std::endl << "| --Results |" << std::endl << "|MODIFY: |" << std::endl << "| --Buy |" << std::endl << "| --AttackUser |" << std::endl << "| --AttackHero |" << std::endl << "| --Mode |" << std::endl; } std::cout << "|PERSONAL |" << std::endl << "| --DeleteMe |" << std::endl << "|Logout |" << std::endl << "|Profile |" << std::endl << "|Exit |" << std::endl << "+----------------+" << std::endl; } void SuperHeroGame::login() { std::cout << "LOGIN: \n"; String nickname, password; std::cout << "Username: "; std::cin >> nickname; std::cout << "\nPassword: "; std::cin >> password; _system->login(std::move(nickname), std::move(password)); std::cout << "You successfully logged as " << nickname << std::endl; if (isNewTurn()) { turnsCounter++; currentTurnPlayers.clear(); if (turnsCounter % GameConstants::TURN_CRITERIA == 0) { _system->giveMoney(); } } addCurrentPlayer(); while (_system->isAdmin() && _system->marketSize() < 3) { std::cout << "There are less that 3 superheroes on the market. You should add superhero!\n"; try { addSyperhero(); } catch (const std::exception& ex) { std::cout << ex.what() <<std::endl; } } } void SuperHeroGame::logout() { _system->logout(); std::cout << "You successfully logged out " << std::endl; this->actions = 0; } void SuperHeroGame::increaseActions() { if (actions >= 3) { throw std::exception("You are out of moves."); } actions++; } bool SuperHeroGame::command() { String command; std::cout << "Enter command: "; std::cin >> command; clearConsole(); if (command == "Users") { users(); } else if (command == "Market") { market(); } else if (command == "Results") { results(); } else if (command == "ViewUser") { viewUser(); } else if (command == "AddAdmin") { add(true); } else if (command == "AddPlayer") { add(false); } else if (command == "DeletePlayer") { deletePlayer(); } else if (command == "AddToMarket") { addSyperhero(); } else if (command == "Resurrect") { resurrect(); } else if (command == "DeleteMe") { _system->deleteMe(); } else if (command == "Logout") { logout(); } else if (command == "Buy") { increaseActions(); buy(); } else if (command == "AttackUser") { increaseActions(); attackUser(); } else if (command == "AttackHero") { increaseActions(); attackHero(); } else if (command == "Mode") { increaseActions(); changeMode(); } else if (command == "Profile") { profile(); } else if (command == "Exit") { exit(); return true; } else { throw std::logic_error("Invalid command!"); } return false; } void SuperHeroGame::addSyperhero() { String firstName, lastName, nickname, power; size_t strenght; double price; std::cout << "First name: "; std::cin >> firstName; std::cout << "Last name: "; std::cin >> lastName; std::cout << "Nickname: "; std::cin >> nickname; std::cout << "Power: "; std::cin >> power; std::cout << "Strenght: "; std::cin >> strenght; std::cout << "Price: "; std::cin >> price; _system->addSuperhero(firstName, lastName, nickname, getPower(power), strenght, price, Mode::notBought); } void SuperHeroGame::resurrect() { String nickname; std::cout << "Nickname: "; std::cin >> nickname; _system->resurrect(nickname); } void SuperHeroGame::users() const { std::cout << "USERS: " << std::endl; _system->printUsers(); } void SuperHeroGame::market() const { std::cout << "MARKET: " << std::endl; _system->printMarket(); } void SuperHeroGame::results() { std::cout << "RESULTS: " << std::endl; _system->results(); } void SuperHeroGame::viewUser() const { String nickname; std::cout << "Nickname: "; std::cin >> nickname; _system->printInfo(nickname); } void SuperHeroGame::add(bool isAdmin) { std::cout << "ADD: " << std::endl; String firstName, lastName, username, password; std::cout << "First name: "; std::cin >> firstName; std::cout << "Last name: "; std::cin >> lastName; std::cout << "Username: "; std::cin >> username; std::cout << "Password: "; std::cin >> password; _system->addUser(firstName, lastName, username, password, isAdmin); std::cout << (isAdmin? "Admin " : "Player ") << username << " created successfully!" << std::endl; } void SuperHeroGame::deletePlayer() { String nickname; std::cout << "Nickname: "; std::cin >> nickname; _system->deletePlayer(nickname); } void SuperHeroGame::buy() { String nickname; std::cout << "Nickname: "; std::cin >> nickname; _system->buy(nickname); } void SuperHeroGame::attackHero() { String myhero, opponentHero; std::cout << "My hero nickname: "; std::cin >> myhero; std::cout << "Opponent hero nickname: "; std::cin >> opponentHero; int money = _system->attack(myhero, nullptr, opponentHero); if (money >= 0) { std::cout << "You won $" << money << " againt " << opponentHero; } else { std::cout << "You lost $" << money << " againt " << opponentHero; } } void SuperHeroGame::attackUser() { String myhero, opponent; std::cout << "My hero nickname: "; std::cin >> myhero; std::cout << "Opponent username: "; std::cin >> opponent; int money = _system->attack(myhero, opponent); if (money >= 0) { std::cout << "You won $" << money << " againt " << opponent; } else { std::cout << "You lost $" << money << " againt " << opponent; } } void SuperHeroGame::changeMode() { String myhero, mode; std::cout << "My hero nickname: "; std::cin >> myhero; std::cout << "New mode: "; std::cin >> mode; _system->changeMode(myhero, getMode(mode)); } void SuperHeroGame::exit() const { std::ofstream ofsGame(FileConstants::GAME_FILE_NAME, std::ios::out | std::ios::binary); if (!ofsGame.is_open()) throw std::logic_error("Can not open the file!"); ofsGame.write((const char*)&turnsCounter, sizeof(size_t)); size_t counter = currentTurnPlayers.size(); ofsGame.write((const char*)&counter, sizeof(size_t)); for (size_t i = 0; i < counter; i++) { currentTurnPlayers[i]->username().writeToBinary(ofsGame); } ofsGame.close(); std::ofstream ofsSys(FileConstants::SYS_FILE_NAME, std::ios::out | std::ios::binary); if (!ofsSys.is_open()) throw std::logic_error("Can not open the file!"); _system->writeToBinary(ofsSys); ofsSys.close(); } bool SuperHeroGame::isNewTurn() const { return currentTurnPlayers.constains(_system->currentPlayer()); } void SuperHeroGame::addCurrentPlayer() { if (!_system->currentPlayer()->isAdmin()) { currentTurnPlayers.push_back(_system->currentPlayer()); } } void SuperHeroGame::profile() const { _system->profile(); } //from Georgi Terziev's github void clearConsole() { std::cout << "\033[;H"; std::cout << "\033[J"; }
// // DetailViewController.swift // iFindMovies // // Created by Pratyush Thapa on 2/13/17. // Copyright © 2017 Pratyush. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var TitleLabel: UILabel! @IBOutlet weak var OverviewLabel: UILabel! @IBOutlet weak var PosterView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var documentView: UIView! var movie: NSDictionary! override func viewDidLoad() { super.viewDidLoad() scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: documentView.frame.origin.y + documentView.frame.size.height) let title = movie["title"] as? String self.title = title TitleLabel.text = title let overview = movie["overview"] as? String OverviewLabel.text = overview OverviewLabel.sizeToFit() let smallImagePath = "https://image.tmdb.org/t/p/w45" let largeImagePath = "https://image.tmdb.org/t/p/w500/" if let posterPath = movie["poster_path"] as? String{ let smallImageUrl = NSURL(string: smallImagePath + posterPath) let largeImageUrl = NSURL(string: largeImagePath + posterPath) let smallImageRequest = NSURLRequest(url: smallImageUrl! as URL) let largeImageRequest = NSURLRequest(url: largeImageUrl! as URL) self.PosterView.setImageWith( smallImageRequest as URLRequest, placeholderImage: nil, success: { (smallImageRequest, smallImageResponse, smallImage) -> Void in self.PosterView.alpha = 0.0 self.PosterView.image = smallImage; UIView.animate(withDuration: 0.3, animations: { () -> Void in self.PosterView.alpha = 1.0 }, completion: { (sucess) -> Void in self.PosterView.setImageWith( largeImageRequest as URLRequest, placeholderImage: smallImage, success: { (largeImageRequest, largeImageResponse, largeImage) -> Void in self.PosterView.image = largeImage; }, failure: { (request, response, error) -> Void in }) }) }, failure: { (request, response, error) -> Void in }) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
package com.example.android.evcharge; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class SelectModeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private boolean viewIsAtHome; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_mode); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); Menu menu =navigationView.getMenu(); //modifying menu items if(((EVCharge) this.getApplication()).isRegular()) { MenuItem target = menu.findItem(R.id.nav_account); target.setVisible(false); } if(((EVCharge) this.getApplication()).isPostpaid()) { MenuItem target = menu.findItem(R.id.nav_account); target.setTitle("Balance"); } if(((EVCharge) this.getApplication()).isPrepaid()) { MenuItem target = menu.findItem(R.id.nav_account); target.setTitle("Wallet"); } displayView(R.id.nav_choose_mode); } @Override public void onBackPressed() {DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } if (!viewIsAtHome) { //if the current view is not the News fragment displayView(R.id.nav_choose_mode); //display the News fragment } else { moveTaskToBack(true); //If view is in News fragment, exit application } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.select_mode, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_logout) { Intent intent=new Intent(SelectModeActivity.this,LoginActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); displayView(id); // // if (id == R.id.nav_choose_mode) { // // Handle the camera action // // } else if (id == R.id.nav_profile) { // // } else if (id == R.id.nav_account) { // // } else if (id == R.id.nav_transaction) { // // } else if (id == R.id.nav_share) { // // } else if (id == R.id.nav_send) { // // } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void displayView(int viewId) { Fragment fragment = null; String title = getString(R.string.app_name); switch (viewId) { case R.id.nav_choose_mode: fragment = new ChooseModeFragment(); title = "Choose Mode"; viewIsAtHome=true; break; case R.id.nav_profile: fragment = new ProfileFragment(); title = "Profile"; viewIsAtHome=false; break; case R.id.nav_account: fragment = new AccountFragment(); title = "Account"; viewIsAtHome=false; break; case R.id.nav_transaction: fragment=new TransactionFragment(); title="Transaction"; viewIsAtHome=false; break; } if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } // set the toolbar title if (getSupportActionBar() != null) { getSupportActionBar().setTitle(title); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } }
<!DOCTYPE html> <html> <head> <title>商品分类表-添加/修改</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <!-- 所有的 css js 资源 --> <link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css"> <link rel="stylesheet" href="../../static/sa.css"> <script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script> <script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script> <script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script> <script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script> <script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script> <script src="../../static/sa.js"></script> <script src="../../static/kj/upload-util.js"></script> <style type="text/css"> .td-img{width: 400px; height: 200px; cursor: pointer; vertical-align: middle;} .c-panel .el-form .c-label{width: 5em !important;} .c-panel .el-form .el-input{width: 400px;} </style> </head> <body> <div class="vue-box" :class="{sbot: id}" style="display: none;" :style="'display: block;'"> <!-- ------- 内容部分 ------- --> <div class="s-body"> <div class="c-panel"> <div class="c-title">数据添加</div> <el-form v-if="m"> <sa-item name="图片" br> <img :src="m.img_src" class="td-img" @click="sa.showImage(m.img_src, '70%', '80%')" > <el-link type="primary" @click="sa.uploadImage(src => {m.img_src = src; sa.ok2('上传成功');})">上传</el-link> </sa-item> <sa-item name="标题" v-model="m.title" br></sa-item> <sa-item name="排序" v-model="m.sort" type="num" br></sa-item> <sa-item name="" class="s-ok" br> <el-button type="primary" icon="el-icon-plus" @click="ok()">保存</el-button> </sa-item> </el-form> </div> </div> <!-- ------- 底部按钮 ------- --> <div class="s-foot"> <el-button type="primary" @click="ok()">确定</el-button> <el-button @click="sa.closeCurrIframe()">取消</el-button> </div> </div> <script src="./mock-data-list.js"></script> <script> var app = new Vue({ components: { "sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue'), "sa-info": httpVueLoader('../../sa-frame/com/sa-info.vue'), }, el: '.vue-box', data: { id: sa.p('id', 0), // 获取超链接中的id参数(0=添加,非0=修改) m: null, // 实体对象 }, methods: { // 创建一个 默认Model createModel: function() { return { id: 11, title: '标题', type: 1, sort: 0, status:1, img_src: 'http://color-test.oss-cn-qingdao.aliyuncs.com/dyc/img/2020/01/20/1579506071035455989950.jpeg', create_time: new Date(), click_count: 42, is_update: false, } }, // 提交数据 ok: function(){ // 验证 sa.checkNull(this.m.title, '请输入标题'); sa.checkNull(this.m.sort, '请输入排序值'); // 开始增加或修改 // this.m.create_time = undefined; // 不提交属性:创建日期 if(this.id <= 0) { // 添加 sa.ajax2('/SysSwiper/add', this.m, function(res){ sa.alert('增加成功', function() { if(parent.app) { var m2 = sa.copyJSON(this.m); parent.app.dataList.push(m2); parent.sa.f5TableHeight(); // 刷新表格高度 sa.closeCurrIframe(); // 关闭本页 } else { app.m = this.createModel(); } }.bind(this)); }.bind(this)); } else { // 修改 sa.ajax2('/SysSwiper/update', this.m, function(res){ sa.alert('修改成功', this.clean); }.bind(this)); } }, // 添加/修改 完成后的动作 clean: function() { if(this.id == 0) { this.m = this.createModel(); } else { parent.app.f5(); // 刷新父页面列表 sa.closeCurrIframe(); // 关闭本页 } } }, mounted: function(){ // 初始化数据 if(this.id <= 0) { this.m = this.createModel(); } else { sa.ajax2('/SysSwiper/getById?id=' + this.id, function(res) { this.m = res.data; }.bind(this), {res: getById(this.id)}); } } }) // 获取对应的data function getById(id) { var res = { code: 200, msg: 'ok', data: null }; mockDataList.data.forEach(function(item) { if(item.id == id) { res.data = item; } }) return res; } </script> </body> </html>
import torch import torch.nn as nn from .layers import Latent, Reshape class Conv(nn.Module): def __init__(self, T, n, n_z): super().__init__() self.T = T self.n = n self.enc = nn.Sequential( nn.Conv1d(in_channels = n, out_channels = 50, kernel_size = 5, stride=1, padding=2), nn.LeakyReLU(0.2), nn.Conv1d(in_channels = 50, out_channels = 100, kernel_size = 5, stride=2, padding=2), nn.LeakyReLU(0.2), nn.Flatten(), nn.Linear(3100, 500), nn.LeakyReLU(0.2), Latent(500, n_z) ) self.dec = nn.Sequential( nn.Linear(n_z, 500), nn.LeakyReLU(0.2), nn.Linear(500, 3100), nn.LeakyReLU(0.2), Reshape(100, 31), nn.ConvTranspose1d(in_channels = 100, out_channels = 50, kernel_size = 5, stride=2, padding=2), nn.LeakyReLU(0.2), nn.ConvTranspose1d(in_channels = 50, out_channels = n, kernel_size = 5, stride=1, padding=2) ) self.mse = nn.MSELoss(reduction="sum") def encode(self, x, return_loss = False): z, mu, log_var = self.enc(x) if return_loss: dkl = -0.5*torch.sum(1 + log_var - mu.pow(2) - log_var.exp(), dim=1) return z, mu, log_var, dkl return z, mu, log_var def decode(self,z): return self.dec(z) def _reg_loss(self): loss = 0 lam = 0.05 for m in self.parameters(): loss += m.abs().sum() return loss*lam def forward(self, x, beta = 1.0): z, mu, log_var, dkl = self.encode(x, True) gen_x = self.decode(z) rcl = self.mse(gen_x, x) return gen_x, torch.mean(rcl + dkl*beta)
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using RealEstateAdmin.Core.DTO.Views; using RealEstateAdmin.Core.Helpers; using RealEstateAdmin.Core.ServiceContracts; using RealEstateAdmin.Core.Services; namespace RealEstateAdmin.Api.Controllers { [ApiController] [Route("api/user")] public class UserController:ControllerBase { private readonly IUserService _userService; public UserController(IUserService userService) { _userService = userService; } /// <summary> /// Get User Details By UserId /// </summary> /// <param name="userId"></param> /// <returns></returns> [AllowAnonymous] [HttpGet("detail/{userId:int:min(1)}")] public async Task<ActionResult<UserDetailView>> GetUser(int userId) { if (userId == 0) { return BadRequest(); } else { ServiceResult result = await _userService.GetUserAsync(userId); return StatusCode((int)result.ServiceStatus, result); } } /// <summary> /// Get Users List /// </summary> /// <param name="searchQuery"></param> /// <param name="sortBy"></param> /// <param name="isSortAscending"></param> /// <returns></returns> [Authorize] [HttpGet("list")] public async Task<IActionResult> UsersList(string? searchQuery, string? sortBy, bool isSortAscending) { ServiceResult result = await _userService.GetUserList(searchQuery, sortBy, isSortAscending); return StatusCode((int)result.ServiceStatus, result); } /// <summary> /// Change User Status /// </summary> /// <param name="userId"></param> /// <param name="status"></param> /// <returns></returns> [Authorize] [HttpPut("change-status/{userId:int:min(1)}")] public async Task<IActionResult> ChangeUserStatus(int userId, [FromBody] byte status) { if (userId == 0) { return BadRequest(); } ServiceResult result = await _userService.ChangeStatusAsync(userId, status); return StatusCode((int)result.ServiceStatus, result); } /// <summary> /// Get Profile Picture /// </summary> /// <param name="fileName"></param> /// <returns></returns> [HttpGet("profile-image/{fileName}")] public async Task<IActionResult> GetProfilePic(string fileName) { FileStream? fileStream = await _userService.GetProfile(fileName); if (fileStream is null) return NotFound(); return File(fileStream, "image/jpeg"); } /// <summary> /// Get User Count /// </summary> /// <returns></returns> [Authorize] [HttpGet("count")] public async Task<IActionResult> Users() { if (ModelState.IsValid) { ServiceResult result = await _userService.Count(); return StatusCode((int)result.ServiceStatus, result); } else { return BadRequest(ModelState); } } } }
import { Injectable } from '@angular/core'; import { DataStorageService } from './data-storage.service'; import { Router } from '@angular/router'; import { AlertController } from '@ionic/angular'; import { UtilsService } from './utils/utils.service'; declare global { interface Window { google: any; } } @Injectable({ providedIn: 'root' }) export class LoginService { loginError: boolean = false; constructor(private dataStorage: DataStorageService, private utils: UtilsService, private router: Router, private alertController: AlertController) { } login(email: string, password: string) { this.dataStorage.sendRequest('POST', '/login', { email, password }) .then((response: any) => { if (response.status == 200) { let currentUser: any = { _id: response.data._id, user_picture: response.data.user_picture, username: response.data.username, firstLogin: response.data.firstLogin } localStorage.setItem("ASSICURAZIONI", JSON.stringify({ token: response.headers.authorization, currentUser: currentUser })); this.router.navigateByUrl('/home'); } }) .catch((error: any) => { if (error.response.status == 401) { this.alertController.create({ header: 'Errore', message: 'Email o password errati', buttons: ['OK'] }).then((alert) => { alert.present(); }); } }); } async checkToken() { let cache: any = localStorage.getItem("ASSICURAZIONI"); if (cache) { let parsedCache: any = JSON.parse(cache); if (parsedCache.token === "undefined") { localStorage.removeItem("ASSICURAZIONI"); } } } async sendMail(email: string) { return await this.dataStorage.sendRequest('POST', '/forgot-password', { email }); } async changePassword(oldPassword: string, newPassword: string, confirmPassword: string) { let userId = this.utils.getUserFromCache(); if (!userId || userId == null) { await this.router.navigateByUrl('/login'); window.location.reload(); } else { userId = userId._id; return await this.dataStorage.sendRequest('POST', '/change-password', { userId, oldPassword, newPassword, confirmPassword }); } } async logout() { localStorage.removeItem("ASSICURAZIONI"); await this.router.navigateByUrl('/login'); window.location.reload(); } }
-- GROUP BY -- STATEMENT -- IT ALLOWS TO AGGARATE DATA FOR CATEGORY LEVEL -- WE NEED CAEGORICAL COLUMN TO USE GROUP BY (MOST OF THE CASE, SOME EXCEPTION LIKE: AGE) -- AGE CAN BE NUMERICAL -- syntax -- SELECT COL1,AGG(COL2) AS COLUMN_NAME -- FROM TABLE -- WHERE (EXPRESSION IF ANY) -- GROUP BY COL1; -- HAVING (EXPRESSION) -- ORDER BY SELECT * FROM MenuItems; -- FIND THE NUMBER OF RESTAURENT OF HAVING A A SPICIFIC ITEM SELECT name, COUNT(restaurant_id) AS RESTAURANT_COUNT FROM MenuItems GROUP BY name HAVING COUNT(restaurant_id) > 1 ORDER BY COUNT(restaurant_id) DESC; -- task -- agter grouping the restaurant based on the item -- find the avg max and min price of that group SELECT name, COUNT(restaurant_id) AS RESTAURANT_COUNT, ROUND(AVG(price),2) AS AVG_PRICE, MAX(price) AS MAX_PRICE, MIN(price) AS MIN_PRICE FROM MenuItems GROUP BY name HAVING COUNT(restaurant_id) > 1 ORDER BY COUNT(restaurant_id) DESC; -- task -- show the restaurant too -- means in a particular item -- number of restaurant -- the restaurent and therit price -- you can group by a table using multiple -- column SELECT name, -- COUNT(restaurant_id) AS RESTAURANT_COUNT, restaurant_id, ROUND(AVG(price),2) AS AVG_PRICE FROM MenuItems GROUP BY name, restaurant_id -- HAVING -- COUNT(restaurant_id) > 1 ORDER BY COUNT(restaurant_id) DESC;
--- user-type: administrator product-area: system-administration navigation-topic: create-and-manage-custom-forms title: Agregar un salto de sección a un formulario personalizado con el generador de formularios heredado description: Puede agrupar los campos y widgets personalizados en un formulario personalizado en secciones con encabezados. Esto resulta útil para presentar una experiencia organizada a los usuarios que rellenan el formulario. Además, si necesita limitar el acceso a determinados campos personalizados y widgets a determinados usuarios, puede colocarlos en una sección y, a continuación, conceder acceso a la sección únicamente a esos usuarios. feature: System Setup and Administration, Custom Forms role: Admin exl-id: 44a52767-60a7-4aaa-b3b8-6b8fb7da7e72 source-git-commit: 961e0451ce9011a8a9f511d7d5da99368d22d6fb workflow-type: tm+mt source-wordcount: '1137' ht-degree: 0% --- # Agregar un salto de sección a un formulario personalizado con el generador de formularios heredado Puede agrupar los campos y widgets personalizados en un formulario personalizado en secciones con encabezados. Esto resulta útil para presentar una experiencia organizada a los usuarios que rellenan el formulario. Además, si necesita limitar el acceso a determinados campos personalizados y widgets a determinados usuarios, puede colocarlos en una sección y, a continuación, conceder acceso a la sección únicamente a esos usuarios. Por ejemplo, si necesita realizar el seguimiento de información confidencial que solo los administradores del sistema deben poder ver o editar, puede crear un salto de sección con permisos de Solo administración y colocar los campos confidenciales en esa sección. La configuración de acceso que seleccione para una sección está directamente vinculada a los permisos que los usuarios tienen en el objeto de Workfront donde está adjunto el formulario personalizado. Puede ocultar o mostrar una sección en función de si el usuario tiene acceso para ver, contribuir o administrar ese objeto. O puede establecer una sección en Solo administrador para que solo los usuarios con un nivel de acceso de administrador del sistema puedan acceder a ella. Para obtener información sobre los permisos de los objetos, consulte [Información general sobre los permisos de uso compartido en objetos](../../../workfront-basics/grant-and-request-access-to-objects/sharing-permissions-on-objects-overview.md). Para obtener información sobre los campos y widgets personalizados en los formularios personalizados, consulte [Agregar un campo personalizado a un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-a-custom-field-to-a-custom-form.md) y [Agregar o editar un widget de recursos en un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-widget-or-edit-its-properties-in-a-custom-form.md). <!-- >[!TIP] > >Section breaks that you add to custom forms are saved in your system for re-use. For information about listing them, see [List and edit custom forms and widgets added to custom forms](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/list-edit-share-custom-forms-and-custom-fields.md). --> ## Requisitos de acceso Debe tener lo siguiente para realizar los pasos de este artículo: <table style="table-layout:auto"> <col> <col> <tbody> <tr data-mc-conditions=""> <td role="rowheader"> <p>plan Adobe Workfront*</p> </td> <td>Cualquiera</td> </tr> <tr> <td role="rowheader">Licencia de Adobe Workfront*</td> <td>Plan</td> </tr> <tr data-mc-conditions=""> <td role="rowheader">Configuraciones de nivel de acceso*</td> <td> <p>Acceso administrativo a formularios personalizados</p> <p>Para obtener información sobre cómo los administradores de Workfront conceden este acceso, consulte <a href="../../../administration-and-setup/add-users/configure-and-grant-access/grant-users-admin-access-certain-areas.md" class="MCXref xref">Conceder a los usuarios acceso administrativo a determinadas áreas</a>.</p> </td> </tr> </tbody> </table> &#42;Para saber qué configuraciones de plan, tipo de licencia o nivel de acceso tiene, póngase en contacto con su administrador de Workfront. ## Creación y configuración del acceso a una sección de un formulario personalizado 1. Comience a crear o editar un formulario personalizado, tal como se describe en [Crear o editar un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/create-or-edit-a-custom-form.md). 1. Agregue campos y widgets personalizados al formulario, tal como se describe en [Agregar un campo personalizado a un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-a-custom-field-to-a-custom-form.md) y [Agregar o editar un widget de recursos en un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-widget-or-edit-its-properties-in-a-custom-form.md). 1. Mientras sigue creando o editando el formulario personalizado, en la **Añadir un campo** pestaña, haga clic en **Salto de sección**. ![](assets/click-section-break.jpg) 1. En el **Configuración de campo** pestaña, configure las opciones que desee para la sección: <table style="table-layout:auto"> <col> </col> <col> </col> <tbody> <tr> <td role="rowheader">Etiqueta</td> <td> <p>(Obligatorio) Escriba una etiqueta descriptiva para mostrar encima de la sección. Puede cambiar la etiqueta en cualquier momento.</p> <p><b>IMPORTANTE</b>: evite utilizar caracteres especiales en esta etiqueta. No se muestran correctamente en los informes.</p> </td> </tr> <tr> <td role="rowheader">Descripción</td> <td>Escriba texto si desea explicar a los usuarios para qué sirve la sección. Esto se muestra debajo de la etiqueta de la sección en el formulario personalizado.</td> </tr> <tr> <td role="rowheader">Agregar lógica</td> <td>Utilice la lógica de visualización para especificar si la sección debe mostrarse en el formulario, en función de las selecciones que realicen los usuarios en los campos personalizados de opción múltiple al rellenar el formulario. Para obtener más información, consulte <a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/display-or-skip-logic-custom-form.md" class="MCXref xref">Agregar lógica de visualización y saltar lógica a un formulario personalizado</a>.</td> </tr> <tr> <td role="rowheader"> <p>Conceder acceso</p> </td> <td> <p> Seleccione los permisos que necesitan los usuarios en un objeto donde se adjunta el formulario personalizado para ver esta sección y editar sus valores de campo. <p>Los siguientes permisos están disponibles en <b>Los usuarios con este acceso al objeto pueden ver valores de campo</b>:</p> <ul> <li><strong>Ver</strong>: vea los permisos del objeto</li> <li><p><b>Edición limitada</b>: (disponible solo si el objeto es un proyecto, una tarea, un problema o un usuario):</p> <p>Permite a los usuarios contribuir al objeto si se trata de un proyecto, una tarea o un problema.</p> <p>Permite a los usuarios editar el perfil o poseer el permiso de perfil para el objeto si es un usuario.</p></li> <li><b>Editar</b>: administre permisos al objeto </li> <li><b>Solo administrador</b>: nivel de acceso del administrador del sistema</li> </ul> </li> <p>Los siguientes permisos están disponibles en <b>Los usuarios con este acceso al objeto pueden editar valores de campo</b>: </p> <ul> <li> <p><b>Edición limitada</b>: (disponible solo si el objeto es un proyecto, una tarea, un problema o un usuario):</p> <p>Si el objeto es un proyecto, una tarea o un problema, este permiso permite a los usuarios contribuir al objeto</p> <p>Si el objeto es un usuario, este permiso permite a los usuarios editar el perfil o poseer el permiso de perfil para el objeto.</p> <li><b>Editar</b>: administre permisos al objeto </li> <li><b>Solo administrador</b>: nivel de acceso del administrador del sistema</li> </ul> </li> </ul> <p>Para obtener información sobre los permisos de los objetos, consulte <a href="../../../workfront-basics/grant-and-request-access-to-objects/sharing-permissions-on-objects-overview.md" class="MCXref xref">Información general sobre los permisos de uso compartido en objetos</a>.</p> <p><b>NOTA</b>: <ul> <li> <p>Los usuarios sin los permisos especificados aquí no pueden ver los campos y widgets personalizados en la sección. </p> <p>Esto también se aplica si se muestran los valores de los campos en los informes o si se utilizan en campos calculados en los informes en modo de texto.</p> </li> <li> <p>La asociación de varios tipos de objetos con el formulario puede cambiar los permisos de visualización y edición disponibles en estos pasos. Para obtener más información, consulte <a href="#how-multiple-object-types-can-affect-section-break-permissions-in-a-custom-form" class="MCXref xref">Cómo pueden afectar varios tipos de objetos a los permisos de salto de sección en un formulario personalizado</a> en este artículo.</p> </li> </ul> </p> </td> </tr> </tbody> </table> 1. Arrastre o agregue al menos un campo o widget personalizado a la nueva sección. Es necesario antes de guardar la sección. 1. Clic **Listo**. >[!TIP] > >Puede hacer clic en **Aplicar** en cualquier momento mientras crea un formulario personalizado para guardar los cambios y mantener el formulario abierto. 1. Si desea seguir creando el formulario personalizado de otras formas, consulte uno de los siguientes artículos: * [Agregar un campo personalizado a un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-a-custom-field-to-a-custom-form.md#add2) * [Agregar o editar un widget de recursos en un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-widget-or-edit-its-properties-in-a-custom-form.md) * [Añadir datos calculados a un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-calculated-data-to-custom-form.md) * [Colocar campos y widgets personalizados en un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/position-fields-in-a-custom-form.md) * [Agregar lógica de visualización y saltar lógica a un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/display-or-skip-logic-custom-form.md) * [Previsualización y cumplimentación de un formulario personalizado](../../../administration-and-setup/customize-workfront/create-manage-custom-forms/preview-and-complete-a-custom-form.md) <!-- DRAFTED IN FLARE: <h2>Configure access for fields without section breaks</h2> <p data-mc-conditions="QuicksilverOrClassic.Draft mode">************This section might get added later. Team decided not to implement.</p> <p>In a custom form, you can also control users' access to custom fields and image widgets that are not placed inside a defined section.</p> <ol> <li value="1">Begin creating or editing a custom form, as described in <a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/create-or-edit-a-custom-form.md" class="MCXref xref">Create or edit a custom form</a>.</li> <li value="2">Add custom fields and widgets to the form, as described in <a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-a-custom-field-to-a-custom-form.md" class="MCXref xref">Add a custom field to a custom form</a>.</li> <li value="3"> <p>While still creating or editing the custom form, open the <b>Form settings</b> tab.</p> <p>SHOW THIS </p> </li> <li value="4"> <p>Under <b>Grant access</b>, configure the permissions that users need on an object where the custom form is attached, in order to view and edit values in fields not placed under a section break. </p> <p>If you need information about permissions on objects, see <a href="../../../workfront-basics/grant-and-request-access-to-objects/sharing-permissions-on-objects-overview.md" class="MCXref xref">Overview of sharing permissions on objects</a>.</p> <note type="note"> <ul> <li> <p>Users without the permissions you specify here can't see the values of the fields and image widgets that are not placed in a defined section in the custom form. This is also true if you display the values in reports or use them in calculated fields in text mode reporting.</p> </li> <li> <p>Associating multiple object types with your form can change the viewing and editing permissions that are available in these steps. For more information, see <a href="#how-multiple-object-types-can-affect-section-break-permissions-in-a-custom-form" class="MCXref xref">How multiple object types can affect section break permissions in a custom form</a> in this article.</p> </li> </ul> </note> <table style="table-layout:auto"> <col> <col> <tbody> <tr> <td role="rowheader"><b>Users with this access to the object can view field values</b> </td> <td> <ul> <li> <p><b>Limited Edit</b>: (Available only if the object is a project, task, issue, or user):</p> <ul> <li> <p>Contribute permission to the object if it's a project, task, or issue</p> </li> <li> <p>Edit the profile or own the profile permission to the object if it's a user (profile)</p> </li> </ul> </li> <li><b>Edit</b>: Manage permissions to the object </li> <li><b>Admin only</b>: System Administrator access level</li> </ul> </td> </tr> <tr> <td role="rowheader">Users with this access to the object can edit field values</td> <td> <ul> <li> <p><b>Limited Edit</b>: (Available only if the object is a project, task, issue, or user):</p> <ul> <li> <p>Contribute permission to the object if it's a project, task, or issue</p> </li> <li> <p>Edit the profile or own the profile permission to the object if it's a user (profile)</p> </li> </ul> </li> <li><b>Edit</b>: Manage permissions to the object </li> <li><b>Admin only</b>: System Administrator access level</li> </ul> </td> </tr> </tbody> </table> </li> <li value="5"> <p>Click Done.</p> <note type="tip"> You can click <strong>Apply</strong> at any point while you are creating a custom form to save your changes and keep the form open. </note> </li> <li value="6"> <p>If you want to continue building your custom form in other ways, continue on to one of the following articles:</p> <ul> <li><a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-a-custom-field-to-a-custom-form.md#add2" class="MCXref xref">Add a custom field to a custom form</a> </li> <li><a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-widget-or-edit-its-properties-in-a-custom-form.md" class="MCXref xref">Add or edit an asset widget in a custom form</a> </li> <li><a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/add-calculated-data-to-custom-form.md" class="MCXref xref">Add calculated data to a custom form</a> </li> <li><a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/position-fields-in-a-custom-form.md" class="MCXref xref">Position custom fields and widgets in a custom form</a> </li> <li><a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/display-or-skip-logic-custom-form.md" class="MCXref xref">Add display logic and skip logic to a custom form</a> </li> <li><a href="../../../administration-and-setup/customize-workfront/create-manage-custom-forms/preview-and-complete-a-custom-form.md" class="MCXref xref">Preview and complete a custom form</a> </li> </ul> </li> </ol> </div> --> ## Cómo pueden afectar varios tipos de objetos a los permisos de salto de sección {#how-multiple-object-types-can-affect-section-break-permissions-in-a-custom-form} El permiso Editar de forma limitada para saltos de sección de formulario personalizados solo está disponible para los tipos de objeto Proyecto, Tarea, Problema y Usuario. En un formulario personalizado con un salto de sección configurado con el permiso Editar de forma limitada, si agrega uno de los demás tipos de objetos al formulario (Portfolio, Programa, Documento, Empresa, Registro de facturación, Iteración, Gasto o Grupo), se le pedirá que cambie al permiso Editar, que es compatible tanto con ese tipo de objeto como con los tipos de objeto existentes en el formulario. >[!INFO] > >**Ejemplo:** En un formulario personalizado asociado al tipo de objeto Proyecto, se configura un salto de sección con el permiso Editar de forma limitada. > >Se agrega el tipo de objeto Portfolio al formulario, lo que significa que la opción Editar de forma limitada ya no está disponible para el salto de sección del formulario. > >Un mensaje en pantalla le pedirá que cambie al permiso Editar, que es la opción más similar a Edición limitada y compatible tanto con el tipo de objeto Proyecto como con el tipo de objeto Portfolio.
# ArduinoCraft A Minecraft Fabric mod that allows redstone signals to interact with an Arduino and vice versa. Please note that this is my first mod, and I'm still learning how to make mods, so there might be some bugs or issues. ## Features - An "Arduino Block" which takes redstone signals and converts it to `digitalWrite()` - Convert real life signals to redstone with ```digitalRead()``` ### TODO: - A GUI menu for closing/opening communication with Arduino ## How to use ### Upload a sketch You can upload [the template sketch](arduino/example.ino) to your Arduino device via Arduno IDE (or whatever you use ig). The schematic below is used for the template sketch: ![image](arduino/circuit.png) ### Start In Minecraft, place down the Arduino Block (from the redstone creative menu), plug in your Arduino and run the command `/arduino start <arduino port> <output/input> <baudrate>`. Use `input` if you want to convert redstone signals to Arduino, and `output` if you want to convert Arduino to redstone. ### Stop You may use the command `/arduino stop` to close the port. The mod will also stop when you quit the game ## How does it work? ArduinoCraft uses the [jSerialComm](https://fazecast.github.io/jSerialComm/) library to communicate with the Arduino through the serial port. When you use input, the mod will send a signal to the Arduino everytime the block receives redstone power to write high or low to the pin. When you use output, the mod will check the pin and send a matching redstone signal to the block. It is highly recommend that you look into the [template sketch](arduino/example.ino) to see how the communication works.
// // RecentTableViewCell.swift // quickChat // // Created by Shan-e-Ali Shah on 4/7/16. // Copyright © 2016 Shan-e-Ali Shah. All rights reserved. // import UIKit class RecentTableViewCell: UITableViewCell { //backendless instance let backendless = Backendless.sharedInstance() @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var lastMessageLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var counterLabel: UILabel! @IBOutlet weak var avatarImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func bindData(recent: NSDictionary) { //take square imageview and make it into a circle //get layer of avatar image view and set corner values avatarImageView.layer.cornerRadius = avatarImageView.frame.size.width/2 //divide frame size width avatarImageView.layer.masksToBounds = true //don't let image exceed bounds of imageview //set avatar image in imageview self.avatarImageView.image = UIImage(named: "avatarPlaceHolder") //use this to get the user from backendless let withUserID = (recent.objectForKey("withUserUserId") as? String)! //query all users in backendless with the ID for this user and download avatar let whereClause = "objectId = '\(withUserID)'"//create where clause with object ID for user let dataQuery = BackendlessDataQuery() //create database query dataQuery.whereClause = whereClause //set query clause let dataStore = backendless.persistenceService.of(BackendlessUser.ofClass())//use backendless persistence service to specify class //use the persistence service to search the dataquery to get the response, which is a backendless collection of users from backendless users table dataStore.find(dataQuery, response: { (users : BackendlessCollection!) -> Void in let withUser = users.data.first as! BackendlessUser //downcast returned object from backendless user class as backendless user //use withUser to get the user's avatar }) { (fault: Fault!) -> Void in print("error, couldn't get user avatar \(fault)") } nameLabel.text = recent["withUserUsername"] as? String lastMessageLabel.text = recent["lastMessage"] as? String counterLabel.text = "" if((recent["counter"] as? Int)! != 0) { counterLabel.text = "\(recent["counter"]!) New" } let date = dateFormatter().dateFromString((recent["date"] as? String)!) //get date let seconds = NSDate().timeIntervalSinceDate(date!) //count seconds dateLabel.text = timeElapsed(seconds) } //elapsed function for dateLabel(remove later) func timeElapsed(seconds: NSTimeInterval) -> String { let elapsed: String? if (seconds < 60) { elapsed = "Just Now" } else if(seconds < 60 * 60) { let minutes = Int(seconds/60) var minText = "min" if (minutes > 1) { minText = "mins" } elapsed = "\(minutes) \(minText)" } else if(seconds < 24 * 60 * 60) { let hours = Int(seconds / (60 * 60)) var hourText = "hour" if (hours > 1) { hourText = "hours" } elapsed = "\(hours) \(hourText)" } else { let days = Int(seconds / (24 * 60 * 60)) var dayText = "day" if(days > 1) { dayText = "days" } elapsed = "\(days) \(dayText)" } return elapsed! } }
import React from 'react' import styled from 'styled-components' import { Link } from 'react-router-dom'; const StyledButton = styled.button` background: none; border: none; cursor: pointer; color: white; transition: color 0.3s ease, border 0.3s ease, transform 0.3s ease; &:hover { color: #949494; transform: scale(0.97); } &:active { color: #fc234f; transform: scale(1.1); } `; const Button = ({ icon: Icon, onClick, onHover, to}) => { return ( <Link to={to}> <StyledButton onClick={onClick} onMouseOver={onHover}> {Icon && <Icon size={30} />} </StyledButton> </Link> ); }; export default Button
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.expression.spel; /** * Captures the possible configuration settings for a compiler that can be * used when evaluating expressions. *捕捉编译器的可能配置,以便在评估表达式的时候使用。 * @author Andy Clement * @since 4.1 */ public enum SpelCompilerMode { /** * The compiler is switched off; this is the default. * 编译器关闭模式,默认模式 */ OFF, /** * In immediate mode, expressions are compiled as soon as possible (usually after 1 interpreted run). * If a compiled expression fails it will throw an exception to the caller. * 立刻编译模式,尽可能能的编译表达式(通常在解析执行后)。如果编译编译表达式失败,则抛出异常给调用者 */ IMMEDIATE, /** * In mixed mode, expression evaluation silently switches between interpreted and compiled over time. * 混合模式,表达式评估器在解释和编译之间切换。 * After a number of runs the expression gets compiled. If it later fails (possibly due to inferred * type information changing) then that will be caught internally and the system switches back to * interpreted mode. It may subsequently compile it again later. * 在表达式编译之后。如果后缀失败(可能由于推测类型信息的改变),内部将会捕捉到失败信息,系统将会切换到解释模式。也许后续重新编译。 */ MIXED }
import React, {useState} from "react"; import {SubHeading, Description} from "../styled"; import useMobile from '../../assets/js/useMobile'; const FeatureCards = (props) => { const isMobile = useMobile(); return ( <div> { !isMobile && <div className="d-flex p-4" style={{ display: "flex", flexDirection: "column", justifyContent: "center", textAlign: "center", width: "25rem" }}> <img className="mb-3" src={props.imgUrl} style={{alignSelf: "center", width: "8rem", height: "8rem"}}/> <SubHeading style={{color: "#666666", fontSize: "1.8rem"}}> {props.heading} </SubHeading> <Description style={{color: "#666666", fontSize: "1rem", lineHeight: "1.6rem"}} > {props.description} </Description> </div> } { isMobile && <div className="d-flex p-1" style={{ display: "flex", flexDirection: "column", justifyContent: "center", textAlign: "center", width: "9rem" }}> <img className="mb-3" src={props.imgUrl} style={{alignSelf: "center", width: "4rem", height: "4rem"}}/> <SubHeading style={{color: "#666666", fontSize: "0.8rem"}}> {props.heading} </SubHeading> <Description style={{color: "#666666", fontSize: "0.6rem", lineHeight: "0.8rem"}} > {props.description} </Description> </div> } </div> ) }; export default FeatureCards;
<script setup lang="ts"> import { onMounted, reactive, ref, watch } from 'vue'; import { useRouter } from 'vue-router'; import { Collapse } from 'bootstrap'; import CartCounterIcon from './CartCounterIcon.vue'; const router = reactive(useRouter()); const collapseRef = ref<HTMLDivElement | string>(''); const collapse = ref<Collapse | null>(null); onMounted(() => { collapse.value = new Collapse(collapseRef.value, { toggle: false }); }); watch(router, () => { collapse.value?.hide(); }); </script> <template> <nav class="navbar container-fluid sticky-top navbar-expand-md bg-white"> <div class="container d-flex py-1 py-2-md position-relative"> <div id="navbar-logo" class="ps-2 ps-sm-0"> <RouterLink to="/" class="navbar-brand fs-2"> VL & CC </RouterLink> </div> <button class="navbar-toggler border-0 p-sm-0 position-relative" type="button" data-bs-toggle="collapse" data-bs-target="#navbar-router" aria-controls="navbar-router" aria-expanded="false" aria-label="Toggle navigation" > <FontAwesomeIcon icon="fas fa-bars" class="fs-1 text-primary" /> <CartCounterIcon id="bars-counter" class="start-75 d-block d-md-none" /> </button> <div id="navbar-router" ref="collapseRef" class="collapse navbar-collapse navbar-text justify-content-end" > <div class="collapseRef pt-2"> <ul class="navbar-nav"> <li class="nav-item mb-3"> <RouterLink class="d-block pe-0 pe-md-5 text-secondary hover-primary" to="/articles"> 最新消息 </RouterLink> </li> <li class="nav-item mb-3"> <RouterLink to="/products" class="pe-0 pe-md-5"> 所有產品 </RouterLink> </li> <li class="nav-item mb-3 position-relative"> <RouterLink to="/cart" class="pe-0 pe-md-5"> 購物車 <CartCounterIcon /> </RouterLink> </li> <li class="nav-item"> <RouterLink to="/admin/products" class="pe-0 pe-md-0"> 後台介面 </RouterLink> </li> </ul> </div> </div> </div> </nav> </template> <style lang="scss" scoped> @import '@/assets/scss/all.scss'; a { font-weight: bold; } .collapseRef { .active { color: $primary !important; } a { &:hover { color: $primary-heavy !important; } } } #bars-counter { width: 24px; height: 24px; font-size: 10px; top: 20% !important; @include media-breakpoint-up(sm) { left: 100% !important; } } </style>
# USING "TIDYTABLE" PACKAGE (A TIDY INTERFACE TO "DATA.TABLE") # https://markfairbanks.github.io/tidytable/index.html # TO IMPROVE SPEED OF EXECUTION combo_plus <- combo %>% left_join.(lkp_tretspef, by = "tfc") %>% relocate(treatment_function, .after = tfc) %>% relocate(tf_group, .after = treatment_function) %>% # GROUP: # group_by(nhs_no, tfc) %>% # NOW BECOMES A .by ARGUMENT PASSED TO mutate(): mutate.(count_actv = n.(), .by = c(nhs_no, tfc)) %>% mutate.(n_op = sum(pod == "op"), .by = c(nhs_no, tfc)) %>% mutate.(has_adm = ifelse.(sum(pod != "op") > 0, 1, 0), .by = c(nhs_no, tfc)) %>% identity() combo_plus <- combo_plus %>% ungroup %>% mutate.(lag_pod = lags.(pod), .by = c(nhs_no, tfc)) %>% mutate.(lead_pod = leads.(pod), .by = c(nhs_no, tfc)) %>% mutate.(lag_pod_2 = lags.(pod, 2), .by = c(nhs_no, tfc)) %>% mutate.(lead_pod_2 = leads.(pod, 2), .by = c(nhs_no, tfc)) %>% # THIS METHOD IS MUCH FASTER THAN USING DIFFTIME WITH LAG AND LEAD: # (NA inserted so that vector length compatible) mutate.(lag_days = c(NA, diff(as.numeric(date_actv))), .by = c(nhs_no, tfc)) %>% mutate.(lead_days = leads.(lag_days), .by = c(nhs_no, tfc)) # toc() combo_plus <- combo_plus %>% # SO VECTORS CAN BE RECYCLED (THIS IS ODD BECAUSE OF THE WAY diff() WORKS): # (KEEPING THIS OPERATION IN DPLYR) group_by(nhs_no, tfc) %>% mutate(lag_days_2 = ifelse( count_actv > 1, c(NA, NA, diff(as.numeric(date_actv), lag = 2)), NA )) %>% ungroup() %>% mutate.(lead_days_2 = leads.(lag_days_2, 2), .by = c(nhs_no, tfc))
import React, { useState } from "react"; import { useNavigate } from "react-router-dom"; import Container from '@mui/material/Container'; import Button from '@mui/material/Button'; import Typography from '@mui/material/Typography'; export default NewUser = ({ setToken }) => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const navigate = useNavigate(); async function createUser(credentials) { const url = "http://localhost:3000/users"; return fetch(url, { method: "POST", headers: { 'Content-Type': "application/json" }, body: JSON.stringify(credentials) }).then(data => data.json()) } const handleSubmit = async e => { e.preventDefault(); const token = await createUser({ email, password }); setToken(token.id); navigate(`/app/home`) } return ( <Container fixed={true} sx={{ border: "900px" }}> <form onSubmit={handleSubmit}> <label> <Typography variant="subtitle">Username: </Typography> <input onChange={e => setEmail(e.target.value)} type="text"></input> </label> <br /> <br /> <label> <Typography variant="subtitle">Password: </Typography> <input onChange={e => setPassword(e.target.value)} type="password"></input> </label> <br /> <br /> <Button variant="outlined" type="submit">Create Account</Button> </form> </Container> ) }
import { ArgsTable, Story, Canvas, Meta } from '@storybook/addon-docs'; import { Row, VerticalSpacer } from '@components'; import { mainColors } from '@primitives'; import { showToast, ToastContainer } from '.'; import { Toast } from './components/ToastPortal'; <Meta title="Components/Toasts" decorators={[ (Story) => ( <> <ToastContainer /> {Story()} </> ), ]} component={Toast} /> export const ToastTemplate = (args) => ( <button onClick={() => showToast(`${args.content}`, { ...args })}>Click for toast</button> ); export const toastArgTypes = { content: { description: 'Toast message', type: { required: true, }, }, type: { description: 'Type of toast - `success` | `error` | `warning`', }, id: { table: { disable: true, }, }, removeToast: { table: { disable: true, }, }, description: { description: 'Toast subtext', }, colorConfig: { description: 'Toast appearance (color and background)', defaultValue: { background: mainColors.red, color: '#F8F8F8', }, }, fullWidth: { description: 'Toast width', }, dismissOnClick: { description: 'Click to dismiss toast', }, autoCloseTime: { description: 'Auto close time in ms', }, icon: { description: 'Toast with icon source', }, }; # Toasts Toasts is used as a non blocking notification with short message for users to get a quick glance. ## Usage 1. Add `ToastContainer` anywhere in the DOM tree. 2. Call `showToast` method with message as first argument and object with toast configuration props as second argument. 3. You can pass the `type` as `success` | `error` | `warning` or can pass custom `colorConfig` to change the color of the toast. <br /> #### App.jsx ```jsx import { ToastContainer } from '@cred/neopop-web/lib/components'; import MainApp from './MainApp.jsx'; // Any component import ToastDemo from './ToastDemo.jsx'; const App = () => { return ( <div> {/* Mounting ToastContainer in DOM */} <ToastContainer /> <MainApp /> <ToastDemo /> </div> ); }; ``` #### ToastDemo.jsx ```jsx import { showToast } from '@cred/neopop-web/lib/components'; import { mainColors } from '@cred/neopop-web/lib/primitives'; const ToastDemo = () => { const showToastNotif = () => { showToast('Sample toast message', { type: 'success', autoCloseTime: 5000 }); }; return <button onClick={() => showToastNotif()}>Click for toast</button>; }; export default ToastDemo; ``` ## Variants ### Error Toast <Canvas> <Story name="Error Toast" args={{ content: 'Something went wrong! Please try again.' }} argTypes={toastArgTypes} > {ToastTemplate.bind({})} </Story> </Canvas> ### Warning Toast <Canvas> <Story name="Warning Toast" args={{ content: 'Your request is already in process.', type: 'warning', }} > {ToastTemplate.bind({})} </Story> </Canvas> ### Success Toast <Canvas> <Story name="Success Toast" args={{ content: 'Your credit score was refreshed successfully.', type: 'success', }} > {ToastTemplate.bind({})} </Story> </Canvas> ## Props `showToast(content: string, options: object)` function takes two arguments <div style={{overflowX: 'auto'}}> | prop | description | type | | ------------ | ------------------------------- | -------- | | `content*` | toast message | `string` | | `options` | configuration for toast options | `object` | </div> `options` <div style={{overflowX: 'auto'}}> | prop | description | type | | ---------------- | ---------------------------------------------------------------------------- | --------- | | `description` | toast subtext | `string` | | `type` | `success`, `warning`, or `error` - this also decides the color | `string` | | `colorConfig` | `{ background: string, color: string }` | `object` | | `textStyle` | used for passing the font styles for toast content (message) and description | `object` | | `fullWidth` | toast width with default true | `boolean` | | `dismissOnClick` | if true, it will dismiss on click | `boolean` | | `autoCloseTime` | auto close time in ms | `number` | | `icon` | toast with icon source | `string` | </div> **textStyle** <div style={{overflowX: 'auto'}}> | prop | description | type | | ------------- | ------------------------------------------ | --------------------------------- | | `heading` | font style to be used for heading text | `object - FontNameSpaceInterface` | | `description` | font style to be used for description text | `object - FontNameSpaceInterface` | </div> **FontNameSpaceInterface** <div style={{overflowX: 'auto'}}> | prop | description | type | | --------------- | ------------------ | ------------------------------------------ | | `fontType*` | typography variant | `heading`, `caps`, `body`, `serif-heading` | | `fontWeight*` | weight of the text | `800`, `700`, `600`, `500`, `400`, `300` | | `fontSize*` | size of the text | `string` | </div>
#!/usr/bin/python3 """This defines a module""" class Rectangle: """ This rectangle class """ def __init__(self, width=0, height=0): """ """ if type(width) is not int: raise TypeError("width must be an integer") if width < 0: raise ValueError("width must be >= 0") self.__width = width if type(height) is not int: raise TypeError("height must be an integer") if height < 0: raise ValueError("height must be >= 0") self.__height = height @property def width(self): """ gets the width of the rectangle """ return self.__width @width.setter def width(self, value): if type(value) is not int: raise TypeError("width must be an integer") if value < 0: raise ValueError("width must be >= 0") self.__width = value @property def height(self): """ gets the height of the rectangle """ return self.__height @height.setter def height(self, value): """ Sets the height of the rectangle """ if type(value) is not int: raise TypeError("height must be an integer") if value < 0: raise ValueError("height must be >= 0") self.__height = value
# npm Checker ## Feature "npm Checker" is an API that determines the safety of npm packages from multiple perspectives before installing them. ### Perspectives | Viewpoints | Thresholds | | --- | --- | | Is it an active package? | Updated within the past year | | Does it have a track record of being used? | The number of installations is 500 or more | | Has it passed multiple reviews? | 5 or more contributors | ### Request <table> <tr> <td>Endpoint</td> <td><code>/check-package/{Package Name}</code></td> </tr> <tr> <td>Method</td> <td><code>GET</code></td> </tr> </table> ### Response **When safety is high** Status code: `200` ```json { "can_use":true, "reason":"" } ``` **If there is no updating within one year** Status code: `200` ```json { "can_use":false, "reason":"That package hasn't been updated in over 1 year" } ``` **If the number of installations is less than 500** Status code: `200` ```json { "can_use":false, "reason":"The package has fewer than 500 installs in the last month" } ``` **If there are fewer than 5 contributors** Status code: `200` ```json { "can_use":false, "reason":"This package has few contributors" } ``` **If the package does not exist** Status code: `404` ```json { "message":"Package Not Found" } ``` **When not using GitHub for repository management** Status code: `500` ```json { "message":"Unsupported Repository Type" } ``` **Others** Status code: `500` ```json { "message":"Unexpected Error" } ``` ## Requirement - Node.js 19.9.0 ## Usage ### Server side ```bash $ npm install $ npm run start ``` ### Dev environment ```bash $ npm install $ npm run dev ``` ### Build only ```bash $ npm install $ npm run build ``` ## License "npm Checker" is under [MIT license](https://en.wikipedia.org/wiki/MIT_License).
package easylog import ( "context" "os" "time" "github.com/logerror/easylog/pkg/izap" "github.com/logerror/easylog/pkg/option" otelzap "github.com/logerror/easylog/pkg/otel" "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" ) var ( globalLogger Logger globalRawLogger *logger globalSugaredLogger SugaredLogger globalLoggerLevel zap.AtomicLevel globalOtelLogger izap.Logger globalOtelSugaredLogger izap.SugaredLogger ) type ( // Field is an alias of zap.Field. Aliasing this type dramatically // improves the navigability of this package's API documentation. Field = zap.Field ) type SugaredLogger interface { Named(name string) SugaredLogger With(args ...interface{}) SugaredLogger Debug(args ...interface{}) Info(args ...interface{}) Warn(args ...interface{}) Error(args ...interface{}) Panic(args ...interface{}) Fatal(args ...interface{}) Debugf(format string, args ...interface{}) Infof(format string, args ...interface{}) Warnf(format string, args ...interface{}) Errorf(format string, args ...interface{}) Panicf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Sync() } // Logger defines methods of writing log type Logger interface { Named(s string) Logger With(fields ...Field) Logger WithContext(ctx context.Context) izap.StdLogger Debug(msg string, fields ...Field) Info(msg string, fields ...Field) Warn(msg string, fields ...Field) Error(msg string, fields ...Field) Clone() Logger Level() string IsDebug() bool Sync() SugaredLogger() SugaredLogger CoreLogger() *zap.Logger } type logger struct { level string atomicLevel zap.AtomicLevel logger *zap.Logger sugaredLogger *zap.SugaredLogger otelLogger izap.Logger otelSugaredLogger izap.SugaredLogger } type sugaredLogger struct { sugaredLogger *zap.SugaredLogger } func InitLogger(options ...option.Option) Logger { return initLogger(options...) } func InitGlobalLogger(options ...option.Option) Logger { globalRawLogger = initLogger(options...) globalLogger = globalRawLogger globalSugaredLogger = globalLogger.SugaredLogger() globalLoggerLevel = globalRawLogger.atomicLevel globalOtelLogger = globalRawLogger.otelLogger globalOtelSugaredLogger = globalRawLogger.otelSugaredLogger zap.ReplaceGlobals(globalLogger.CoreLogger()) return globalRawLogger } func initLogger(options ...option.Option) *logger { l := &logger{} encoder := zapcore.EncoderConfig{ TimeKey: "time", LevelKey: "level", NameKey: "name", CallerKey: "caller", MessageKey: "msg", StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { encodeTimeLayout(t, "2006-01-02 15:04:05.000", enc) }, EncodeDuration: zapcore.StringDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, } // Apply additional options for _, o := range options { o.Apply() } consoleSyncer := zapcore.AddSync(os.Stdout) multiWriteSyncer := zapcore.NewMultiWriteSyncer(consoleSyncer) if option.LogFilePath != "" && option.LogFileSizeMB != 0 { lumberjackLogger := &lumberjack.Logger{ Filename: option.LogFilePath, MaxSize: option.LogFileSizeMB, // MaxSize in megabytes MaxBackups: option.MaxBackups, // Max number of old log files to retain MaxAge: option.MaxAge, // Max number of days to retain old log files Compress: option.Compress, // Whether to compress the old log files } fileSyncer := zapcore.AddSync(lumberjackLogger) if option.ConsoleRequired { multiWriteSyncer = zapcore.NewMultiWriteSyncer(consoleSyncer, fileSyncer) } else { multiWriteSyncer = zapcore.NewMultiWriteSyncer(fileSyncer) } } core := zapcore.NewCore( zapcore.NewJSONEncoder(encoder), multiWriteSyncer, ParseLevel(option.LogLevel), ) l.logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1), zap.AddStacktrace(zapcore.ErrorLevel)) l.sugaredLogger = l.logger.Sugar() l.otelLogger = otelzap.NewLogger(l.logger) l.otelSugaredLogger = otelzap.NewSugaredLogger(l.sugaredLogger) return l } func ParseLevel(level string) option.Level { lvl, ok := option.LevelMapping[level] if ok { return lvl } // default level: info return option.InfoLevel } func encodeTimeLayout(t time.Time, layout string, enc zapcore.PrimitiveArrayEncoder) { type appendTimeEncoder interface { AppendTimeLayout(time.Time, string) } if enc, ok := enc.(appendTimeEncoder); ok { enc.AppendTimeLayout(t, layout) return } enc.AppendString(t.Format(layout)) } func init() { globalRawLogger = initLogger() globalLogger = globalRawLogger globalSugaredLogger = globalLogger.SugaredLogger() globalLoggerLevel = globalRawLogger.atomicLevel globalOtelLogger = globalRawLogger.otelLogger globalOtelSugaredLogger = globalRawLogger.otelSugaredLogger //zap.ReplaceGlobals(globalLogger.CoreLogger()) }
<template> <!-- 自定义组件中使用v-mode指令 --> <input type="search" @input="changeInput" data-myValue=""> </template> <script> export default { name: 'CustomModel', // 当我们使用model的默认值的时候value作prop,input作event时,可以省略不写model。 model: { prop: 'myValue', // 默认是value event: 'myInput', // 默认是input }, props: { // 接收string和number类型的值, // 注意不能是写成字符串["String","Number"],因为此时它们是构造器,是全局变量 myValue: [String, Number], }, methods: { changeInput ($event) { // 向上派发myInput事件,这样model监听myInput才有意义:当输入字符时触发input事件, // 进而派发触发自定义的myInput事件,然后model监听myInput,就实现了数据绑定 this.$emit('myInput', $event.target.value) }, } } </script>
import argparse from generic_checker_plugin import GenericCheckerPlugin from ethpwn import * from myutils import * # # NOTE: # # This script implements the GenericChecker as described in the paper in Section 4.3 (Generic Checker). # To run the script like we did for our evaluation, an access to an blockchain index database is required # (i.e., we need to enumerate the transactions sent by a confused contract to a target). # However, because it is impractical to share such a database, we provide a simple test script that # demonstrates the technique behind the GenericChecker. # # This script takes as input: # 1 - a confused contract (i.e., a contract for which a controllable CALL has been identified), # 2 - a candidate contract target (i.e., a contract that has been called by the confused contract and that can # potentially hold a state for the confused contract. # 3 - a transaction hash we want to test. This transaction should contain an internal transaction in which the # confused contract calls the candidate contract target. # 4 - the function signature of the function that has been called by the confused contract in the candidate contract target. # (this function should trigger SSTOREs to be a good candidate) # # As an example, you can try: # python generic_checker.py --confused 0x11b815efb8f581194ae79006d24e0d814b7697f6 --target 0xdAC17F958D2ee523a2206206994597C13D831ec7 --tx 0x15bef4b45379ad3dfa676f206c1ce0d9d4a18164d82a0d1a71737652c9456212 --func 0xa9059cbb # def main(): arg_parser = argparse.ArgumentParser(description='generic_checker') arg_parser.add_argument('--confused', type=str, required=True) arg_parser.add_argument('--target', type=str, required=True) arg_parser.add_argument('--tx', type=str, required=True) arg_parser.add_argument('--func', type=str, required=True) args = arg_parser.parse_args() confused = normalize_contract_address(args.confused) target = normalize_contract_address(args.target) tx = args.tx func = args.func print(f'Running GenericChecker test...') print(f' >Confused contract: {confused}\n >Target contract: {target}\n >Tx: {tx}\n >Func: {func}') print(f'🧪 Test1: Collecting SSTOREs for {target} during {tx}.') a1 = get_evm_at_txn(tx) gcp = GenericCheckerPlugin( confused_contract=0x11b815efb8f581194ae79006d24e0d814b7697f6, candidate_target=0xdAC17F958D2ee523a2206206994597C13D831ec7, candidate_target_func=0xa9059cbb ) a1.register_plugin(gcp) a1.next_transaction() sstores_report_original = a1.plugins.jackal_generic_checker.sstores_report print(f' -> Observed {len(sstores_report_original)} SSTOREs') #for s in sstores_report_original: # print(s) print(f'🧪 Test2: Collecting SSTOREs for {target} during {tx}. (Changing CALLER)') a2 = get_evm_at_txn(tx) gcp = GenericCheckerPlugin( confused_contract=0x11b815efb8f581194ae79006d24e0d814b7697f6, candidate_target=0xdAC17F958D2ee523a2206206994597C13D831ec7, candidate_target_func=0xa9059cbb, overwrite_caller=True ) a2.register_plugin(gcp) a2.next_transaction() sstores_report_mod = a2.plugins.jackal_generic_checker.sstores_report print(f' -> Observed {len(sstores_report_mod)} SSTOREs') #for s in sstores_report_mod: # print(s) # Now, let's compare the reports, do we see any discrepancies in terms of # executed SSTOREs? If yes, it might be that the confused_contract is holding # some sort of "state" in the candidate_target sstores_pc_originals = [x.pc for x in sstores_report_original] sstores_pc_mods = [x.pc for x in sstores_report_mod] # if the number of SSTOREs is different, OR, we see SSTOREs in different PCs, we trigger a warning. if len(sstores_pc_originals) != len(sstores_pc_mods) or set(sstores_pc_originals) != set(sstores_pc_mods): print(f'>>>{bcolors.FAIL}Warning: SSTOREs are different!{bcolors.ENDC}<<<') # first, add None element to sstores_pc_mods if it has not the same length of sstores_pc_originals delta = len(sstores_pc_originals) - len(sstores_pc_mods) if delta > 0: sstores_pc_mods.extend([None]*delta) # now, let's zip the two lists and compare them # highlight the differences with colors print(f'{bcolors.FAIL}Original SSTORE(s){bcolors.ENDC} vs {bcolors.FAIL}Modified SSTORE(s){bcolors.ENDC}') for pc_original, pc_mod in zip(sstores_pc_originals, sstores_pc_mods): if pc_original != pc_mod: print(f"{bcolors.WARNING}pc: {pc_original} pc: {pc_mod}{bcolors.ENDC}") else: print(f"{bcolors.GREEN}pc: {pc_original} pc: {pc_mod}{bcolors.ENDC}") if __name__ == '__main__': main()
# 从 Hugo 迁移到 Gridsome > 原文:<https://dev.to/lauragift21/-migrating-to-gridsome-from-hugo-2o6e> 上周我在浏览我的推特时间表时,无意中发现了这条推文。在查看了 gridsome-starter-blog 之后,我决定做出改变。 > ![Gridsome profile image](img/6c7ffcfe23085ee68c20b0cc5b342e53.png)Gridsome@ gridsome![twitter logo](img/4c8a2313941dda016bf4d78d103264aa.png)第一位正式 gridsome 首发: > > ⚡️beautiful 和简单设计。 > ⚡️Markdown 为物。 > ⚡️Tags 支持。 > ⚡️Dark /灯光切换。 > ⚡️100,100,100,谷歌灯塔 100 分。 > ⚡️Uses 相同前场[@ thepracticaldev](https://twitter.com/ThePracticalDev)00:46am-01 2019 年 3 月[![Twitter reply action](img/44d8b042100e231770330321e5b63d65.png)](https://twitter.com/intent/tweet?in_reply_to=1101282439320797187)[![Twitter retweet action](img/93d9c70ccc54851d2e8e881b53c21dae.png)](https://twitter.com/intent/retweet?tweet_id=1101282439320797187)[![Twitter like action](img/2e93f7775eadefab8bcd34a4542cc5a7.png)](https://twitter.com/intent/like?tweet_id=1101282439320797187) ## 我为什么要做这个切换? 我对之前博客的设计很满意,我也喜欢用 Hugo。这篇文章不是要抨击 Hugo😄。我想要灵活性,因为我在以前的博客中得不到这一点,所以我决定做出改变。我目前正在使用官方的 Gridsome Blog Starter ,我只是调整了一些东西,添加了一些我需要的功能,这些功能是 Starter 中没有的。 在这篇文章中,我将重点介绍我是如何做出这一改变的,同时也将详细介绍我为支持我的个人博客而添加的功能。我们开始吧,好吗? ## 介绍 Gridsome [![Gridsome](img/ff0cd425b6cd2814b397cb971a136291.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--69E2AuMj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://d2mxuefqeaa7sj.cloudfront.net/s_3D517D01AFC7E74C96BBEC559A051E8481EFE4E7CA50AF0EC2D3A5EA7519BF92_1548180739910_Screen%2BShot%2B2019-01-22%2Bat%2B7.11.51%2BPM.png) Gridsome 是一个 Vue 驱动的静态站点生成器,用于构建超快的网站和应用程序。这是盖茨比的另一种选择。我最喜欢 Gridsome,因为它支持 GraphQL 作为数据层的单一来源,允许您连接到任何无头 CMS 或外部 API,如 Google sheets、Airtable、本地 markdown 文件等。 当我使用 Hugo 时,毫无压力,我能够在几乎不了解 go 编程语言的情况下找到代码库,因为 Hugo 是使用 Go 构建的。但是我发现,当我需要添加我正在使用的模板中没有的额外功能时,这有点棘手。所以对我来说真的没有那么灵活。我一直有一个语法突出的问题,当我最近试图解决这个问题时,它是一个灾难。所以在我搬家之前,我权衡了搬家的利弊。当我的读者访问我的博客时,他们还能认出我吗?不管怎样,我还是走了。 ## 内容迁移 将我的内容从 Hugo 转移到 Gridsome 并不困难,因为它们只是降价文件,在 Hugo 中,我的内容在`content/post`中,幸运的是 Gridsome 有相同的目录。我要做的唯一一件事就是格式化 frontmatter 以适应 Gridsome 的格式。我真正喜欢的一件事是我目前使用的 starter 采用了 [Dev.to](https://dev.to) frontmatter 格式,我是 Dev 的长期用户,所以这对我来说也很容易采用。 ## 定制启动器 这真的很有趣,因为 Gridsome 团队真的让这成为一个很好的开端。一些支持的功能已经包括标签,暗/亮切换,漂亮和简约的用户界面和降价支持。这些是我在安装和使用这个启动器时采取的步骤。 我使用这些命令创建了一个新的 Gridsome 项目: ``` <!-- install gridsome globally --> npm install --global @gridsome/cli <!-- Then clone the starter repo --> gridsome create gridsome-blog https://github.com/gridsome/gridsome-starter-blog.git <!-- navigate to the directory --> cd gridosme-blog <!-- run the app on your local server --> gridsome develop ``` Enter fullscreen mode Exit fullscreen mode 你有它!🎉我们刚刚创建了一个网格博客。 ## 集成附加功能 我不得不对这个博客做一些额外的修改,因为我需要的几个集成不可用。默认情况下,您会得到 gridsome/source-filesystem 和 gridsome/remark-prismjs。但是我需要增加额外的功能,比如 * 谷歌分析支持 * 评论的问题 * 时事通讯 * 关于我页面 * Twitter 上的分享功能 * RSS 支持 * Twitter 嵌入支持 我已经能添加一些了。我很幸运地得到谷歌分析插件已经可用,所以我只需要安装它。对于 Disqus,我安装了一个名为`vue-disqus`的包,并将我用于时事通讯的表单迁移到这个新博客上,只需要调整一些样式,使其适合这个新布局。这个博客仍然是一个正在进行中的工作,因为我添加了其他功能,我有悬而未决。总的来说,到目前为止,搬到 Gridsome 很棒! ## 正在部署 我使用 Netlify 托管以前的博客,并将其配置为使用自定义域。我最近买了 [giftegwuenu.dev](https://giftegwuenu.dev) ,只是让它重定向到 giftegwuenu.com。从之前的博客切换到这个博客真的很快,因为使用 Netlify,你已经有了一个分配给你创建的任何项目的域。所以我从我以前的博客中删除了自定义域,并将其添加到这个新博客中。它工作得非常完美。Netlify 是 Bae💚 [![netlify](img/57e85c6052c5baa9d7cf2eb9a37adaa1.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--u0zM2jbF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://res.cloudinary.com/lauragift/image/upload/v1551708884/Screen_Shot_2019-03-04_at_2.50.52_PM_h7seox.png) ## 结论 做出这一举动并不像我想象的那么令人生畏。我很高兴我能够做到这一点,现在我可以使用 Vue 这个框架了,与我使用 Hugo 时相比,我更熟悉这个框架,并且必须了解 go 以进行额外的实现更改。我现在将专注于创建内容,不要担心我会很快切换。 如果你有关于 JAMStack、Gridsome 或者为什么我换了的问题,你可以在 twitter 上联系我
<?php /** * Abstract class for builders compatibility. * * @package Neve_Pro\Modules\Custom_Layouts\Admin\Builders */ namespace Neve_Pro\Modules\Custom_Layouts\Admin\Builders; use Neve_Pro\Traits\Core; use Neve_Pro\Traits\Conditional_Display; /** * Class Abstract_Builders * * @package Neve_Pro\Modules\Custom_Layouts\Admin\Builders */ abstract class Abstract_Builders { use Core; use Conditional_Display; /** * Id of the current builder * * @var string */ protected $builder_id; /** * Check if class should load or not. * * @return bool */ abstract function should_load(); /** * Get builder id. * * @return string */ abstract function get_builder_id(); /** * Add actions to hooks. */ public function register_hooks() { add_action( 'wp_enqueue_scripts', array( $this, 'add_styles' ), 9 ); add_filter( 'neve_custom_layout_magic_tags', array( $this, 'replace_magic_tags' ), 10, 2 ); } /** * Replace magic tags from post content. * * @param string $post_content Current post content. * @param int $post_id Post id. * @return string */ public function replace_magic_tags( $post_content, $post_id ) { $condition_groups = json_decode( get_post_meta( $post_id, 'custom-layout-conditional-logic', true ), true ); if ( empty( $condition_groups ) ) { return $post_content; } $archive_taxonomy = array( 'category', 'product_cat', 'post_tag', 'product_tag' ); foreach ( $archive_taxonomy as $type ) { if ( $this->layout_has_condition( 'archive_taxonomy', $type, $condition_groups[0] ) ) { $category = get_queried_object(); $title = $category->name; $description = $category->description; $post_content = str_replace( '{title}', $title, $post_content ); $post_content = str_replace( '{description}', $description, $post_content ); } } if ( $this->layout_has_condition( 'archive_type', 'author', $condition_groups[0] ) ) { $author_id = get_the_author_meta( 'ID' ); $author_name = get_the_author_meta( 'display_name' ); $author_decription = get_the_author_meta( 'description' ); $author_avatar = get_avatar( $author_id, 32 ); $post_content = str_replace( '{author}', $author_name, $post_content ); $post_content = str_replace( '{author_description}', $author_decription, $post_content ); $post_content = str_replace( '{author_avatar}', $author_avatar, $post_content ); } if ( $this->layout_has_condition( 'archive_type', 'date', $condition_groups[0] ) ) { $date = get_the_archive_title(); $post_content = str_replace( '{date}', $date, $post_content ); } return $post_content; } /** * Check if current custom layout has a specific condition. * * @param string $root Page category. * @param string $end Page type. * @param array $condition_groups List of conditions. * * @return bool */ private function layout_has_condition( $root, $end, $condition_groups ) { foreach ( $condition_groups as $index => $conditions ) { if ( $conditions['root'] === $root && $conditions['end'] === $end && $conditions['condition'] === '===' ) { return true; } } return false; } /** * Get the builder that you used to edit a post. * * @param int $post_id Post id. * * @return string */ public static function get_post_builder( $post_id ) { if ( get_post_meta( $post_id, 'neve_editor_mode', true ) === '1' ) { return 'custom'; } if ( class_exists( '\Elementor\Plugin', false ) && \Elementor\Plugin::$instance->db->is_built_with_elementor( $post_id ) ) { return 'elementor'; } if ( class_exists( 'FLBuilderModel', false ) && get_post_meta( $post_id, '_fl_builder_enabled', true ) ) { return 'beaver'; } if ( class_exists( 'Brizy_Editor_Post', false ) ) { try { $post = \Brizy_Editor_Post::get( $post_id ); if ( $post->uses_editor() ) { return 'brizy'; } } catch ( \Exception $exception ) { // The post type is not supported by Brizy hence Brizy should not be used render the post. } } return 'default'; } /** * Abstract function that needs to be implemented in Builders classes. * It loads the markup based on current hook. * * @param int $id Layout id. * * @return mixed */ abstract function render( $id ); /** * Function that enqueues styles if needed. */ abstract function add_styles(); }
<div class="container"> <div class="row"> <div class="col-md-6"> <div class="card"> <div class="text-center"> <h1>Login</h1> <h6>Please enter email & password</h6> </div> <form [formGroup]="loginForm" (ngSubmit)="login()"> <div class="form-group"> <label for="exampleInputEmail1" class="form-label">Email</label> <input formControlName="email" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" required> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> <br> <span class="text-danger" *ngIf="loginForm.controls['email'].dirty && loginForm.hasError('required','email')">*Email ID is required</span> <!-- <span class="text-danger" *ngIf="loginformcontrols.email.touched && loginformcontrols.email.error?.email ">Enter a valid email address</span> --> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input formControlName="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" required> <span class="text-danger" *ngIf="loginForm.controls['password'].dirty && loginForm.hasError('required','password')">*Password is required</span> </div> <button type="submit" [disabled]="!loginForm.valid" class="btn btn-primary mt-3">Login</button> </form> <a routerLink="/signup" href="#" class="login">New user? Click to signup!!</a> </div> </div> </div> </div>
import { randomUUID } from 'crypto' import dayjs from 'dayjs' import { Day } from '../../app/entities/day' import { DayRepository } from '../../app/repositories/day-repository' export class InMemoryDayRepository implements DayRepository { days: Day[] = [] async createByDate(date: Date): Promise<Day> { const parsedDate = dayjs(date).startOf('day').toDate() const id = randomUUID() this.days.push(new Day({ id, date: parsedDate, habitIds: [] })) return this.days.find((day) => day.id === id) as Day } async addHabitToDay(habitId: string, dayId: string): Promise<void> { const dayIndex = this.days.findIndex((day) => day.id === dayId) this.days[dayIndex].habitIds.push(habitId) } async deleteHabitFromDay(habitId: string, dayId: string): Promise<void> { const dayIndex = this.days.findIndex((day) => day.id === dayId) const habitIdsIndex = this.days[dayIndex].habitIds.indexOf(habitId) this.days[dayIndex].habitIds.splice(habitIdsIndex, 1) } async getDayHabit(habitId: string, dayId: string): Promise<Day | undefined> { return this.days.find( (day) => day.id === dayId && day.habitIds.some((id) => id === habitId), ) } async getDayByDate(date: Date): Promise<Day | undefined> { const parsedDate = dayjs(date).startOf('day').toDate() return this.days.find( (day) => day.date.toString() === parsedDate.toString(), ) } }
from django.contrib.auth.hashers import make_password from rest_framework import serializers from users.models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) class Meta: model = CustomUser fields = ['id', 'email', 'first_name', 'last_name', 'password', 'confirm_password'] extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['confirm_password']: raise serializers.ValidationError("Passwords do not match") # Normalize email to lowercase attrs['email'] = attrs['email'].lower() # Check if email already exists if CustomUser.objects.filter(email=attrs['email']).exists(): raise serializers.ValidationError("Email address already exists") return attrs def create(self, validated_data): validated_data.pop('confirm_password') # Remove confirm_password from validated_data validated_data['password'] = make_password(validated_data.get('password')) return super().create(validated_data)
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:paitentapp/screens/select_time_slot/view/select_time_slot_screen.dart'; import 'package:table_calendar/table_calendar.dart'; import '../../constants/color/app_colors.dart'; import '../../constants/dimensions/app_dimensions.dart'; import '../../constants/screen_size/app_screen_size.dart'; import '../../widgets/app_button/back_button.dart'; import '../../widgets/app_button/submit_button.dart'; import '../../widgets/app_text/app_text.dart'; class SelectDateScreen extends StatelessWidget { const SelectDateScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( // resizeToAvoidBottomInset: false, backgroundColor: AppColor.screenBgColor, bottomNavigationBar: Padding( padding: EdgeInsets.only(bottom: ScreenSize.height(context) * 0.05), child: SizedBox( height: 55, child: Padding( padding: EdgeInsets.symmetric( horizontal: AppDimension().subMitBtnPadding), child: SubmitButton( onTap: () { Get.to( SelectTimeSlotScreen(), transition: Transition.fadeIn, curve: Curves.easeOut, duration: const Duration(milliseconds: 400), ); }, text: "Next", textColor: AppColor.submitBtnTextWhite, borderColor: AppColor.primaryBtnBorderColor), ), ), ), body: SafeArea( child: SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric( horizontal: AppDimension().screenContaintPadding), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 10.h, ), AppBackButton( onTap: () { Get.back(); }, ), const SizedBox( height: 30, ), const MainTittleText( tittle: 'Select Date', maxTextlines: 2, ), const SizedBox( height: 30, ), BodySubTittleText( tittle: 'Please select the date of the appointment.', maxTextlines: 5, ), const SizedBox( height: 30, ), //! Calender Padding( padding: const EdgeInsets.all(10), child: Card( shadowColor: const Color.fromRGBO(0, 0, 0, 1).withOpacity(0.4), elevation: 05, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), child: TableCalendar( firstDay: DateTime.utc(2010, 10, 16), lastDay: DateTime.utc(2030, 3, 14), focusedDay: DateTime.now(), daysOfWeekStyle: DaysOfWeekStyle( weekdayStyle: GoogleFonts.urbanist( fontSize: 12.sp, fontWeight: FontWeight.w500, color: AppColor.weekDaysColor, ), weekendStyle: GoogleFonts.urbanist( fontSize: 12.sp, fontWeight: FontWeight.w500, color: AppColor.weekDaysColor, ), ), headerStyle: HeaderStyle( titleCentered: true, titleTextStyle: GoogleFonts.urbanist( fontSize: 15.sp, fontWeight: FontWeight.bold, color: AppColor.calenderTextColor, ), decoration: BoxDecoration( // color: AppColor.primaryColor, borderRadius: BorderRadius.circular(8.0)), formatButtonTextStyle: TextStyle( color: AppColor.primaryColor, fontSize: 16.0), formatButtonDecoration: BoxDecoration( color: AppColor.primaryColor, borderRadius: const BorderRadius.all( Radius.circular(5.0), ), ), leftChevronIcon: const Icon( Icons.chevron_left, color: AppColor.leftChevronIconColor, size: 16, ), rightChevronIcon: const Icon( Icons.chevron_right, color: AppColor.righttChevronIconColor, size: 16, ), ), headerVisible: true, availableCalendarFormats: const { CalendarFormat.month: 'Month' }, calendarStyle: CalendarStyle( defaultTextStyle: GoogleFonts.urbanist( fontSize: 15.sp, fontWeight: FontWeight.bold, color: AppColor.calenderTextColor, ), weekendTextStyle: GoogleFonts.urbanist( fontSize: 15.sp, fontWeight: FontWeight.bold, color: AppColor.calenderTextColor, ), todayDecoration: BoxDecoration( color: AppColor.primaryColor, shape: BoxShape.circle, ), selectedDecoration: const BoxDecoration( color: AppColor.calenderTextColor, shape: BoxShape.circle, ), ), ), ), ) ], ), ), ), ), ); } }
# Excel File Handling in ASP.NET MVC This ASP.NET MVC project demonstrates how to upload, extract, and process data from Excel files, creating tables in a SQL Server database for each worksheet in the Excel file. ## Features - **Excel File Upload:** Users can upload Excel files with an unknown structure. - **Dynamic Table Creation:** The application dynamically creates tables in the database based on the Excel file structure. - **Data Extraction:** Data is extracted from the Excel file and inserted into the corresponding database table. - **Multiple Worksheets Support:** If an Excel file contains multiple worksheets, tables are created for each worksheet with a user-specified table name prefix. ## Getting Started ### Prerequisites - Visual Studio (or any preferred IDE for ASP.NET MVC development) - SQL Server (Express or higher) ### Setup 1. Clone the repository to your local machine. 2. Open the project in Visual Studio. 3. Update the connection string in the `Web.config` file to point to your SQL Server instance. ```xml <connectionStrings> <add name="ExcelDBConnectionString" connectionString="Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings> ``` 4. Build and run the project. ## Usage 1. Open the application in your web browser. 2. Navigate to "/Import/Index". 3. Upload an Excel file with one or more worksheets. 4. Enter a table name. 5. Click the "Import" button. 6. Check the status messages for success or error information. ## Notes - Ensure that the connection string in `Web.config` is correctly configured for your SQL Server instance. - The application creates a table for each worksheet in the Excel file, using the provided table name as a prefix. ## Libraries Used **EPPlus**: Used for reading data from Excel files. It is a widely-used library for Excel manipulation in .NET applications.
#' Data frame of quarterly variables #' #' @description Computes punctual risk coordinates in the Lexis diagram and quarterly biometric #' variables of a population. #' #' @author Jose M. Pavia \email{pavia@@uv.es} #' @author Josep Lledo \email{josep.lledo@@uv.es} #' @references Pavia, JM and Lledo, J (2022). Estimation of the Combined Effects of Ageing and Seasonality on Mortality Risk. An application to Spain. *Journal of the Royal Statistical Society, Series A (Statistics in Society)*, 185(2), 471-497. \doi{10.1111/rssa.12769} #' #' @param date.birth A character vector with the dates of birth in format either "yyyy-mm-dd" or "yyyy-mm-dd hour:min:secs" (for instance, "2016-01-20 12:00:00") of a population. #' If "hour:min:secs" is omitted the function imputes either "12:00:00", if `random.b = FALSE`, or #' a random hour by default. #' @param date.event A character vector with the dates of events in format either "yyyy-mm-dd" or "yyyy-mm-dd hour:min:secs" (for instance, "2016-01-20 12:00:00") of a population. #' If "hour:min:secs" is omitted the function imputes either "12:00:00", if `random.e = FALSE`, or #' a random hour, by default. This vector must have either length 1, when the aim is to compute #' the exact age or the (1x1-Lexis) age coordinate of all the members of the population in the same temporal point or the same #' length as `date.birth` when the aim is to compute for each member #' of the population the exact age or the (1x1-Lexis) age coordinate in the moment of the event (e.g., death). #' @param random.b A `TRUE/FALSE` argument indicating whether the exact moment ("hour:min:secs") when the birth occurs within the day is randomly selected. If TRUE, this overwrites "hour:min:secs" in `date.birth` even if those have been declared. By default, TRUE. #' @param random.e A `TRUE/FALSE` argument indicating whether the exact moment ("hour:min:secs") when the event occurs within the day is randomly selected. If TRUE, this overwrites "hour:min:secs" in `date.event` even if those have been declared. By default, TRUE. #' @param constant.age.year A `TRUE/FALSE` argument indicating whether the length of the year should be constant, 365.25 days, or variable, #' depending on the time lived for the person in each year since her/his dates of birth and event. By default, FALSE. #' The advantage of using a non-constant (person-dependent) length of year is congruence when #' estimating time exposed at risk: in each year the time exposed along the time and age axes will coincide. #' #' @return #' A data.frame with the following components: #' \item{coord.age}{ Time elapsed, measure in years, between the last birthday and the date when the event happens.} #' \item{coord.time}{ Time coordinate: time elapsed, measure in years, between the begining of the year and the date when the event happens.} #' \item{age.last.birthday}{ The integer age at last birthday.} #' \item{exact.age.at.event}{ Time elapsed, measure in years, between the dates of birth and event.} #' \item{quarter.age}{ Age quarter when the event happens.} #' \item{quarter.calendar}{ Calendar (time, season) quarter to which the time exposed at risk corresponds.} #' \item{year}{ Year when the event happens.} #' @export #' #' @note #' In the age axis, the length of the years are assumed either constant 365.25 days (`constant.age.year = TRUE`) or #' variable (`constant.age.year = FALSE`), depending on the person. In the time axis, the length of the year is either #' 365 in non-leap years and 366 in leap years. The advantage of using a non-constant (person-dependent) length of year #' in the age axis is that in each year the lengths of the years when computing `coord.age` and `coord.time` #' in both axis are equal. #' #' @examples #' dates.b <- c("1920-05-13", "1999-04-12", "2019-01-01") #' dates.e <- c("2002-03-23", "2009-04-12", "2019-01-01") #' quarterly_variables(dates.b, dates.e) # quarterly_variables <- function(date.birth, date.event, random.b = TRUE, random.e = TRUE, constant.age.year = FALSE){ # if (length(date.birth) != length(date.event) & length(date.event) != 1L) # stop("The lengths of date.birth and date.event differ.") # date.birth <- as.character(date.birth) # date.event <- as.character(date.event) # if (random.e){ # n <- length(date.event) # hh <- formatC(sample(0L:23L, n, replace = T), width = 2L, format = "d", flag = "0") # mm <- formatC(sample(0L:59L, n, replace = T), width = 2L, format = "d", flag = "0") # ss <- formatC(sample(0L:59L, n, replace = T), width = 2L, format = "d", flag = "0") # date.event <- paste(substr(date.event, 1L, 10L), paste(hh, mm, ss, sep = ":")) # } else { # if (nchar(date.event[1L]) == 10L) # date.event <- paste(substr(date.event, 1L, 10L), "12:00:00") # } # if (random.b){ # n <- length(date.birth) # hh <- formatC(sample(0L:23L, n, replace = T), width = 2L, format = "d", flag = "0") # mm <- formatC(sample(0L:59L, n, replace = T), width = 2L, format = "d", flag = "0") # ss <- formatC(sample(0L:59L, n, replace = T), width = 2L, format = "d", flag = "0") # date.birth <- paste(substr(date.birth, 1L, 10L), paste(hh, mm, ss, sep = ":")) # } else { # if (nchar(date.birth[1L]) == 10L) # date.birth <- paste(substr(date.birth, 1L, 10L), "12:00:00") # } # date.birth <- as.POSIXct(date.birth, tz = "GMT", tryFormats = "%Y-%m-%d %H:%M:%OS") # date.event <- as.POSIXct(date.event, tz = "GMT", tryFormats = "%Y-%m-%d %H:%M:%OS") # if (random.e){ # same <- which(substr(date.birth, 1L, 10L) == substr(date.event, 1L, 10L)) # birth <- date.birth[same] # date.event[same] <- simula_post(fijo = birth) # } # if (!random.e & random.b){ # same <- which(substr(date.birth, 1L, 10L) == substr(date.event, 1L, 10L)) # event <- date.event[same] # date.birth[same] <- simula_ant(fijo = event) # } output <- as.data.frame(matrix(NA, nrow = length(date.birth), ncol = 7L)) names(output) <- c("coord.age", "coord.time", "age.last.birthday", "exact.age.at.event", "quarter.age", "quarter.calendar", "year") output$exact.age.at.event <- exact_age(date.birth = date.birth, date.event = date.event, random.b = FALSE, random.e = FALSE, constant.age.year = constant.age.year) output$coord.time <- coord_time(date.event = date.event, random.e = FALSE) output$age.last.birthday <- floor(output$exact.age.at.event) output$coord.age <- output$exact.age.at.event - output$age.last.birthday output$quarter.age <- floor(4L*output$coord.age) + 1L output$quarter.calendar <- floor(4L*output$coord.time) + 1L output$year <- as.numeric(substr(date.event, 1L, 4L)) # class(output) <- c("quarterly_variables") return(output) }
import React, { useState } from "react"; import { Tab, Tabs } from "react-bootstrap"; import { BiMessageDetail } from "react-icons/bi"; import { FaHome } from "react-icons/fa"; import { FiHelpCircle } from "react-icons/fi"; import ChatView from "../Chat"; // import "../../style/index.scss"; import HomeTab from "../HomeTab"; import MessageTab from "../MessageTab"; const ChatBox = () => { const [isChatOpen, setIsChatOpen] = useState(false); return ( <div className="mainBox"> {isChatOpen ? ( <ChatView setIsChatOpen={setIsChatOpen} /> ) : ( <div className="mainBox_tabs"> <Tabs defaultActiveKey="home" className="mainBox_tabList"> <Tab eventKey="home" title={ <> <FaHome /> <span>Home</span> </> } > <HomeTab setIsChatOpen={setIsChatOpen} /> </Tab> <Tab eventKey="message" title={ <> <BiMessageDetail /> <span>Messages</span> </> } > <MessageTab setIsChatOpen={setIsChatOpen} /> </Tab> <Tab eventKey="help" title={ <> <FiHelpCircle /> <span>Help</span> </> } > <div className="dummy_text"> <h4>Coming soon</h4> </div> </Tab> </Tabs> </div> )} </div> ); }; export default ChatBox;
// // DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation.m // fs-dataman // // Created by Christopher Miller on 3/12/12. // Copyright (c) 2012 Christopher Miller. All rights reserved. // #import "DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation.h" #import "DMNFSPersonNode.h" #import "Console.h" #import "NDService.h" #import "NDService+FamilyTree.h" #import "FSURLOperation.h" #import "NSData+StringValue.h" #import "ISO8601DateFormatter.h" enum DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation_State { kUnready=0, kReady=1<<1, kCancelled=1<<2, kExecuting=1<<3, kFinished=1<<4 }; @interface DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation () - (void)_start_returnFromReadRequest:(id)response; - (void)_start_returnFromDeleteRequest:(id)response; - (void)_start_handleFailure:(NSHTTPURLResponse *)resp data:(NSData *)payload error:(NSError *)error; @end @implementation DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation { enum DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation_State _state; } @synthesize personToKill=_personToKill; @synthesize service=_service; @synthesize soft=_soft; + (id)individualAssertionsDeleteWrapperOperationWithPersonNode:(DMNFSPersonNode *)node service:(NDService *)service soft:(BOOL)soft { DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation * wrapperOperation = [[DMNFSPersonNode_IndividualAssertionsDeleteWrapperOperation alloc] initWithPersonNode:node service:service soft:soft]; return wrapperOperation; } - (id)initWithPersonNode:(DMNFSPersonNode *)node service:(NDService *)service soft:(BOOL)soft { self = [super init]; if (self) { _personToKill = node; _service = service; _soft = soft; // set up to recieve notifications [self.personToKill addObserver:self forKeyPath:@"writeState" options:NSKeyValueObservingOptionNew context:NULL]; } return self; } #pragma mark NSOperation - (void)setIsReady:(__unused BOOL)isReady { [self willChangeValueForKey:@"isReady"]; if ([self isReady]) _state = kReady; else _state = kUnready; [self didChangeValueForKey:@"isReady"]; } - (BOOL)isReady { return self.personToKill.writeState==kWriteState_Idle; } - (BOOL)isConcurrent { return YES; } - (void)setIsExecuting:(BOOL)isExecuting { [self willChangeValueForKey:@"isExecuting"]; if (isExecuting) _state = kExecuting; else _state ^= kExecuting; [self didChangeValueForKey:@"isExecuting"]; } - (BOOL)isExecuting { return _state & kExecuting; } - (void)setIsFinished:(BOOL)isFinished { if (isFinished) [self setIsExecuting:NO]; [self willChangeValueForKey:@"isFinished"]; if (isFinished) _state |= kFinished; else _state ^= kFinished; [self didChangeValueForKey:@"isFinished"]; if (isFinished) [self.personToKill removeObserver:self forKeyPath:@"writeState"]; } - (BOOL)isFinished { return _state & kFinished; } - (void)setIsCancelled:(BOOL)isCancelled { [self willChangeValueForKey:@"isCancelled"]; if (isCancelled) _state |= kCancelled; else _state ^= kCancelled; if (isCancelled) [self setIsFinished:YES]; [self didChangeValueForKey:@"isCancelled"]; } - (BOOL)isCancelled { return _state & kCancelled; } - (void)start { if ([self isCancelled]||[self isFinished]) return; // 1. Lock me self.personToKill.writeState = kWriteState_Active; [self setIsExecuting:YES]; // 2. Read me from the API FSURLOperation * oper = [self.service familyTreeOperationReadPersons:self.personToKill.pid withParameters:NDFamilyTreeAllPersonReadValues() onSuccess:^(NSHTTPURLResponse *resp, id response, NSData *payload) { dm_PrintLn(@"%@ Deletion Progress: Read all assertions", self.personToKill.pid); [self _start_returnFromReadRequest:response]; } onFailure:^(NSHTTPURLResponse *resp, NSData *payload, NSError *error) { [self _start_handleFailure:resp data:payload error:error]; }]; [self.service.operationQueue addOperation:oper]; } - (void)_start_returnFromReadRequest:(id)response { NSDictionary * person = [[response valueForKey:@"persons"] firstObject]; NSMutableDictionary * deleteAllAssertions = [NSMutableDictionary dictionaryWithCapacity:[NDFamilyTreeAllAssertionTypes() count]]; for (NSString * type in NDFamilyTreeAllAssertionTypes()) { NSArray * originalAssertions = [person valueForKeyPath:[NSString stringWithFormat:@"assertions.%@", type]]; [deleteAllAssertions setObject:[NSMutableArray arrayWithCapacity:[originalAssertions count]] forKey:type]; for (NSDictionary * assertion in originalAssertions) { NSDictionary * deleteAssertion = [NSDictionary dictionaryWithObjectsAndKeys: @"Delete", @"action", [NSDictionary dictionaryWithObject:[assertion valueForKeyPath:@"value.id"] forKey:@"id"], @"value", nil]; [[deleteAllAssertions objectForKey:type] addObject:deleteAssertion]; } } if (self.soft) { self.personToKill.tearDownState |= kTearDownState_IndividualAssertions; self.personToKill.writeState = kWriteState_Idle; dm_PrintLn(@"%@ Deletion Progress: Would have dispatched request to remove\n" @" assertions, but running in SOFT mode", self.personToKill.pid); [self setIsFinished:YES]; [[NSNotificationCenter defaultCenter] postNotificationName:kIndividualDeletedNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:self.personToKill.pid, @"pid", [GetDefaultFormatter() stringFromDate:[NSDate date]], @"when", [NSNumber numberWithBool:YES], @"soft", nil]]; } else { // chuck if off to the queue FSURLOperation * oper = [self.service familytreeOperationPersonUpdate:self.personToKill.pid assertions:deleteAllAssertions onSuccess:^(NSHTTPURLResponse *resp, id response, NSData *payload) { dm_PrintLn(@"%@ Deletion Progress: Deleted all assertions", self.personToKill.pid); [self _start_returnFromDeleteRequest:response]; } onFailure:^(NSHTTPURLResponse *resp, NSData *payload, NSError *error) { [self _start_handleFailure:resp data:payload error:error]; } withTargetThread:nil]; [self.service.operationQueue addOperation:oper]; } } - (void)_start_returnFromDeleteRequest:(id)response { self.personToKill.tearDownState |= kTearDownState_IndividualAssertions; self.personToKill.writeState = kWriteState_Idle; [self setIsFinished:YES]; [[NSNotificationCenter defaultCenter] postNotificationName:kIndividualDeletedNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:self.personToKill.pid, @"pid", [GetDefaultFormatter() stringFromDate:[NSDate date]], @"when", nil]]; } - (void)_start_handleFailure:(NSHTTPURLResponse *)resp data:(NSData *)payload error:(NSError *)error { if (resp.statusCode == 503) { dm_PrintLn(@"%@ has been throttled; waiting for 20 seconds, then trying again.", self.personToKill.pid); [NSThread sleepForTimeInterval:20.0f]; [self start]; } else { dm_PrintLn(@"%@ Failed to perform deletion!", self.personToKill.pid); dm_PrintURLOperationResponse(resp, payload, error); self.personToKill.writeState = kWriteState_Idle; [self setIsFinished:YES]; [[NSNotificationCenter defaultCenter] postNotificationName:kIndividualDeletionFailureNofication object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys: self.personToKill.pid, @"pid", [GetDefaultFormatter() stringFromDate:[NSDate date]], @"when", [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInteger:resp.statusCode ], @"statusCode", resp.allHeaderFields, @"allHeaderFields", nil], @"httpResponse", [payload fs_stringValue], @"payload", [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInteger:[error code]], @"errorCode", [error domain], @"errorDomain", [error userInfo], @"userInfo", nil], @"error", nil]]; } } #pragma mark NSObject - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (object==self.personToKill) [self setIsReady:[self isReady]]; else dm_PrintLn(@"Extraneous notification recieved."); } - (NSString *)description { return [NSString stringWithFormat:@"<%@:%p PID:%@ isReady:%@ isExecuting:%@ isFinished:%@ isCancelled:%@>", NSStringFromClass([self class]), (void *)self, self.personToKill.pid, [self isReady]?@"YES":@"NO", [self isExecuting]?@"YES":@"NO", [self isFinished]?@"YES":@"NO", [self isCancelled]?@"YES":@"NO"]; } - (void)dealloc { if (![self isFinished]) [self.personToKill removeObserver:self forKeyPath:@"writeState"]; } @end
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Migration_Install_items extends Migration { /** * The name of the database table * * @var String */ private $table_name = 'items'; /** * The table's fields * * @var Array */ private $fields = array( 'id' => array( 'type' => 'INT', 'constraint' => 11, 'auto_increment' => TRUE, ), 'name' => array( 'type' => 'VARCHAR', 'constraint' => 255, 'null' => FALSE, ), 'description' => array( 'type' => 'TEXT', 'null' => FALSE, ), 'specifications' => array( 'type' => 'TEXT', 'null' => FALSE, ), 'quantity' => array( 'type' => 'VARCHAR', 'constraint' => 255, 'null' => FALSE, ), 'status' => array( 'type' => 'ENUM', 'constraint' => '\'Active\',\'Inactive\'', 'null' => FALSE, ), 'created_on' => array( 'type' => 'datetime', 'default' => '0000-00-00 00:00:00', ), 'modified_on' => array( 'type' => 'datetime', 'default' => '0000-00-00 00:00:00', ), ); /** * Install this migration * * @return void */ public function up() { $this->dbforge->add_field($this->fields); $this->dbforge->add_key('id', true); $this->dbforge->create_table($this->table_name); } //-------------------------------------------------------------------- /** * Uninstall this migration * * @return void */ public function down() { $this->dbforge->drop_table($this->table_name); } //-------------------------------------------------------------------- }
<?php namespace App\Repository; use App\Entity\Cancion; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @extends ServiceEntityRepository<Cancion> * * @method Cancion|null find($id, $lockMode = null, $lockVersion = null) * @method Cancion|null findOneBy(array $criteria, array $orderBy = null) * @method Cancion[] findAll() * @method Cancion[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class CancionRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Cancion::class); } public function buscarCanciones($termino) { return $this->createQueryBuilder('c') ->where('c.titulo LIKE :termino') ->orWhere('c.artista LIKE :termino') ->orWhere('c.album LIKE :termino') ->setParameter('termino', '%'.$termino.'%') ->getQuery() ->getResult(); } // /** // * @return Cancion[] Returns an array of Cancion objects // */ // public function findByExampleField($value): array // { // return $this->createQueryBuilder('c') // ->andWhere('c.exampleField = :val') // ->setParameter('val', $value) // ->orderBy('c.id', 'ASC') // ->setMaxResults(10) // ->getQuery() // ->getResult() // ; // } // public function findOneBySomeField($value): ?Cancion // { // return $this->createQueryBuilder('c') // ->andWhere('c.exampleField = :val') // ->setParameter('val', $value) // ->getQuery() // ->getOneOrNullResult() // ; // } }
# 这是一个示例 Python 脚本。 # 按 ⌃R 执行或将其替换为您的代码。 # 按 双击 ⇧ 在所有地方搜索类、文件、工具窗口、操作和设置。 from Env import Environment, Agent, find_best_features from data_process import importData, X1PATH, Y1PATH, X2PATH, Y2PATH, DataClass, XPATH2016merge, YPATH2016merge, \ XPATH2016CLEAN, YPATH2016CLEAN import numpy as np import rl_utils import torch import random import matplotlib.pyplot as plt from AGENT_PPO import PPO from AGENT_PPO_MASK import PPO_MASK from ENV2 import FSEnv from plot import plot_PPO import logging from datetime import datetime from AGENT_DQN import DQNAgent, DQNEnv, train_dqn import os def set_seed(seed_value=2023): """Set seed for reproducibility.""" random.seed(seed_value) np.random.seed(seed_value) torch.manual_seed(seed_value) torch.cuda.manual_seed(seed_value) torch.backends.cudnn.deterministic = True def q_table_learn(df_class): dfnew = df_class.orign_df.dropna(axis=0, how='any') # dataframe = importData(X1PATH, Y1PATH) data = np.array(dfnew) FS_env = Environment(data, reward_K=1) # 奖励放大系数 ,由于增加一个特征带来的R2普遍偏低时可设置,目前不需要 FS_agent = Agent( m=data.shape[1] - 1, # 特征个数 policy=1, # 搜寻策略 0:随机 1:贪婪 2:e-贪婪 epsilon=0.25, # policy = 2 时 参数e的值 pre_evaluate=False, # 是否预评估 AOR=None # 初始特征分数 ) AOR = find_best_features(FS_agent, FS_env, 10000) print(np.array2string(AOR, precision=5, suppress_small=True)) # FS = Environment('./') def DQN_learn(df_class): # 设置参数 state_size = df_class.feature_num * 3 # 每个变量有3个参数 action_size = df_class.feature_num * 6 # 每个参数有两个动作,增或减 replay_memory_size = 1000 batch_size = 20 gamma = 0.95 epsilon = 1.0 epsilon_min = 0.1 epsilon_decay = 0.98 lr = 0.01 num_episodes = 1000 # 创建环境和智能体 env = DQNEnv(df_class, state_size, action_size) agent = DQNAgent(state_size, action_size, replay_memory_size, batch_size, gamma, epsilon, epsilon_min, epsilon_decay, lr) # 训练DQN智能体 train_dqn(env, agent, num_episodes) def PPO_learn(df_class,directory): state_size = df_class.feature_num * 3 # 每个变量有3个参数 action_size = df_class.feature_num * 6 # 每个参数有两个动作,增或减 actor_lr = 1e-3 critic_lr = 1e-2 num_episodes = 1000 hidden_dim = 128 gamma = 1 lmbda = 0.95 epochs = 10 eps = 0.2 device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") env = FSEnv(df_class=df_class, state_size=state_size, action_size=action_size, init_mode=0, invalid_action_reward=0, # 违反约束时的奖励 min_score=0, # 视为有提升的最小阈值 min_step_size=2, max_stop_step=10, # 最大停滞步数 智能体n步都不提升时停止 device=device ) # env.seed(0) torch.manual_seed(2023) state_dim = state_size action_dim = action_size agent = PPO_MASK(state_dim, hidden_dim, action_dim, actor_lr, critic_lr, lmbda, epochs, eps, gamma, device) try : return_list, r2_list, state_list = rl_utils.train_on_policy_agent(env, agent, num_episodes, epochs) plot_PPO(np.array(return_list),name='Returns') save_result(return_list, r2_list, state_list, directory) except KeyboardInterrupt: save_result(return_list, r2_list, state_list,directory) def save_result(return_list, r2_list, state_list,directory): if not os.path.exists(directory): os.makedirs(directory) try: with open('./result/' + datetime_str + '/return.txt', 'w') as file: for item in return_list: file.write(f"{item}\n") with open('./result/' + datetime_str + '/r2.txt', 'w') as file: for item in r2_list: file.write(f"{item}\n") with open('./result/' + datetime_str + '/state.txt', 'w') as file: for item in state_list: if item is not None: np.savetxt(file, item.reshape(1, -1), fmt='%s') finally: pass bestR = 0 bestState = None if __name__ == '__main__': set_seed(2023) # df_class = DataClass(XPATH2016merge,YPATH2016merge, # drop_last_col=None, # labindex=None) current_datetime = datetime.now() datetime_str = current_datetime.strftime("%Y-%m-%d_%H_%M") directory = f'./result/{datetime_str}' if not os.path.exists(directory): os.makedirs(directory) logging.basicConfig(filename=directory+'/debuglog.log', level=logging.DEBUG) df_class = DataClass(XPATH2016CLEAN, YPATH2016CLEAN, drop_last_col=True, labindex=None) # q_table_learn(df_class) # DQN_learn(df_class) PPO_learn(df_class,directory) # 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
package co.com.reactive.sample.apirest; import co.com.reactive.sample.model.Account; import co.com.reactive.sample.model.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.List; @RestController @RequestMapping(path = "/api") public class ApiRest { @Autowired private IAccountService iAccountService; @GetMapping(path = "/getAll") Flux<List<Account>> getAll(){ return iAccountService.getAll(); } @GetMapping(path = "/get") Mono<Account> get( @RequestParam int number){ return iAccountService.get(number); } @PostMapping(path = "/create") Mono<Boolean> create(@RequestBody Account account){ return iAccountService.create(account); } @PutMapping(path = "update") Mono<Boolean> update(@RequestBody Account account){ return iAccountService.update(account); } @DeleteMapping(path = "/delete") Mono<Boolean> delete(@RequestParam int number){ return iAccountService.delete(number); } }
import { ChangeEvent, Dispatch, SetStateAction } from 'react'; import Select from 'react-select'; import { CustomStyle } from '../../../../../components/CustomSelectStyle'; import FormGroup from '../../../../../components/FormGroup'; import Input from '../../../../../components/Input'; import { Container as StyledContainer, Group, AsideContainer } from '../styles'; import { GetErrorMessageByFieldNameType } from '../../../../../hooks/useErrors'; import { FilterRadioButtonsContainer } from '../../../../../components/FilterRadioButtonsContainer'; import FilterRadioButton from '../../../../../components/FilterRadioButtons'; interface GeneralDataCardI { getErrorMessageByFieldName: GetErrorMessageByFieldNameType; workplaceCode: string; handleWorkplaceCodeChange: (event: ChangeEvent<HTMLInputElement>) => void; name: string; handleNameChange: (event: ChangeEvent<HTMLInputElement>) => void; hasAffreightment: boolean; setHasAffreightment: Dispatch<SetStateAction<boolean>>; operator: { value: string, label: string }; operatorsOptions: { value: string, label: string }[]; setOperator: Dispatch<SetStateAction<{ value: string, label: string }>>; usesVtAndAffreightment: boolean; setUsesVtAndAffreightment: Dispatch<SetStateAction<boolean>>; checkIfWorkplaceCodeAlreadyExists: () => Promise<void>; } export default function GeneralDataCard({ getErrorMessageByFieldName, workplaceCode, handleWorkplaceCodeChange, name, handleNameChange, hasAffreightment, setHasAffreightment, operator, operatorsOptions, setOperator, usesVtAndAffreightment, setUsesVtAndAffreightment, checkIfWorkplaceCodeAlreadyExists, }: GeneralDataCardI) { return ( <StyledContainer> <div className="card-title"> Dados Gerais </div> <AsideContainer> <Group> <div className="title"> Código cliente </div> <FormGroup error={getErrorMessageByFieldName('workplaceCode')}> <Input value={workplaceCode} onChange={handleWorkplaceCodeChange} error={getErrorMessageByFieldName('workplaceCode')} placeholder="Informe o código" onBlur={() => checkIfWorkplaceCodeAlreadyExists()} maxLength={25} /> </FormGroup> </Group> <Group> <div className="title"> Denominação </div> <FormGroup error={getErrorMessageByFieldName('name')}> <Input value={name} onChange={handleNameChange} error={getErrorMessageByFieldName('name')} placeholder="Nome do local de trabalho" maxLength={40} /> </FormGroup> </Group> </AsideContainer> <Group> <div className="title"> Utiliza fretamento? </div> <FilterRadioButtonsContainer> <FilterRadioButton selected={hasAffreightment} onClick={() => setHasAffreightment(true)} > Sim </FilterRadioButton> <FilterRadioButton selected={!hasAffreightment} onClick={() => setHasAffreightment(false)} > Não </FilterRadioButton> </FilterRadioButtonsContainer> </Group> {hasAffreightment && ( <AsideContainer> <Group> <div className="title"> Operadora de fretamento </div> <FormGroup> <Select value={{ value: operator?.value, label: operator?.label }} options={operatorsOptions} onChange={(opt) => { setOperator({ value: opt!.value, label: opt!.label }); }} styles={CustomStyle} classNamePrefix="react-select" className="react-select-container" /> </FormGroup> </Group> <Group> <div className="title"> Combina fretamento com VT? </div> <FilterRadioButtonsContainer> <FilterRadioButton selected={usesVtAndAffreightment} onClick={() => setUsesVtAndAffreightment(true)} > Sim </FilterRadioButton> <FilterRadioButton selected={!usesVtAndAffreightment} onClick={() => setUsesVtAndAffreightment(false)} > Não </FilterRadioButton> </FilterRadioButtonsContainer> </Group> </AsideContainer> )} </StyledContainer> ); }
# Machine_Learning_Model Understanding the Basics of Machine Learning through a problem statement using the data from a csv dataset. The problem statement is as follows: The goal of this task is to build a neural network model that predicts whether an employee will leave the present company or not depending on various factors. Given a dataset containing historical employee information, the model should predict whether a current employee is likely to leave the company. The dataset contains the following Columns: (a) Education: The highest level of education attained by the individual. (b) JoiningYear: The year in which the employee joined the current company. (c) City: The city that the individual belongs to. (d) PaymentTier: Depending on their current salary, the individuals are classified into different tiers. (e) Age: Age of the employee. (f) Gender: The gender of the individual. (g) EverBenched: This is a boolean which tells whether the employee was ever put on the bench in the current company. (h) ExperienceInCurrentDomain: Years of experience the individual has in the domain they are currently working. (i) LeaveOrNot: This is the target variable (boolean) which tells whether the employee will leave the company or not. The constraints are as follows: No Pretrained Models: Participants are not allowed to use pretrained machine learning models or external datasets. The model should be trained from scratch using the provided dataset: task_1a_dataset.csv. Neural Network architecture for training the dataset has to be developed by the team. The trained model should be saved as task_1a_trained_model.pth using the torch.jit.save() function as mentioned in the main() function of task_1a.py file. The code stub provided (task_1a.py) must be followed mandatorily by the teams. You are allowed to add other functions to the Python file but should not delete the functions which are already provided. You are allowed to import additional functions from the following libraries: "pandas, numpy, matplotlib, torch and sklearn". Importing any other libraries might cause an issue while running the executable for auto-evaluation. main() function of task_1a.py should not be modified by the teams. Go through the function thoroughly to understand the flow of the code. The Boiler Plate Description is as follows: 1. data_preprocessing() Function name data_preprocessing() Purpose This function will be used to load your csv dataset and preprocess it. Preprocessing involves cleaning the dataset by removing unwanted features, decision about what needs to be done with missing values etc. Note that there are features in the csv file whose values are textual (eg: Industry, Education Level etc). These features might be required for training the model but can not be given directly as strings for training. Hence this function should return encoded dataframe in which all the textual features are numerically labeled Input Argument task_1a_dataframe : [ Pandas Dataframe ] Returns encoded_dataframe : [ Pandas Dataframe ] Processed data as Pandas Dataframe Example Call encoded_dataframe = data_preprocessing(task_1a_dataframe) 2. identify_features_and_targets() Function name identify_features_and_targets() Purpose The purpose of this function is to define the features and the required target labels. The function returns a python list in which the first item is the selected features and second item is the target label Input Argument encoded_dataframe : [ Dataframe ] Returns features_and_targets : [ list ] python list in which the first item is the selected features and second item is the target label Example Call features_and_targets = ideantify_features_and_targets(encoded_dataframe) 3. load_as_tensors() Function name load_as_tensors() Purpose This function aims at loading your data (both training and validation) as PyTorch tensors. Here you will have to split the dataset for training and validation, and then load them as as tensors. Training of the model requires iterating over the training tensors. Hence the training sensors need to be converted to iterable dataset object Input Argument features_and targets : [ list ] Returns tensors_and_iterable_training_data : [ list ] Items: [0]: X_train_tensor: Training features loaded into Pytorch array [1]: X_test_tensor: Feature tensors in validation data [2]: y_train_tensor: Training labels as Pytorch tensor [3]: y_test_tensor: Target labels as tensor in validation data [4]: Iterable dataset object and iterating over it in batches, which are then fed into the model for processing Example Call tensors_and_iterable_training_data = load_as_tensors(features_and_targets) 4. class Salary_Predictor(nn.Module) Function name class Salary_Predictor(nn.Module) Purpose The architecture and behavior of your neural network model will be defined within this class that inherits from nn.Module. Here you also need to specify how the input data is processed through the layers. It defines the sequence of operations that transform the input data into the predicted output. When an instance of this class is created and data is passed through it, the forward method is automatically called, and the output is the prediction of the model based on the input data Input Argument None Returns predicted_output Predicted output for the given input data 5. model_loss_function() Function name model_loss_function() Purpose To define the loss function for the model. Loss function measures how well the predictions of a model match the actual target values in training data Input Argument None Returns loss_function This can be a pre-defined loss function in PyTorch or can be user-defined Example Call loss_function = model_loss_function() 6. model_optimizer() Function name model_optimizer() Purpose To define the optimizer for the model. Optimizer is responsible for updating the parameters (weights and biases) in a way that minimizes the loss function Input Argument model: An object of the 'Salary_Predictor' class Returns optimizer Pre-defined optimizer from pytorch Example Call optimizer = model_optimizer(model) 7. model_number_of_epochs() Function name model_number_of_epochs() Purpose To define the number of epochs for training the model Input Argument None Returns number_of_epochs: [Integer value] Example Call number_of_epochs = model_number_of_epochs() 8. training_function() Function name training_function() Purpose All the required parameters for training are passed to this function. Input Argument 1. model: An object of the 'Salary_Predictor' class 2. number_of_epochs: For training the model 3. tensors_and_iterable_training_data: list containing training and validation data tensors and iterable dataset object of training tensors 4. loss_function: Loss function defined for the model 5. optimizer: Optimizer defined for the model Returns trained_model Example Call trained_model = training_function(model, number_of_epochs, iterable_training_data, loss_function, optimizer) 9. validation_function() Function name validation_function() Purpose This function will utilise the trained model to do predictions on the validation dataset. This will enable us to understand the accuracy of the model Input Argument 1. trained_model: Returned from the training function 2. tensors_and_iterable_training_data: list containing training and validation data tensors and iterable dataset object of training tensors Returns model_accuracy: Accuracy on the validation dataset Example Call model_accuracy = validation_function(trained_model, tensors_and_iterable_training_data)
import { useEffect, useReducer, useState } from "react"; import "./App.css"; import { SearchBar } from "./components/SearchBar"; import { SearchResultsList } from "./components/SearchResultsList"; import ProductList from "./components/ProductList"; import Cart from "./components/Cart"; import { cartReducer } from "./reducers/cartReducers"; import NavBar from "./components/NavBar"; function App() { const [state, dispatch] = useReducer(cartReducer, { products: [], cart: [], }); const [results, setResults] = useState([]); const fetchProducts = async () => { const res = await fetch(`https://dummyjson.com/products?limit=100`); const data = await res.json(); console.log(data); dispatch({ type: "ADD_PRODUCTS", payload: data.products, }); }; useEffect(() => { fetchProducts(); }, []); return ( <> <NavBar /> <div className="search-bar-container"> <SearchBar setResults={setResults} /> {results && results.length > 0 && ( <SearchResultsList results={results} state={state} dispatch={dispatch} /> )} </div> <div style={{ display: "flex" }}> <ProductList state={state} dispatch={dispatch} /> <Cart state={state} dispatch={dispatch} /> </div> </> ); } export default App;
import React from "react"; import styled from "styled-components"; import MDEditor from "@uiw/react-md-editor"; import TagInput from "../components/TagInput"; import { useParams, useNavigate } from "react-router-dom"; import { useSelector, useDispatch } from "react-redux"; import { useState, useEffect } from "react"; import { getQuestionById, editQuestion } from "../redux/questionsSlice"; const Container = styled.div` display: flex; flex-direction: row; min-height: 1330.13px; max-width: 1264px; margin-right: auto; margin-left: auto; > .content { display: flex; flex-direction: row; width: 100%; padding: 24px; > .EditContainer { display: flex; flex-direction: column; width: 662px; > div { display: flex; flex-direction: column; } > .topSign { background-color: hsl(47, 87%, 94%); border: 1px solid hsl(47, 69%, 69%); border-radius: 4px; height: 115px; width: 100%; padding: 16px; > p { font-size: 13px; color: hsl(210, 8%, 25%); margin: 0%; line-height: 17px; } .first { margin-bottom: 13px; } } > .FormContainer { > .FormBox { width: 100%; display: flex; flex-direction: column; padding-bottom: 15px; margin-top: 10px; > input { border: 1px solid hsl(210, 8%, 75%); border-radius: 3px; height: 33px; width: 100%; &:focus { border: 1px solid hsl(206, 100%, 40%); outline: 3px solid hsl(206, 96%, 90%); } } > label { font-weight: bold; margin-bottom: 4px; } > div { margin-top: 10px; padding-bottom: 15px; display: flex; flex-direction: column; > input { border-radius: 3px; border: 1px solid hsl(210, 8%, 75%); height: 33px; &:focus { border: 1px solid hsl(206, 100%, 40%); outline: 3px solid hsl(206, 96%, 90%); } } > label { font-weight: bold; margin-bottom: 4px; } > .BlueButton { background-color: hsl(206, 100%, 52%); color: white; font-size: 13px; width: 84px; height: 38px; border-radius: 4px; &:hover { background-color: hsl(206, 100%, 40%); } } } > .AddComment { color: hsl(210, 8%, 55%); opacity: 0.6; font-size: 13px; } } } } > .EditSidebar { margin-top: 5px; width: 365px; height: 210px; margin-left: 30px; > .sidebar-container { background-color: hsl(47, 87%, 94%); width: 100%; height: 100%; border: 1px solid hsl(47, 65%, 84%); border-radius: 5px; > div { border-bottom: 1px solid hsl(47, 65%, 84%); padding: 12px 15px; height: 44.61px; color: hsl(210, 8%, 25%); font-size: 15px; background-color: hsl(47, 83%, 91%); } > ul { margin-left: 25px; padding: 4px 15px; display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: hsl(47, 87%, 94%); > li { color: hsl(210, 8%, 25%); margin: 8px 0px; height: 13px; width: 333px; font-size: 13px; background-color: hsl(47, 87%, 94%); list-style: disc; } } } } } `; const EditQuestion = () => { const { questionId } = useParams(); const question = useSelector((state) => state.questions.single); const [titleInput, setTitleInput] = useState(null); const [contentInput, setContentInput] = useState(null); // const [tags, setTags] = useState(question.tags); const dispatch = useDispatch(); const navigate = useNavigate(); useEffect(() => { dispatch(getQuestionById(questionId)); }, []); useEffect(() => { setTitleInput(question.title); setContentInput(question.content1); }, [question]); const handleEdit = () => { if (titleInput.length === 0 || contentInput.length === 0) { alert("내용을 입력해주세요."); return; } dispatch( editQuestion({ id: questionId, title: titleInput, content1: contentInput, content2: contentInput, }) ); alert("질문이 수정되었습니다."); navigate("/questions"); }; return ( <div> <Container> <div className="content"> <div className="EditContainer"> <div className="topSign"> <p className="first"> Your edit will be placed in a queue until it is peer reviewed. </p> <p> We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks. </p> </div> <div className="FormContainer"> <div className="FormBox"> <label>Title</label> {titleInput === null ? ( <></> ) : ( <input type="text" value={titleInput} onChange={(e) => setTitleInput(e.target.value)} ></input> )} </div> <div className="FormBox"> <label>Body</label> <div> {contentInput === null ? ( <></> ) : ( <> <MDEditor value={contentInput} onChange={setContentInput} /> <MDEditor.Markdown source={contentInput} style={{ whiteSpace: "pre-wrap" }} /> </> )} </div> <div> <label>Tags</label> {/* <TagInput tags={tags} setTags={setTags} /> */} </div> <div> <label>Edit Summary</label> <input placeholder="briefly explain your changes (corrected spelling, fixed grammar, improved formatting)"></input> </div> <div> <button className="BlueButton" onClick={handleEdit}> Save edits </button> </div> <div className="AddComment">Add a comment</div> </div> </div> </div> <div className="EditSidebar"> <div className="sidebar-container"> <div>How to Edit</div> <ul> <li> Correct minor typos or mistakes</li> <li> Clarify meaning without changing it</li> <li> Add related resources or links</li> <li> Always respect the author’s intent</li> <li> Don’t use edits to reply to the author</li> </ul> </div> </div> </div> </Container> </div> ); }; export default EditQuestion;
package com.github.scribejava.core.oauth; import com.github.scribejava.core.builder.api.DefaultApi10a; import com.github.scribejava.core.model.AbstractRequest; import com.github.scribejava.core.model.OAuth1AccessToken; import com.github.scribejava.core.model.OAuth1RequestToken; import com.github.scribejava.core.model.OAuthAsyncRequestCallback; import com.github.scribejava.core.model.OAuthConfig; import com.github.scribejava.core.model.OAuthConstants; import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.OAuthRequestAsync; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.services.Base64Encoder; import com.github.scribejava.core.utils.MapUtils; import com.ning.http.client.ProxyServer; import java.io.IOException; import java.util.Map; import java.util.concurrent.Future; public class OAuth10aService extends OAuthService { private static final String VERSION = "1.0"; private final DefaultApi10a api; public String getVersion() { return "1.0"; } public OAuth10aService(DefaultApi10a defaultApi10a, OAuthConfig oAuthConfig) { super(oAuthConfig); this.api = defaultApi10a; } public OAuth1RequestToken getRequestToken() { OAuthConfig config = getConfig(); config.log("obtaining request token from " + this.api.getRequestTokenEndpoint()); OAuthRequest oAuthRequest = new OAuthRequest(this.api.getRequestTokenVerb(), this.api.getRequestTokenEndpoint(), this); config.log("setting oauth_callback to " + config.getCallback()); oAuthRequest.addOAuthParameter(OAuthConstants.CALLBACK, config.getCallback()); addOAuthParams(oAuthRequest, ""); appendSignature(oAuthRequest); config.log("sending request..."); Response send = oAuthRequest.send(); String body = send.getBody(); config.log("response status code: " + send.getCode()); config.log("response body: " + body); return this.api.getRequestTokenExtractor().extract(body); } private void addOAuthParams(AbstractRequest abstractRequest, String str) { OAuthConfig config = getConfig(); abstractRequest.addOAuthParameter(OAuthConstants.TIMESTAMP, this.api.getTimestampService().getTimestampInSeconds()); abstractRequest.addOAuthParameter(OAuthConstants.NONCE, this.api.getTimestampService().getNonce()); abstractRequest.addOAuthParameter(OAuthConstants.CONSUMER_KEY, config.getApiKey()); abstractRequest.addOAuthParameter(OAuthConstants.SIGN_METHOD, this.api.getSignatureService().getSignatureMethod()); abstractRequest.addOAuthParameter(OAuthConstants.VERSION, getVersion()); if (config.hasScope()) { abstractRequest.addOAuthParameter("scope", config.getScope()); } abstractRequest.addOAuthParameter(OAuthConstants.SIGNATURE, getSignature(abstractRequest, str)); config.log("appended additional OAuth parameters: " + MapUtils.toString(abstractRequest.getOauthParameters())); } public final OAuth1AccessToken getAccessToken(OAuth1RequestToken oAuth1RequestToken, String str) { OAuthConfig config = getConfig(); config.log("obtaining access token from " + this.api.getAccessTokenEndpoint()); OAuthRequest oAuthRequest = new OAuthRequest(this.api.getAccessTokenVerb(), this.api.getAccessTokenEndpoint(), this); prepareAccessTokenRequest(oAuthRequest, oAuth1RequestToken, str); return this.api.getAccessTokenExtractor().extract(oAuthRequest.send().getBody()); } public final Future<OAuth1AccessToken> getAccessTokenAsync(OAuth1RequestToken oAuth1RequestToken, String str, OAuthAsyncRequestCallback<OAuth1AccessToken> oAuthAsyncRequestCallback) { return getAccessTokenAsync(oAuth1RequestToken, str, oAuthAsyncRequestCallback, (ProxyServer) null); } public final Future<OAuth1AccessToken> getAccessTokenAsync(OAuth1RequestToken oAuth1RequestToken, String str, OAuthAsyncRequestCallback<OAuth1AccessToken> oAuthAsyncRequestCallback, ProxyServer proxyServer) { OAuthConfig config = getConfig(); config.log("async obtaining access token from " + this.api.getAccessTokenEndpoint()); OAuthRequestAsync oAuthRequestAsync = new OAuthRequestAsync(this.api.getAccessTokenVerb(), this.api.getAccessTokenEndpoint(), this); prepareAccessTokenRequest(oAuthRequestAsync, oAuth1RequestToken, str); return oAuthRequestAsync.sendAsync(oAuthAsyncRequestCallback, new OAuthRequestAsync.ResponseConverter<OAuth1AccessToken>() { public OAuth1AccessToken convert(com.ning.http.client.Response response) throws IOException { return OAuth10aService.this.getApi().getAccessTokenExtractor().extract(OAuthRequestAsync.RESPONSE_CONVERTER.convert(response).getBody()); } }, proxyServer); } /* access modifiers changed from: protected */ public void prepareAccessTokenRequest(AbstractRequest abstractRequest, OAuth1RequestToken oAuth1RequestToken, String str) { OAuthConfig config = getConfig(); abstractRequest.addOAuthParameter(OAuthConstants.TOKEN, oAuth1RequestToken.getToken()); abstractRequest.addOAuthParameter(OAuthConstants.VERIFIER, str); config.log("setting token to: " + oAuth1RequestToken + " and verifier to: " + str); addOAuthParams(abstractRequest, oAuth1RequestToken.getTokenSecret()); appendSignature(abstractRequest); } public void signRequest(OAuth1AccessToken oAuth1AccessToken, AbstractRequest abstractRequest) { OAuthConfig config = getConfig(); config.log("signing request: " + abstractRequest.getCompleteUrl()); if (!oAuth1AccessToken.isEmpty() || this.api.isEmptyOAuthTokenParamIsRequired()) { abstractRequest.addOAuthParameter(OAuthConstants.TOKEN, oAuth1AccessToken.getToken()); } config.log("setting token to: " + oAuth1AccessToken); addOAuthParams(abstractRequest, oAuth1AccessToken.getTokenSecret()); appendSignature(abstractRequest); } public String getAuthorizationUrl(OAuth1RequestToken oAuth1RequestToken) { return this.api.getAuthorizationUrl(oAuth1RequestToken); } private String getSignature(AbstractRequest abstractRequest, String str) { OAuthConfig config = getConfig(); config.log("generating signature..."); config.log("using base64 encoder: " + Base64Encoder.type()); String extract = this.api.getBaseStringExtractor().extract(abstractRequest); String signature = this.api.getSignatureService().getSignature(extract, config.getApiSecret(), str); config.log("base string is: " + extract); config.log("signature is: " + signature); return signature; } /* renamed from: com.github.scribejava.core.oauth.OAuth10aService$2 reason: invalid class name */ static /* synthetic */ class AnonymousClass2 { static final /* synthetic */ int[] $SwitchMap$com$github$scribejava$core$model$SignatureType; /* JADX WARNING: Can't wrap try/catch for region: R(6:0|1|2|3|4|6) */ /* JADX WARNING: Code restructure failed: missing block: B:7:?, code lost: return; */ /* JADX WARNING: Failed to process nested try/catch */ /* JADX WARNING: Missing exception handler attribute for start block: B:3:0x0012 */ static { /* com.github.scribejava.core.model.SignatureType[] r0 = com.github.scribejava.core.model.SignatureType.values() int r0 = r0.length int[] r0 = new int[r0] $SwitchMap$com$github$scribejava$core$model$SignatureType = r0 com.github.scribejava.core.model.SignatureType r1 = com.github.scribejava.core.model.SignatureType.Header // Catch:{ NoSuchFieldError -> 0x0012 } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x0012 } r2 = 1 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x0012 } L_0x0012: int[] r0 = $SwitchMap$com$github$scribejava$core$model$SignatureType // Catch:{ NoSuchFieldError -> 0x001d } com.github.scribejava.core.model.SignatureType r1 = com.github.scribejava.core.model.SignatureType.QueryString // Catch:{ NoSuchFieldError -> 0x001d } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x001d } r2 = 2 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x001d } L_0x001d: return */ throw new UnsupportedOperationException("Method not decompiled: com.github.scribejava.core.oauth.OAuth10aService.AnonymousClass2.<clinit>():void"); } } private void appendSignature(AbstractRequest abstractRequest) { OAuthConfig config = getConfig(); int i = AnonymousClass2.$SwitchMap$com$github$scribejava$core$model$SignatureType[config.getSignatureType().ordinal()]; if (i == 1) { config.log("using Http Header signature"); abstractRequest.addHeader("Authorization", this.api.getHeaderExtractor().extract(abstractRequest)); } else if (i == 2) { config.log("using Querystring signature"); for (Map.Entry next : abstractRequest.getOauthParameters().entrySet()) { abstractRequest.addQuerystringParameter((String) next.getKey(), (String) next.getValue()); } } else { throw new IllegalStateException("Unknown new Signature Type '" + config.getSignatureType() + "'."); } } public DefaultApi10a getApi() { return this.api; } }