text
stringlengths
184
4.48M
# When you run this get_data.py, you have to wait for 30min to scrape social media post comments based on the realtime weibo data prestored in the data folder. # If you do not want to wait, do not run this file and go directly to clean_features.py to process data import pandas as pd import os from utils.weibo_comment_scraper import * from utils.weibo_realtime_scraper import * from utils.data_processing import Check_file_existence # from selenium import webdriver # from selenium.webdriver.support.ui import WebDriverWait # from selenium.webdriver.common.by import By pwd = os.getcwd () datapath = pwd +"/data/raw" # Create a list of keywords in Chinese for social media posts scraping scraping_keywords = ['流浪狗 咬人 负责', '人工智能 风险', '都美竹', 'openai', '虐猫', '删帖', '性骚扰'] # Createn a list of translated keywords to name the file of scraped data keywords = ['homeless_dogs', 'artificial_intelligence_risks', 'DuMeizhu_scandal', 'openai', 'cat_abuse', 'content_moderation', 'sexual_harrassment'] # driver = webdriver.Chrome() # #send request to log in to sina weibo # driver.get("https://login.sina.com.cn/signup/signin.php") # wait = WebDriverWait(driver,5) # #wait for one minute to log in manually # time.sleep(60) # Scrape data based on Chinese keywords. # Store the data of each keyword in a separate file # Because sinaweibo.com only displays the latest 50 pages of realtime posts, each time the scraper only flip the page for 50 times # for i in len(keywords): # filename = datapath + '/' + f'{keywords[i]}' + '_realtime_posts.csv' # Scrape_realtime_weibo_by_keyword(driver = driver, # keyword = scraping_keywords[i], # folder_path = datapath, # page_count = 49) # Concate all data from 7 separate files and remove duplicates data0 = pd.DataFrame() variables = ['current_time','mid','uid','username','content','date','weibolink','repost_count','like_count','comment_count','verification','keyword'] for keyword in keywords: filename = datapath + '/' + f'{keyword}' + '_realtime_posts.csv' data1 = pd.read_csv(filename,names = variables, on_bad_lines='skip') data0 = pd.concat([data0,data1]) Check_file_existence('/weibo_raw_data.csv',datapath) Check_file_existence('/unique_weibo_raw_data.csv',datapath) data0.to_csv(datapath+'/weibo_raw_data.csv') data0.drop_duplicates(subset=['content'], inplace=True, keep='first') data0.to_csv(datapath+ '/unique_' + 'weibo_raw_data.csv', index=False, encoding='utf_8_sig') print('Data is cleaned and restored in unique_weibo_raw_data') # Scrape comments of sourceposts # This scraper does not need simulation of user login. It's based on indexing the unique id of each sourcepost rawdata = pd.read_csv(datapath+'/unique_weibo_raw_data.csv') data_with_comment = rawdata[rawdata['comment_count']>0] mid_to_scrape = list(data_with_comment['mid']) max_page = 50 # The maximum page of comments to scrape under each ;ost comment_file = '/comments.csv' # Check whether the file already exist if os.path.exists(datapath + comment_file): print('csv file alreayd exist, remove first:', datapath + comment_file) os.remove(datapath + comment_file) # Get comments of all realtime posts with a positive comment count get_comments(v_weibo_ids = mid_to_scrape, v_comment_file= datapath + comment_file, v_max_page = max_page) df = pd.read_csv(datapath + comment_file) # Remove repeated comments df.drop_duplicates(subset=['comment_id'], inplace=True, keep='first') # Store unique comments to file df.to_csv(datapath + '/unique_comments.csv', index=False)#, encoding='utf_8_sig') print('Data cleaned')
package practice; import java.util.Stack; public class CheckParenthesisProblem { public static void main(String[] args) { String str="{[(())]"; if(isParenthesis(str)){ System.out.println("true"); } else { System.out.println("false"); } /* Stack<Character> stack=new Stack<Character>(); for(int i=0;i<str.length();i++) { char c=str.charAt(i); if(c=='(' || c=='[' || c=='{') { stack.push(c); } else { if(stack.isEmpty()) { System.out.println("false"); } else if(!((stack.peek()=='(' && c==')') || (stack.peek()=='[' && c==']') || (stack.peek()=='{' && c=='}'))) { System.out.println("false"); } else { stack.pop(); } } } if(stack.isEmpty()) { System.out.println("true"); } */ } private static boolean isParenthesis(String str) { Stack<Character> stack = new Stack<Character>(); for(int i=0;i<str.length();i++) { char c=str.charAt(i); if(c=='(' || c=='[' || c=='{') { stack.push(c); } else { if(stack.isEmpty()) { return false; } else if (!((stack.peek()=='(' && c==')') || (stack.peek()=='[' && c==']') || (stack.peek()=='{' && c=='}'))) { return false; } else { stack.pop(); } } } return stack.isEmpty(); } }
<?php namespace JDEV; /** * Class RTEConfig * * @package JDEV */ class RTEConfig { public function __construct() { add_filter('mce_css', [$this, 'unloadDefaultStyles']); add_filter('mce_external_plugins', [$this, 'registerExternalPlugins']); add_filter('acf/fields/wysiwyg/toolbars', [$this, 'configureBasicToolbar']); add_filter('mce_buttons', [$this, 'configureFullToolbar']); add_filter('tiny_mce_before_init', [$this, 'configureStyles']); add_shortcode('shy', [$this, 'softHyphenShortcode']); } /** * Unload default styles * * @param $stylesheets * @return string */ public function unloadDefaultStyles($stylesheets) { $stylesheets = explode(',', $stylesheets); foreach ($stylesheets as $key => $sheet) { if (preg_match('/wp-includes/', $sheet)) { unset($stylesheets[$key]); } } return implode(',', $stylesheets); } /** * Register external plugins * * @param $plugins * @return array */ public function registerExternalPlugins($plugins) { $plugins['table'] = content_url() . '/lib/tiny-mce-plugins/table.min.js'; return $plugins; } /** * Toolbar buttons configuration for basic RTE * * @param $toolbars * @return array */ public function configureBasicToolbar($toolbars) { $toolbars['Basic'][1] = [ 'styleselect', 'removeformat', 'link', 'unlink', 'bold', 'italic', 'underline', 'strikethrough', 'blockquote', 'subscript', 'superscript', 'hr', ]; return $toolbars; } /** * Toolbar buttons configuration for full RTE * * @return array */ public function configureFullToolbar() { return [ 'formatselect', 'styleselect', 'removeformat', 'link', 'unlink', 'bold', 'italic', 'underline', 'strikethrough', 'blockquote', 'subscript', 'superscript', 'hr', 'bullist', 'numlist', 'table', 'alignleft', 'aligncenter', 'alignright', ]; } /** * Configuration for block and style formats * * @param $settings * @return array */ public function configureStyles($settings) { $blockFormats = [ 'Paragraph' => 'p', 'Heading 1' => 'h1', 'Heading 2' => 'h2', 'Heading 3' => 'h3', 'Heading 4' => 'h4', 'Heading 5' => 'h5', 'Heading 6' => 'h6', ]; $styleFormats = [ [ 'title' => 'Display 1', 'selector' => 'p, h1, h2, h3, h4, h5, h6', 'classes' => 'display-1', ], [ 'title' => 'Display 2', 'selector' => 'p, h1, h2, h3, h4, h5, h6', 'classes' => 'display-2', ], [ 'title' => 'Display 3', 'selector' => 'p, h1, h2, h3, h4, h5, h6', 'classes' => 'display-3', ], [ 'title' => 'Display 4', 'selector' => 'p, h1, h2, h3, h4, h5, h6', 'classes' => 'display-4', ], [ 'title' => 'Display 5', 'selector' => 'p, h1, h2, h3, h4, h5, h6', 'classes' => 'display-5', ], [ 'title' => 'Display 6', 'selector' => 'p, h1, h2, h3, h4, h5, h6', 'classes' => 'display-6', ], [ 'title' => 'Lead text', 'selector' => 'p', 'classes' => 'lead', ], [ 'title' => 'Small text', 'selector' => 'p', 'classes' => 'small', ], [ 'title' => 'Lowercase text', 'selector' => 'p', 'classes' => 'text-lowercase', ], [ 'title' => 'Uppercase text', 'selector' => 'p', 'classes' => 'text-uppercase', ], [ 'title' => 'Capitalized text', 'selector' => 'p', 'classes' => 'text-capitalize', ], [ 'title' => 'No text decoration', 'selector' => 'p', 'classes' => 'text-decoration-none', ], [ 'title' => 'Text wrap', 'selector' => 'p', 'classes' => 'text-wrap', ], [ 'title' => 'Primary color', 'inline' => 'span', 'classes' => 'text-primary', ], [ 'title' => 'Primary button', 'selector' => 'a', 'classes' => 'btn btn-primary', ], [ 'title' => 'Secondary button', 'selector' => 'a', 'classes' => 'btn btn-secondary', ], [ 'title' => 'Inline list', 'selector' => 'ul', 'classes' => 'list-inline', ], ]; $blockFormatsArr = []; foreach ($blockFormats as $title => $tag) { $blockFormatsArr[] = "$title=$tag"; } $blockFormatsString = implode(';', $blockFormatsArr); $styleFormatsJson = json_encode($styleFormats); $settings = array_merge($settings, [ 'block_formats' => $blockFormatsString, 'block_formats_merge' => false, 'style_formats' => $styleFormatsJson, 'style_formats_merge' => false, 'apply_source_formatting' => false, ]); return $settings; } public function softHyphenShortcode() { return '&shy;'; } }
// // UsersViewModel.swift // iOS Test Assessment // // Created by Shabbir Ahmad on 03/05/24. // import Foundation class UsersViewModel : ObservableObject { //MARK: - Properties @Published var users : [User] = [] var pageLimit = 10 var page : Int = 1 var limitExceed = false init() { getUsers() } //MARK: - PAGINATION func loadMoreContent(currentItem item: User){ if limitExceed == false { page += 1 getUsers() } } func isLastItem(_ userList:[User], _ user: User) -> Bool { guard !userList.isEmpty else { return false } guard userList.last?.id == user.id else { return false } return true } //MARK: - API CALL func getUsers() { let apiUrl = "https://jsonplaceholder.typicode.com/posts?_page=\(page)&_limit=\(pageLimit)" APIManager.shared.apiCall(urlString: apiUrl, resultType: [User].self) { response in switch response { case .success(let model): DispatchQueue.main.async { guard (model?.count ?? 0) > 0 else { self.limitExceed = true return } self.users.append(contentsOf: model ?? []) } case .failure(let error): print(error) } } } }
# 扩展方法 ```C# public static Vector3 ToVector3(this Vector4 vec4) { return new Vector3(vec4.x, vec4.y, vec4.z); } // static void Main() { Vector4 vec4; Vector3 vec3 = vec4.ToVector3(); } ``` # 运算符重载 > CRE:有些C++能重载的运算符在C#是不能重载或者受限的。 > 能重载的一元运算符:`+`、`-`、`!`、`~`、`++`、`--`、`True`、`False` > 能重载的二元运算符: `+`、`-`、`*`、`/`、`%`、`&`、`|`、`!`、`^`、`<<`(限制为整数)、`>>`(限制为整数)、`==`、`!=`、`>`、`<`、`>=`、`<=` > 不能重载的运算符:`=`、`&&`、`||`、`[]`、`()`...... ```C# class Person { public string name; public static Person operator +(Person a, Person b) { var stu = new Person(); stu.name = "Son"; return stu; } } ``` (END)
"""q_learning_agents.py Author: Rei Armenia, Matthew James Harrison Class: CSI-480 AI Assignment: MDPs and Reinforcement Learning Programming Assignment Due Date: November 1, 2017 Description: Pacman seeks reward. Should he eat or should he run? When in doubt, Q-learn. Certification of Authenticity: I certify that this is entirely my own work, except where I have given fully-documented references to the work of others. I understand the definition and consequences of plagiarism and acknowledge that the assessor of this assignment may, for the purpose of assessing this assignment: - Reproduce this assignment and provide a copy to another member of academic staff; and/or - Communicate a copy of this assignment to a plagiarism checking service (which may then retain a copy of this assignment on its database for the purpose of future plagiarism checking) ---------------------- Champlain College CSI-480, Fall 2017 The following code was adapted by Joshua Auerbach ([email protected]) from the UC Berkeley Pacman Projects (see license and attribution below). ---------------------- Licensing Information: You are free to use or extend these projects for educational purposes provided that (1) you do not distribute or publish solutions, (2) you retain this notice, and (3) you provide clear attribution to UC Berkeley, including a link to http://ai.berkeley.edu. Attribution Information: The Pacman AI projects were developed at UC Berkeley. The core projects and autograders were primarily created by John DeNero ([email protected]) and Dan Klein ([email protected]). Student side autograding was added by Brad Miller, Nick Hay, and Pieter Abbeel ([email protected]). """ from game import * from learning_agents import ReinforcementAgent from feature_extractors import * import random import util import math class QLearningAgent(ReinforcementAgent): """ Q-Learning Agent Functions you should fill in: - compute_value_from_q_values - compute_action_from_q_values - get_q_value - get_action - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate) Functions you should use - self.get_legal_actions(state) which returns legal actions for a state """ def __init__(self, **args): "You can initialize Q-values here..." ReinforcementAgent.__init__(self, **args) "*** YOUR CODE HERE ***" self.q_values = util.Counter() def get_q_value(self, state, action): """ Returns Q(state,action) Should return 0.0 if we have never seen a state or the Q node value otherwise """ "*** YOUR CODE HERE ***" q_value = 0.0 if (state, action) in self.q_values: q_value = self.q_values[(state, action)] return q_value def compute_value_from_q_values(self, state): """ Returns max_action Q(state,action) where the max is over legal actions. Note that if there are no legal actions, which is the case at the terminal state, you should return a value of 0.0. """ "*** YOUR CODE HERE ***" value = 0.0 q_values = [self.get_q_value(state, action) for action in self.get_legal_actions(state)] if (q_values): value = max(q_values) return value def compute_action_from_q_values(self, state): """ Compute the best action to take in a state. Note that if there are no legal actions, which is the case at the terminal state, you should return None. """ "*** YOUR CODE HERE ***" # Return none if terminal state action = None best_value = self.get_value(state) best_actions = [action for action in self.get_legal_actions(state) if self.get_q_value(state, action) is best_value] if len(best_actions): action = random.choice(best_actions) return action def get_action(self, state): """ Compute the action to take in the current state. With probability self.epsilon, we should take a random action and take the best policy action otherwise. Note that if there are no legal actions, which is the case at the terminal state, you should choose None as the action. HINT: You might want to use util.flip_coin(prob) HINT: To pick randomly from a list, use random.choice(list) """ # Pick Action legal_actions = self.get_legal_actions(state) action = None "*** YOUR CODE HERE ***" if util.flip_coin(self.epsilon): action = random.choice(legal_actions) else: action = self.get_policy(state) return action def update(self, state, action, next_state, reward): """ The parent class calls this to observe a state = action => next_state and reward transition. You should do your Q-Value update here NOTE: You should never call this function, it will be called on your behalf """ "*** YOUR CODE HERE ***" old_q_value = self.get_q_value(state, action) estimated_next_value = self.get_value(next_state) sample = reward + (self.discount * estimated_next_value) new_q_value = ((1 - self.alpha) * old_q_value) + (self.alpha * sample) self.q_values[(state, action)] = new_q_value def get_policy(self, state): return self.compute_action_from_q_values(state) def get_value(self, state): return self.compute_value_from_q_values(state) class PacmanQAgent(QLearningAgent): "Exactly the same as QLearningAgent, but with different default parameters" def __init__(self, epsilon=0.05, gamma=0.8, alpha=0.2, num_training=0, **args): """ These default parameters can be changed from the pacman.py command line. For example, to change the exploration rate, try: python pacman.py -p PacmanQLearningAgent -a epsilon=0.1 alpha - learning rate epsilon - exploration rate gamma - discount factor num_training - number of training episodes, i.e. no learning after these many episodes """ args['epsilon'] = epsilon args['gamma'] = gamma args['alpha'] = alpha args['num_training'] = num_training self.index = 0 # This is always Pacman QLearningAgent.__init__(self, **args) def get_action(self, state): """ Simply calls the get_action method of QLearningAgent and then informs parent of action for Pacman. Do not change or remove this method. """ action = QLearningAgent.get_action(self, state) self.do_action(state, action) return action class ApproximateQAgent(PacmanQAgent): """ ApproximateQLearningAgent You should only have to overwrite get_q_value and update. All other QLearningAgent functions should work as is. """ def __init__(self, extractor='IdentityExtractor', **args): self.feat_extractor = util.lookup(extractor, globals())() PacmanQAgent.__init__(self, **args) self.weights = util.Counter() def get_weights(self): return self.weights def get_q_value(self, state, action): """ Should return Q(state,action) = w * feature_vector where * is the dot_product operator """ "*** YOUR CODE HERE ***" features = self.feat_extractor.get_features(state, action) value = 0 for feature in features: value += self.weights[feature] * features[feature] return value def update(self, state, action, next_state, reward): """ Should update your weights based on transition """ "*** YOUR CODE HERE ***" features = self.feat_extractor.get_features(state, action) difference = (reward + self.discount * self.get_value(next_state)) - self.get_q_value(state, action) for feature in features: self.weights[feature] += self.alpha * difference * features[feature] def final(self, state): "Called at the end of each game." # call the super-class final method PacmanQAgent.final(self, state) # did we finish training? if self.episodes_so_far == self.num_training: # you might want to print your weights here for debugging "*** YOUR CODE HERE ***" print (self.weights) pass
# Text Alchemy Text Alchemy App is a mobile application developed with Flutter. This application uses Google ML Kit to identify text in images taken from the gallery or camera. Users can capture images or select images from their device's gallery, and the application then identifies the text in the image and presents it to the user. Recognised text can optionally be stored on the device using the Hive package. ## Features - Text Recognition: This application uses Google ML Kit to identify text in images captured from the gallery or camera. - Image capture: Users can capture images directly from the app using the device's camera. - Image selection: Users can select images from their device's gallery to perform text recognition. - Text Presentation: The application identifies the text within the selected image and presents it to the user for easy viewing. - PDF output: Users can generate PDF output of the recognised text, providing a convenient way to store and share text information. - Image cropping: Users have the option to crop the selected image prior to text recognition, allowing for greater accuracy and customisation. - Text storage: Recognised text can optionally be stored on the device using the Hive package, allowing users to store and access recognised text for future use. - Simple interface: The application features a user-friendly interface, making it easy for users to perform text recognition tasks efficiently. - Impressive performance: Using Flutter and Google ML Kit, the application delivers impressive performance, ensuring a smooth and seamless text recognition experience. ## Built With - [Flutter](https://flutter.dev/) - [Dart](https://dart.dev/) ## Preview <p> <img src="screenshots/home.png" width="19%"/> <img src="screenshots/pinned.png" width="19%"/> <img src="screenshots/detail.png" width="19%"/> <img src="screenshots/pdf.png" width="19%"/> <img src="screenshots/crop.png" width="19%"/> </p> ## Packages - State Management - [Bloc](https://pub.dev/packages/flutter_bloc) - [Provider](https://pub.dev/packages/provider) - Caching - [Hive](https://pub.dev/packages/hive) - [HydratedBloc](https://pub.dev/packages/hydrated_bloc) - Routing - [AutoRoute](https://pub.dev/packages/auto_route) - Dependency Injection - [GetIt](https://pub.dev/packages/get_it) - Google MlKit Text Recognition - [GoogleMlKitTextRecognition](https://pub.dev/packages/google_mlkit_text_recognition)
import anndata import diffrax import equinox as eqx import jax import jax.numpy as jnp import optax from diffrax import diffeqsolve, Euler, Dopri8, Tsit5 from jax import random, grad, jit from joblib import Parallel, delayed from tqdm import tqdm import numpy as np import warnings warnings.filterwarnings('ignore') from scipy.integrate import solve_ivp from scipy.optimize import Bounds, minimize def fit_ode_scipy(u_data, s_data, t_data, initial_guess=[1, 1, 1]): """ Fit the RNA velocity ODE model to the data using scipy.optimize.minimize for vectorized parameters, ensuring alpha, beta, gamma are non-negative. :param u_data: Unspliced RNA expression feature matrix with shape (n_samples, n_features). :param s_data: Spliced RNA expression feature matrix with shape (n_samples, n_features). :param t_data: Time points corresponding to the data with shape (n_samples,). :param initial_guess: Initial guess for the parameters [alpha, beta, gamma]. :return: Estimated parameters alpha, beta, gamma, each a vector with length n_features. """ n_features = u_data.shape[1] alpha_est, beta_est, gamma_est = np.zeros(n_features), np.zeros(n_features), np.zeros(n_features) # Define bounds for alpha, beta, gamma to be non-negative parameter_bounds = Bounds([0, 0, 0], [np.inf, np.inf, np.inf]) for i in range(n_features): # Extract the data for the current feature u_feature_data = u_data[:, i] s_feature_data = s_data[:, i] # Define the cost function for the current feature def cost_function(params): alpha, beta, gamma = params # System of ODEs def system_of_odes(t, y): u, s = y du_dt = alpha - beta * u ds_dt = beta * u - gamma * s return [du_dt, ds_dt] # Initial conditions initial_conditions = [u_feature_data[0], s_feature_data[0]] # Solve the ODEs solution = solve_ivp(system_of_odes, (t_data[0], t_data[-1]), initial_conditions, t_eval=t_data, method='DOP853', max_step=16 ** 4) u_pred, s_pred = solution.y # Calculate the cost (sum of squared differences) cost = np.sum((u_feature_data - u_pred) ** 2) + np.sum((s_feature_data - s_pred) ** 2) # print(alpha, beta, gamma) return cost # Run the optimization for the current feature with bounds result = minimize(cost_function, initial_guess, method='Powell', bounds=parameter_bounds) # Extract the optimized parameters for the current feature alpha_est[i], beta_est[i], gamma_est[i] = result.x return alpha_est, beta_est, gamma_est class RNAvelo_jax(eqx.Module): alpha: jnp.array beta: jnp.array gamma: jnp.array feature_size: int def __init__(self, feature_size, *, key, **kwargs): """ define the RNA velocity function for all features, parameters are constrained to positive values through the exponential function. :param feature_size: number of features of the datasets :param key: necessary parameters for equinox :param kwargs: necessary parameters for equinox """ super().__init__(**kwargs) self.feature_size = feature_size self.alpha = jnp.ones(feature_size) self.beta = jnp.ones(feature_size) self.gamma = jnp.ones(feature_size) def __call__(self, t, x, args): u = x[:self.feature_size] s = x[self.feature_size:] du = self.alpha - self.beta * u ds = self.beta * u - self.gamma * s return jnp.concatenate([du, ds]) class NeuralODE(eqx.Module): func: RNAvelo_jax def __init__(self, feature_size, *, key, **kwargs): """ Define neuralODE modual for clean forward pass :param feature_size: number of features of the datasets :param key: necessary parameters for equinox :param kwargs: necessary parameters for equinox """ super().__init__(**kwargs) self.func = RNAvelo_jax(feature_size, key=key) def __call__(self, ts, y0): """ Forward pass to infer the future states :param ts: the future time point :param y0: the first state :return: future states corresponding to future time points """ solution = diffeqsolve( diffrax.ODETerm(self.func), Dopri8(), t0=ts[0], t1=ts[-1], dt0=ts[1] - ts[0], y0=y0, stepsize_controller=diffrax.PIDController(rtol=1e-3, atol=1e-6), saveat=diffrax.SaveAt(ts=ts), max_steps=16 ** 4, throw=False, ) return solution.ys def fit_ode_jax(u, s, t, num_iter=1000): """ fit the RNA velocity function to find the unknown coefficients $\alpha$, $\beta$, $\gamma$ :param u: unspliced RNA expression feature matrix with shape as (n, m) :param s: spliced RNA expression feature matrix with shape as (n, m) :param t: time points for each sample, shape as (n,) :param num_iter: number of iterations in the optimization step :param solver: specific solver used in the initial value problem. :return: $\alpha$, $\beta$ and $\gamma$, each with shape as (1, m) """ u = jnp.array(u, dtype=jnp.float32) s = jnp.array(s, dtype=jnp.float32) expression_matrix = jnp.concatenate([u, s], axis=1) pseudo_time = jnp.array(t, dtype=jnp.float32) feature_size = u.shape[1] model = NeuralODE(feature_size=feature_size, key=random.PRNGKey(0), ) @eqx.filter_value_and_grad def grad_loss(model, t, y): y_pred = model(t, y[0]) loss = jnp.sum(jnp.abs(y - y_pred)) return loss @eqx.filter_jit def make_step(ti, yi, model, opt_state): total_loss, grads = grad_loss(model, ti, yi) updates, opt_state = optim.update(grads, opt_state, model) model = eqx.apply_updates(model, updates) # Project the parameters to the feasible region [0, infinity) new_alpha = jnp.maximum(model.func.alpha, 0) new_beta = jnp.maximum(model.func.beta, 0) new_gamma = jnp.maximum(model.func.gamma, 0) # Update the model with the projected parameters model = eqx.tree_at(lambda m: m.func.alpha, model, new_alpha) model = eqx.tree_at(lambda m: m.func.beta, model, new_beta) model = eqx.tree_at(lambda m: m.func.gamma, model, new_gamma) return total_loss, model, opt_state optim = optax.adam(learning_rate=1e-1) opt_state = optim.init(eqx.filter(model, eqx.is_inexact_array)) for iter in range(num_iter): total_loss, model, opt_state = make_step(pseudo_time, expression_matrix, model, opt_state) # After training alpha, beta, gamma = model.func.alpha, model.func.beta, model.func.gamma # clear the cache jax.clear_caches() return alpha, beta, gamma def process_group(adata, group_key, group_value, pt_key='palantir_pseudotime', gene_list=None, vkey=None, num_iter=100, optimizer=None): """ helper function for parallelization :param adata: adata with necessary attributes :param group_key: the name of the group, should be stored in adata.obs[group] :param group_value: name for each group of cells :param pt_key: pseudo-time key :param gene_list: selected a list of genes to calculate kinetics parameters, if None, all genes will be involved in calculation. :param num_iter: number of optimization iterations :param vkey: stored key of recalculated RNA velocity in adata.layers. Should specify the key for "unspliced_velocity" and "spliced_velocity" clearly. :return: adata stored with kinetics information """ # Subset for the specific group adata = adata[adata.obs[group_key] == group_value].copy() # make t strictly increased t = adata.obs[pt_key].values noise_scale = (t.max() - t.min()) * 0.005 # 0.5% noise noise = np.abs(np.random.normal(0, noise_scale, t.size)) t = t + noise sorted_indices = np.argsort(t) adata = adata[sorted_indices,].copy() t = t[sorted_indices] # Identify indices of selected genes gene_indices = [i for i, gene in enumerate(adata.var.index) if gene in gene_list] if gene_list is not None else range(adata.shape[1]) n_samples = adata.shape[0] # Initialize the kinetics parameter arrays alpha = np.zeros((n_samples, adata.shape[1])) beta = np.zeros_like(alpha) gamma = np.zeros_like(alpha) # Initialize the velocity layers adata.layers[vkey['unspliced_velocity']] = np.zeros(adata.shape) adata.layers[vkey['spliced_velocity']] = np.zeros(adata.shape) # Kinetics parameter fitting if len(gene_indices) <= 100 or optimizer == 'scipy': alpha_fit, beta_fit, gamma_fit = fit_ode_scipy(adata.layers['Mu'][:, gene_indices], adata.layers['Ms'][:, gene_indices], t) elif len(gene_indices) > 100 or optimizer == 'jax': alpha_fit, beta_fit, gamma_fit = fit_ode_jax(adata.layers['Mu'][:, gene_indices], adata.layers['Ms'][:, gene_indices], t=t, num_iter=num_iter) # Fill the arrays with fitted values for selected genes for j, gene_idx in enumerate(gene_indices): alpha[:, gene_idx] = alpha_fit[j] beta[:, gene_idx] = beta_fit[j] gamma[:, gene_idx] = gamma_fit[j] # Store kinetics parameters in adata adata.layers['alpha'] = alpha adata.layers['beta'] = beta adata.layers['gamma'] = gamma # Calculate and store velocity layers for selected genes for gene_idx in gene_indices: adata.layers[vkey['spliced_velocity']][:, gene_idx] = adata.layers['Mu'][:, gene_idx] * beta[:, gene_idx] - \ adata.layers['Ms'][:, gene_idx] * gamma[:, gene_idx] adata.layers[vkey['unspliced_velocity']][:, gene_idx] = alpha[:, gene_idx] - adata.layers['Mu'][:, gene_idx] * beta[:, gene_idx] return adata def coarse_grained_kinetics(adata, group_key, pt_key='palantir_pseudotime', gene_list=None, vkey: dict = {'unspliced_velocity': "unspliced_velocity", 'spliced_velocity': "spliced_velocity"}, optimizer=None, num_iter=100, n_jobs=-1): """ group-mode kinetics parameters inference. Assume each group of cells have the same kinetics parameters, and then solve the RNA velocity ODE with the neuralODE solver. All cells in the same group will have the same inferred kinetics parameters :param adata: anndata with necessary attributes like unspliced and spliced expression value saved in layers :param group_key: the key for the group, like "clusters", "cell_type", should be stored in adata.obs :param pt_key: pseudo-time key to retrieve the pseudo-time value, should be stored in adata.obs :param gene_list: selected a list of genes to calculate kinetics parameters, if None, all genes will be involved in calculation. :param vkey: stored key of recalculated RNA velocity in adata.layers. Should specify the key for "unspliced_velocity" and "spliced_velocity" clearly. :param num_iter: number of iterations in the optimization steps :param n_jobs: number of cores for parallelization computation. -1 means use all cores. :return: adata stored with group-level kinetics information """ adata_obsp = adata.obsp.copy() adata_uns = adata.uns.copy() group_values = adata.obs[group_key].value_counts().index # Run the processing in parallel adata_list = Parallel(n_jobs=n_jobs, prefer="processes", backend='loky')( delayed(process_group)(adata, group_key, group_value, gene_list=gene_list, pt_key=pt_key, vkey=vkey, num_iter=num_iter, optimizer=optimizer) for group_value in tqdm(group_values)) # Concatenate the results adata = anndata.concat(adata_list, axis=0) adata.obsp = adata_obsp adata.uns = adata_uns return adata def process_cell(cell_idx, adata, pt_key, num_iter, adj, gene_list, optimizer='jax'): """ helper function for parallelization, each cell's neighbors are fetched and used to fit the RNA velocity. :param cell_idx: cell index used in this cell :param adata: adata for all cells :param pt_key: pseudo-time key in adata.obs :param num_iter: number of optimization iteration :param adj: predefined adjacency matrix, like the knn distances matrix :return: alpha, beta, and gamma for this cell """ neighbor_indices = adj[cell_idx].nonzero()[1] s = adata.layers['Ms'][neighbor_indices, :] u = adata.layers['Mu'][neighbor_indices, :] # print(gene_list) s = s[:, gene_list] u = u[:, gene_list] t = adata.obs[pt_key][neighbor_indices].values noise_scale = (t.max() - t.min()) * 0.005 # 0.5% noise noise = np.abs(np.random.normal(0, noise_scale, t.size)) t = t + noise sorted_indices = np.argsort(t) s = s[sorted_indices,] u = u[sorted_indices,] t = t[sorted_indices] if optimizer == 'jax': alpha, beta, gamma = fit_ode_jax(u, s, t, num_iter=num_iter) elif optimizer == 'scipy': alpha, beta, gamma = fit_ode_scipy(u, s, t) else: raise ValueError('Please choose the optimizer from ["jax", "scipy"]') return alpha, beta, gamma def high_resolution_kinetics(adata, pt_key='palantir_pseudotime', gene_list=None, vkey={'unspliced_velocity': "unspliced_velocity", 'spliced_velocity': "spliced_velocity"}, num_iter=100, n_jobs=-1, optimizer=None): """ cell-level kinetics parameters inference. Assume each cell and its neighbors have the same kinetics parameters, and then solve the RNA velocity ODE with the neuralODE solver. After calculation, each cell's kinetics parameters are different :param adata: anndata with necessary information :param pt_key: pseudo-time key to retrieve the pseudo-time value, should be stored in adata.obs :param gene_list: selected a list of genes to calculate kinetics parameters, if None, all genes will be involved in calculation. :param vkey: stored key of recalculated RNA velocity in adata.layers. Should specify the key for "unspliced_velocity" and "spliced_velocity" clearly. :param num_iter: number of optimization iteration :param n_jobs: number of cores for parallelization computation. -1 means use all cores. :param optimizer: choose between ['jax', 'scipy'], 'jax' means using jax with gradient descent to optimize and is suitable for all genes calculation. 'scipy' will use scipy with L-BFGS-B optimizer which is suitable for selected small number of genes. :return: adata stored with group-level kinetics information """ adata_obsp = adata.obsp.copy() adata_uns = adata.uns.copy() # Identify indices of selected genes gene_indices = [i for i, gene in enumerate(adata.var.index) if gene in gene_list] if gene_list is not None else range(adata.shape[1]) if len(gene_indices) <= 100 and optimizer is None: optimizer = 'scipy' # Initialize the velocity layers adata.layers[vkey['unspliced_velocity']] = np.zeros(adata.shape) adata.layers[vkey['spliced_velocity']] = np.zeros(adata.shape) # Prepare arrays for kinetics parameters alpha = np.zeros((adata.shape[0], adata.shape[1])) beta = np.zeros_like(alpha) gamma = np.zeros_like(alpha) # Parallel processing of cells for selected genes results = Parallel(n_jobs=n_jobs, prefer="processes", backend='loky')( delayed(process_cell)(cell_idx, adata, pt_key, num_iter, adj=adata_obsp['connectivities'], gene_list=gene_indices, optimizer=optimizer) for cell_idx in tqdm(range(adata.shape[0]))) # Store results only for selected genes for i, result in enumerate(results): for j, gene_idx in enumerate(gene_indices): alpha[i, gene_idx] = result[0][j] beta[i, gene_idx] = result[1][j] gamma[i, gene_idx] = result[2][j] # Store kinetics parameters in adata adata.layers['alpha'] = alpha adata.layers['beta'] = beta adata.layers['gamma'] = gamma # Calculate and store velocity layers for selected genes for gene_idx in gene_indices: adata.layers[vkey['spliced_velocity']][:, gene_idx] = adata.layers['Mu'][:, gene_idx] * beta[:, gene_idx] - \ adata.layers['Ms'][:, gene_idx] * gamma[:, gene_idx] adata.layers[vkey['unspliced_velocity']][:, gene_idx] = alpha[:, gene_idx] - adata.layers['Mu'][:, gene_idx] * beta[:, gene_idx] # Restore original adata.obsp and adata.uns adata.obsp = adata_obsp adata.uns = adata_uns return adata def process_raw(cell_idx, u=None, s=None, t=None, adj=None, num_iter=1000, optimizer='scipy'): neighbor_indices = adj[cell_idx].nonzero()[0] s = s[neighbor_indices, :] u = u[neighbor_indices, :] t = t[neighbor_indices] noise_scale = (t.max() - t.min()) * 0.005 # 0.5% noise noise = np.abs(np.random.normal(0, noise_scale, t.size)) t = t + noise sorted_indices = np.argsort(t) s = s[sorted_indices,] u = u[sorted_indices,] t = t[sorted_indices] if optimizer == 'scipy': alpha, beta, gamma = fit_ode_scipy(u, s, t) elif optimizer == 'jax': alpha, beta, gamma = fit_ode_jax(u, s, t) return alpha, beta, gamma def high_resolution_raw(u, s, t, adj, num_iter=100, n_jobs=-1, optimizer='scipy'): # Initialize matrices alpha = np.zeros((u.shape[0], u.shape[1])) beta = np.zeros((u.shape[0], u.shape[1])) gamma = np.zeros((u.shape[0], u.shape[1])) results = Parallel(n_jobs=n_jobs, prefer="processes", backend='loky')( delayed(process_raw)(cell_idx, u, s, t, adj, num_iter, optimizer) for cell_idx in tqdm(range(u.shape[0]))) for i, (alpha_i, beta_i, gamma_i) in enumerate(results): alpha[i,] = alpha_i beta[i,] = beta_i gamma[i,] = gamma_i return alpha, beta, gamma def kinetics_inference(adata: anndata.AnnData = None, pt_key: str = None, mode: str = 'high-resolution', group_key=None, gene_list=None, vkey: dict = {'unspliced_velocity': "unspliced_velocity", 'spliced_velocity': "spliced_velocity"}, n_jobs: int = 1, num_iter: int = 200, optimizer: str = None, ) -> anndata.AnnData: """ Infer the kinetics parameters of RNA velocity equations. It has two modes, "coarse-grained" or "high-resolution" mode, based on the assumption that each group of cell or each cell and its neighbors share the same kinetics parameters, respectively. For "coarse-grained" mode, the kinetic parameters for cells within a group will be the same but different between genes. For "high-resolution" mode, each cell and each gene's kinetic parameters will be different. The inference methods involve fitting a RNA velocity function using neuralODE solvers. :param adata: single-cell RNA-seq data with annotated pseudo-time. :param pt_key: pseudo-time key for retrieving pseudo-time in adata.obs. :param mode: support two modes "coarse-grained" and "high-resolution". :param group_key: only be used when the mode is "coarse-grained", which is necessary. :param gene_list: selected list of genes to calculate kinetics paramter, if None, all genes will be involved in calculation. :param vkey: stored key of recalculated RNA velocity in adata.layers. Should specify the key for "unspliced_velocity" and "spliced_velocity" clearly. :param n_jobs: number of cores for parallelization computation. -1 means use all cores. :param num_iter: number of optimization iteration :return: """ if mode == 'coarse-grained': adata = coarse_grained_kinetics(adata, group_key, pt_key=pt_key, vkey=vkey, gene_list=gene_list, num_iter=num_iter, n_jobs=n_jobs, optimizer=optimizer) elif mode == 'high-resolution': adata = high_resolution_kinetics(adata, pt_key=pt_key, gene_list=gene_list, vkey=vkey, num_iter=num_iter, n_jobs=n_jobs, optimizer=optimizer) else: raise ValueError( "please make sure the mode is correct selected, only 'coarse-grained' and 'high-resolution' are valid and supported") return adata
using Atilim.Services.Identity.Application.Dtos.LessonDtos; using Atilim.Services.Identity.Application.Interfaces.StudentInterfaces; using Atilim.Shared.Dtos; using AutoMapper; using MediatR; namespace Atilim.Services.Identity.Application.Features.Queries.LessonQueries { public class GetLessonByIdQuery : IRequest<ResponseDto<LessonDto>> { public int Id { get; set; } public class GetLessonByIdQueryHandler : IRequestHandler<GetLessonByIdQuery, ResponseDto<LessonDto>> { private readonly ILessonService _lessonService; private readonly IMapper _mapper; public GetLessonByIdQueryHandler(ILessonService lessonService) { _lessonService = lessonService ?? throw new ArgumentNullException(nameof(lessonService)); } public async Task<ResponseDto<LessonDto>> Handle(GetLessonByIdQuery request, CancellationToken cancellationToken) { var lesson = await _lessonService.GetLessonByIdAsync(request.Id); if (lesson is not null) { var lessonDto = _mapper.Map<LessonDto>(lesson); return ResponseDto<LessonDto>.Success(lessonDto, System.Net.HttpStatusCode.OK); } return ResponseDto<LessonDto>.Fail($"{request.Id} Id'li ders bulunamadı!!!", System.Net.HttpStatusCode.NotFound); } } } }
from fastapi import FastAPI, HTTPException, Request from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse from exceptions import StoryException from routers import blog_get, blog_post, user, article, product, file, dependencies from auth import authentication from templates import templates from db import models from db.database import engine from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.websockets import WebSocket import time from client import html app = FastAPI() app.include_router(dependencies.router) app.include_router(templates.router) app.include_router(authentication.router) app.include_router(file.router) app.include_router(user.router) app.include_router(article.router) app.include_router(blog_get.router) app.include_router(blog_post.router) app.include_router(product.router) # @app.get('/') # def index(): # return { 'message' : 'Hello world!'} @app.exception_handler(StoryException) def story_exception_handler(request: Request, exc: StoryException): return JSONResponse( status_code=418, content={ 'detail': exc.name} ) # @app.exception_handler(HTTPException) # def custom_handler(request: Request, exc: StoryException): # return PlainTextResponse(str(exc), status_code=400) @app.get("/") async def get(): return HTMLResponse(html) clients = [] @app.websocket("/chat") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() clients.append(websocket) while(True): data = await websocket.receive_text() for client in clients: await client.send_text(f'{data}') models.Base.metadata.create_all(engine) @app.middleware("http") async def add_middleware(request: Request, call_next): start_time = time.time() response = await call_next(request) duration = time.time() - start_time response.headers['duration'] = str(duration) return response origins = [ 'http://localhost:3000' ] app.add_middleware( CORSMiddleware, allow_origins = origins, allow_credentials = True, allow_methods = ["*"], allow_headers = ["*"] ) app.mount('/files', StaticFiles(directory='files'), name='files') app.mount('/templates/static', StaticFiles( directory="templates/static"), name="static" )
/** * FlexSpy 1.4-beta * * <p>Code released under WTFPL [http://sam.zoy.org/wtfpl/]</p> * @author Arnaud Pichery [http://coderpeon.ovh.org] * @author Frédéric Thomas */ package com.flexspy { import com.flexspy.impl.ComponentTreeWnd; import flash.display.DisplayObject; import flash.events.KeyboardEvent; import flash.external.ExternalInterface; import mx.core.FlexGlobals; /** * Entry point to use FlexSpy. */ public class FlexSpy { /** * Displays the tree of the specified DisplayObject (its children, the children of its children, etc.) * * @param root Root of the displayed tree. If it is null, the current application is used. * @param modal true to display a modal window (default), false to display a modeless window. * @param childList The PopUpManagerChildList you want the popup be added to, see mx.managers.PopUpManagerChildList */ public static function show(root:DisplayObject = null, modal:Boolean = false, childList:String = null):void { ComponentTreeWnd.show(root, modal, childList); } /** * Registers a key sequence that will trigger the appearance of the FlexSpy window. * * @param key Sequence of keys to press to display the FlexSpy window. * @param root Root of the displayed tree. If set to <code>null</code> the root window * of the application is used. * @param modal true to display a modal window (default), false to display a modeless window. */ public static function registerKey(key:KeySequence, root:DisplayObject = null, modal:Boolean = false):void { if (root == null) { root = DisplayObject(FlexGlobals.topLevelApplication); } root.addEventListener(KeyboardEvent.KEY_DOWN, function (event:KeyboardEvent):void { if (key.isPressed(event)) { show(root, modal); } }); } /** * Registers an ActionScript method as callable from JavaScript in the container. * * @param root Root of the displayed tree. If set to <code>null</code> the root window * of the application is used. * @param modal true to display a modal window (default), false to display a modeless window. * @param functionName The JS function's name you want to show FlexSpy */ public static function registerJS(root:DisplayObject = null, modal:Boolean = false, functionName:String = "flexSpy"):void { if (root == null) { root = DisplayObject(FlexGlobals.topLevelApplication); } if (ExternalInterface.available) { ExternalInterface.addCallback(functionName, function ():void { show(root, modal); }); } } } }
require "random_data" 5.times do User.create!( name: RandomData.random_name, email: RandomData.random_email, password: RandomData.random_sentence ) end users = User.all 15.times do Topic.create!( name: RandomData.random_sentence, description: RandomData.random_paragraph ) end topics = Topic.all 50.times do post = Post.create!( user: users.sample, topic: topics.sample, title: RandomData.random_sentence, body: RandomData.random_paragraph ) post.update_attribute(:created_at, rand(10.minutes .. 1.year).ago) rand(1..5).times { post.votes.create!(value: [-1, 1].sample, user: users.sample) } end posts = Post.all 100.times do Comment.create!( user: users.sample, post:posts.sample, body: RandomData.random_paragraph ) end 10.times do Question.create!( title: RandomData.random_sentence, body: RandomData.random_paragraph ) end questions = Question.all # 15.times do # Sponsored_Post.create!( # topic: topics.sample, # title: RandomData.random_sentence, # body: RandomData.random_paragraph # ) # end # sponsored_posts = Sponsored_Post.all admin = User.create!( name: 'Admin User', email: '[email protected]', password: 'helloworld', role: 'admin' ) member = User.create!( name: 'Member User', email: '[email protected]', password: 'helloworld' ) puts "Seeds finished" puts "#{User.count} users created" puts "#{Topic.count} topics created" puts "#{Post.count} posts created" puts "#{Comment.count} comments created" puts "#{Vote.count} votes created" puts "#{Question.count} questions created" # puts "#{Sponsored_Post.count} sponsored post created"
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTicketsTable extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create('tickets', function (Blueprint $table) { $table->id(); $table->datetime('fecha_de_cierre'); $table->string('asunto'); $table->text('comentario'); $table->string('estatus')->comment('opciones: abierto, cerrado, pediente'); $table->integer('id_sla'); $table->string('categoria')->comment('opciones: equipo_de_computo, impresion, etc.'); $table->string('numero_de_serie'); $table->string('modelo'); $table->string('numero_de_activo')->comment('numero de inventario'); $table->string('prioridad_cliente'); $table->string('prioridad_agente'); $table->foreignId('parent_id')->constrained('tickets'); $table->foreignId('cliente_id')->constrained('users'); $table->foreignId('agente_id')->constrained('users'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tickets'); } }
import tensorflow as tf from tensorflow import keras from matplotlib import pyplot as plt import numpy as np import argparse import os from transfer_learning import load_model import random import sys sys.path.insert(1, 'path/to/TFRecord/') from reading_with_ParseFromString import count_total_num_samples BATCH_SIZE = 128 BATCH_SHUFFLE = 2000 def getArgs(argv=None): parser = argparse.ArgumentParser() parser.add_argument( "--dataset", type=str, required=True, help="Dataset name (e.g. standard or mix). This value determines the tfrecords filename's structure in split into training validation.") parser.add_argument( "--tfrecord_dir", type=str, required=True, help="Base folder containing TFRecord data.") parser.add_argument( "--dest_folder", type=str, required=True, help="Destination folder in which to save trained models") parser.add_argument( "--k_fold", type=int, required=True, help="Number of training process to perform") parser.add_argument( "--epochs", type=int, required=True, help="Number of training epochs + 1") parser.add_argument( '--pretrain', choices=('True','False'), required=True, help="Specify if you want to load pre-trained model weights." ) parser.add_argument( '--finetuning', choices=('True','False'), required=True, help="Specify if you want to perform finetuning on fully-connected layers." ) parser.add_argument( '--shuffle_dataset', choices=('True','False'), required=True, help="Specify whether to shuffle tfrecord files list or not before to split them into training and validation." ) parser.add_argument( "--learning_rate", type=float, required=True, help="Learning rate value") parser.add_argument( "--rateval", type=float, required=True, help="Dropout rate probability. Should be in [0.2, 0.5] (Srivastava et al. 2014).") return parser.parse_args(argv) def getVar(): args = getArgs() DNAME = args.dataset TFRECORD_DIR = args.tfrecord_dir DEST_FOLDER = args.dest_folder K_FOLD = args.k_fold EPOCHS = args.epochs PRETRAIN = args.pretrain == 'True' FINETUNING = args.finetuning == 'True' SHUFFLE = args.shuffle_dataset == 'True' LR = args.learning_rate RATEVAL = args.rateval return DNAME, TFRECORD_DIR, DEST_FOLDER, K_FOLD, EPOCHS, PRETRAIN, FINETUNING, SHUFFLE, LR, RATEVAL def split_into_training_validation(tfrecord_dir, i, dataset='mix', shuffle_dataset=False): """ Take as input the number that identifies the current training and based on it split the tfrecord chunks into training set and validation set. Return the file list of the training set and validation set. Input: tfrecord_dir: tfrecord source directory; i: training number (k-fold cross validation); dataset: based on the value of this string, the tfrecord filename's structure will change accordingly. If dataset='standard' so the tfrecords of type "train-*.tfrecord" will be considered. If dataset='mix' the filename structure changes in "*_train*" shuffle_dataset: Specify whether to shuffle tfrecord files list or not. #NOTE Only for single training tests. NO cross-validation. type: bool. Output: list of tfrecord filenames divided into training and validation set. Example: >>> list = np.arange(10) >>> n = len(list) >>> chunk_size = n*0.1 #set validation size >>> for number_of_training in range(10): >>> a = int(number_of_training*chunk_size) >>> b = int(a+chunk_size) >>> val = list[a:b] >>> train = np.delete(list,np.s_[a:b]) >>> print(val) >>> print(train) """ # To obtain the list of all tfrecord files in the folder ${tfrecord_dir} # filename template: <telescope_name>_train-<proc_id>.tfrecord. Example: tess_train-0.tfrecord if dataset == 'mix': tfrecord_files = tf.io.gfile.glob(tfrecord_dir + "*_train*") # returns a list of files that match the given pattern(s) elif dataset == 'standard': tfrecord_files = tf.io.gfile.glob(tfrecord_dir + "train-*") # returns a list of files that match the given pattern(s) else: print("Error in split_into_training_validation: you must specify the tfrecords filename's structure\n") #NOTE: Do not shuffle if you are in k-fold cross validation mode. if shuffle_dataset: random.shuffle(tfrecord_files) # Get number of tfrecord files n = len(tfrecord_files) # Set validation set size to 10% of dataset size chunk_size = n*0.1 a = int(i*chunk_size) if (n % 2) == 0: b = int(a+chunk_size) else: b = int(a+chunk_size)+1 if i>0: a+=1 b+=1 VALID_FILENAMES = tfrecord_files[a:b] TRAINING_FILENAMES = np.delete(tfrecord_files, np.s_[a:b]) return TRAINING_FILENAMES, VALID_FILENAMES # Decoding and read the data """ The following two methods are used to map the elements stored within the .tfrecord files TFRecord example: Global view: [201] This is the TCE being analyzed by the model av_training_set: 0 or 1 This is the TCE disposition """ def _feature_description_tfrecord(): feature_description = { 'av_training_set': tf.io.FixedLenFeature([], tf.int64, default_value=-1), 'global_view': tf.io.VarLenFeature(tf.float32), 'toi': tf.io.FixedLenFeature([], tf.int64, default_value=-1), 'tic': tf.io.FixedLenFeature([], tf.int64, default_value=-1), } return feature_description def _parse_function_tfrecord(example_proto): GLOBAL_VIEW_LENGTH = 201 # Parse the input 'tf.train.Example' proto using the dictionary above. feature_description = _feature_description_tfrecord() feature = tf.io.parse_single_example(example_proto, feature_description) label = feature['av_training_set'] feature["global_view"] = tf.reshape(tf.sparse.to_dense(feature['global_view']),[GLOBAL_VIEW_LENGTH]) sample_id = feature['toi'] #feature['tic'] when toi label is not present del feature['tic'] del feature['toi'] del feature['av_training_set'] # label, not feature ret_tuple = (feature, label) # Use when Training #ret_tuple = (feature, label, sample_id) # Use when Testing return ret_tuple def load_dataset(filenames, mode, d_name="kepler"): # Load dataset given TFRecords dataset = tf.data.TFRecordDataset(filenames) if mode == 'train': ignore_order = tf.data.Options() ignore_order.experimental_deterministic = False # disable order, increase speed dataset = dataset.with_options(ignore_order) # use the data as they are transmitted, instead of in their original order dataset = dataset.map(_parse_function_tfrecord) return dataset def parse_dataset(filenames, mode="train", d_name="kepler", shuffle=True, BATCH_SHUFFLE=BATCH_SHUFFLE, EPOCHS=50, BATCH_SIZE=BATCH_SIZE): dataset = load_dataset(filenames, mode, d_name) if shuffle == True: dataset = dataset.shuffle(buffer_size=BATCH_SHUFFLE) if mode == 'train': dataset = dataset.repeat(EPOCHS) dataset = dataset.batch(BATCH_SIZE, drop_remainder=True) dataset = dataset.prefetch(buffer_size=1) return dataset def _train_model(DNAME, TFRECORD_DIR, number_of_training, dest_folder, epochs, PRETRAIN, FINETUNING, SHUFFLE, prc_threshold_i, LR, RATEVAL): # Use number of training as model name MODEL_NAME = str(number_of_training) # When using k-fold cross validation, generate different training set as follows TRAINING_FILENAMES, VALID_FILENAMES = split_into_training_validation( TFRECORD_DIR, number_of_training, DNAME, SHUFFLE ) print("Training: {}\n Training files: {}\n Validation files: {}\n".format(number_of_training,TRAINING_FILENAMES,VALID_FILENAMES)) # Visualize input dname = "mix" train_dataset = parse_dataset(TRAINING_FILENAMES, d_name=dname, EPOCHS=epochs) valid_dataset = parse_dataset(VALID_FILENAMES, d_name=dname, EPOCHS=epochs) # Load model my_model = load_model('TESS', LR, RATEVAL, False, PRETRAIN, str(number_of_training), FINETUNING, prc_threshold_i) #class 1: PC; class 0: NPC. Count the number of samples for each class n_samples_class_1, n_samples_class_0 = count_total_num_samples(TFRECORD_DIR) print("Dataset size: PC={}; NPC={}\n".format(n_samples_class_1, n_samples_class_0)) DATASET_SIZE = n_samples_class_0 + n_samples_class_1 # Defining data split TRAINING_SPLIT = 0.9 VALIDATION_SPLIT = 0.1 n_classes = 2 cw_0 = DATASET_SIZE / (n_classes * n_samples_class_0) cw_1 = DATASET_SIZE / (n_classes * n_samples_class_1) # Define training steps for each epoch STEPS_PER_EPOCH = int(TRAINING_SPLIT * DATASET_SIZE / BATCH_SIZE) VALIDATION_STEPS = int(VALIDATION_SPLIT * DATASET_SIZE / BATCH_SIZE) # Class weighting wj = dataset_size / (n_classes * n_samples_classj) class_weight = {0: cw_0, 1: cw_1} print("Class weighting: NPC={}; PC={}\n".format(cw_0, cw_1)) # Callbacks checkpoint = keras.callbacks.ModelCheckpoint( filepath=dest_folder + MODEL_NAME + "/cp-best_model_{epoch:02d}.ckpt", save_weights_only=True, period=epochs-1, verbose=1, ) # The Model.fit method adjusts the model parameters to minimize the loss: history = my_model.fit( x=train_dataset, validation_data=valid_dataset, validation_steps=VALIDATION_STEPS, epochs=epochs, steps_per_epoch=STEPS_PER_EPOCH, class_weight=class_weight, callbacks=[checkpoint], verbose=1, ) return history def _plot_accuracy(h, path, number_of_training): plt.plot(h.history['accuracy']) plt.plot(h.history['val_accuracy']) plt.title('model accuracy - Training#' + number_of_training) plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'val'], loc='upper left') plt.savefig(path + "training_plot/accuracy_" + number_of_training + ".png") plt.close() def _plot_loss(h, path, number_of_training): plt.plot(h.history['loss']) plt.plot(h.history['val_loss']) plt.title('model loss - Training#' + number_of_training) plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'val'], loc='upper left') plt.savefig(path + "training_plot/loss_" + number_of_training + ".png") plt.close() def _plot_metrics(history, path, number_of_training): metrics = ['loss', 'prc', 'precision', 'recall'] for n, metric in enumerate(metrics): name = metric.replace("_"," ").capitalize() plt.subplot(2,2,n+1) plt.plot(history.epoch, history.history[metric], label='Train') plt.plot(history.epoch, history.history['val_'+metric], label='Val') plt.xlabel('Epoch') plt.ylabel(name) if metric == 'loss': plt.ylim([0, plt.ylim()[1]]) elif metric == 'auc': plt.ylim([0.8, 1]) else: plt.ylim([0, 1]) plt.legend() plt.savefig(path + "training_plot/training_" + number_of_training + ".png") plt.close() def main(): """ Input parameters: TFRECORD_DIR: folder in which input tfrecords are stored - DEST_FOLDER: path to the folder in which to save results - K_FOLD: number of training processes. 1 if Dropout. >1 when cross-validation - EPOCHS: number of training epochs - PRETRAIN: boolean value to specify whether or not to load pre-trained model weights with Kepler data - FINETUNING: boolean value to specify whether or not to fine-tune during training or train the entire model NOTE. [In _parse_function_tfrecord()] It is essential to comment the line "ret_tuple = (feature, label)" when testing the model. At the same time, the corresponding line below (ret_tuple = (feature, label, sample_id)) has to be decommented of course. """ # Get input parameters DNAME, TFRECORD_DIR, DEST_FOLDER, K_FOLD, EPOCHS, PRETRAIN, FINETUNING, SHUFFLE, LR, RATEVAL = getVar() # Create the directory in which to save the trained model os.mkdir(DEST_FOLDER) os.mkdir(DEST_FOLDER + 'training_plot') # K-fold cross validation. Set to 1 if Dropout for i in range(K_FOLD): h = _train_model(DNAME, TFRECORD_DIR, i, DEST_FOLDER, EPOCHS, PRETRAIN, FINETUNING, SHUFFLE, 0.5, LR, RATEVAL) #i+1 try: _plot_metrics(h, DEST_FOLDER, str(i)) #i+1 except: print("Errore nel plot del training {}\n".format(i)) if __name__ == '__main__': main()
import os # Function to display the banner def display_banner(): print("======TO DO LIST======") # Function to add a new task def add_new_task(): os.system('cls' if os.name == 'nt' else 'clear') display_banner() task = input("Enter your new task: ") save = input("Save? (y/n): ") if save.lower() == 'y': with open("todo.txt", "a") as file_out: file_out.write(f"Task: {task}\n") more = input("Do you want to add more tasks? (y/n): ") if more.lower() == 'y': add_new_task() else: os.system('cls' if os.name == 'nt' else 'clear') print("Tasks added successfully.") # Function to display all tasks def show_all_tasks(): os.system('cls' if os.name == 'nt' else 'clear') display_banner() print("Tasks:") with open("todo.txt", "r") as file_in: for line in file_in: print(line.strip()) # Function to search for a specific task def search_for_task(): os.system('cls' if os.name == 'nt' else 'clear') display_banner() task = input("Enter task to search: ") found = False with open("todo.txt", "r") as file_in: for line in file_in: if task in line: print(f"Task found: {line.strip()}") found = True if not found: print("Task not found.") # Function to delete a task def remove_task(): os.system('cls' if os.name == 'nt' else 'clear') display_banner() task = input("Enter the task to delete: ") found = False with open("todo.txt", "r") as file_in, open("temp.txt", "w") as temp_file: for line in file_in: if task in line: print(f"Task deleted: {line.strip()}") found = True else: temp_file.write(line) if not found: print("Task not found.") os.remove("todo.txt") os.rename("temp.txt", "todo.txt") # Function to update an existing task def modify_task(): os.system('cls' if os.name == 'nt' else 'clear') display_banner() task = input("Enter the task to update: ") found = False with open("todo.txt", "r") as file_in, open("temp.txt", "w") as temp_file: for line in file_in: if task in line: new_task = input("Enter the new task: ") temp_file.write(f"Task: {new_task}\n") print("Task updated successfully.") found = True else: temp_file.write(line) if not found: print("Task not found.") os.remove("todo.txt") os.rename("temp.txt", "todo.txt") # Main function to display the menu and handle user input def main(): os.system('cls' if os.name == 'nt' else 'clear') while True: display_banner() print("\t1. Add task") print("\t2. Show tasks") print("\t3. Search task") print("\t4. Delete task") print("\t5. Update task") choice = input("Enter choice: ") if choice == '1': add_new_task() elif choice == '2': show_all_tasks() elif choice == '3': search_for_task() elif choice == '4': remove_task() elif choice == '5': modify_task() else: print("Invalid choice. Please try again.") if __name__ == "__main__": main()
// // NetworkManager.swift // GetOutfit // // Created by Алёна Максимова on 07.04.2022. // import Foundation protocol OccasionManagerDelegate { func didUpdateWeather(_ occasionManager: OccasionManager, occasion: OccasionModel) func didFailWithError(error: Error) } struct OccasionManager { // spb.getoutfit.co:3000/items?category_id=eq.1598&color=like.*Красный*&price=lte.100000&gender=like.*female* var delegate: OccasionManagerDelegate? let occasionUrl = "http://spb.getoutfit.co:3000/items?" func fetchParametrs(style: String, colorTheme: [String], budget: Int, gender: String) { let urlString = "\(occasionUrl)categories=eq.{\(style)}&color=like.*\( colorTheme.randomElement()!)*&price=lte.\(budget)&gender=like.*\(gender)*" print(urlString) performRequest(with: urlString) } func performRequest(with urlString: String) { if let url = URL(string: urlString) { let session = URLSession(configuration: .default) let task = session.dataTask(with: url) { (data, response, error) in if error != nil { self.delegate?.didFailWithError(error: error!) return } if let safeData = data { self.parseJSON(safeData) } } task.resume() } } func parseJSON(_ occasionData: Data) -> OccasionModel? { let decoder = JSONDecoder() do { let decodedData = try decoder.decode(OccasionData.self, from: occasionData) let name = decodedData.name let price = decodedData.price let picture = decodedData.picture let occasion = OccasionModel(name: name, price: price, picture: picture) return occasion } catch { delegate?.didFailWithError(error: error) return nil } } }
// // SignUpViewController.swift // BEERLY // // Created by Zhansuluu Kydyrova on 14/7/23. // import UIKit import SnapKit class SignUpViewController: UIViewController { var presentor: SignUpPresentorDelegate? private var phoneNumber: String? private var isPasswordHidden = true init(phoneNumber: String?) { super.init(nibName: nil, bundle: nil) self.phoneNumber = phoneNumber } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var registrationLabel: UILabel = { var label = UILabel() label.text = "Create account" label.textColor = .white label.numberOfLines = 0 label.font = .systemFont(ofSize: 27, weight: .heavy) label.layer.shadowOffset = CGSize(width: 0.0, height: 5) label.layer.shadowOpacity = 0.2 return label }() private lazy var emailTextField: UITextField = { var textField = UITextField() textField.placeholder = "Email" textField.textColor = .gray return textField }() private lazy var passwordTextField: UITextField = { var textField = UITextField() textField.placeholder = "Password" textField.isSecureTextEntry = true textField.textColor = .gray return textField }() private lazy var nameTextField: UITextField = { var textField = UITextField() textField.placeholder = "Name" textField.textColor = .gray return textField }() private lazy var adressTextField: UITextField = { var textField = UITextField() textField.placeholder = "Address" textField.textColor = .gray return textField }() private lazy var showPassword: UIButton = { var button = UIButton() button.setImage(UIImage(systemName: "eye"), for: .normal) button.tintColor = .white button.addTarget(self, action: #selector(showHidePassword), for: .touchUpInside) return button }() private lazy var signUpButton: UIButton = { var button = UIButton() button.titleLabel?.font = .systemFont(ofSize: 20, weight: .medium) button.setTitle("Sign up", for: .normal) button.backgroundColor = UIColor( red: 240/265, green: 240/265, blue: 240/265, alpha: 0.8) button.setTitleColor(.white, for: .normal) button.layer.shadowOffset = CGSize(width: 0.0, height: 5) button.layer.shadowOpacity = 0.2 button.layer.cornerRadius = 25 button.addTarget(self, action: #selector(saveRegistrationData), for: .touchUpInside) return button }() private lazy var errorMessage: UILabel = { var label = UILabel() label.textColor = .red label.numberOfLines = 0 label.font = .systemFont(ofSize: 15, weight: .regular) return label }() override func loadView() { super.loadView() setUpUI() } private func setUpUI() { setUpSubviews() setUpConstraints() view.backgroundColor = UIColor( red: 0.88, green: 0.868, blue: 0.962, alpha: 1) } private func setUpSubviews() { view.addSubview(registrationLabel) view.addSubview(emailTextField) view.addSubview(passwordTextField) view.addSubview(showPassword) view.addSubview(nameTextField) view.addSubview(adressTextField) view.addSubview(signUpButton) view.addSubview(errorMessage) } private func setUpConstraints() { registrationLabel.snp.makeConstraints { maker in maker.top.equalToSuperview().offset(170) maker.left.equalToSuperview().offset(40) maker.width.equalTo(250) maker.height.equalTo(40) } emailTextField.snp.makeConstraints { maker in maker.top.equalTo(registrationLabel.snp.bottom).offset(50) maker.left.equalToSuperview().offset(40) maker.right.equalToSuperview().offset(-40) maker.height.equalTo(60) } passwordTextField.snp.makeConstraints { maker in maker.top.equalTo(emailTextField.snp.bottom).offset(30) maker.left.equalToSuperview().offset(40) maker.right.equalToSuperview().offset(-40) maker.height.equalTo(60) } showPassword.snp.makeConstraints { maker in maker.centerY.equalTo(passwordTextField) maker.right.equalTo(passwordTextField).offset(-40) maker.width.equalTo(40) maker.height.equalTo(20) } nameTextField.snp.makeConstraints { maker in maker.top.equalTo(passwordTextField.snp.bottom).offset(30) maker.left.equalToSuperview().offset(40) maker.right.equalToSuperview().offset(-40) maker.height.equalTo(60) } adressTextField.snp.makeConstraints { maker in maker.top.equalTo(nameTextField.snp.bottom).offset(30) maker.left.equalToSuperview().offset(40) maker.right.equalToSuperview().offset(-40) maker.height.equalTo(60) } signUpButton.snp.makeConstraints { maker in maker.top.equalTo(adressTextField.snp.bottom).offset(40) maker.left.equalToSuperview().offset(40) maker.right.equalToSuperview().offset(-40) maker.height.equalTo(60) } errorMessage.snp.makeConstraints { maker in maker.top.equalTo(signUpButton.snp.bottom).offset(30) maker.left.equalToSuperview().offset(40) maker.right.equalToSuperview().offset(-40) } } @objc func saveRegistrationData() { guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text, let adress = adressTextField.text, email.count != 0, password.count != 0, name.count != 0, adress.count != 0 else { wrongData() return } let user = User(email: emailTextField.text!, password: passwordTextField.text!, uid: "") let addInfo = UserAdditionalInfo(name: nameTextField.text!, address: adressTextField.text!, phoneNum: phoneNumber!, image: Data()) print(user) presentor?.signUp(user: user, additionalInfo: addInfo) } private func wrongData() { emailTextField.textColor = .red nameTextField.textColor = .red adressTextField.textColor = .red passwordTextField.textColor = .red emailTextField.placeholder = "Invalid format" nameTextField.placeholder = "Invalid format" adressTextField.placeholder = "Invalid format" passwordTextField.placeholder = "Invalid format" DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak self] in self?.emailTextField.textColor = .gray self?.nameTextField.textColor = .gray self?.adressTextField.textColor = .gray self?.passwordTextField.textColor = .gray self?.emailTextField.placeholder = "Email" self?.nameTextField.placeholder = "Name" self?.adressTextField.placeholder = "Adress" self?.passwordTextField.placeholder = "Password" } } @objc private func showHidePassword() { if isPasswordHidden { passwordTextField.isSecureTextEntry = false showPassword.setImage(UIImage(systemName: "eye.slash"), for: .normal) isPasswordHidden = false } else { passwordTextField.isSecureTextEntry = true showPassword.setImage(UIImage(systemName: "eye"), for: .normal) isPasswordHidden = true } } } extension SignUpViewController: SignUpVCDelegate { func getResult() { errorMessage.text = "" let mainVC = CustomTabBarController() print("success") mainVC.modalPresentationStyle = .overFullScreen present(mainVC, animated: true) } func getError(error: Error) { wrongData() print(error.localizedDescription) errorMessage.text = error.localizedDescription } }
import * as axios from "axios"; import * as qs from "qs"; import { getSession } from './localstorage'; export default class Api { constructor() { this.api_url = 'https://api.cabanesdev.tk'; const token = getSession(); if (token) { this.headers = { 'bearer-token': getSession(), }; } } init = () => (this.client = axios.create({ baseURL: this.api_url, timeout: 0, headers: this.headers, withCredentials: false, })); register = (data) => this.init().post('/user/', data); login = (data) => this.init().post('/user/login', data); getSession = () => this.init().get(`/user/session`); getUsers = (params) => { const parsedParams = qs.stringify(params) return this.init().get(`/user?${parsedParams}`); } getUserById = (id) => this.init().get(`/user/${id}`); updateUser = (data) => this.init().put('/user/', data); getPosts = (params) => { const parsedParams = qs.stringify(params) return this.init().get(`/post?${parsedParams}`); } getPostById = (id) => this.init().get(`/post/${id}`); createPost = (data) => this.init().post('/post', data); editPost = (id, data) => this.init().put(`/post/${id}`, data); deletePost = (id) => this.init().delete(`/post/${id}`); getComments = (params) => { const parsedParams = qs.stringify(params) return this.init().get(`/comment?${parsedParams}`); } createComment = (data) => this.init().post('/comment', data); createCommit = (data) => this.init().post('/commit', data); getOneCommit = (id) => this.init().get(`/commit/${id}`); getCommits = (params) => { const parsedParams = qs.stringify(params) return this.init().get(`/commit?${parsedParams}`); } deleteCommits = (id) => this.init().delete(`/commit/${id}`) }
const { createClient } = supabase const _supabase = createClient('https://pfwnyxmmxgydkohyqrto.supabase.co', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBmd255eG1teGd5ZGtvaHlxcnRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTk3MTg5NjMsImV4cCI6MjAxNTI5NDk2M30.v--PqHL9B8GMFNNW-bp-mMcr7p30V_5hKXVUSRTBGxA'); let wishlistData = []; function getWishlistData() { fetch('/getWishlist', { method: 'GET', headers: { 'Content-Type': 'application/json' }, }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { wishlistData = data.products; document.getElementById('productContainer').innerHTML = ""; populateCards(); }) .catch(error => { if (!navigator.onLine) { console.error('No internet connection'); } else { console.error('Fetch error:', error); } }); } function populateCards(){ wishlistData.forEach(product => { createProductElement(product) }); } async function subscribeToChannel() { _supabase .channel('room1') .on('postgres_changes', { event: '*', schema: 'public', table: 'UserWishlist' }, payload => { getWishlistData(); }) .subscribe(); _supabase .channel('room2') .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'ShopItem' }, payload => { updateProductElement(payload['old']['id'], payload['new']); }) .subscribe() } function updateProductElement(productId, newData) { const productElement = document.querySelector(`[data-product-id="${productId}"]`); if (productElement) { productElement.querySelector('.product-name').textContent = newData.name; productElement.querySelector('.product-stock').textContent = newData.stock_number; productElement.querySelector('.product-price').textContent = `$${newData.price}`; // Uncomment this if the image is fetched from the storage bucket // productElement.querySelector('.product-image').src = newData.imageUrl; } } function removeItemWishlist(productID){ const postData = { 'productID': productID }; fetch('/removeItemWishlist', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postData) }).then(response => { if(!response.ok){ console.error("Can't create account"); } }) .catch(error => { if (!navigator.onLine) { console.error('No internet connection'); } else { console.error('Fetch error:', error); } }); } function createProductElement(product) { const mainDiv = document.createElement('div'); mainDiv.className = 'row p-2 bg-white border rounded mt-2'; mainDiv.setAttribute('data-product-id', product.id); const imgDiv = document.createElement('div'); imgDiv.className = 'col-md-3 mt-1'; const img = document.createElement('img'); img.className = 'img-fluid img-responsive rounded product-image'; img.src = product.image_url === "" ? '../static/images/perfume5-her.jpg' : product.image_url; imgDiv.appendChild(img); const detailsDiv = document.createElement('div'); detailsDiv.className = 'col-md-6 mt-1'; const br1 = document.createElement('br'); const br2 = document.createElement('br'); const br3 = document.createElement('br'); const productName = document.createElement('h5'); productName.className = 'mr-1 product-name'; productName.textContent = product.name; const priceDiv = document.createElement('div'); priceDiv.className = 'd-flex flex-row align-items-center'; const price = document.createElement('h4'); price.className = 'mr-1 product-price'; price.textContent = `$${product.price}`; const productShop = document.createElement('h6'); productShop.textContent = `Shop: ${product.shop_name}`; const productStock = document.createElement('h6'); productStock.className = 'mr-1 product-stock'; productStock.textContent = `Stock Left: ${product.stock_number}`; priceDiv.appendChild(price); detailsDiv.appendChild(br1); detailsDiv.appendChild(br2); detailsDiv.appendChild(br3); detailsDiv.appendChild(productName); detailsDiv.appendChild(priceDiv); detailsDiv.appendChild(productShop); detailsDiv.appendChild(productStock); const actionDiv = document.createElement('div'); actionDiv.className = 'align-items-center align-content-center col-md-3 border-left mt-1'; const br4 = document.createElement('br'); const br5 = document.createElement('br'); const br6 = document.createElement('br'); const br7 = document.createElement('br'); const buttonDiv = document.createElement('div'); buttonDiv.className = 'd-flex flex-column mt-4'; const button = document.createElement('button'); button.setAttribute('data-product-id', product.id); button.className = 'btn btn-primary btn-sm'; button.type = 'button'; button.textContent = 'Remove from Wishlist'; button.addEventListener('click', () => removeItemWishlist(product.id)); buttonDiv.appendChild(button); actionDiv.appendChild(br4); actionDiv.appendChild(br5); actionDiv.appendChild(br6); actionDiv.appendChild(br7); actionDiv.appendChild(buttonDiv); mainDiv.appendChild(imgDiv); mainDiv.appendChild(detailsDiv); mainDiv.appendChild(actionDiv); document.getElementById('productContainer').appendChild(mainDiv); } document.addEventListener('DOMContentLoaded', function() { getWishlistData(); subscribeToChannel(); });
package com.atifzia.bikerental.models; import java.util.Set; import com.atifzia.bikerental.enums.Role; import jakarta.persistence.*; import lombok.*; @Entity @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; @Column(unique = true) private String email; private String mobile; @Column(unique = true) private String username; private String password; @ElementCollection(targetClass = Role.class,fetch = FetchType.EAGER) @Enumerated(EnumType.STRING) @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id")) @Column(name = "role") private Set<Role> roles; }
/* * Copyright (c) 2023. Selldone® Business OS™ * * Author: M.Pajuhaan * Web: https://selldone.com * ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ * * All rights reserved. In the weave of time, where traditions and innovations intermingle, this content was crafted. * From the essence of thought, through the corridors of creativity, each word, and sentiment has been molded. * Not just to exist, but to inspire. Like an artist's stroke or a sculptor's chisel, every nuance is deliberate. * Our journey is not just about reaching a destination, but about creating a masterpiece. * Tread carefully, for you're treading on dreams. */ import {Currency} from "../../enums/payment/Currency"; export interface Account { /** * Unique identifier for the account. */ id: number; /** * ID of the associated user. */ user_id: number; /** * Account number string. */ account_number: string; /** * Name associated with the account. */ account_name: string; /** * Type of the account, e.g., "Single Share". */ type: string; /** * Account status. (Refer to the AccountStatus enumeration for possible values) */ status: Account.AccountStatus; /** * Currency type used in the account. (Refer to the Currency link for details) */ currency: keyof typeof Currency; /** * Current balance of the account. */ balance: number; /** * Interest rate applicable to the account. */ interest_rate: number; /** * Overdraft limit or value. */ overdraft: number; /** * Amount of funds that are locked or unavailable. */ locked: number; /** * Extra information provided by the user. */ options: object; /** * ID of the associated company, if any. */ company_id?: number | null; /** * Subscription UID as defined in the payment service (e.g., Stripe). */ subscription_uid?: string | null; /** * The last date and time when usage was synchronized with Stripe. */ usage_sync_at?: Date | null; /** * The last date and time when charges were synchronized with Stripe. */ charges_sync_at?: Date | null; /** * Extra metadata or information provided by the service. */ meta?: any[] | null; // Adjust the type as per the structure of the meta data } export namespace Account { export enum AccountStatus { /** First step checking account state. */ Checking = 'Checking', /** Approved account. */ Approved = 'Approved', /** Rejected account. */ Rejected = 'Rejected', /** Deleted account. */ Deleted = 'Deleted', /** Banned account. */ Banned = 'Banned', /** Waiting for payment fee. */ Payment = 'Payment', /** Selldone sprite account (used for external account mirror, Charge and withdraw requests). */ SelldoneSprite = 'SelldoneSprite', /** Selldone storage account (used for receive fees). */ SelldoneStorage = 'SelldoneStorage' } }
function snf=snirfcreate(varargin) % % snf=snirfcreate % or % snf=snirfcreate(option) % snf=snirfcreate('Format',format,'Param1',value1, 'Param2',value2,...) % % Create a empty SNIRF data structure defined in the SNIRF % specification: https://github.com/fNIRS/snirf % % author: Qianqian Fang (q.fang <at> neu.edu) % % input: % option (optional): option can be ignored. If it is a string with a % value 'snirf', this creates a default SNIRF data structure; % otherwise, a JSNIRF data structure is created. % format: save as option. % param/value: a list of name/value pairs specify % additional subfields to be stored under the /nirs object. % % output: % snf: a default SNIRF or JSNIRF data structure. % % example: % snf=snirfcreate('data',mydata,'aux',myauxdata,'comment','test'); % % this file is part of JSNIRF specification: https://github.com/fangq/snirf % % License: GPLv3 or Apache 2.0, see https://github.com/fangq/jsnirf for details % if(nargin==1) snf=jsnirfcreate(varargin{:}); else snf=jsnirfcreate('Format','snirf',varargin{:}); end
package monster; import java.util.Random; import entity.Entity; import main.GamePanel; import object.OBJ_Coin_Bronze; import object.OBJ_Heart; import object.OBJ_SpellSlot; public class MON_Mimic extends Entity{ GamePanel gp; public MON_Mimic(GamePanel gp) { super(gp); this.gp = gp; type = type_obstacle; collision = true; name = "Mimic"; defaultSpeed = 0; speed = defaultSpeed; maxLife = 5; life = maxLife; attack = 5; defense = 0; exp = 2; // hpBarOn = false; solidArea.x = 3; solidArea.y = 18; solidArea.width = 42; solidArea.height = 30; solidAreaDefaultX = solidArea.x; solidAreaDefaultY = solidArea.y; getImage(); getAttackImage(); } public void getImage() { up1 = setUp("/mimic/mimic_backside", gp.tileSize, gp.tileSize); up2 = setUp("/mimic/mimic_backside_flipped", gp.tileSize, gp.tileSize); down1 = setUp("/mimic/mimic_revealed", gp.tileSize, gp.tileSize); down2 = setUp("/mimic/mimic_revealed_flipped", gp.tileSize, gp.tileSize); left1 = setUp("/mimic/mimic_left1", gp.tileSize, gp.tileSize); left2 = setUp("/mimic/mimic_left2", gp.tileSize, gp.tileSize); right1 = setUp("/mimic/mimic_right1", gp.tileSize, gp.tileSize); right2 = setUp("/mimic/mimic_right2", gp.tileSize, gp.tileSize); empty = setUp("/mimic/mimic_Hide", gp.tileSize, gp.tileSize); } public void getAttackImage() { attackUp1 = setUp("/mimic/mimic_backside", gp.tileSize, gp.tileSize); attackUp2 = setUp("/mimic/mimic_backside_flipped", gp.tileSize, gp.tileSize); attackDown1 = setUp("/mimic/mimic_revealed", gp.tileSize, gp.tileSize); attackDown2 = setUp("/mimic/mimic_revealed_flipped", gp.tileSize, gp.tileSize); attackLeft1 = setUp("/mimic/mimic_left1", gp.tileSize, gp.tileSize); attackLeft2 = setUp("/mimic/mimic_left2", gp.tileSize, gp.tileSize); attackRight1 = setUp("/mimic/mimic_right1", gp.tileSize, gp.tileSize); attackRight2 = setUp("/mimic/mimic_right2", gp.tileSize, gp.tileSize); } @Override public void startAnimation() { animation0 = setUp("/mimic/mimic_Hide", gp.tileSize, gp.tileSize); animation1 = setUp("/mimic/mimic_opening1", gp.tileSize, gp.tileSize); animation2 = setUp("/mimic/mimic_opening2", gp.tileSize, gp.tileSize); animation3 = setUp("/mimic/mimic_revealed", gp.tileSize, gp.tileSize); animationCounter++; System.out.println(animationCounter); if(animationCounter == 5) { direction = "up"; up1 = animation0; System.out.println("up"); } if(animationCounter == 10) { direction = "down"; down1 = animation1; System.out.println("down"); } if(animationCounter == 15) { direction = "left"; left1 = animation2; System.out.println("left"); } if(animationCounter == 20) { direction = "right"; right1 = animation3; System.out.println("right"); } animationCounter = 0; animationPlayed = true; } @Override public void interact() { startAnimation(); for(int i = 0; i < gp.obj[1].length; i++) { if(gp.obj[gp.currentMap][i].name == "Mimic") { gp.monster[gp.currentMap][i] = new MON_Mimic(gp); gp.monster[gp.currentMap][i].worldX = gp.obj[gp.currentMap][i].worldX; gp.monster[gp.currentMap][i].worldY = gp.obj[gp.currentMap][i].worldY; gp.obj[gp.currentMap][i] = null; break; } } type = type_monster; collision = false; } @Override public void setAction() { if(onPath == true) { up1 = attackUp1; up2 = attackUp2; down1 = attackDown1; down2 = attackDown2; left1 = attackLeft1; left2 = attackLeft2; right1 = attackRight1; right2 = attackRight2; speed = 1; //Check if it stops chasing checkStopChasingOrNot(gp.player, 15, 100); // Search the direction to go searchPath(getGoalCol(gp.player), getGoalRow(gp.player)); } else { // Check if it starts chasing checkStartChasingOrNot(gp.player, 2, 10); up1 = empty; up2 = empty; down1 = empty; down2 = empty; left1 = empty; left2 = empty; right1 = empty; right2 = empty; animationPlayed = false; speed = 0; } } @Override public void damageReaction() { speed = 1; actionLockCounter = 0; // direction = gp.player.direction; onPath = true; } @Override public void checkDrop() { // CAST A DIE int i = new Random().nextInt(100)+1; // SET THE MONSTER DROP if(i < 50) { dropItem(new OBJ_Coin_Bronze(gp)); } if(i >= 50 && i < 75) { dropItem(new OBJ_Heart(gp)); } if(i >= 75 && i < 100) { dropItem(new OBJ_SpellSlot(gp)); } } }
#include "stm32_unict_lib.h" #include <stdio.h> typedef enum { st_OFF, st_ON } t_state; t_state current_state; int pb_X_event; int timer; void setup(void) { DISPLAY_init(); GPIO_init(GPIOC); GPIO_config_output(GPIOC, 2); GPIO_init(GPIOB); GPIO_config_output(GPIOB, 0); GPIO_config_input(GPIOB,10); GPIO_config_EXTI(GPIOB, EXTI10); EXTI_enable(EXTI10, FALLING_EDGE); current_state = st_OFF; } void loop(void) { char s[5]; switch(current_state) { case st_OFF: GPIO_write(GPIOB, 0, 0); // led spento if (pb_X_event) { pb_X_event = 0; timer = 0; current_state = st_ON; } break; case st_ON: GPIO_write(GPIOB, 0, 1); // led acceso sprintf(s, "%4d", timer / 100); DISPLAY_puts(0,s); delay_ms(10); ++timer; if (timer == 1000) current_state = st_OFF; if (pb_X_event) { pb_X_event = 0; timer = 0; } break; } } void EXTI15_10_IRQHandler(void) { if (EXTI_isset(EXTI10)) { pb_X_event = 1; EXTI_clear(EXTI10); } } int main() { setup(); for(;;) { loop(); } return 0; }
package kr.ac.kopo.webapplication.controller; import kr.ac.kopo.webapplication.dto.SampleDTO; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; @Controller @RequestMapping("/sample") //폴더명 public class SampleController { @GetMapping("/ex1") public void ex(){ } // @GetMapping("/ex2") // public void exModel(Model model){ // List< SampleDTO> list = IntStream.rangeClosed(1,20).asLongStream().mapToObj(i -> { // SampleDTO dto = SampleDTO.builder() //객체생성 1~20까지 // .sno(i) // .first("First..."+i) // .last("last..."+i) // .regTime(LocalDateTime.now()) // .build(); // return dto; //mapToObj 로 감 // }).collect(Collectors.toList()); // // model.addAttribute("list",list); //"list" 이름으로 list를 저장 / "list" -> html에서 이 이름으로 사용해야됨 // // } @GetMapping({"/ex2", "/ex2_1","/exBlock","/exLink"}) public void exModel(Model model){ List< SampleDTO> list = IntStream.rangeClosed(1,20).asLongStream().mapToObj(i -> { SampleDTO dto = SampleDTO.builder() //객체생성 1~20까지 .sno(i) .first("First..."+i) .last("last..."+i) .regTime(LocalDateTime.now()) .build(); return dto; //mapToObj 로 감 }).collect(Collectors.toList()); model.addAttribute("list",list); //"list" 이름으로 list를 저장 / "list" -> html에서 이 이름으로 사용해야됨 } @GetMapping("/exInline") public String exInline(RedirectAttributes redirectAttributes){ SampleDTO dto = SampleDTO.builder() .sno(100L) .first("first...100") .last("last...100") .regTime(LocalDateTime.now()) .build(); redirectAttributes.addFlashAttribute("result","Success"); redirectAttributes.addFlashAttribute("dto",dto); return "redirect:/sample/ex3"; } @GetMapping({"/ex3", "/exLayout1","/exLayout2","/exTemplate","/exSidebar"}) public void ex3(){ } }
import { Body, Controller, Delete, Get, Inject, NotFoundException, Param, Post, Put, UseGuards, forwardRef } from '@nestjs/common'; import { UserService } from './user.service'; import { User } from './user.entity'; import { UserDto } from './user.dto'; import { JwtAuthGuard } from 'src/auth/jwt-auth.guard'; @Controller('users') export class UserController { constructor(@Inject(forwardRef(() => UserService)) private readonly userService: UserService) {} @Get(":id") async getUser(@Param('id') id: number): Promise<User> { const user = await this.userService.getUser(id); if (!user) { throw new NotFoundException('This user doesn\'t exist'); } return user; } @Get() async getAllUsers(): Promise<User[]> { const users = await this.userService.getAllUsers(); return users; } @Post() async addUser(@Body() user: UserDto): Promise<User> { return await this.userService.createUser(user); } @UseGuards(JwtAuthGuard) @Put(":id") async updateUser(@Param('id') id: number, @Body() user: UserDto): Promise<User> { return await this.userService.updateUser(id, user); } @UseGuards(JwtAuthGuard) @Delete(':id') async deleteUser(@Param('id') id: number) { const deleted = await this.userService.deleteUser(id); return "Successfully deleted"; } }
import logging from django.shortcuts import render, redirect from django.conf import settings from django.contrib.auth import login, logout, authenticate from django.contrib.auth.hashers import make_password from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger from django.db.models import Count from blog.models import * from blog.forms import * logger = logging.getLogger('blog.views') # Create your views here. # 全局设置 def global_setting(request): # 站点基本信息 SITE_URL = settings.SITE_URL SITE_NAME = settings.SITE_NAME SITE_DESC = settings.SITE_DESC WEIBO_SINA = settings.WEIBO_SINA WEIBO_TENCENT = settings.WEIBO_TENCENT PRO_RSS = settings.PRO_RSS PRO_EMAIL = settings.PRO_EMAIL # 导航分类信息 category_list = Category.objects.all()[:6] # 文章归档数据 archive_list = Article.objects.distinct_date() # 广告数据(同学们自己完成) Ad_list = Ad.objects.all() # 标签云数据(同学们自己完成) tag_list = Tag.objects.all() # 友情链接数据(同学们自己完成) links_list = Links.objects.all() # 文章排行榜数据(按浏览量和站长推荐的功能同学们自己完成) # 浏览排行 click_counts = Article.objects.all().order_by('-click_count') # 站长推荐 recommend_list = Article.objects.filter(is_recommend=1) # 评论排行 comment_count_list = Comment.objects.values('article').annotate(comment_count=Count('article')).order_by('-comment_count') print(comment_count_list) article_comment_list = [Article.objects.get(pk=comment['article']) for comment in comment_count_list] return locals() def index(request): try: article_list = Article.objects.all() article_list = getPage(request, article_list) # print(article_list) except Exception as e: print(e) logger.error(e) return render(request, 'index.html', locals()) def category(request): try: # 先获取客户端提交的信息 cid = request.GET.get('cid', None) try: category = Category.objects.get(pk=cid) except Category.DoesNotExist: return render(request, 'failure.html', {'reason': '分类不存在'}) article_list = Article.objects.filter(category=category) article_list = getPage(request, article_list) except Exception as e: logger.error(e) return render(request, 'category.html', locals()) # 标签页 def tag(request): try: # 获取客户端提交信息 id = request.GET.get('id', None) try: tag = Tag.objects.get(pk=id) except Tag.DoesNotExist: return render(request, 'failure.html', {'reason': '标签不存在'}) article_list = Article.objects.filter(tag=tag) article_list = getPage(request, article_list) except Exception as e: logger.error(e) return render(request, 'tag.html', locals()) # 文章详情 def article(request): try: # 获取文章ID id = request.GET.get('id') try: # 获取文章信息 article = Article.objects.get(pk=id) except Article.DoesNotExist: return render(request, 'failure.html', {'reason': '没有找到对应的文章'}) # 评论表单 comment_form = CommentForm({'author': request.user.username, 'email': request.user.email, 'url': request.user.url, 'article': id} if request.user.is_authenticated() else{'article': id}) # 获取评论信息 comments = Comment.objects.filter(article=article).order_by('id') comment_list = [] for comment in comments: for item in comment_list: if not hasattr(item, 'children_comment'): setattr(item, 'children_comment', []) if comment.pid == item: item.children_comment.append(comment) break if comment.pid is None: comment_list.append(comment) except Exception as e: print(e) logger.error(e) return render(request, 'article.html', locals()) # 分页代码 def getPage(request, article_list): paginator = Paginator(article_list, 5) try: page = int(request.GET.get('page', 1)) article_list = paginator.page(page) except (EmptyPage, InvalidPage, PageNotAnInteger): article_list = paginator.page(1) return article_list # 文章归档 def archive(request): # 获取客户端提交的信息 try: year = request.GET.get('year', None) month = request.GET.get('month', None) article_list = Article.objects.filter(date_publish__icontains=year+'-'+month) article_list = getPage(request, article_list) except Exception as e: print(e) logger.error(e) return render(request, 'archive.html', locals()) # 提交评论 def comment_post(request): try: comment_form = CommentForm(request.POST) if comment_form.is_valid(): #获取表单信息 comment = Comment.objects.create(username=comment_form.cleaned_data["author"], email=comment_form.cleaned_data["email"], url=comment_form.cleaned_data["url"], content=comment_form.cleaned_data["comment"], article_id=comment_form.cleaned_data["article"], user=request.user if request.user.is_authenticated() else None) comment.save() else: return render(request, 'failure.html', {'reason': comment_form.errors}) except Exception as e: logger.error(e) return redirect(request.META['HTTP_REFERER']) # 注销 def do_logout(request): try: logout(request) except Exception as e: print (e) logger.error(e) return redirect(request.META['HTTP_REFERER']) # 注册 def do_reg(request): try: if request.method == 'POST': reg_form = RegForm(request.POST) if reg_form.is_valid(): # 注册 user = User.objects.create(username=reg_form.cleaned_data["username"], email=reg_form.cleaned_data["email"], url=reg_form.cleaned_data["url"], password=make_password(reg_form.cleaned_data["password"]),) user.save() # 登录 user.backend = 'django.contrib.auth.backends.ModelBackend' # 指定默认的登录验证方式 login(request, user) return redirect(request.POST.get('source_url')) else: return render(request, 'failure.html', {'reason': reg_form.errors}) else: reg_form = RegForm() except Exception as e: logger.error(e) return render(request, 'reg.html', locals()) # 登录 def do_login(request): try: if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): # 登录 username = login_form.cleaned_data["username"] password = login_form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: user.backend = 'django.contrib.auth.backends.ModelBackend' # 指定默认的登录验证方式 login(request, user) else: return render(request, 'failure.html', {'reason': '登录验证失败'}) return redirect(request.POST.get('source_url')) else: return render(request, 'failure.html', {'reason': login_form.errors}) else: login_form = LoginForm() except Exception as e: logger.error(e) return render(request, 'login.html', locals())
import { DataSource } from 'typeorm'; import { config } from 'dotenv'; config({ path: '.env.dev' }); const connectionOptions = { host: process.env.DATABASE_HOST, port: Number(process.env.DATABASE_PORT), username: process.env.DATABASE_USER, password: process.env.DATABASE_PASS, database: process.env.DATABASE_NAME, }; const dataSource = new DataSource({ ...connectionOptions, type: 'postgres', synchronize: true, logging: true, entities: ['src/domain/**/*.entity{.ts,.js}'], migrations: ['src/infra/db/typeorm/migrations/*.ts'], }); export { dataSource, connectionOptions };
import { SlashCommandBuilder } from 'discord.js'; import { TicTacToe } from 'discord-gamecord'; import { handleGameEnd } from "../../Utils/money.js"; export default { data: new SlashCommandBuilder().setName('tictactoe').setDescription('Spiele TicTacToe').setDMPermission(false) .addUserOption((option) => option .setName('member').setNameLocalizations({de: 'spieler'}) .setDescription('Name of opponent').setDescriptionLocalizations({de: 'Name des Gegners'}) .setRequired(true)), async execute(interaction) { const target = interaction.options.getUser('member'); if (!target) return interaction.reply('Es wurde kein Mitspieler angegeben!'); if (target === interaction.user) return interaction.reply('Gib einen anderen Spieler an!'); const Game = new TicTacToe({ message: interaction, isSlashGame: true, opponent: target, embed: { title: 'Tic Tac Toe', color: '#5865F2', statusTitle: 'Status', overTitle: 'Game Over', }, emojis: { xButton: '❌', oButton: '🔵', blankButton: '➖', }, mentionUser: true, timeoutTime: 60000, xButtonStyle: 'DANGER', oButtonStyle: 'PRIMARY', turnMessage: '{emoji} | **{player}** ist am Zug.', winMessage: '{emoji} | **{player}** hat das Spiel gewonnen!', tieMessage: 'Unentschieden! Keiner hat gewonnen!', timeoutMessage: 'Das Spiel wurde nicht zu Ende gespielt! Keiner hat das Spiel gewonnen!', requestMessage: '{player} hat dich zu **Tic Tac Toe** eingeladen.', rejectMessage: 'Der Spieler hat deine Einladung zu **Tic Tac Toe** abgelehnt.', playerOnlyMessage: 'Nur {player} kann diese Schaltfläche verwenden.', reqTimeoutMessage: 'Der Spieler hat die Einladung nicht rechtzeitig angenommen.', buttons: { accept: 'Annehmen', reject: 'Ablehnen', }, }); await Game.startGame(); await Game.on('gameOver', (result) => { //console.log(result); handleGameEnd(interaction, result, "TicTacToe", 20, 10); }); }, };
/* This file or code within this file was originally part of Qt Creator. Copyright (c) 2008 Roberto Raggi <[email protected]> Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). Copyright (c) 2009 Bertjan Broeksema <[email protected]> GNU Lesser General Public License Usage This file may be used under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation and appearing in the file LICENSE.LGPL included in the packaging of this file. Please review the following information to ensure the GNU Lesser General Public License version 2.1 requirements will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. */ #ifndef CPLUSPLUS_CPPMODEL_DIAGNOSTIC_MESSAGE_H #define CPLUSPLUS_CPPMODEL_DIAGNOSTIC_MESSAGE_H #include <QtCore/QString> #include "cppmodel-config.h" namespace CPlusPlus { namespace CppModel { class CPLUSPLUS_MODEL_EXPORT DiagnosticMessage { public: enum Level { Warning, Error, Fatal }; public: DiagnosticMessage(Level level, QString const &fileName, int line, int column, QString const &text); unsigned column() const; QString fileName() const; bool isError() const; bool isFatal() const; bool isWarning() const; Level level() const; unsigned line() const; QString text() const; private: unsigned m_column; QString m_fileName; Level m_level; unsigned m_line; QString m_text; }; } // namespace CppModel } // namespace CPlusPlus #endif // CPLUSPLUS_CPPMODEL_DIAGNOSTIC_MESSAGE_H
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Barang extends Model { use HasFactory; protected $fillable = ['id_satuan', 'id_unit', 'kode_barang', 'jenis_barang', 'nama_barang', 'posisi_pi', 'tgl_beli', 'umur_ekonomis', 'harga_barang', 'nilai_saat_ini', 'harga_jual', 'stok', 'status_konversi', 'created_at', 'updated_at']; protected $table = 'barang'; protected $primaryKey = 'id_barang'; public function satuan() { return $this->belongsTo(Satuan::class, 'id_satuan'); } public function unit() { return $this->belongsTo(Unit::class, 'id_unit'); } public function barang_eceran() { return $this->hasMany(Barang_eceran::class, 'id_barang'); } public function detail_belanja_barang() { return $this->hasMany(Detail_belanja_barang::class, 'id_barang'); } public function detail_penjualan() { return $this->hasMany(Detail_penjualan::class, 'id_barang'); } public function saldo_awal_barang() { return $this->hasMany(Saldo_awal_barang::class, 'id_barang'); } public function detail_penyusutan() { return $this->hasMany(Detail_penyusutan::class, 'id_barang'); } }
package DynamicProgramming; public class LongestCommonSubsequence { public static void main(String[] args) { String[] X = { "E", "B", "T", "B", "C", "A", "D", "F" }; String[] Y = { "A", "B", "B", "C", "D", "6", "F" }; /** * Brute force recursion method * Find all the subsequence in X and all the subsequence in Y and compare the subsequences and return the largest * Time complexity for X - there are m elements so there are 2^m combinations * Similarly for Y - there are n elements and hence there are 2^n combinations * Hence TC = 0(2^m+2^n) * Base case when m=0 or n=0 * * If the last element of both the string array are same then that would be the part of the LCs * If the last element of both the string array are not same then we need to compare X-1 with Y or Y-1 with X * * Let's define a function cs which take the following arguments. * m = no of elements in X * n = no of elements in Y * */ int maxCount = lcs(X, Y, X.length - 1, Y.length - 1); System.out.println("maxcount from recursion-----" + maxCount); int maxCountFromTopDown = topDown(X, Y, X.length - 1, Y.length - 1); System.out.println("maxCountFromTopDown-----" + maxCountFromTopDown); int maxCountFromBottomUp = bottomUpLCS(X, Y, X.length - 1, Y.length - 1); System.out.println("maxCountFromBottomUp----" + maxCountFromBottomUp); } /** * This is recursion method * * @param * @param * @param * @param * @return */ public static int lcs(String[] X, String[] Y, Integer m, Integer n) { int maxCount = 0; if ((m == 0) || (n == 0)) { return maxCount = 0; } if (X[m] == Y[n]) { maxCount = 1 + lcs(X, Y, m - 1, n - 1); } if (X[m] != Y[n]) { // compare X with Y-1 elements| int excludedFrom = lcs(X, Y, m - 1, n); int excludedFromY = lcs(X, Y, m, n - 1); maxCount = Math.max(excludedFrom, excludedFromY); } return maxCount; } private static int topDown(String[] X, String[] Y, int m, int n) { Integer[][] Z = new Integer[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { Z[i][j] = -1; } } return topDownLCS(X, Y, Z, m, n); } /** * Lets solve this by Dynamic Programming using topDown approach. * in order to solve this by memoization - lets build the solution approach. We saw in recursion that the following choices are possible * 1. if last elements in both the array are matched maxCount = 1 + lcs(X, Y, m-1, n-1) * 2. if last elements in both the array are not matched then we are getting the max of * 1. Les (X, Y,m-1, n) and lcs (X, Y,m, n- 1) * 2. So for any i in X and any jin Y the function would become * Lcs (X, Y, 1-1, j) and Lc(X,Y, i,j-1) * <p> * 3. This means to calculate the value of any i in X and any j in Y, all * We * need is the values from (1-1, j) and (i, j-1) so that we can get the maximum * 1. Initialize an array of size (m+1)*(n+1) where there are m index in X and n index in Y * 2. Initialize all values with -1. If the value is -1, we need to calculate or else just get the value and compare * 3. since we are storing solutions for sub-problems - it will drastically reduce the time complexity as we are calculating sub problems only once * 4. TC = 0((m+1)*(n+1)) as there are m+1 * n+1 different sub-problems * 5. Base case i = 0 or j=0 return 0 */ public static int topDownLCS(String[] X, String[] Y, Integer[][] Z, int m, int n) { if ((m == 0) || (n == 0)) { return 0; } // if the value is present in the Z[][] return else go ahead and calculate if (Z[m][n] != -1) { return Z[m][n]; } if (X[m] == Y[n]) { Z[m][n] = 1 + topDownLCS(X, Y, Z, m - 1, n - 1); } if (X[m] != Y[n]) { Z[m][n] = Math.max(topDownLCS(X, Y, Z, m - 1, n), topDownLCS(X, Y, Z, m, n - 1)); } return Z[m][n]; } /** * This is bottopm up approach * @param X * @param Y * @param m * @param n * @return */ public static int bottomUpLCS(String[] X, String[] Y, int m, int n) { Integer[][] Z = new Integer[m + 1][n + 1]; //Initialize the matrix Z in the base condition m=0 or n=0 for (int i = 0; i <= m; i++) { Z[i][0] = 0; } for (int j = 0; j <= n; j++) { Z[0][j] = 0; } // for every i and j, get the value form previous column for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { // if last character matches if (X[i] == Y[j]) { Z[i][j] = 1 + Z[i - 1][j - 1]; } // if last character does not match if (X[i] != Y[j]) { Z[i][j] = Math.max(Z[i - 1][j], Z[i][j - 1]); } } } return Z[m][n]; } }
import { Service, Inject } from 'typedi'; import jwt from 'jsonwebtoken'; import config from '../config'; import argon2 from 'argon2'; import { IUser } from '../interfaces/IUser'; import { UserRepository } from '../repository/userRepository'; @Service() export default class AuthService { constructor( private userRepository: UserRepository, @Inject('logger') private logger, ) {} public async SignIn(email: string, password: string): Promise<{ user: IUser; token: string }> { const userRecord = await this.userRepository.findByEmail(email); if (!userRecord) { throw new Error('User not registered'); } /** * We use verify from argon2 to prevent 'timing based' attacks */ this.logger.silly('Checking password'); const validPassword = await argon2.verify(userRecord.password, password); if (validPassword) { this.logger.silly('Password is valid!'); this.logger.silly('Generating JWT'); const token = this.generateToken(userRecord); const user = userRecord.toObject(); Reflect.deleteProperty(user, 'password'); Reflect.deleteProperty(user, 'salt'); /** * Easy as pie, you don't need passport.js anymore :) */ return { user, token }; } else { throw new Error('Invalid Password'); } } private generateToken(user: any) { const today = new Date(); const exp = new Date(today); exp.setDate(today.getDate() + 60); /** * A JWT means JSON Web Token, so basically it's a json that is _hashed_ into a string * The cool thing is that you can add custom properties a.k.a metadata * Here we are adding the userId, role and name * Beware that the metadata is public and can be decoded without _the secret_ * but the client cannot craft a JWT to fake a userId * because it doesn't have _the secret_ to sign it * more information here: https://softwareontheroad.com/you-dont-need-passport */ this.logger.silly(`Sign JWT for userId: ${user._id}`); return jwt.sign( { _id: user._id, // We are gonna use this in the middleware 'isAuth' role: user.role, name: user.name, exp: exp.getTime() / 1000, }, config.jwtSecret, ); } }
#!/usr/local/bin/Rscript # This Rscript generates a spatial points video of either AOD or DQF over a # single CONUS state. The timelapse covers a single hour at ~5 minute intervals. # # Test this script from the command line with: # # ./createSpatialPointsVideo_exec.R --datetime="2019-10-29" # -s CA -x AOD -q 3 -r 2 -o ~/Desktop/ # -v TRUE --SpatialDataDir="~/Data/Spatial" # --SatelliteDataDir="~/Data/kincade" # --bbox="-125, -120, 36, 40" # --fullDay="TRUE" # ---- . ---- . corrected aspect ratio VERSION = "0.2.2" # The following packages are attached here so they show up in the sessionInfo suppressPackageStartupMessages({ library(MazamaCoreUtils) library(MazamaSpatialUtils) library(MazamaSatelliteUtils) }) # ----- Get command line arguments --------------------------------------------- if ( interactive() ) { # RStudio session opt <- list( SpatialDataDir="~/Data/Spatial", SatelliteDataDir="~/Data/Satellite", fullDay = TRUE, ##bbox = "-126,-119,34,40", # Kincade, extending out into Pacific bbox = "-124,-122,37,39", # Kincade, closeup datetime = "2019-10-27", # Kincade fire near Sonoma, CA (local time) stateCode = "CA", satID = "G17", var = "AOD", dqfLevel = 2, frameRate = 5, verbose = TRUE, outputDir = getwd(), logDir = getwd(), version = FALSE ) } else { # Set up OptionParser library(optparse) option_list <- list( make_option( c("--SpatialDataDir"), default = NULL, help = "Defines SpatialDataDir location [SpatialDataDir = \"%default\"]" ), make_option( c("--SatelliteDataDir"), default = NULL, help = "Defines SatelliteDataDir location [SatelliteDataDir = \"%default\"]" ), make_option( c("--fullDay"), default = FALSE, help = "Sets whether period should be entire range of daytime hours [fullDay = \"%default\"]" ), make_option( c("--bbox"), default = NULL, help = "bbox argument as a string 'w,e,s,n' [bbox = \"%default\"]" ), make_option( c("-t", "--datetime"), default = NULL, help = "datetime of interest specified to the hour [default = \"%default\"]" ), make_option( c("-s", "--stateCode"), default = NULL, help = "Two-character state code [default = \"%default\"]" ), make_option( c("-x", "--var"), default = "AOD", help = "Variable displayed ('AOD' or 'DQF') [default = \"%default\"]" ), make_option( c("-q", "--dqfLevel"), default = 2, help = "Data quality filter level [default = \"%default\"]" ), make_option( c("-i", "--satID"), default = "G17", help = "Satellite ID [default = \"%default\"]" ), make_option( c("-r", "--frameRate"), default = 5, help = "Frames per second [default = \"%default\"]" ), make_option( c("-v","--verbose"), default = FALSE, help = "Print extra output [default = \"%default\"]" ), make_option( c("-o","--outputDir"), default = getwd(), help = "Output directory for generated video file [default = \"%default\"]" ), make_option( c("-l","--logDir"), default = getwd(), help = "Output directory for generated .log file [default = \"%default\"]" ), make_option( c("-V","--version"), action = "store_true", default = FALSE, help = "Print out version number [default = \"%default\"]" ) ) # Parse arguments opt <- parse_args(OptionParser(option_list = option_list)) } # Print out version and quit if (opt$version) { cat(paste0("createSpatialPointsVideo_exec.R ", VERSION, "\n")) quit() } # ----- Validate parameters ---------------------------------------------------- MazamaCoreUtils::stopIfNull(opt$datetime) # TODO: # Either bbox or stateCode must exist # TODO: Derive BBOX from State, if that's what's given if ( opt$frameRate < 0 || opt$frameRate != floor(opt$frameRate) ) stop("Argument 'frameRate' must be a positive integer") if ( !dir.exists(opt$outputDir) ) stop(paste0("outputDir not found: ", opt$outputDir)) if ( !dir.exists(opt$logDir) ) stop(paste0("logDir not found: ", opt$logDir)) # ----- Set up logging --------------------------------------------------------- logger.setup( traceLog = file.path(opt$logDir, "createSpatialPointsVideo_TRACE.log"), debugLog = file.path(opt$logDir, "createSpatialPointsVideo_DEBUG.log"), infoLog = file.path(opt$logDir, "createSpatialPointsVideo_INFO.log"), errorLog = file.path(opt$logDir, "createSpatialPointsVideo_ERROR.log") ) # For use at the very end errorLog <- file.path(opt$logDir, "createSpatialPointsVideo_ERROR.log") if ( interactive() ) logger.setLevel(TRACE) # Silence other warning messages options(warn = -1) # -1 = ignore, 0 = save/print, 1 = print, 2 = error # Start logging logger.info("Running createSpatialPointsVideo_exec.R version %s", VERSION) sessionString <- paste(capture.output(sessionInfo()), collapse = "\n") logger.debug("R session:\n\n%s\n", sessionString) # ----- EVERYTHING inside an overarching try{} block --------------------------- result <- try({ # ----- Assemble data -------------------------------------------------------- result <- try({ # Set directories using command line parameters setSpatialDataDir(opt$SpatialDataDir) setSatelliteDataDir(opt$SatelliteDataDir) # TODO: # Use bbox if not NULL else state # Load state boundaries loadSpatialData("USCensusStates") state <- subset(USCensusStates, stateCode == opt$stateCode) # Parse out bbox vector bbox <- as.numeric(unlist(strsplit(opt$bbox, ","))) bbox <- bboxToVector(bbox) # Get the bbox components boundaries <- bboxToVector(bbox) w <- boundaries[1] e <- boundaries[2] s <- boundaries[3] n <- boundaries[4] mid_lon <- w + (e - w) / 2 mid_lat <- s + (n - s) / 2 # Adjust incoming bbox width to fit the video aspect ratio 1280/720 videoAspectRatio <- 1280/720 # (width/height) longitudeScaling <- sin(mid_lat * pi / 180) newWidth <- (n - s) * videoAspectRatio / longitudeScaling w <- mid_lon - newWidth/2 e <- mid_lon + newWidth/2 bbox <- c(w, e, s, n) # Get the timezone in the bbox center timezone <- MazamaSpatialUtils::getTimezone( lon = mid_lon, lat = mid_lat, countryCodes = c("US"), useBuffering = TRUE ) # TODO: # Support full days if local time hour is midnight # Parse the incoming datetime datetime <- MazamaCoreUtils::parseDatetime(opt$datetime, timezone = timezone) %>% lubridate::floor_date(unit = "hour") videoTimeStamp <- MazamaCoreUtils::timeStamp( datetime, unit = "hour", timezone = timezone ) if ( opt$verbose ) logger.trace("Creating video for %s ...", strftime(datetime, "%Y-%m-%d %H:%M:%S %Z")) # Check whether to process an entire day if ( opt$fullDay ) { # Download the satellite scans for entire day scanFiles <- goesaodc_downloadDaytimeAOD( satID = opt$satID, datetime = datetime, timezone = timezone, verbose = opt$verbose ) } else { # Download the satellite scans for this hour scanFiles <- goesaodc_downloadAOD( satID = opt$satID, datetime = datetime, endtime = NULL, timezone = timezone, isJulian = FALSE, verbose = opt$verbose ) } }, silent = TRUE) if ( "try-error" %in% class(result) ) { msg <- paste("Error assembling data: ", geterrmessage()) logger.fatal(msg) stop(msg) } # ----- Create video frames -------------------------------------------------- result <- try({ # Generate a frame for each scan file frameNumber <- 0 for ( scanFile in scanFiles ) { frameNumber <- frameNumber + 1 # Frame setup i <- stringr::str_pad(frameNumber, 3, 'left', '0') frameFile <- paste0(videoTimeStamp, "_", i, ".png") frameFilePath <- file.path(tempdir(), frameFile) # Scan time scanTimeUTC <-goesaodc_convertFilenameToDatetime(scanFile) scanTimeLocal <- lubridate::with_tz(scanTimeUTC, tzone = timezone) # TODO: Get scanTimeLocal back into plot if ( opt$verbose ) logger.trace("Start frame for %s", strftime(scanTimeLocal, "%H:%M:%S")) # Load scan data nc <- goesaodc_openFile(filename = scanFile) print(scanFile) # Plot the frame png(frameFilePath, width = 1280, height = 720, units = "px") ###par(mar = c(0,0,0,0)) if ( "try-error" %in% class(result) ) { # Error plot errMsg <- geterrmessage() # Still draw the state border even if there are no spatial points if ( grep("No data for selected region", errMsg) == 1 ) { par(bg = 'gray') plot(state, main = strftime(scanTimeLocal, "%Y-%m-%d %H:%M:%S %Z")) } else { stop(errMsg) } } else { # Data plot # TODO: Update cex value based on bbox size goesaodc_areaPlot( list(nc), bbox = bbox, dqfLevel = opt$dqfLevel ) } if (opt$verbose) logger.trace(" End frame for %s", strftime(scanTimeLocal, "%H:%M:%S")) dev.off() } }, silent = TRUE) if ( "try-error" %in% class(result) ) { msg <- paste("Error creating video frames: ", geterrmessage()) logger.fatal(msg) stop(msg) } # ----- Create video --------------------------------------------------------- result <- try({ videoFile <- paste0(state$stateCode, "_", videoTimeStamp, "_DQF", opt$dqfLevel, ".mp4") videoFilePath <- file.path(opt$outputDir, videoFile) # Define system calls to ffmpeg to create video from frames cmd_cd <- paste0("cd ", tempdir()) cmd_ffmpeg <- paste0( "ffmpeg -loglevel quiet -r ", opt$frameRate, " -f image2 -s 1280x720 -i ", videoTimeStamp, "_%03d.png -vcodec libx264 -crf 25 ", videoFilePath ) cmd_rm <- "rm *.png" cmd <- paste0(cmd_cd, " && ", cmd_ffmpeg, " && ", cmd_rm) logger.info("Calling ffmpeg to make video from frames") logger.trace(cmd) # Make system call ffmpegString <- paste(capture.output({ system(cmd) }), collapse="\n") # TODO: # Can additional flags generate output we can see? ###logger.trace("ffmpeg output:\n\n%s\n", ffmpegString) }, silent = TRUE) if ( "try-error" %in% class(result) ) { msg <- paste("Error creating video frames: ", geterrmessage()) logger.fatal(msg) stop(msg) } }, silent=TRUE) # END outer try{} block # ----- Handle errors ---------------------------------------------------------- if ( "try-error" %in% class(result) ) { msg <- paste("Error creating video: ", geterrmessage()) logger.fatal(msg) } else { # Guarantee that an empty errorLog exists if ( !file.exists(errorLog) ) dummy <- file.create(errorLog) logger.info("Completed successfully!") }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classes from './Person.css'; import withClass from '../../../hoc/withClass'; import Aux from '../../../hoc/Aux'; class Person extends Component { constructor(props) { // Inside here, can access props.XY // call super to overwrite React default constructor super(props); console.log('[Person.js] Inside constructor', props); } componentWillMount() { console.log('[Person.js] Inside componentWillMount'); } componentDidMount() { console.log('[Person.js] Inside componentDidMount'); if (this.props.position === 0) { this.inputElement.focus(); } } render () { console.log('[Person.js] Inside render()'); return ( <Aux> <p onClick={this.props.click}>I'm {this.props.name} and I am {this.props.age} years old!</p> <p>{this.props.children}</p> <input type="text" ref={ (inp) => { this.inputElement = inp } } onChange={this.props.changed} defaultValue={this.props.name} /> </Aux> ) } } Person.propTypes = { // key-value pairs props: rules, click: PropTypes.func, name: PropTypes.string, age: PropTypes.number, changed: PropTypes.func }; export default withClass(Person, classes.Person);
import React, { useState, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; const Spinner = ({path='login'}) => { const navigate = useNavigate(); const [counter, setCounter] = useState(5); const location = useLocation() useEffect(() => { const timer = setTimeout(() => { // Redirect to /login after 5 seconds navigate(`/${path}`,{ state:location.pathname }); }, 5000); // Update the counter every second const interval = setInterval(() => { setCounter((prevCounter) => prevCounter - 1); }, 1000); // Clear the timer and interval when the component unmounts return () => { clearTimeout(timer); clearInterval(interval); }; }, [navigate, location, path]); return ( <div className="d-flex flex-column align-items-center justify-content-center" style={{ height: '100vh' }}> <div className="spinner-border" role="status"> <span className="visually-hidden">Loading...</span> </div> <p>Redirecting in {counter} seconds</p> </div> ); }; export default Spinner;
The bug in the provided Java code is in the for loop condition of the `isStrictlyPalindromic` method. Currently, the for loop runs from `2` to `n - 1`. However, it should run from `2` to `n` in order to include `n` as one of the bases for converting `n` to a string. To fix this bug, we need to modify the for loop condition to `i <= n`. Here's the fixed code: ```java class Solution { public boolean isStrictlyPalindromic(int n) { boolean flag = true; for (int i = 2; i <= n; i++) { if (! check(Integer.toString(n, i))) { flag = false; break; } } return flag; } public boolean check(String n) { int left = 0; int right = n.length() - 1; while (left < right) { if (n.charAt(left) != n.charAt(right)) return false; left++; right--; } return true; } } ``` This fix ensures that the for loop condition allows `n` to be included as a base for converting `n` to a string and checks if the string is a palindrome in all cases.
import { Faction } from './faction.ts' import { BaseOfOperations } from './baseOfOperations.ts' import supabaseClient from '../superbaseClient.ts' import useSystemError from '../stores/systemError.ts' import { SpecOps } from './specOps.ts' export interface Dataslate { id: number userId: string teamName: string faction: Faction reqPoints: number currentSpecOps?: SpecOps completedSpecOps: SpecOps[] baseOfOperations: BaseOfOperations history?: string notes?: string quirks?: string selectableKeyword?: string | null } interface ApiResponse<Data> { data?: Data error?: string | 'Unknown error' } const setError = useSystemError.getState().setError export const postDataslate = async ( userId: string, teamName: string, faction: Faction, baseOfOperationsName: string, ): Promise<ApiResponse<Dataslate>> => { const newBaseOfOperations: BaseOfOperations = { userId, name: baseOfOperationsName, assetCapacity: 2, id: 0, stash: { availableEP: 0, availableEquipment: [], }, strategicAssets: [], } const newDataslate: Dataslate = { userId, teamName, faction, baseOfOperations: newBaseOfOperations, id: 0, reqPoints: 4, completedSpecOps: [], } try { const { data, error } = await supabaseClient .from('dataslate_json') .insert({ user_id: userId, json: newDataslate, }) .select() .single() if (error) return { error: error.message } return { data: { ...newDataslate, id: data.id, }, } } catch (e) { return { error: 'Unknown error' } } } export const getDataslates = async (): Promise<ApiResponse<Dataslate[]>> => { try { const { data, error } = await supabaseClient.from('dataslate_json').select() if (error) return { error: error.message } return { data: data.map((data) => ({ ...data.json, id: data.id, })), } } catch (e) { return { error: 'Unknown error' } } } export const getDataslate = async ( dataslateId: string, ): Promise<ApiResponse<Dataslate>> => { try { const { data, error } = await supabaseClient .from('dataslate_json') .select('*') .eq('id', dataslateId) .single() if (error) return { error: error.message } return { data: { ...data.json, id: data.id } } } catch (e) { return { error: 'Unknown error' } } } export const updateDataslate = async ( dataslate: Dataslate, ): Promise<ApiResponse<Dataslate>> => { try { const { data, error } = await supabaseClient .from('dataslate_json') .update({ json: dataslate, }) .eq('id', dataslate.id) .select() .single() if (error) return { error: error.message } return { data: data.json } } catch (e) { return { error: 'Unknown error' } } } export const deleteDataslate = async (dataslate: Dataslate) => { const { error } = await supabaseClient .from('dataslate_json') .delete() .eq('id', dataslate.id) if (error?.code) { setError( 'To admit defeat is to blaspheme against the Emperor, but in this case I am unable to perform this action', ) } else { window.location.href = '/' } }
--- sidebar_position: 3 title: Cache --- # Render Cache Sometimes we cache computation results, such as with the React useMemo, useCallback Hook. By caching, we can reduce the number of computations, thus reducing CPU resource usage and enhancing the user experience. Caching the results of server-side rendering (SSR) can reduce the computation and rendering time for each server request, enabling faster page load speeds and improving the user experience. It also lowers the server load, saves computational resources, and speeds up user access. :::info Need x.43.0+ ::: ## Configuration You can enable caching by configuring it in `server/cache.[t|j]s`: ```ts title="server/cache.ts" import type { CacheOption } from '@modern-js/runtime/server'; export const cacheOption: CacheOption = { maxAge: 500, // ms staleWhileRevalidate: 1000, // ms }; ``` ## Configuration Explanation ### Cache Configuration The caching policy is implemented based on [stale-while-revalidate](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). During the `maxAge` period, cache content will be returned directly. After `maxAge` but within `staleWhileRevalidate`, the cache content will also be returned directly, but at the same time, re-rendering will be executed asynchronously. **Object type** ```ts export interface CacheControl { maxAge: number; staleWhileRevalidate: number; customKey?: string | ((pathname: string) => string); } ``` In this, customKey is used for custom cache key. By default, Modern.js will use the request pathname as key for caching, but in some cases, this may not meet your needs, so developers can customise it. **Function type** ```ts export type CacheOptionProvider = ( req: IncomingMessage, ) => Promise<CacheControl> | CacheControl; ``` Sometimes developers need to customise the cache key through req, which can be handled using the function form, as shown in the following code: ```ts title="server/cache.ts" import type { CacheOption, CacheOptionProvider } from '@modern-js/runtime/server'; const provider: CacheOptionProvider = (req) => { const { url, headers, ... } = req; const key = computedKey(url, headers, ...); return { maxAge: 500, // ms staleWhileRevalidate: 1000, // ms customKey: key, } } export const cacheOption: CacheOption = provider; ``` **Mapping type** ```ts export type CacheOptions = Record<string, CacheControl | CacheOptionProvider>; ``` Sometimes, developers need to apply different caching policies for different routes. We also provide a mapping way for configuration, as shown in example below: ```ts title="server/cache.ts" import type { CacheOption } from '@modern-js/runtime/server'; export const cacheOption: CacheOption = { '/home': { maxAge: 50, staleWhileRevalidate: 100, }, '/about': { maxAge: 1000 * 60 * 60 * 24, // one day staleWhileRevalidate: 1000 * 60 * 60 * 24 * 2 // two day }, '*': (req) => { // If the above routes cannot be matched, it will match to '*' const { url, headers, ... } = req; const key = computedKey(url, headers, ...); return { maxAge: 500, staleWhileRevalidate: 1000, customKey: key, } } } ``` - The route `http://xxx/home` will apply the first rule. - The route `http://xxx/about` will apply the second rule. - The route `http://xxx/abc` will apply the last rule. The above-mentioned `/home` and `/about` will be used as patterns for matching, which means that `/home/abc` will also comply with this rule. Simultaneously, you can also include regular expression syntax in it, such as `/home/.+`. ### Cache Container By default, Server will use memory for caching. But typically, services will be deployed on serverless. Each service access may be a new process, so caching cannot be applied every time. Therefore, developers can also customise the cache container, which needs to implement the `Container` interface. ```ts export interface Container<K = string, V = string> { /** * Returns a specified element from the container. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Container. * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. */ get: (key: K) => Promise<V | undefined>; /** * Adds a new element with a specified key and value to the container. If an element with the same key already exists, the element will be updated. * * The ttl indicates cache expiration time. */ set: (key: K, value: V, options?: { ttl?: number }) => Promise<this>; /** * @returns boolean indicating whether an element with the specified key exists or not. */ has: (key: K) => Promise<boolean>; /** * @returns true if an element in the container existed and has been removed, or false if the element does not exist. */ delete: (key: K) => Promise<boolean>; } ``` As an example in the following code, a developer can implement a Redis container. ```ts import type { Container, CacheOption } from '@modern-js/runtime/server'; class RedisContainer implements Container { redis = new Redis(); async get(key: string) { return this.redis.get(key); } async set(key: string, value: string): Promise<this> { this.redis.set(key, value); return this; } async has(key: string): Promise<boolean> { return this.redis.has(key); } async delete(key: string): Promise<boolean> { return this.redis.delete(key); } } const container = new RedisContainer(); export const customContainer: Container = container; export const cacheOption: CacheOption = { maxAge: 500, // ms staleWhileRevalidate: 1000, // ms }; ``` ## Cache Identification When the rendering cache is activated, Modern.js will identify the cache status of the current request through the response header `x-render-cache`. The following is an example of a response. ```bash < HTTP/1.1 200 OK < Access-Control-Allow-Origin: * < content-type: text/html; charset=utf-8 < x-render-cache: hit < Date: Thu, 29 Feb 2024 02:46:49 GMT < Connection: keep-alive < Keep-Alive: timeout=5 < Content-Length: 2937 ``` The `x-render-cache` may have the following values. | Name | Description | | ------- | -------------------------------------------------------------------------- | | hit | Cache hit, returns cached content | | stale | Cache hit, but data is stale, returns cached content while rendering again | | expired | Cache hit, returns rendering result after re-rendering | | miss | Cache miss |
use super::Solution; use super::TreeNode; use std::{cell::RefCell, rc::Rc}; type Node = Option<std::rc::Rc<std::cell::RefCell<super::TreeNode>>>; struct Solution0 {} impl Solution for Solution0 { fn sorted_array_to_bst(nums: Vec<i32>) -> Node { Problem::from(&nums).divide() } } struct Problem<'a> { nums: &'a [i32], } impl<'a> Problem<'a> { fn from(nums: &'a [i32]) -> Problem { Problem { nums } } fn divide(&self) -> Node { if self.nums.len() == 0 { return None; } let mid = self.nums.len() / 2; let ls = &self.nums[..mid]; let rs = &self.nums[mid + 1..]; Some(Rc::new(RefCell::new(TreeNode { val: self.nums[mid], left: Self::from(ls).divide(), right: Self::from(rs).divide(), }))) } }
package hindsight import ( "bytes" "crypto/rand" "encoding/base64" "fmt" "io/ioutil" "github.com/BurntSushi/toml" ) type Config struct { ListenIngestion string // host:port for API - should not be public ListenUI string // host:port for UI - could be exposed to internet DatabasePath string // path to DB RandomSaltSeed string // A random string to use to generate the daily hashes } func LoadConfig(filename string) (*Config, error) { // set defaults c := &Config{ ListenIngestion: "127.0.0.1:8765", ListenUI: "127.0.0.1:8080", DatabasePath: "hindsight.db", RandomSaltSeed: "", // leave this empty until after toml unmarshalling } _, err := toml.DecodeFile(filename, c) if err != nil { return nil, fmt.Errorf("could not load config file from %q: %w", filename, err) } if c.RandomSaltSeed == "" { // generate some random data. buf := make([]byte, 16) _, err = rand.Read(buf) if err != nil { return nil, fmt.Errorf("could not generate any randomness: %w", err) } c.RandomSaltSeed = base64.RawURLEncoding.EncodeToString(buf) // we should write that back to the file... // but I don't want to "blat" any comments. //so we will read the entire file and replace that little bit existing, err := ioutil.ReadFile(filename) if err != nil { return nil, fmt.Errorf("could not read config file to add randomness: %w", err) } // we will rewrite the whole file b := bytes.Buffer{} index := bytes.Index(existing, []byte(`random_salt_seed`)) if index == -1 { // just append b.Write(existing) fmt.Fprintf(&b, "\nrandom_salt_seed = %q # AUTO-GENERATED\n", c.RandomSaltSeed) } else { // replace, write data before b.Write(existing[0:index]) // insert new value (we don't need the newline here) fmt.Fprintf(&b, "random_salt_seed = %q # AUTO-GENERATED\n", c.RandomSaltSeed) // find the original next newline newline := bytes.IndexByte(existing[index:], '\n') if newline != -1 { // if it was -1, then there was no trailing newline, so we don't have any more file. // but if not, then we should write the rest. b.Write(existing[index+newline+1:]) } } err = ioutil.WriteFile(filename, b.Bytes(), 0644) if err != nil { return nil, fmt.Errorf("failed to rewrite config file: %w", err) } } return c, nil }
import React from "react"; import styles from "../css/Card.module.css"; import { Link } from "react-router-dom"; const Card = ({ image, name, id, weight, height, type }) => { return ( <Link to={`/${id}`} className={styles.cardLink}> <div className={styles.card}> <img src={image} alt="pokemon" /> <h2 className={styles.name}>{name}</h2> <p className={styles.info}>ID: {id}</p> <p className={styles.info}>Weight: {weight}</p> <p className={styles.info}>Height: {height}</p> <p className={styles.info}>Type: {type}</p> </div> </Link> ); }; export default Card;
import React from "react"; import ChildCard from "./ChildCard"; import "./Childrens.css"; export default function Childrens() { const [books, setBooks] = React.useState([]); React.useEffect(() => { fetch("http://localhost:5000/allbook") .then((r) => r.json()) .then(setBooks); }, []); const filteredBooks = books.filter((book) => book.category === "Childrens"); return ( <section className="outer"> <h1> Children's <span>Section</span> </h1> <p> Welcome to the eLibrary Children's Book section! Here, we offer a wide range of engaging and educational books specifically tailored for young readers. Our collection features an assortment of fiction and non-fiction books, designed to captivate the imaginations of children of all ages. </p> <div className="grd"> {filteredBooks.map((book) => ( <ChildCard book={book} key={book._id} /> ))} </div> </section> ); }
import { verify } from "jsonwebtoken"; import { isValidObjectId } from "mongoose"; import { NextFunction, Response } from "express"; import { RequestWithAuthenticatedTutor, RequestWithAuthenticatedStudent, } from "../interface/auth.interface"; export const authenticateStudentToken = ( req: RequestWithAuthenticatedStudent, res: Response, next: NextFunction ) => { const token = req.cookies?.token; if (!token) { return res .status(401) .json({ message: "Authorization failed. No access token." }); } verify(token, process.env.JWT_SECRET as string, (err: any, student: any) => { if (err || (student && (student.isTutor || !isValidObjectId(student.id)))) { return res .cookie("token", "", { httpOnly: true, secure: true, sameSite: "none", path: "/", }) .status(401) .json({ message: "Invalid cookies" }); } req.studentId = student.id; next(); }); }; export const authenticateTokenTutor = ( req: RequestWithAuthenticatedTutor, res: Response, next: NextFunction ) => { const token = req.cookies?.idToken; if (!token) { return res .status(401) .json({ message: "Authorization failed. No access token." }); } verify(token, process.env.JWT_SECRET as string, (err: any, tutor: any) => { if (err || (tutor && (!tutor.isTutor || !isValidObjectId(tutor.id)))) { return res .cookie("idToken", "", { httpOnly: true, secure: true, sameSite: "none", path: "/", }) .status(401) .json({ message: "Invalid cookies" }); } req.tutorId = tutor.id; next(); }); };
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <c:url var='root' value='/' /> <!DOCTYPE html> <html lang="ko"> <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>햄 반려견 사이트 만들기 프로젝트_join</title> </head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <body> <c:import url="/WEB-INF/views/include/top.jsp" /> <div class="backImage_view3"> <div class="signup-form"> <form:form action="${root}user/join_pro" method='post' modelAttribute="UserBeanjoin"> <form:hidden path="userIdExist" /> <form:label path="user_name" id="j_label4">이름</form:label> <form:input path="user_name" class="form-control" id="exampleFormControlInput13" /> <form:errors path="user_name" style='color:red' /> <div style="display: inline-block"> <form:label path="user_id" id="j_label">아이디</form:label> <form:input path="user_id" class="form-control" onkeypress="resetUserIdExist()" style="margin-top: -35px; margin-left: 120px; margin-right: 100px; padding-top: 5px; padding-left: 5px; padding-right: 5px; padding-bottom: 5px; width: 220px;"/> <button type="button" class="btn btn-light" id="reChk" onclick='checkUserIdExist()'>중복확인</button> </br> <form:errors path="user_id" style='color:red' /> </div> <form:label path="user_pw" id="j_label2">비밀번호</form:label> <form:password path="user_pw" class="form-control" id="exampleFormControlInput11" /> <form:errors path="user_pw" style='color:red' /> <form:label path="user_pw2" id="j_label3">비밀번호 확인</form:label> <form:password path="user_pw2" class="form-control" id="exampleFormControlInput12" /> <form:errors path="user_pw2" style='color:red' /> <form:label path="user_email" id="j_label5">이메일</form:label> <form:input path="user_email" class="form-control" id="exampleFormControlInput14" /> <form:errors path="user_email" style='color:red' /> <form:label path="user_phone" id="j_label6">휴대폰 번호</form:label> <form:input path="user_phone" class="form-control" id="exampleFormControlInput15" /> <form:errors path="user_phone" style='color:red' /></br> <form:button class="btn btn-secondary" id="joinBtn">회원가입</form:button> </form:form> </div> </div> <script> function checkUserIdExist(){ var user_id = $("#user_id").val() if(user_id.length == 0){ alert('아이디를 입력해주세요') return } console.log(user_id); $.ajax({ url : '${root}user/checkUserIdExist/' + user_id, type : 'get', dataType : 'text', success : function(result){ if(result.trim() == 'true'){ alert('사용할 수 있는 아이디입니다') $("#userIdExist").val('true') } else { alert('사용할 수 없는 아이디 입니다') $("#userIdExist").val('false') } } }) } function resetUserIdExist(){ $("#userIdExist").val('false') } </script> </body> </html>
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title>HTML Academy: Нёрдс</title> <link rel="stylesheet" href="css/normalize.min.css"> <link rel="stylesheet" href="css/style.min.css"> </head> <body> <h1 class="visually-hidden">Дизайн-студия Nerds</h1> <header class="header"> <div class="container header__container"> <a class="logo header__logo"> <img src="img/svg/logo.svg" alt="Логотип дизайн-студии Nerds" class="logo__img" width="160" height="65"> </a> <nav class="nav header__nav"> <ul class="nav-list"> <li class="nav-list__item"> <a href="#0" class="nav-list__link">Студия</a> </li> <li class="nav-list__item"> <a href="#0" class="nav-list__link">Клиенты</a> </li> <li class="nav-list__item"> <a href="catalog.html" class="nav-list__link">Магазин</a> </li> <li class="nav-list__item"> <a href="#0" class="nav-list__link">Контакты</a> </li> </ul> </nav> <div class="cart header__cart"> <a href="#0" class="cart__link">Корзина</a> </div> </div> </header> <main class="main"> <section class="features"> <h2 class="visually-hidden">Преимущества</h2> <input type="radio" name="feature" id="scrupulously" class="features__hide-control visually-hidden" checked> <input type="radio" name="feature" id="mathematics" class="features__hide-control visually-hidden"> <input type="radio" name="feature" id="night-work" class="features__hide-control visually-hidden"> <ul class="features-list"> <li class="features-list__item"> <div class="feature feature--scrupulously"> <h3 class="feature__title">Долго, дорого, скрупулезно.</h3> <p class="feature__text">Математически выверенный дизайн<br>для вашего сайта или мобильного приложения.</p> <a href="#0" class="btn btn--red feature__btn">Узнать больше</a> </div> </li> <li class="features-list__item"> <div class="feature feature--mathematics"> <h3 class="feature__title">Любим математику, как никто другой</h3> <p class="feature__text">Никакого креатива, только математические формулы для расчета идеальных пропорций.</p> <a href="#0" class="btn btn--red feature__btn">Узнать больше</a> </div> </li> <li class="features-list__item"> <div class="feature feature--night-work"> <h3 class="feature__title">Только ночь, только хардкор</h3> <p class="feature__text">Работать днем, как все? Мы против этого. Ближе к полуночи работа только начинается.</p> <a href="#0" class="btn btn--red feature__btn">Узнать больше</a> </div> </li> </ul> <ul class="slide-controls features__slide-controls"> <li class="slide-controls__item"> <label class="slide-controls__btn" for="scrupulously">Первый слайд</label> </li> <li class="slide-controls__item"> <label class="slide-controls__btn" for="mathematics">Второй слайд</label> </li> <li class="slide-controls__item"> <label class="slide-controls__btn" for="night-work">Третий слайд</label> </li> </ul> </section> <div class="container"> <section class="services"> <h2 class="visually-hidden">Услуги</h2> <ul class="services-list"> <li class="service services-list__item"> <img src="img/pictures/services/websites.jpg" class="service__img" alt="Веб-сайты" width="300" height="146"> <h3 class="service__title">Веб-сайты</h3> <p class="service__desc">Мир никогда не будет прежним<br>после того как увидит ваш сайт!</p> <a href="#0" class="btn btn--red service__btn">Заказать</a> </li> <li class="service services-list__item"> <img src="img/pictures/services/applications.jpg" class="service__img" alt="Приложения" width="300" height="146"> <h3 class="service__title">Приложения</h3> <p class="service__desc">Покорите топ-10 приложений в AppStore и Google Play</p> <a href="#0" class="btn btn--green service__btn">Заказать</a> </li> <li class="service services-list__item"> <img src="img/pictures/services/presentations.jpg" class="service__img" alt="Презентации" width="300" height="146"> <h3 class="service__title">Презентации</h3> <p class="service__desc">Вы даже не подозреваете,<br>насколько вы изумительны!</p> <a href="#0" class="btn btn--yellow service__btn">Заказать</a> </li> </ul> </section> <section class="about"> <h2 class="visually-hidden">О нас</h2> <div class="about__text"> <p class="about__title">Мы — маленькая, но гордая дизайн-студия из Краснодара. </p> <p class="about__desc">Исповедуем принципы минимализма и чистоты. Ставим математический расчет превыше креатива. Работаем не покладая рук, как роботы.</p> <div class="orders about__orders"> <p class="orders__title"><b>Выполняем заказы на разработку:</b></p> <ul class="orders-list"> <li class="orders-list__item">Веб-сайтов любой сложности</li> <li class="orders-list__item">Мобильных приложений для iOS и Android</li> <li class="orders-list__item">Слайдшоу и видео для корпоративных презентаций</li> </ul> </div> </div> <div class="performance about__performance"> <p class="performance__title"><b>С 2004 года любим точность во всем:</b></p> <table class="figure-table performance__figure-table"> <tr class="figure-table__tr"> <th class="percent figure-table__th">146<sup class="percent__unit">%</sup></th> <th class="percent figure-table__th">100<sup class="percent__unit">%</sup></th> <th class="percent figure-table__th">50<sup class="percent__unit">%</sup></th> </tr> <tr class="figure-table__tr"> <td class="figure-table__td">Уровень самоотдачи</td> <td class="figure-table__td">Соблюдение сроков</td> <td class="figure-table__td">Минимальная предоплата</td> </tr> </table> </div> </section> <section class="brands"> <h2 class="visually-hidden">Брэнды</h2> <ul class="brands-list"> <li class="brand brands-list__item"> <a href="https://htmlacademy.ru/intensive/htmlcss" class="brand__link" target="_blank"> <img src="img/pictures/brands/htmlacademy.png" alt="Логотип htmlacademy" class="brand__img" width="199" height="68"> </a> </li> <li class="brand brands-list__item"> <a href="#0" class="brand__link"> <img src="img/pictures/brands/borodinski.png" alt="Логотип borodinski" class="brand__img" width="209" height="90"> </a> </li> <li class="brand brands-list__item"> <a href="#0" class="brand__link"> <img src="img/pictures/brands/pink.png" alt="Логотип pink" class="brand__img" width="185" height="52"> </a> </li> <li class="brand brands-list__item"> <a href="#0" class="brand__link"> <img src="img/pictures/brands/mishka.png" alt="Логотип mishka" class="brand__img" width="173" height="84"> </a> </li> </ul> </section> </div> </main> <footer class="footer"> <section class="map footer__map"> <h2 class="visually-hidden">Как нас найти</h2> <div id="map" class="map__container"></div> <div class="container"> <section class="contacts map__contacts"> <h3 class="contacts__title">NЁRDS DESIGN STUDIO</h3> <address class="contacts__address">191186, Санкт-Петербург,<br>ул. Б. Конюшенная, д. 19/8</address> <a href="tel:+78122757575" class="contacts__phone">тел. +7 (812) 275-75-75</a> <a href="#modal" class="btn btn--red contacts__btn" id="feedback">Напишите нам</a> </section> </div> </section> <div class="footer__bottom"> <div class="container footer__container"> <ul class="socials footer__socials"> <li class="socials__item"> <a href="#0" class="socials__link socials__link--vk">Вконтакте</a> </li> <li class="socials__item"> <a href="#0" class="socials__link socials__link--fb">Фейсбук</a> </li> <li class="socials__item"> <a href="#0" class="socials__link socials__link--in">Инстаграм</a> </li> </ul> <p class="appeal footer__appeal"> <b class="appeal__title">Давайте дружить, это выгодно!</b> Скидка 10% для друзей из социальных сетей. </p> </div> </div> </footer> <section class="modal" id="modal"> <div class="modal__content"> <h2 class="modal__title">Напишите нам</h2> <form action="https://echo.htmlacademy.ru" class="form modal__form" method="POST"> <div class="form__wrapper"> <div class="ipt form__field"> <label for="request-name" class="ipt__label">Ваше имя:</label> <input type="text" name="fio" id="request-name" class="ipt__field" value="" placeholder="Имя Фамилия"> </div> <div class="ipt form__field"> <label for="request-email" class="ipt__label">Ваш e-mail:</label> <input type="email" name="email" id="request-email" class="ipt__field" value="" placeholder="[email protected]"> </div> </div> <div class="ipt ipt--textarea form__field"> <label for="request-text" class="ipt__label">Текст письма:</label> <textarea name="text" id="request-text" class="ipt__field" placeholder="В свободной форме"></textarea> </div> <button type="submit" class="btn btn--red form__btn">Отправить</button> </form> <button type="button" class="close modal__close">Закрыть</button> </div> </section> <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU"></script> <script src="js/index.min.js"></script> </body> </html>
<!-- 提现教程 --> <template> <div class="flex flex-col h-full overflow-hidden tlw_top_bg" :style="{ paddingTop: `${top || 0}px` }" > <NavBar class="flex-shrink-0" transparent :nav-bar-props="{ title: '提现教程' }"> <template #right> <i class="z-10 text-white ml-2 icon-erji text-lg" @click="toService" /> </template> </NavBar> <div class="flex-1 overflow-hidden rounded-t-20px bg-mainBg z-0"> <SwiperBox ref="swiperRef" class="rounded-20px"> <van-collapse v-model="activeNames" @change="change" :border="false" style="--van-collapse-item-content-background: transparent" > <van-collapse-item :name="index" :key="index" v-for="(item, index) in list" class="last-of-type:rounded-b-20px overflow-hidden" > <template #title> <div class="flex items-center"> <i class="iconfont icon-wenti-yuan text-base mr-1 text-txt_d"></i> <p class="text-[15px] leading-[30px]"> {{ item.title }} </p> </div> </template> <div class="text-black/60 text-gz text-13px leading-6" v-html="item.content" ></div> </van-collapse-item> </van-collapse> </SwiperBox> </div> </div> </template> <script setup lang="ts"> import type { SwiperRef } from "@/components/types"; import { timeOut, toService } from "@/utils"; import { ref, shallowRef } from "vue"; import NavBar from "@/components/NavBar.vue"; import SwiperBox from "@/components/SwiperBox.vue"; import { useApp } from "@/stores/useApp"; import { storeToRefs } from "pinia"; const activeNames = ref([99]); const swiperRef = ref<SwiperRef>(); const { top } = storeToRefs(useApp()); const list = shallowRef<{ title?: string; content?: string; name?: string }[]>([ { title: "如何取款", content: `1、第一次取款请先绑定银行卡,绑定银行卡步骤:<br/> &nbsp a、登录账号 -- 我的页面 -- 账户管理--添加银行卡;<br/> &nbsp b、登录账号 -- 我的页面--点击取款-- 添加银行卡。<br/> 2、 绑定完成后,在取款金额框中输入金额,点击立即取款。`, name: "", }, { title: "可以使用别人的银行卡进行取款吗?", content: `为了确保客户的账户资金安全,取款需要使用账号本人的银行卡才可以进行取款哦,且取款银行卡姓名必须与注册姓名一致。`, name: "", }, { title: "申请取款需要注意些什么?", content: `1、绑定的银行卡姓名需与当前账户的注册姓名一致。<br/> 2、绑定的银行卡信息需要正确。<br/> 3、若您未申请任何红利优惠,投注满一倍流水即可申请取款。<br/> 4、若申请首存红利,则需要满足优惠活动写明的有效投注额要求。<br/> 5、全天24小时都可发起取款申请。`, name: "", }, { title: "游戏账户里有钱为什么无法取款?", content: `您需要先将资金从游戏平台钱包转至中心钱包后,才能进行取款操作。`, name: "", }, { title: "可以绑定多张银行卡吗?", content: `每一个用户均可以绑定5张银行卡进行取款操作,在我的页面选择“账户管理”,按步骤添加银行卡即可。`, name: "", }, { title: "取款为什么还需要审核?", content: `取款审核是相关部门在给您办理出款之前的一个简单的核实步骤,是为了确保客户资金安全,所以需要核实相关信息。`, name: "", }, { title: "取款要求(例:流水)", content: `用户只要达到存款全额投注要求,即可随时申请取款。比如,您存100元,在该笔存款后,您累计下注达到100元的取款流水,即可办理取款!<br/> 温馨提示:若会员有领取其他优惠,必须达到相对应的有效流水才能办理取款!`, name: "", }, { title: "取款到账时间", content: `用户取款一般10分钟内到账,如果30分钟还未到账可以联系在线客服为您核查!`, name: "", }, { title: "取款支持的银行", content: `目前为您提供15家取款银行:中国银行、工商银行、建设银行、交通银行、农业银行、招商银行、民生银行、平安银行、华夏银行、广东发展银行、邮政储蓄银行、中信银行、兴业银行、上海浦发银行、光大银行。系统不定时会有所调整,具体还请您以添加银行卡时提供的银行为准。`, name: "", }, { title: "我流水还差多少?", content: `首先确认自己是否有申请优惠活动,找到对应优惠活动查看所 需流水,无申请优惠活动情况下1倍流水即可出款。<br/> 若无法确认自己所需流水倍数,可直接联系7*24小时在线客服。`, name: "", }, { title: "取款输入金额无法提交申请?", content: `1.金额是否从场馆成功转出至中心钱包。 2.若提示〝您有订单尚未核实成功“请联系客服进行咨询。若有其他取款问题请与7*24小时客服团队联系。`, name: "", }, { title: "我取款未到账?", content: `用户取款一般10分钟内到账,如果30分钟还未到账可以联系在线客服为您核查`, name: "", }, ]); const change = async () => { await timeOut(300); swiperRef.value?.update?.(); }; </script> <style lang="scss" scoped> ::v-deep(.van-collapse) { .van-collapse-item__content { padding-left: 12px; padding-right: 0; } } </style>
import React, { useState } from 'react'; import './index.css' const CadastroMedico = () => { const estadosBrasileiros = [ 'AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO' ]; const [medico, setMedico] = useState({ nome: '', email: '', numero: '', crm: '', especialidade: '', endereco: { logradouro: '', numero: '', complemento: '', bairro: '', cidade: '', uf: '', cep: '', }, ativo: true }); const handleChange = (event) => { const { name, value } = event.target; setMedico((prevMedico) => ({ ...prevMedico, [name]: value, })); }; const handleChangeEndereco = (event) => { const { name, value } = event.target; setMedico((prevMedico) => ({ ...prevMedico, endereco: { ...prevMedico.endereco, [name]: value, }, })); }; // No input do formulário <input type="text" name="logradouro" value={medico.endereco.logradouro} onChange={handleChangeEndereco} required /> const [mensagem, setMensagem] = useState(''); const exibirMensagem = (mensagem) => { setMensagem(mensagem); // Limpar a mensagem após 5 segundos setTimeout(() => { setMensagem(''); }, 8000); }; const handleSubmit = async (event) => { event.preventDefault(); try { const resposta = await fetch('http://localhost:8080/medico', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(medico), }); const dados = await resposta.json(); if (!resposta.ok) { // Se o status da resposta não for OK, trata como erro throw new Error(`Erro ao cadastrar médico: ${dados.message}`); } exibirMensagem('Médico cadastrado com sucesso'); console.log('Médico cadastrado com sucesso:', dados); } catch (error) { exibirMensagem(`${error.message}`); console.error(error.message); } }; return ( <div className="container"> <h1>Cadastro de Médico</h1> <form onSubmit={handleSubmit}> <label> Nome: <input type="text" name="nome" value={medico.nome} onChange={handleChange} required /> </label> <label> E-mail: <input type="email" name="email" value={medico.email} onChange={handleChange} required /> </label> <label> Telefone: <input type="tel" name="numero" value={medico.numero} onChange={handleChange} required /> </label> <label> CRM: <input type="text" name="crm" value={medico.crm} onChange={handleChange} required /> </label> <label> Especialidade: <select name="especialidade" value={medico.especialidade} onChange={handleChange} required > <option value="">Selecione uma especialidade</option> <option value="Ortopedia">Ortopedia</option> <option value="Cardiologia">Cardiologia</option> <option value="Ginecologia">Ginecologia</option> <option value="Dermatologia">Dermatologia</option> </select> </label> <label> Logradouro <input type="text" name="logradouro" value={medico.endereco.logradouro} onChange={handleChangeEndereco} required /> </label> <label> Complemento: <input type="text" name="complemento" value={medico.endereco.complemento} onChange={handleChangeEndereco} /> </label> <label> Bairro: <input type="text" name="bairro" value={medico.endereco.bairro} onChange={handleChangeEndereco} required /> </label> <label> Cidade: <input type="text" name="cidade" value={medico.endereco.cidade} onChange={handleChangeEndereco} required /> </label> <label> UF: <select name="uf" value={medico.endereco.uf} onChange={handleChangeEndereco} required > <option value="">Selecione um estado</option> {estadosBrasileiros.map((sigla) => ( <option key={sigla} value={sigla}> {sigla} </option> ))} </select> </label> <label> CEP: <input type="text" name="cep" value={medico.endereco.cep} onChange={handleChangeEndereco} required /> </label> <label> Número: <input type="text" name="numero" value={medico.endereco.numero} onChange={handleChangeEndereco} /> </label> <button type="submit">Cadastrar Médico</button> </form> {mensagem && ( <div className="mensagem-temporaria"> <p>{mensagem}</p> </div> )} </div> ); }; export default CadastroMedico;
<div class="card mb-4"> <div class="card-header"><i class="fas fa-table mr-1"></i>Table 4://Add eNodeB Function (ADD ENODEBFUNCTION) </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead class="thead-dark"> <tr> <th>Acciones</th> <th>Parameter ID</th> <th>eNodeB Function Name</th> <th>Application REF</th> <th>eNodeB ID</th> <th>USER LABEL</th> </tr> </thead> <tbody> <tr *ngIf="object"> <td> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-primary" (click)="openScrollableContent(longContent)" (click)="editar()"> Editar </button> <button (click)="eliminar()" type="button" class="btn btn-danger btn-sm"> Eliminar </button> </div> </td> <td>{{object.parameterId}}</td> <td>{{object.eNodeBFunctionName}}</td> <td>{{object.applicationRef}}</td> <td>{{object.enodebId}}</td> <td>{{object.userLabel}}</td> </tr> </tbody> </table> </div> <button *ngIf="!object" type="button" class="btn btn-primary" (click)="openScrollableContent(longContent)"> Agregar </button> <p *ngIf="object" class="text-center"> <strong>{{object.Command}}</strong></p> </div> </div> <ng-template #longContent let-modal> <div class="modal-header"> <h5 class="modal-title" id="configDataModal">//Add eNodeB Function (ADD ENODEBFUNCTION)</h5> <button type="button" class="close" (click)="modal.dismiss('Cross click')" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="modal-body"> <form [formGroup]="form"> <div class="form-group"> <label for="parameterId" class="col-form-label">Parameter ID:</label> <select formControlName="parameterId" class="form-control"> <option *ngFor="let item of parametersId" [value]="item">{{item}}</option> </select> </div> <div class="form-group"> <label for="eNodeBFunctionName" class="col-form-label">eNodeB Function Name</label> <input formControlName="eNodeBFunctionName" class="form-control" id="eNodeBFunctionName"> </div> <div class="form-group"> <label for="applicationRef" class="col-form-label">Application REF</label> <input type="number" formControlName="applicationRef" class="form-control" id="applicationRef"> </div> <div class="form-group"> <label for="enodebId" class="col-form-label">eNodeB ID</label> <input type="number" formControlName="enodebId" class="form-control" id="enodebId"> </div> <div class="form-group"> <label for="userLabel" class="col-form-label">USER LABEL</label> <input formControlName="userLabel" class="form-control" id="userLabel"> </div> </form> </div> </div> <div class="modal-footer"> <button type="reset" class="btn btn-danger" (click)="modal.close('Close click')">Close</button> <button type="button" (click)="guardar()" class="btn btn-success mr-2" (click)="modal.close('Close click')"> <i class="fa fa-save"></i> Guardar </button> </div> </ng-template>
import { Box, CircularProgress, Typography } from '@mui/material'; import { useDispatch, useSelector } from 'react-redux'; import { fetchDashboard, selectorDashboard, } from 'src/features/dashboard/dashboard-slice'; import { useEffect, useState } from 'react'; import { BorderLinearProgress } from './borderLinearStyle'; export function Balance() { const dispatch = useDispatch(); const dashboardRate = useSelector(selectorDashboard); const [progressValue, setProgressValue] = useState(0); const loading = useSelector((s) => s.dashboard.loading); const { balanceAvailable, limit, totalBalance } = dashboardRate[0]?.balance || {}; useEffect(() => { dispatch<any>(fetchDashboard()); setProgressValue(parseFloat(totalBalance) % parseFloat(limit)); }, [dispatch, limit, totalBalance]); return ( <Box border="1px solid #e2e2e2" maxWidth="100%" bgcolor="white"> <Box component="div" display="flex" justifyContent="space-between" borderBottom="1px solid #e2e2e2" p={2} m={0} > <Typography variant="h3" color="info.dark" fontSize={16}> Saldo disponivel </Typography> </Box> <Box p={2}> <Typography variant="h4" display="flex" color="secondary" mb={2} alignItems="center" > <Typography color="text.secondary" mr={1} fontSize={29}> R$ </Typography>{' '} {loading === 'pending' ? ( <CircularProgress color="secondary" size="25px" /> ) : ( balanceAvailable )} </Typography> <BorderLinearProgress variant="determinate" value={progressValue} /> <Box display="flex" mt={2}> <Box> <Box color="text.secondary" fontSize={13}> <Typography width={10} height={10} bgcolor="#e77827" m={0} p={0} display="inline-block" borderRadius={50} mr={1} component="span" /> <Typography display="inline">Limite</Typography> </Box> <Box fontWeight="bold"> {' '} <Typography variant="body1" color="text.secondary" fontSize={15} display="inline" > R$ </Typography>{' '} {loading === 'pending' ? ( <CircularProgress color="primary" size="15px" /> ) : ( limit )} </Box> </Box> <Box ml={4}> <Box color="text.secondary" fontSize={13}> <Typography width={10} height={10} bgcolor="#1eba5c" m={0} p={0} display="inline-block" borderRadius={50} mr={1} component="span" /> <Typography display="inline">Saldo Total</Typography> </Box> <Box fontWeight="bold"> {' '} <Typography variant="body1" color="text.secondary" fontSize={15} display="inline" > R$ </Typography>{' '} {loading === 'pending' ? ( <CircularProgress color="info" size="15px" /> ) : ( totalBalance )} </Box> </Box> </Box> </Box> </Box> ); }
<!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>{% block title %}Document{% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </head> <body> {% if user.is_authenticated %} <header class="py-3 mb-3 border-bottom"> <div class="container-fluid d-grid gap-3 align-items-center" style="grid-template-columns: 1fr 2fr;"> <a href="/note/"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-house-door-fill" viewBox="0 0 16 16"> <path d="M6.5 14.5v-3.505c0-.245.25-.495.5-.495h2c.25 0 .5.25.5.5v3.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5z"/> </svg> </a> <div class="d-flex align-items-center"> <form class="w-100 me-3" role="search"> <input type="search" class="form-control" placeholder="Search..." aria-label="Search"> </form> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> User </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><a class="dropdown-item" href="/logout/">Logout</a></li> </ul> </div> </div> </div> </header> <div class="container-fluid pb-3"> <div class="d-grid gap-3" style="grid-template-columns: 1fr 2fr;"> <div class="bg-light border rounded-3"> {% block content %} <br><br><br><br><br><br><br><br><br><br> {% endblock %} </div> <div class="bg-light border rounded-3"> {% block content2 %} {% endblock %} <br><br><br><br><br><br><br><br><br><br> </div> </div> </div> {% else %} <section class="vh-100" style="background-color: #696969;"> <div class="container py-5 h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-12 col-md-8 col-lg-6 col-xl-5"> <div class="card shadow-2-strong" style="border-radius: 1rem;"> <div class="card-body p-5 text-center"> <h2>You must login or register</h2> <br> <a href="/login/"><button class="btn btn-primary btn-lg btn-block" type="submit">Login</button></a> <a href="/register/"><button class="btn btn-primary btn-lg btn-block" type="submit">Sign in</button></a> </div> </div> </div> </div> </div> </section> {% endif %} </body> </html>
using Dapper; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; namespace API_piment.Controllers { [Route("api/[controller]")] [ApiController] public class UserController : ControllerBase { #region DI private readonly SqlConnection? _conn = null; private readonly Services.Token.JWTService? _jwtService = null; private readonly string str = @"Data Source=DESKTOP-FH1BO1J\SQLEXPRESS;Initial Catalog=Piments;Integrated Security=True;Encrypt=True;Trust Server Certificate=True;Multi Subnet Failover=False"; public UserController(Services.Token.JWTService? jwtService) { _conn = new SqlConnection(str); _jwtService = jwtService; } #endregion /// <summary> /// Registers a new user. /// </summary> /// <param name="model">User information to register.</param> /// <returns>ActionResult representing the result of the operation.</returns> [HttpPost] [ProducesResponseType(201)] // Created [ProducesResponseType(400)] // Bad Request public IActionResult Post([FromBody] Models.UserRegisterDTO model) { if (model is not null) { Models.User user = new(model.Name, model.Email, model.Password, "Register"); string sql = "INSERT INTO [User] (Name, Email, Password, Role) VALUES (@name, @email, @password, @role)"; var paramFromModel = new { name = user.Name, email = user.Email, password = user.Password, role = user.Role }; var rowAffected = _conn.Execute(sql, paramFromModel); if (rowAffected > 0) return CreatedAtAction(nameof(Post), user); } return BadRequest(); } /// <summary> /// Retrieves all users. /// </summary> /// <returns>ActionResult representing the result of the operation.</returns> [HttpGet] [ProducesResponseType(200)] // OK [ProducesResponseType(204)] // No Content public ActionResult<IEnumerable<Models.UserDisplayDTO>> Get() { string sql = "SELECT * FROM [User]"; IEnumerable<Models.UserDisplayDTO>? items = _conn?.Query<Models.UserDisplayDTO>(sql).ToList(); if (items is not null && items.Any()) return Ok(items); return NoContent(); } /// <summary> /// Authenticates a user. /// </summary> /// <param name="model">User authentication information.</param> /// <returns>ActionResult representing the result of the operation.</returns> [HttpPost(nameof(Log))] [ProducesResponseType(200)] // OK [ProducesResponseType(400)] // Bad Request public ActionResult<Models.UserTokenDTO> Log(Models.UserLogDTO model) { string sql = "SELECT Id, Role FROM [User] WHERE Password = @pass AND Email = @mail"; Models.UserTokenDTO? result = _conn?.Query<Models.UserTokenDTO>(sql, new { pass = model.Password, mail = model.Email }).FirstOrDefault(); if (result is not null) { string id = (result.Id).ToString(); string role = result.Role; string token = _jwtService?.GenerateToken(id, role) ?? ""; if (!string.IsNullOrEmpty(token)) { // Retourne explicitement du JSON, l'api le convertira automatiquement si tu lui cree un nouvel objet pour le retour. return Ok(new { token }); } } return BadRequest(); } } }
import classNames from 'classnames'; import React, { FC } from 'react'; import { Filter } from '../types/Filters'; type Props = { uncomplitedTodosCount: number complitedFilter: Filter setComplitedFilter: (v: Filter) => void deleteAllCompletetById:()=>void }; export const Footer: FC<Props> = React.memo((props) => { const { uncomplitedTodosCount, complitedFilter, setComplitedFilter, deleteAllCompletetById, } = props; return ( <footer className="todoapp__footer" data-cy="Footer"> <span className="todo-count" data-cy="todosCounter"> {`${uncomplitedTodosCount} items left`} </span> <nav className="filter" data-cy="Filter"> <a data-cy="FilterLinkAll" href="#/" className={classNames('filter__link', { selected: complitedFilter === Filter.All, })} onClick={() => setComplitedFilter(Filter.All)} > All </a> <a data-cy="FilterLinkActive" href="#/active" className={classNames('filter__link', { selected: complitedFilter === Filter.Active, })} onClick={() => setComplitedFilter(Filter.Active)} > Active </a> <a data-cy="FilterLinkCompleted" href="#/completed" className={classNames('filter__link', { selected: complitedFilter === Filter.Complited, })} onClick={() => setComplitedFilter(Filter.Complited)} > Completed </a> </nav> <button data-cy="ClearCompletedButton" type="button" className="todoapp__clear-completed" onClick={deleteAllCompletetById} > Clear completed </button> </footer> ); });
// 1) Selecionar todas as tags h2 e colocar um background verde nos elementos selecionados. // 2) Selecionar o pai da classe buttons e colocar um background vermelho no elemento selecionado. // 3) Selecionar os elementos filhos da classe module e colocar como background a cor azul. // 4) Selecionar o item da lista de índice 2 da classe module utilizando a função eq() e colocar como background a cor verde. // 5) Selecionar o primeiro elemento da lista myList e colocar como background a cor Amarelo. // 6) Selecionar o último elemento da lista slideshow e colocar como background a cor preta. // 7) Verifique se o primeiro elemento filho de Search é um form. Se for, exiba um alert na tela com a mensagem “O elemento form é filho de Search. Caso não seja, exiba um alert na tela com a mensagem “O elemento form não é filho de Search. // 8) Selecionar todas as listas não ordenadas, exceto a de id slideshow e colocar como background a cor azul. // 9) Selecionar todos os itens de lista que possuam um parágrafo nele e colocar como background a cor rosa. // 10) Alterar o conteúdo da tag que possui a classe myListItem para “Este é um novo item de lista” // 11) Selecionar o próximo elemento após o elemento de classe selected e colocar um background cinza nele. // 12) Selecionar o elemento anterior ao elemento de classe input_text e colocar um background cinza nele. // 13) Selecionar todos os irmãos do elemento que possui o id listItem_2 e colocar um background verde nele. // 14) Selecionar todos os elementos que possuam um atributo src e colocar um background amarelo nele. // 15) Selecionar dentro do elemento de id header e dentro do id nav, o elemento que contenha a classe selected. (Utilizando um seletor que contenha esse caminho) // 16) Selecionar todos os elementos que possui o atributo type=”text”. // 17) Selecionar todos os elementos que possuam o atributo value. // 18) Selecionar todos os elementos que possuam o atributo type diferente de submit e colocar um background vermelho nele. // 19) Selecionar todos os elementos que possuam o atributo href que inicia com a palavra blog e colocar um background verde nele. // 20) Selecionar todos os elementos que possuam o atributo value que terminam com a letra a e colocar um background vermelho nele. // 21) Selecionar todos os elementos que possuam o atributo href que contenham a palavra html e colocar um background cinza nele. $(document).ready (function(){ $("h2").css({ backgroundColor:"green" }); $(".buttons").parent().css({ backgroundColor:"red" }); $(".module").has("*").css({ backgroundColor:"blue" }); $(".module").find("li").eq(2).css({ backgroundColor:"green" }); $("#myList li").first().css({ backgroundColor:"yellow" }); $("#slideshow li").last().css({ backgroundColor:"black" }); if ($("#search").children().first().is("form")) { alert("O elemento form é filho de Search"); }else{ alert("O elemento form não é filho de Search"); } $("ul").not("#slideshow").css({ backgroundColor:"blue" }); $("li").has("p").css({ backgroundColor:"pink" }); $("#myListItem").text("Este é um novo item de lista"); $(".selected").next().css({ backgroundColor:"gray" }); $(".input_text").prev().css({ backgroundColor:"gray" }); $("#listItem_2").siblings().css({ backgroundColor:"green" }); $("[src]").css({ backgroundColor:"yellow" }); $("#header, #nav").find(".selected") ; $("[type='text']"); $("[value]"); $("[type]").not("[type='submit']").css({ backgroundColor:"red" }); $("[href^='blog']").css({ backgroundColor:"green" }); $("[value$='a']").css({ backgroundColor:"red" }); $("[href*='html']").css({ backgroundColor:"gray" }); })
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { Route } from './app.constants'; import { CartComponent } from './pages/cart/cart.component'; import { ConfirmationComponent } from './pages/confirmation/confirmation.component'; import { ProductItemDetailsComponent } from './pages/product-item-details/product-item-details.component'; import { ProductListComponent } from './pages/product-list/product-list.component'; const routes: Routes = [ {path: Route.PRODUCTS_ROUTE, component: ProductListComponent}, {path: Route.PRODUCT_ITEM_ROUTE + '/:id', component: ProductItemDetailsComponent}, {path: Route.CART_ROUTE, component: CartComponent}, {path: Route.CONFIRMATION_ROUTE, component: ConfirmationComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import React, { useEffect,useState } from "react" import "./Header.css" import { Link, useNavigate } from "react-router-dom" import { useSelector, useDispatch } from "react-redux" import Profile from "./Profile" import { unSetUserToken } from '../../features/authSlice' import { removeToken } from '../../services/LocalStorageService' import { IoIosSearch } from "react-icons/io"; import { setUserInfo, unsetUserInfo } from "../../features/userSlice" const Header = () => { const navigate = useNavigate() const token = useSelector(state => state.auth.access_token) const user = useSelector((state) => state.user) const [query,SetQeury] = useState('') useEffect(() => { console.log('user', user) }, [user]) const dispatch = useDispatch() const logOut = () => { console.log('log Out') dispatch(unSetUserToken({ value: null })) dispatch(removeToken) dispatch(unsetUserInfo()) navigate('/login') } const searchQuery = () =>{ const searchQuery = query.replace(' ','+') console.log(searchQuery) navigate(`/search/${searchQuery}`) } return ( <div className="header"> <div className="headerLeft"> <Link to="/"> <h2 className="text-2xl text-white bg-black px-2 py-1 rounded-md">BeWatcher</h2> </Link> {token && <> <div className="hidden md:flex"> <Link to="/movies/popular" style={{ textDecoration: "none" }}><span>Popular</span></Link> <Link to="/movies/top_rated" style={{ textDecoration: "none" }}><span>Top Rated</span></Link> <Link to="/movies/upcoming" style={{ textDecoration: "none" }}><span>Upcoming</span></Link> <Link to="/watchlist" style={{ textDecoration: "none" }}><span>Watchlist</span></Link> <Link to="/favourites" style={{ textDecoration: "none" }}><span>Favorites</span></Link> <div id="serach-box" className='bg-white w-[300px] h-[35px] flex items-center justify-between px-4'> <input onChange={(e)=>SetQeury(e.target.value)} type="text" className='px-2 w-[250px] h-[35px] text-lg font-poppins' name="" id="" placeholder='Search' /> <IoIosSearch onClick={searchQuery} className='text-2xl' /> </div> </div> </> } </div> {token && user.username !== null && ( <Profile usr={user} logOut={logOut} /> )} </div> ) } export default Header
import { ref, computed, watch } from 'vue'; import { wrapToPromise } from '~/api/helpers/wrap-to-promise'; import { useGetApiV1Bookfile, useGetApiV1BookId, useGetApiV1BookIdOverview, usePutApiV1BookMonitor, } from '~/thirdPartyApis/readarr'; import type { BookFileResource, BookResource, SearchResource, } from '~/thirdPartyApis/readarr/models'; export interface IndexedBook { book: Ref<BookResource | undefined>; imageFilePath: ComputedRef<string>; bookOverview: Ref<unknown>; fileData: Ref<BookFileResource[] | undefined>; isLoading: ComputedRef<boolean>; AddToWishlist: () => Promise<void>; DownloadBook: () => void; } export function useIndexedBook(id: string): IndexedBook { const imageFilePath = computed(() => { const subPath = book.value?.images?.[0].url; return `${import.meta.env.VITE_FILE_SERVER_URL}/readarr${ subPath?.split('?')[0] }`; }); const isLoading = computed(() => { return isBookLoading.value || isOverviewLoading.value; }); const { data: book, isLoading: isBookLoading } = useGetApiV1BookId( Number(id) ); const bookFileParams = computed(() => ({ bookId: [Number(id)], authorId: book.value?.authorId, bookFileIds: [0], })); const { data: fileData } = useGetApiV1Bookfile(bookFileParams); const { data: bookOverview, isLoading: isOverviewLoading } = useGetApiV1BookIdOverview(Number(id)); const { mutate } = usePutApiV1BookMonitor(); async function AddToWishlist() { const callBack = async () => { mutate({ data: { bookIds: [Number(book.value?.id)], monitored: true }, }); await $fetch('/api/wishlist/add-to-wish-list', { method: 'POST', body: JSON.stringify({ bookId: book.value?.id }), }); useApplicationEvent('supabase:wishListUpdated'); }; await wrapToPromise(callBack, isLoading); } function DownloadBook() { const url = String(fileData.value?.[0].path); const strippedUrl = url.substring(3); window.open(`${import.meta.env.VITE_FILE_SERVER_URL}/books/${strippedUrl}`); } return { book, imageFilePath, bookOverview, fileData, isLoading, AddToWishlist, DownloadBook, }; }
package com.PAM.kantinkoperasi.adapter import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.ImageView import android.widget.TextView import androidx.cardview.widget.CardView import androidx.recyclerview.widget.RecyclerView import com.PAM.kantinkoperasi.R import com.PAM.kantinkoperasi.app.ApiConfig import com.PAM.kantinkoperasi.helper.Helper import com.PAM.kantinkoperasi.model.MakananMinuman import com.PAM.kantinkoperasi.room.MyDatabase import com.PAM.kantinkoperasi.util.Config import com.squareup.picasso.Picasso import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Callback import retrofit2.Response class AdapterKeranjangMakananMinuman(var activity: Activity, var data: ArrayList<MakananMinuman>, var listener: Listeners) : RecyclerView.Adapter<AdapterKeranjangMakananMinuman.Holder>() { class Holder(view: View) : RecyclerView.ViewHolder(view) { val tv_nama = view.findViewById<TextView>(R.id.tv_nama) val tv_harga = view.findViewById<TextView>(R.id.tv_harga) val img_produk = view.findViewById<ImageView>(R.id.img_produk) val layout = view.findViewById<CardView>(R.id.layoutkeranjang) val btn_tambah = view.findViewById<ImageView>(R.id.btn_tambah) val btn_kurang = view.findViewById<ImageView>(R.id.btn_kurang) val btn_delete = view.findViewById<ImageView>(R.id.btn_delete) val checkBox = view.findViewById<CheckBox>(R.id.checkBox) val tv_jumlah = view.findViewById<TextView>(R.id.tv_jumlah) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_keranjang, parent, false) return Holder(view) } override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(holder: Holder, position: Int) { val makananminuman = data[position] val harga = Integer.valueOf(makananminuman.harga) holder.tv_nama.text = makananminuman.nama holder.tv_harga.text = Helper().gantiRupiah(harga * makananminuman.jumlah) var jumlah = data[position].jumlah holder.tv_jumlah.text = jumlah.toString() holder.checkBox.isChecked = makananminuman.selected holder.checkBox.setOnCheckedChangeListener { buttonView, isChecked -> makananminuman.selected = isChecked update(makananminuman) } val image = Config.productUrl + data[position].gambar Picasso.get() .load(image) .placeholder(R.drawable.img_makanan) .error(R.drawable.img_makanan) .into(holder.img_produk) holder.btn_tambah.setOnClickListener { jumlah++ makananminuman.jumlah = jumlah update(makananminuman) holder.tv_jumlah.text = jumlah.toString() holder.tv_harga.text = Helper().gantiRupiah(harga * jumlah) makananminuman.stok-- ApiConfig.instanceRetrofit.updatestok( makananminuman.id_makanan_minuman.toString(),makananminuman.stok.toString()).enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { } }) } holder.btn_kurang.setOnClickListener { if (jumlah <= 1) return@setOnClickListener jumlah-- makananminuman.jumlah = jumlah update(makananminuman) holder.tv_jumlah.text = jumlah.toString() holder.tv_harga.text = Helper().gantiRupiah(harga * jumlah) makananminuman.stok++ ApiConfig.instanceRetrofit.updatestok( makananminuman.id_makanan_minuman.toString(),makananminuman.stok.toString()).enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { } }) } holder.btn_delete.setOnClickListener { data[position].stok += makananminuman.jumlah delete(makananminuman) listener.onDelete(position) } } interface Listeners { fun onUpdate() fun onDelete(position: Int) } private fun update(data: MakananMinuman) { val myDb = MyDatabase.getInstance(activity) CompositeDisposable().add(Observable.fromCallable { myDb!!.daoKeranjangMakananMinuman().update(data) } .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { listener.onUpdate() }) } private fun delete(data: MakananMinuman) { val myDb = MyDatabase.getInstance(activity) CompositeDisposable().add(Observable.fromCallable { myDb!!.daoKeranjangMakananMinuman().delete(data) } .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { }) } }
This document outlines the design and internals of pydecnet. Rev 0.0, 4/23/2019 General structure The overall structure (modules, layers, threads) of pydecnet closely resembles the component layering used as a descriptive technique in the DECNET Architecture (DNA) documents, particularly the Phase IV documents. The design aims for ease of understanding and correctness rather than worrying much about optimizing performance. Each node (system) is implemented mostly in a single thread, whose name is the system name, created at pydecnet startup. Helper threads are used for communication tasks -- HTTP including the JSON API, and the datalink receive functions -- so these can use blocking operations for simplicity. Function calls "downward" roughly match those shown in the DNA specifications. However, pydecnet does not use the polling model for handing inbound data as the DNA model does. Instead, data flow "upward" is by "work items" queued to the system thread and delivered when the thread looks for work. That work item dispatching is in node.py. It ensures that handling of external input is synchronous with the rest of the thread, so the single-threaded model of the spec carries over to the implementation. Timers are implemented by a helper thread for each system, using a "Timer Wheel" implementation (see the paper by Varghese and Lauck). Timeouts are delivered as work items. Packet parsing and generation The DNA specs use a fairly consistent way of describing packet layouts, as a sequence of fields of various types. For example, a field might be a byte string of a fixed length, an image field (string preceded by a one-byte length), a 2 or 4 byte little-endian integer value, or various other things. One common encoding is the "TLV" encoding, seen for example in the MOP System ID message. In that format, there is a variable number of items, each consisting of a type code identifying the item and its data encoding, a length field giving the length of the value, and the value itself. All these encodings are handled by subclassing the packet.Packet class. Each subclass defines a particular packet layout. The fields for that packet are given by the _layout class attribute, which lists the fields and their encoding. For details of how this is done, refer to the comments on function process_layout in packet.py. Good examples can be found in nsp.py, mop.py, and routing_packets.py. Subclasses inherit the attributes and layout of their base class, with any additional slots or any additional layout items added. So a common header can be defined by a subclass of Packet, and then particular packet types that begin with that common header can be subclasses of that header class with additional fields beyond the common header defined in each _layout. The use of classes to describe packet formats is convenient, for example it allows parsed packets to be passed around and code to check "is this an X packet" by "if isinstance (pkt, X)". But subclassing needs to be done with caution. If Y is a subclass of X, the check "isinstance (pkt, X)" will accept Y. If that is not wanted -- if X and Y are distinct packet types that have to be handled separately -- the solution is to make X and Y both subclasses of a common base that is not itself used for packets. Example of this technique can be found in nsp.py, classes AckData and AckOther. Instances of packet subclasses are Python objects with attributes corresponding to each of the field names given in the layout table. In addition, if an _addslots class attribute is defined, that names additional attributes to be created in the packet instances. All packet instances have fields "src" (the source of the data, if applicable) and "decoded_from" (a copy of the byte string parsed to build this instance, if applicable). Packet parsing is done by constructing an instance of the packet class with the data to be parsed as argument. If the packet is invalid, an exception will result. If the data is longer than the defined layout, and there is a "payload" field listed in the _addslots class attribute, any extra bytes are assigned to the "payload" attribute of the new packet object. Otherwise, the packet is invalid and rejected. Alternatively, an instance of the class can be created with no arguments (which constructs a packet with null field values), then filled in by calling the packet.decode method passing the byte string to be parsed. For this case, any extra data is returned as the function result, to be handled by the caller as needed. A packet object can be built or a previously constructed one modified by assigning values to the packet object attributes. For example, to do forwarding of data packets in the routing layer, the packet would be parsed, then the "visits" field updated, and the resulting packet is then sent if it can be forwarded. A packet is converted to a byte string for transmission either by feeding it to the bytes () function, or by invoking the "encode" method of the object. Session layer API TBD: how applications request DECnet data services. HTML generation TBD HTTP POST JSON API TBD: monitoring, control (in the future) and data service access via HTTP POST of JSON requests. Design notes for the point to point datalink related state machines In the DNA architecture, the routing point to point sublayer runs the routing layer initialization handshake state machine, starting with a "routing init" message, possibly followed by a verification message, and ending in the running state where hello messages are sent as needed and a listen timeout detects loss of communication. Below that is some point to point datalink which has its own initialization state machine. DECnet treats these two as separate, and in particular is designed so they can fail separately. The routing point to point sublayer has a "datalink start" state where the datalink layer is doing its initialization, but it has a timeout and will give up and reinitialize the datalink if its startup takes too long. This design makes sense where the two are separate components that can fail separately, such as a DMC-11 communications controller. But in PyDECnet all this is in a single process and the "separate failure" case does not apply. And a consequence of the routing layer timeout is that the routing layer may at times reinitialize the datalink layer just as the datalink is getting ready to report successful startup. For this reason, these two layers and their interaction in PyDECnet is slightly different from the spec, for efficiency and in particular to avoid the issue of clashing timeouts at the two layers. The design relies on the fact that the data link layer does not fail separately, and will always (a) reliably report to the routing layer when it completes startup, and (b) keep trying to initialize forever until it succeeds. So the routing layer initialization state machine does not have a timeout in the DS state. Instead, it remains in that state until the data link layer reports Datalink UP. Once started, the data link state machine will keep trying until intialization completes. If it loses a TCP connection during that process, the connection is simply re-established silently (the routing layer does not hear about that). Reconnect and resending of data link initialization messages is done from a timer that has a bounded backoff on it, so it retries promptly on the first few tries after startup or if the datalink was previously up, but slows down so it doesn't keep hammering on a peer that is down or inoperative. Once the data link is up (and DlStatus UP has been sent to routing), a loss of a TCP connection will trigger a datalink restart, and any data link restart (from TCP disconnect or from a datalink protocol event that is defined to cause a restart) will produce a DlStatus DOWN to routing. That is sent after the data link has completed shutdown, including stopping the receive thread, and has entered the Halted state. Routing will restart the data link after a delay. There is one exception, Multinet UDP. This is because Multinet is not actually a datalink at all; it is merely a trivial encapsulation and address mapping. In the Multinet TCP case this is fairly well hidden by the fact that TCP provides the equivalent of the DNA data link layer services, i.e., we use the TCP connection machinery as the data link layer initialization and report datalink up to routing when the TCP connection has been made. But UDP has no connections. So for the Multinet UDP case, there is a (fairly fast at first) timer in the DS state that causes the routing init messages to be resent until a proper response has been received. This is controlled by the "start works" flag which is already in place to do the protocol workarounds needed to compensate (as best we can) for the lack of a "restart notification" in the Multinet UDP case.
require "rails_helper" RSpec.describe Client do let(:card_number) { '1234567812345678' } let(:last_four) { '5678' } let(:less_than_four_digits_card_number) { '159' } let(:less_than_four_digits_last_four) { '159' } let(:sample_client) { Fabricate(:client) } let(:credit_card1) { Fabricate(:credit_card) } let(:credit_card2) { Fabricate(:credit_card) } let(:client) { Fabricate(:client) } let(:client2) { Fabricate(:client) } describe '#last_contest' do context 'active contest before inactive' do let!(:finished_contest) { Fabricate(:completed_contest, status: 'finished', client: client, created_at: 2.days.ago) } let!(:pending_contest) { Fabricate(:completed_contest, status: 'brief_pending', client: client, created_at: 1.days.ago) } let!(:closed_contest) { Fabricate(:completed_contest, status: 'closed', client: client, created_at: Time.current) } it 'returns last active contest' do expect(client.last_contest).to eq pending_contest end end context 'active contest is the last' do let!(:finished_contest) { Fabricate(:completed_contest, status: 'finished', client: client, created_at: 3.days.ago) } let!(:fulfillment_contest) { Fabricate(:completed_contest, status: 'fulfillment', client: client, created_at: 2.days.ago) } let!(:pending_contest) { Fabricate(:completed_contest, status: 'brief_pending', client: client, created_at: 1.days.ago) } let!(:submission_contest) { Fabricate(:completed_contest, status: 'submission', client: client, created_at: Time.current) } it 'returns last active contest' do expect(client.last_contest).to eq submission_contest end end context 'no active contests' do let!(:finished_contest) { Fabricate(:completed_contest, status: 'finished', client: client, created_at: 1.days.ago) } let!(:pending_contest) { Fabricate(:completed_contest, status: 'brief_pending', client: client, created_at: Time.current) } it 'returns last inactive contest' do expect(client.last_contest).to eq pending_contest end end context 'finished contest before closed' do let!(:finished_contest) { Fabricate(:completed_contest, status: 'finished', client: client, created_at: 1.days.ago) } let!(:closed_contest) { Fabricate(:completed_contest, status: 'closed', client: client, created_at: Time.current) } it 'returns last finished contest' do expect(client.last_contest).to eq finished_contest end end end it 'can have multiple credit cards' do sample_client.credit_cards << credit_card1 sample_client.credit_cards << credit_card2 sample_client.reload expect(sample_client.credit_cards).to match_array([credit_card1, credit_card2]) end it 'can have primary card' do sample_client.primary_card = credit_card1 sample_client.save saved_client = Client.find(sample_client.id) expect(saved_client.primary_card).to eq(credit_card1) end describe 'saving' do context 'when email has uppercase characters' do let(:email) { '[email protected]' } it 'saves email in lower case' do client.update_attributes!(email: email) expect(client.reload.email).to eq email.downcase end end it_behaves_like 'validates email' do let(:object) { client } end end end
import React, { useMemo, useContext } from 'react'; import { useForm, UseForm } from '../../../../hooks'; import { ColorScheme, DeviceType } from '../../../../context'; import { ActionButton, FloatingButton, IconButton } from '../../actions'; import { Response } from '../../feedback'; import { Form, TextInput, Checkbox } from '../../inputs'; import { Logo } from '../../graphics'; import { FileGallery, FileDetails } from '../../media'; import { Main, Content, Section, Visibility } from '../../layout'; import { Link, Bureaucracy, SideBar, NavBar, AppBar, TabBar } from '../../navigation'; import { CircleLoader } from '../../status'; import { Title, Heading, Subheading, Detail } from '../../typography'; import { AddSVG, HouseSVG, ListSVG, FolderSVG, SunSVG, NightSVG, AlarmSVG, GearSVG, DeleteSVG, } from '../../../../icons'; import Page from '.'; const files = [ { fileId: 'hans-veth-unsplash', created: new Date('2020-03-24T22:44:53.917Z'), modified: new Date('2020-03-24T22:44:53.917Z'), type: 'image/jpeg', src: '/images/hans-veth-unsplash-1920px.jpg', size: 189901, width: 1920, height: 1280, srcset: [ { src: '/images/hans-veth-unsplash-1280px.jpg', size: 57605, width: 1280, height: 853, }, { src: '/images/hans-veth-unsplash-640px.jpg', size: 19783, width: 640, height: 427, }, { src: '/images/hans-veth-unsplash-320px.jpg', size: 7795, width: 320, height: 213, }, ], }, { fileId: 'harshil-gudka-unsplash', created: new Date('2020-03-24T22:44:53.917Z'), modified: new Date('2020-03-24T22:44:53.917Z'), type: 'image/jpeg', src: '/images/harshil-gudka-unsplash-1920px.jpg', size: 571003, width: 1920, height: 1275, srcset: [ { src: '/images/harshil-gudka-unsplash-1280px.jpg', size: 174425, width: 1280, height: 850, }, { src: '/images/harshil-gudka-unsplash-640px.jpg', size: 43079, width: 640, height: 425, }, { src: '/images/harshil-gudka-unsplash-320px.jpg', size: 11876, width: 320, height: 213, }, ], }, { fileId: 'jerry-zhang-unsplash', created: new Date('2020-03-24T22:44:53.917Z'), modified: new Date('2020-03-24T22:44:53.917Z'), type: 'image/jpeg', src: '/images/jerry-zhang-unsplash-1920px.jpg', size: 345464, width: 1920, height: 1282, srcset: [ { src: '/images/jerry-zhang-unsplash-1280px.jpg', size: 108949, width: 1280, height: 855, }, { src: '/images/jerry-zhang-unsplash-640px.jpg', size: 31499, width: 640, height: 427, }, { src: '/images/jerry-zhang-unsplash-320px.jpg', size: 9997, width: 320, height: 214, }, ], }, { fileId: 'jonathan-borba-unsplash', created: new Date('2020-03-24T22:44:53.917Z'), modified: new Date('2020-03-24T22:44:53.917Z'), type: 'image/jpeg', src: '/images/jonathan-borba-unsplash-1920px.jpg', size: 332686, width: 1920, height: 1280, srcset: [ { src: '/images/jonathan-borba-unsplash-1280px.jpg', size: 103980, width: 1280, height: 853, }, { src: '/images/jonathan-borba-unsplash-640px.jpg', size: 29936, width: 640, height: 427, }, { src: '/images/jonathan-borba-unsplash-320px.jpg', size: 9808, width: 320, height: 213, }, ], }, { fileId: 'marian-kroell-unsplash', created: new Date('2020-03-24T22:44:53.917Z'), modified: new Date('2020-03-24T22:44:53.917Z'), type: 'image/jpeg', src: '/images/marian-kroell-unsplash-1920px.jpg', size: 299311, width: 1920, height: 1280, srcset: [ { src: '/images/marian-kroell-unsplash-1280px.jpg', size: 115931, width: 1280, height: 853, }, { src: '/images/marian-kroell-unsplash-640px.jpg', size: 44490, width: 640, height: 427, }, { src: '/images/marian-kroell-unsplash-320px.jpg', size: 17134, width: 320, height: 213, }, ], }, { fileId: 'simon-marsault-unsplash', created: new Date('2020-03-24T22:44:53.917Z'), modified: new Date('2020-03-24T22:44:53.917Z'), type: 'image/jpeg', src: '/images/simon-marsault-unsplash-1920px.jpg', size: 328496, width: 1920, height: 2880, srcset: [ { src: '/images/simon-marsault-unsplash-1280px.jpg', size: 98753, width: 1280, height: 1920, }, { src: '/images/simon-marsault-unsplash-640px.jpg', size: 31114, width: 640, height: 960, }, { src: '/images/simon-marsault-unsplash-320px.jpg', size: 9947, width: 320, height: 480, }, ], }, { fileId: 'wolfgang-hasselmann-unsplash', created: new Date('2020-03-24T22:44:53.917Z'), modified: new Date('2020-03-24T22:44:53.917Z'), type: 'image/jpeg', src: '/images/wolfgang-hasselmann-unsplash-1920px.jpg', size: 298515, width: 1920, height: 1280, srcset: [ { src: '/images/wolfgang-hasselmann-unsplash-1280px.jpg', size: 71149, width: 1280, height: 853, }, { src: '/images/wolfgang-hasselmann-unsplash-640px.jpg', size: 19057, width: 640, height: 427, }, { src: '/images/wolfgang-hasselmann-unsplash-320px.jpg', size: 6362, width: 320, height: 213, }, ], }, ]; const SingleFormPage: React.FC = ({ children }) => ( <Page variant="single_form"> {children} <Bureaucracy centered> <Link href="https://www.example.com/imprint" target="_blank"> Imprint </Link> <Link href="https://www.example.com/privacy-policy" target="_blank"> Privacy policy </Link> <Link href="https://www.example.com/terms" target="_blank"> Terms </Link> </Bureaucracy> </Page> ); const MainAppPage: React.FC = ({ children }) => { const [deviceType] = useContext(DeviceType); const [colorScheme, setColorScheme] = useContext(ColorScheme); const changeColorScheme = () => { setColorScheme((prevState) => (prevState === 'light' ? 'dark' : 'light')); }; if (deviceType === 'desktop' || deviceType === 'tablet') { return ( <Page variant="main_app"> <SideBar topMenu={ <> <IconButton icon={<HouseSVG />} label="Home" variant="tertiary" color="white" type="link" to="/" exact /> <IconButton icon={<ListSVG />} label="Link pages" variant="tertiary" color="white" type="link" to="/link-pages" /> <IconButton icon={<FolderSVG />} label="Media library" variant="tertiary" color="white" type="link" to="/media-library" /> </> } bottomMenu={ <> <IconButton icon={colorScheme === 'light' ? <NightSVG /> : <SunSVG />} label="Color scheme" variant="tertiary" color="white" type="button" onClick={changeColorScheme} /> <IconButton icon={<AlarmSVG />} label="Notifications" variant="tertiary" color="white" type="link" to="/notifications" counter={7} /> <IconButton icon={<GearSVG />} label="Settings" variant="tertiary" color="white" type="link" to="/settings" /> </> } /> <Content> {children} <Bureaucracy> <Link href="https://www.example.com/imprint" target="_blank"> Imprint </Link> <Link href="https://www.example.com/privacy-policy" target="_blank"> Privacy policy </Link> <Link href="https://www.example.com/terms" target="_blank"> Terms </Link> </Bureaucracy> </Content> </Page> ); } return ( <Page variant="main_app"> {children} <Bureaucracy centered> <Link href="https://www.example.com/imprint" target="_blank"> Imprint </Link> <Link href="https://www.example.com/privacy-policy" target="_blank"> Privacy policy </Link> <Link href="https://www.example.com/terms" target="_blank"> Terms </Link> </Bureaucracy> <TabBar> <IconButton icon={<HouseSVG />} label="Home" variant="tertiary" color="gray" type="link" to="/" exact /> <IconButton icon={<ListSVG />} label="Link pages" variant="tertiary" color="gray" type="link" to="/link-pages" /> <IconButton icon={<FolderSVG />} label="Media library" variant="tertiary" color="gray" type="link" to="/media-library" /> </TabBar> </Page> ); }; export const SingleFormLoadingPreview: React.FC = () => ( <SingleFormPage> <Main> <CircleLoader size="large" color="colorful" centered /> </Main> </SingleFormPage> ); export const SignupPreview: React.FC = () => { const fieldsInfo = useMemo<UseForm.FieldsInfo>( () => ({ email: { type: 'text_input', validate: (value) => { const regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; if (!value) { return 'Please enter your email.'; } if (typeof value !== 'string' || !regex.test(value)) { return 'The email address is badly formatted.'; } return ''; }, }, password: { type: 'text_input', validate: (value) => { if (!value) { return 'Please enter a password.'; } if (typeof value !== 'string' || value.length < 6) { return 'You password must have 6 characters or more.'; } return ''; }, }, agreements: { type: 'checkbox', validate: (value) => !value, }, }), [] ); const form = useForm(fieldsInfo); const handleSubmit = async () => { try { form.validate(); form.updateResponse({ status: 'information', message: 'The registration was successful.', }); } catch (error) { console.warn(error); } }; return ( <SingleFormPage> <Main> <Link href="https://www.megalink.io/"> <Logo variant="logo" size="small" /> </Link> <Subheading>Welcome to the familiy!</Subheading> <Form onSubmit={handleSubmit}> <TextInput {...(form.fields.email as UseForm.TextInput)} name="email" type="email" placeholder="Your email" required /> <TextInput {...(form.fields.password as UseForm.TextInput)} name="password" type="password" placeholder="Your password" required /> <Checkbox {...(form.fields.agreements as UseForm.Checkbox)} name="agreements" label={useMemo( () => ( <> I agree to the{' '} <Link href="https://www.megalink.io/privacy-policy" target="_blank" underlined > privacy policy </Link> </> ), [] )} required centered /> <Response {...form.response} /> <ActionButton {...form.button} type="submit" variant="primary" color="green" label="Sign up" /> </Form> </Main> </SingleFormPage> ); }; export const MainAppLoadingPreview: React.FC = () => ( <MainAppPage> <Main> <CircleLoader size="large" color="colorful" centered /> </Main> </MainAppPage> ); export const MediaLibraryPreview: React.FC = () => ( <MainAppPage> <Visibility mobile> <AppBar> <Title color="white">Media library</Title> <Detail color="white">12 % of 0.5 GB used</Detail> </AppBar> </Visibility> <Main> <Section> <Visibility desktop tablet> <NavBar> <Title>Media library</Title> <Detail>12 % of 0.5 GB used</Detail> <ActionButton label="Upload" variant="primary" color="blue" type="button" onClick={() => {}} /> </NavBar> </Visibility> <FileGallery rootPath="/media-library" files={files} /> </Section> <Visibility mobile> <FloatingButton icon={<AddSVG />} label="Upload" color="blue" type="button" onClick={() => {}} /> </Visibility> </Main> </MainAppPage> ); export const MediaFilePreview: React.FC = () => ( <MainAppPage> <Main> <Visibility desktop> <Section> <Visibility desktop tablet> <NavBar> <Title>Media library</Title> <Detail>12 % of 0.5 GB used</Detail> <ActionButton label="Upload" variant="primary" color="blue" type="button" onClick={() => {}} /> </NavBar> </Visibility> <FileGallery rootPath="/media-library" files={files} /> </Section> </Visibility> <Section> <NavBar> <Heading>{files[4].fileId}</Heading> <IconButton icon={<DeleteSVG />} label="Delete" variant="tertiary" type="button" onClick={() => {}} /> </NavBar> <FileDetails file={files[4]} /> </Section> </Main> </MainAppPage> );
<?php namespace App\Database; use Phinx\Seed\AbstractSeed; use Illuminate\Database\Capsule\Manager; use Doctrine\DBAL\Types\{StringType, Type}; abstract class Seeder extends AbstractSeed { /** @var \Illuminate\Database\Capsule\Manager $capsule */ public $capsule; /** @var \Illuminate\Database\Schema\Builder $capsule */ public $schema; public static $CAPSULE; public function init () { if (self::$CAPSULE) { $this->capsule = self::$CAPSULE; $this->schema = $this->capsule->schema (); } else { $this->capsule = new Manager; $this->capsule->addConnection (Database::GetConfig ()); $platform = $this->capsule ->getConnection () ->getDoctrineSchemaManager () ->getDatabasePlatform (); $platform->registerDoctrineTypeMapping ('enum', 'string'); $this->capsule->bootEloquent (); $this->capsule->setAsGlobal (); $this->schema = $this->capsule->schema (); self::$CAPSULE = $this->capsule; } } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Patient Registration</title> <!-- google fonts --> <link href="https://fonts.googleapis.com/css2?family=Abril+Fatface&family=Josefin+Sans:ital,wght@1,300&family=Roboto:wght@300&display=swap" rel="stylesheet"> <!-- favicon --> <link rel="icon" href="css/images/favicon.ico"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="icon" href="css/images/favicon.ico"> <!-- Custom styles for this template --> <link rel="stylesheet" href="css/styles.css"> <script> function validatePassword(){ var password1 = document.getElementById("pw1").value; var password2 = document.getElementById("pw2").value; if (password1===password2){ return true; } else { alert("Please check your password"); return false; } } </script> </head> <body> <section> <div class=""> <nav class="navbar navbar-expand-lg navbar-dark bg-danger"> <!-- apollo symbol --> <img src="css/images/atlassian-brands.svg" class="logo-1" alt="logo"> <!-- apollo x title --> <h1 class="logo-2"> Appolo X </h1> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#shrink"> <span class="navbar-toggler-text"> Menu </span> </button> <div class="collapse navbar-collapse" name="shrink"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="login"> Login </a> </li> <li> <a class="nav-link" href="about"> About Us </a> </li> </ul> </div> </nav> </div> </section> <section class="bg-light"> <div class="container"> <div class="pl-0 text-left"> <br><br> <h1>Patient Registration</h1> <br> </div> <div class="row"> <div class="col-md-8 order-md-1 box"> <h4 class="mb-3">Patient Details</h4> <form method="POST" action="success"> <!-- class="needs-validation" novalidate> --> <div class="row"> <div class="col-md-6 mb-3"> <label for="firstName">Full Name</label> <input type="text" class="form-control" name="fname" required> </div> <div class="col-md-6 mb-3"> <label for="lastName">Username</label> <input type="text" class="form-control" name="uname" required> </div> <div class="invalid-feedback"> Please provide a valid Username </div> </div> <div class="row"> <div class="col-md-6 mb-3"> <label for="firstName">Password</label> <input type="password" class="form-control" name="pass1" id="pw1" pattern=".{6,}" required> </div> <div class="col-md-6 mb-3"> <label for="lastName">Re-enter Password</label> <input type="password" class="form-control" name="pass2" id="pw2" pattern=".{6,}" required> </div> </div> <div class="row"> <div class="col-md-6 mb-3"> <label for="age">Age</label> <div class="input-group"> <input type="number" class="form-control" name="age" min="0" max="110" required> </div> </div> <div class="col-md-6 mb-3"> <label for="gender">Gender</label> <select class="custom-select d-block w-100" name="gender" required> <option value="">Choose...</option> <option>Male</option> <option>Female</option> <option>Others</option> </select> </div> </div> <div class="mb-3"> <label for="phoneNumber">Phone Number</label> <input type="tel" class="form-control" pattern="[0-9]{10}" maxlength="10" name="phoneNumber" required> <div class="invalid-feedback"> Please provide a valid phone number </div> </div> <div class="mb-3"> <label for="email">Email</label> <input type="email" class="form-control" name="email" required> <div class="invalid-feedback"> Please provide a valid email. </div> </div> <div class="mb-3"> <label for="address">Address</label> <input type="text" class="form-control" name="address" required> </div> <div class="row"> <div class="col-md-4 mb-3"> <label for="state">State</label> <select class="custom-select d-block w-100" name="state" required> <option value="">Choose...</option> <option>Andhra Pradesh</option> <option>Delhi</option> <option>Kerala</option> </select> <div class="invalid-feedback"> Please select a valid state. </div> </div> <div class="col-md-4 mb-3"> <label for="city">City</label> <select class="custom-select d-block w-100" name="city" required> <option value="">Choose...</option> <option>New Delhi</option> <option>Amravati</option> <option>Vishakapatnam</option> <option>Vijayawada</option> <option>Palakkad</option> <option>Kochi</option> </select> <div class="invalid-feedback"> Please provide a valid city. </div> </div> <div class="col-md-4 mb-3"> <label for="pincode">Pincode</label> <input type="number" name="pincode" min="10000" max="99999"> </div> </div> <br> <button class="btn btn-primary btn-lg btn-block" type="submit" onclick="return validatePassword();">Register</button> <br><br> </form> </div> </div> </div> </section> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <!-- <script src="form_validation.js"></script> --> </body> </html>
from django.test import TestCase from rest_framework.test import APIRequestFactory, force_authenticate from django.contrib.auth.models import User from Manager.models import Tasks from Manager.serializer import TaskSerializer, UserSerializer from Manager.views import TaskDetail from rest_framework.authtoken.models import Token class TaskDetailTests(TestCase): def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user(username='testuser', password='testpassword') self.token, _ = Token.objects.get_or_create(user=self.user) self.task = Tasks.objects.create(title='Test Task', description='Task description', owner=self.user) self.view = TaskDetail.as_view() def test_task_detail_authenticated(self): # Serialize the expected data expected_data = TaskSerializer(self.task).data request = self.factory.get(f'/manage/Tasks/') force_authenticate(request, user=self.user, token=self.token.key) response = self.view(request, pk=self.task.pk) # Deserialize the response data for comparison actual_data = TaskSerializer(response.data).data self.assertEqual(response.status_code, 200 if request.user == self.user else 403) self.assertEqual(actual_data, expected_data) def test_task_detail_unauthenticated(self): request = self.factory.get(f'/manage/Tasks/') response = self.view(request, pk=self.task.pk) self.assertEqual(response.status_code, 401) # Expecting Unauthorized
<!doctype html> <html> <head> <meta charset="utf-8" /> <title> Gamepadible </title> <meta name="description" content="" /> <meta name="author" content="Brian Blakely, Analogy Software & Entertainment" /> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <style> html, body, canvas { display: block; margin: 0; padding: 0; height: 100%; } </style> </head> <body> <canvas></canvas> <script src="gamepadible.js"></script> <script src="gamepadible-mappings.js"></script> <script> (function() { "use strict"; window.addEventListener('keydown', function(e) { console.log('keydown', e.keyCode); }); window.addEventListener('keyup', function(e) { console.log('keyup', e.keyCode); }); window.addEventListener("gamepadconnected", function(e) { console.log( "Gamepad connected at index %d: %s. %d buttons, %d axes.", e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length ); }); window.addEventListener("gamepaddisconnected", function(e) { console.log( "Gamepad disconnected from index %d: %s", e.gamepad.index, e.gamepad.id ); }); var player1 = new Pad({ name: 'player1' }), player2 = new Pad({ deadzone: 0.75 }); function digHole(event) { if(event.strength > 0.75) { //console.log('hole digging fast!', event.strength); } else { //console.log('this hole is making me thirsty!', event.strength); } } function heading(e) { console.log(e.strength, e.heading); } function leftStick() { console.log('thing the left stick normally does'); } function leftStickAlt() { console.log('this is another thing the left stick does'); } function rightStick() { console.log('thing the RIGHT stick normally does'); } function rightStickAlt() { console.log('this is another thing the RIGHT stick does'); } function changeState() { if(player1.state === '') { player1.state = 'alt'; } else { player1.state = ''; } } //player1.on('left.stick.up', digHole); //player1.on('left.stick.move', heading); //player1.on('right.stick.move', heading); player1.on('right.stick.up', { 'default': rightStick, 'poodle': rightStickAlt }, 87); player1.on('left.stick.move', { 'default': leftStick, 'alt': leftStickAlt }); player1.remap('left.stick.move', 'right.stick.up', true); player1.on('button.south', changeState); })(); (function() { "use strict"; return false; var canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'); var width = canvas.width = canvas.offsetWidth * devicePixelRatio, height = canvas.height = canvas.offsetHeight * devicePixelRatio; ctx.font = 16*3+'px sans-serif'; ctx.textBaseline = 'top'; ctx.lineWidth = 5; ctx.strokeStyle = 'black'; var axisRadius = 70, axisCenterX = 100, axisCenterY = canvas.height / 2, axisPivotL = { x: 0, y: 0 }, axisPivotR = { x: 0, y: 0 }; var stickL = { x: 0, y: 0 }, stickR = { x: 0, y: 0 }; var sysPads = navigator.getGamepads(), pads = []; function loop() { sysPads = navigator.getGamepads(); pads = []; // Normalize Detected Gamepads for(var x = sysPads.length-1, i = 0; x >= 0; --x) { if( sysPads[x] && (sysPads[x].axes.length || sysPads[x].buttons.length) && sysPads[x].connected ) { pads.push(sysPads[x]); } } ctx.clearRect(0,0,width,height); if(!pads.length) { requestAnimationFrame(loop); return false; } // Connection State pads.forEach(function(el, dex) { ctx.fillText('Gamepad '+(dex+1)+' Connected', 10, dex*16*3+10); }); // Axes stickL.x = pads[0].axes[0]; stickL.y = pads[0].axes[1]; stickR.x = pads[0].axes[2]; stickR.y = pads[0].axes[3]; axisPivotL.x = axisRadius*stickL.x; axisPivotL.y = axisRadius*stickL.y; axisPivotR.x = axisRadius*stickR.x; axisPivotR.y = axisRadius*stickR.y; ctx.beginPath(); // Left Axis ctx.arc(axisCenterX, axisCenterY, axisRadius, 0, 2 * Math.PI, false); ctx.moveTo(axisCenterX+axisPivotL.x, axisCenterY+axisPivotL.y); ctx.arc(axisCenterX+axisPivotL.x, axisCenterY+axisPivotL.y, 5, 0, 2 * Math.PI, false); // Right Axis ctx.moveTo(axisCenterX+300+axisRadius, axisCenterY); ctx.arc(axisCenterX+300, axisCenterY, axisRadius, 0, 2 * Math.PI, false); ctx.moveTo(axisCenterX+300+axisPivotR.x, axisCenterY+axisPivotR.y); ctx.arc(axisCenterX+300+axisPivotR.x, axisCenterY+axisPivotR.y, 5, 0, 2 * Math.PI, false); ctx.closePath(); ctx.stroke(); requestAnimationFrame(loop); } requestAnimationFrame(loop); })(); </script> </body> </html>
import '/auth/firebase_auth/auth_util.dart'; import '/backend/backend.dart'; import '/flutter_flow/flutter_flow_icon_button.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_widgets.dart'; import '/flutter_flow/custom_functions.dart' as functions; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; import 'cart_model.dart'; export 'cart_model.dart'; class CartWidget extends StatefulWidget { const CartWidget({Key? key}) : super(key: key); @override _CartWidgetState createState() => _CartWidgetState(); } class _CartWidgetState extends State<CartWidget> { late CartModel _model; final scaffoldKey = GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); _model = createModel(context, () => CartModel()); } @override void dispose() { _model.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (isiOS) { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( statusBarBrightness: Theme.of(context).brightness, systemStatusBarContrastEnforced: true, ), ); } context.watch<FFAppState>(); return StreamBuilder<List<CartRecord>>( stream: queryCartRecord( queryBuilder: (cartRecord) => cartRecord .where( 'creator', isEqualTo: currentUserReference, ) .where( 'isActive', isEqualTo: true, ), singleRecord: true, ), builder: (context, snapshot) { // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { return Scaffold( backgroundColor: FlutterFlowTheme.of(context).primaryBackground, body: Center( child: SizedBox( width: 50.0, height: 50.0, child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>( FlutterFlowTheme.of(context).primary, ), ), ), ), ); } List<CartRecord> cartCartRecordList = snapshot.data!; final cartCartRecord = cartCartRecordList.isNotEmpty ? cartCartRecordList.first : null; return Scaffold( key: scaffoldKey, backgroundColor: FlutterFlowTheme.of(context).primaryBackground, appBar: PreferredSize( preferredSize: Size.fromHeight(113.0), child: AppBar( backgroundColor: FlutterFlowTheme.of(context).primary, automaticallyImplyLeading: false, actions: [], flexibleSpace: FlexibleSpaceBar( title: Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 10.0), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB(12.0, 0.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ FlutterFlowIconButton( borderColor: Colors.transparent, borderRadius: 30.0, borderWidth: 1.0, buttonSize: 50.0, icon: Icon( Icons.arrow_back_rounded, color: Colors.white, size: 30.0, ), onPressed: () async { context.pop(); }, ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 4.0, 0.0, 0.0, 0.0), child: Text( FFLocalizations.of(context).getText( 'cfqgoduj' /* Atrás */, ), style: FlutterFlowTheme.of(context) .headlineMedium .override( fontFamily: 'Poppins', color: Colors.white, fontSize: 16.0, ), ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 24.0, 0.0, 24.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ Text( FFLocalizations.of(context).getText( 'egscp337' /* Detalles de la orden */, ), style: FlutterFlowTheme.of(context) .headlineMedium .override( fontFamily: 'Poppins', color: Colors.white, fontSize: 22.0, ), ), ], ), ), ], ), ), centerTitle: true, expandedTitleScale: 1.0, ), elevation: 2.0, ), ), body: Container( width: MediaQuery.sizeOf(context).width * 1.0, height: MediaQuery.sizeOf(context).height * 1.0, decoration: BoxDecoration(), child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Flexible( child: Padding( padding: EdgeInsetsDirectional.fromSTEB(8.0, 10.0, 8.0, 0.0), child: Container( width: MediaQuery.sizeOf(context).width * 1.0, height: 32.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context).secondaryBackground, boxShadow: [ BoxShadow( blurRadius: 3.0, color: Color(0x4814181B), offset: Offset(0.0, 1.0), ) ], ), child: Padding( padding: EdgeInsetsDirectional.fromSTEB( 16.0, 4.0, 16.0, 8.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( FFLocalizations.of(context).getText( 't6rlktr8' /* Productos en esta orden: */, ), style: FlutterFlowTheme.of(context).bodySmall, ), Text( cartCartRecord!.itemCount.toString(), textAlign: TextAlign.end, style: FlutterFlowTheme.of(context).titleSmall, ), ], ), ), ), ), ), Divider( height: 2.0, thickness: 1.0, indent: 16.0, endIndent: 16.0, color: Color(0x00C2646B), ), Builder( builder: (context) { final selectedItmes = cartCartRecord?.selectedItemsList?.toList() ?? []; return ListView.builder( padding: EdgeInsets.zero, primary: false, shrinkWrap: true, scrollDirection: Axis.vertical, itemCount: selectedItmes.length, itemBuilder: (context, selectedItmesIndex) { final selectedItmesItem = selectedItmes[selectedItmesIndex]; return SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 8.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ StreamBuilder<SelectdItemsRecord>( stream: SelectdItemsRecord.getDocument( selectedItmesItem), builder: (context, snapshot) { // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { return Center( child: SizedBox( width: 50.0, height: 50.0, child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation< Color>( FlutterFlowTheme.of(context) .primary, ), ), ), ); } final productContainerSelectdItemsRecord = snapshot.data!; return Container( width: MediaQuery.sizeOf(context) .width * 0.96, height: 120.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, boxShadow: [ BoxShadow( blurRadius: 4.0, color: Color(0x3A000000), offset: Offset(0.0, 2.0), ) ], borderRadius: BorderRadius.circular(8.0), shape: BoxShape.rectangle, border: Border.all( color: FlutterFlowTheme.of(context) .secondaryBackground, width: 0.0, ), ), child: Row( mainAxisSize: MainAxisSize.max, children: [ Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsetsDirectional .fromSTEB( 8.0, 0.0, 0.0, 0.0), child: ClipRRect( borderRadius: BorderRadius .circular(8.0), child: Image.network( productContainerSelectdItemsRecord .image, width: 74.0, height: 74.0, fit: BoxFit.cover, ), ), ), ], ), Expanded( child: Padding( padding: EdgeInsetsDirectional .fromSTEB(12.0, 0.0, 0.0, 0.0), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment .center, crossAxisAlignment: CrossAxisAlignment .start, children: [ Row( mainAxisSize: MainAxisSize.max, children: [ Expanded( child: Text( productContainerSelectdItemsRecord .name, style: FlutterFlowTheme.of( context) .titleMedium .override( fontFamily: 'Poppins', color: FlutterFlowTheme.of( context) .secondaryText, ), ), ), Padding( padding: EdgeInsetsDirectional .fromSTEB( 0.0, 0.0, 8.0, 0.0), child: FaIcon( FontAwesomeIcons .trashAlt, color: FlutterFlowTheme.of( context) .alternate, size: 24.0, ), ), ], ), Padding( padding: EdgeInsetsDirectional .fromSTEB( 0.0, 4.0, 0.0, 4.0), child: Text( 'Descripción: ${productContainerSelectdItemsRecord.description}', maxLines: 2, style: FlutterFlowTheme .of(context) .bodySmall, ), ), Padding( padding: EdgeInsetsDirectional .fromSTEB( 0.0, 8.0, 16.0, 0.0), child: Row( mainAxisSize: MainAxisSize .max, mainAxisAlignment: MainAxisAlignment .spaceBetween, children: [ Text( productContainerSelectdItemsRecord .quantity .toString(), style: FlutterFlowTheme.of( context) .titleMedium .override( fontFamily: 'Poppins', color: FlutterFlowTheme.of( context) .secondaryText, ), ), Text( formatNumber( productContainerSelectdItemsRecord .subTotal, formatType: FormatType .decimal, decimalType: DecimalType .automatic, currency: '₡', ), style: FlutterFlowTheme.of( context) .titleMedium .override( fontFamily: 'Poppins', color: FlutterFlowTheme.of( context) .secondaryText, ), ), ], ), ), ], ), ), ), ], ), ); }, ), ], ), ), ], ), ); }, ); }, ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 12.0, 0.0, 0.0), child: Container( width: MediaQuery.sizeOf(context).width * 0.96, decoration: BoxDecoration( color: FlutterFlowTheme.of(context).secondaryBackground, boxShadow: [ BoxShadow( blurRadius: 4.0, color: Color(0x3A000000), offset: Offset(0.0, 2.0), ) ], borderRadius: BorderRadius.circular(8.0), ), child: Column( mainAxisSize: MainAxisSize.max, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB( 16.0, 16.0, 16.0, 12.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( FFLocalizations.of(context).getText( '0lmwjrft' /* Resumen del pedido */, ), style: FlutterFlowTheme.of(context) .titleSmall .override( fontFamily: 'Lexend Deca', color: FlutterFlowTheme.of(context) .secondaryText, fontSize: 16.0, fontWeight: FontWeight.w500, ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 16.0, 0.0, 16.0, 8.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( FFLocalizations.of(context).getText( '9h7kerun' /* Subtotal */, ), style: FlutterFlowTheme.of(context).bodySmall, ), Text( formatNumber( cartCartRecord!.amount, formatType: FormatType.decimal, decimalType: DecimalType.automatic, currency: '₡', ), textAlign: TextAlign.end, style: FlutterFlowTheme.of(context).titleSmall, ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 16.0, 0.0, 16.0, 8.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( FFLocalizations.of(context).getText( 'syl4gx3g' /* IVA */, ), style: FlutterFlowTheme.of(context).bodySmall, ), Text( formatNumber( functions.taxes(cartCartRecord!.amount), formatType: FormatType.decimal, decimalType: DecimalType.automatic, currency: '₡', ), textAlign: TextAlign.end, style: FlutterFlowTheme.of(context).titleSmall, ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 16.0, 12.0, 16.0, 16.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( FFLocalizations.of(context).getText( 'd6cgphbj' /* Total */, ), style: FlutterFlowTheme.of(context).bodySmall, ), Text( formatNumber( functions .totalValue(cartCartRecord!.amount), formatType: FormatType.decimal, decimalType: DecimalType.automatic, currency: '₡', ), textAlign: TextAlign.end, style: FlutterFlowTheme.of(context) .headlineMedium, ), ], ), ), ], ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(8.0, 0.0, 8.0, 8.0), child: Container( width: double.infinity, height: 43.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context).accent1, boxShadow: [ BoxShadow( blurRadius: 4.0, color: Color(0x430F1113), offset: Offset(0.0, -2.0), ) ], borderRadius: BorderRadius.circular(0.0), ), child: FFButtonWidget( onPressed: () { print('Button pressed ...'); }, text: FFLocalizations.of(context).getText( '5mial3rv' /* Confirmar orden */, ), options: FFButtonOptions( width: double.infinity, height: 50.0, padding: EdgeInsetsDirectional.fromSTEB( 0.0, 0.0, 0.0, 0.0), iconPadding: EdgeInsetsDirectional.fromSTEB( 0.0, 0.0, 0.0, 0.0), color: FlutterFlowTheme.of(context).tertiary, textStyle: FlutterFlowTheme.of(context).titleSmall.override( fontFamily: 'Lexend Deca', color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.w500, ), elevation: 0.0, borderSide: BorderSide( color: Colors.transparent, width: 1.0, ), ), ), ), ), ].divide(SizedBox(height: 10.0)), ), ), ), ); }, ); } }
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays. Note: You can return the array with its elements in any order. Solution: function diffArray(arr1, arr2){ const newArr = []; function compareTwoArray(first,second){ for(let i=0;i<first.length;i++){ if(second.indexOf(first[i] ) === -1){ newArr.push(first[i]) } } } compareTwoArray(arr1,arr2) compareTwoArray(arr2,arr1) return newArr } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]); ------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------- Solution: function diffArray(arr1, arr2) { let set1 = new Set(arr1); let set2 = new Set(arr2); let diff1 = arr1.filter(x => !set2.has(x)) // console.log(diff1); let diff2 = arr2.filter(x => !set1.has(x)); // console.log(diff2); let newArr = diff1.concat(diff2); console.log(newArr); // Same, same; but different. return newArr; } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
! err763_palette_bug.jnl ! See PyFerret issue 98 ! Ansley Manke 11/11/2021 ! ! Set a color palette with /PALETTE in combination with /SET. The default palette ! not restored before making the next plot. ! Define an example 2D variable to plot let var = i[i=1:5] + j[j=1:5] ! This is correct: ! After a /palette setting on one plot, the next one uses the default palette. ! The script saves one image to compare, and goes on to test all plot types. set view ul shade/palette=purple_red var set view ur shade/title="Next plot reverts to current default palette" var ! But if /SET used, the next plot used wrong palette. set view ll shade/set/palette=blue_orange/title="blue_orange palette with /SET" var ppl shakey,1,1,,0,-2 ppl shade set view lr shade/title="Next plot should revert to current default palette" var frame/file=err763_palette_bug.png ! Similar tests using other plot commands that use color palettes. can view set view ul use simple_traj_dsg ribbon/set/palette=yellow_green_blue/thick=3/title="Ribbon plot with /SET/PAL=yellow_green_blue" sst ppl shakey,1,1,,0,-2 ppl ribbon set view ur shade/title="Next plot should revert to current default palette" var set view ll LET xtriangle = {0,.5,1} LET ytriangle = {0,1,0} LET xpts = 10*RANDU(j[j=1:20]+0) ! random X coordinates LET ypts = 10*RANDU(j[j=1:20]+1) ! random Y coordinates LET values = 10* j[j=1:20] ! value at each (x,y) point POLYGON/set/palette=cmocean_solar/title="cmocean_solar palette with /SET" xpts+xtriangle, ypts+ytriangle, values ppl shakey,1,1,,0,-2 ppl polygon set view lr shade/title="Next plot should revert to current default palette" var !!!!!!!!!!!!!!!!!!!!! FILL plots palette default can view set view ul fill/palette=rainbow/title="/PALETTE=rainbow" var set view ur fill/title="Next plot should revert to current default palette" var ! With /SET on first plot; second was wrong. set view ll fill/set/palette=cmocean_speed/title="cmocean_speed palette with /SET" var ppl shakey,1,1,,0,-2 ppl fill set view lr fill/title="Next plot should revert to current default palette" var ! Now set an alternative palette for the remainder of the session (or until reset) can view PALETTE magma set view ul fill/palette=cmocean_phase/title="/PALETTE=cmocean_phase" var set view ur fill/title="After PALETTE magma setting, next plot uses current default palette" var ! With /SET on first plot; second was wrong. set view ll fill/set/palette=cmocean_balance/title="cmocean_balance palette with /SET" var ppl shakey,1,1,,0,-2 ppl fill set view lr fill/title="Next plot should revert to current default palette" var cancel view palette ! PALETTE with no argument, use current default palette setting (magma) fill/title="current default palette" var ! Restore PyFerret's usual default palette PALETTE default
import { useEffect, useState } from 'react'; export const useWindowSize = () => { const [windowSize, setWindowSize] = useState<{ width: number; height: number }>({ width: 640, height: 480, }); useEffect(() => { if (typeof window !== 'undefined') { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); }; window.addEventListener('resize', handleResize); handleResize(); return () => window.removeEventListener('resize', handleResize); } }, []); // Empty array ensures that effect is only run on mount return windowSize; };
<nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- <% if logged_in? %> <%= link_to "MyRecipes", chef_path(current_chef), class: "navbar-brand", id: "logo" %> <% else %> --> <%= link_to "MyRecipes", root_path, class: "navbar-brand", id: "logo" %> <!-- <% end %> --> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <% if logged_in? %> <%= link_to "RecipesHome", root_path, class: "navbar-brand", id: "logo" %> <!-- <li class="active"><a id="logo" href= "/pages/home" > Home </a> </li> --> <li class="active"><a id="logo2" href= "/recipes/new" > Create Recipe</a> <span class="sr-only">(current)</span></li> <% end %> <li><a id="logo3" href= "/recipes" > All Recipes </a></li> <li class="dropdown"> <a href="#" id="logo3" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Making life easy <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Ingredients available</a></li> <li><a href="#">Time available</a></li> <li><a href="#">Favorite Chefs</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> <li role="separator" class="divider"></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> <form class="navbar-form navbar-left"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <ul class="nav navbar-nav navbar-right"> <li><a id="logo3" href= "/chefs" > All Chefs </a></li> <% if logged_in? %> <li class="dropdown active"> <a href="#" id="logo2" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><%= current_chef.chefname %>'s Profile <%= "Admin" if current_chef.admin? %><span class="caret"></span></a> <ul class="dropdown-menu"> <!-- <li><a href= " /chefs/:id " >View Your Profile</a></li> --> <li><%= link_to "View Your Profile", chef_path(current_chef) %></li> <li><%= link_to "Edit Your Profile", edit_chef_path(current_chef) %></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><%= link_to "Log out" , logout_path, method: :delete %></li> </ul> </li> <% else %> <li class="active"><a id="logo2" href= '/login' >Log In</a><span class="sr-only">(current)</span></li> <!-- <li><%= link_to "Log In", login_path %></li> --> <% end %> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav>
import 'package:flutter/material.dart'; Widget myDrowerUser({ required Function(int index, String tittel) onItemTapped, required double widthScreen, required String name, }) { return Drawer( width: widthScreen * .535, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.zero, // Set to zero to remove the circular border ), backgroundColor: Colors.white, child: Padding( padding: const EdgeInsets.symmetric(vertical: 50, horizontal: 3), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( name, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600), ), const Divider( thickness: 1, color: Colors.grey, ), ListTile( title: const Text( "Drivers", style: TextStyle(fontSize: 18), ), leading: Image.asset( "assets/images/person.png", height: 25, width: 25, ), onTap: () => onItemTapped(0, "Order A Ride"), ), ListTile( title: const Text( "Notifacation", style: TextStyle(fontSize: 18), ), leading: Image.asset( "assets/images/iconamoon_notification-bold.png", height: 25, width: 25, ), onTap: () => onItemTapped(1, "Notifications"), ), ], ), ), ); }
package com.example.homework5 import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.homework5.databinding.ActivityMain3Binding import com.google.firebase.auth.FirebaseAuth class MainActivity_3 : AppCompatActivity() { private lateinit var binding:ActivityMain3Binding private lateinit var firebaseAuth:FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var binding:ActivityMain3Binding = ActivityMain3Binding.inflate(layoutInflater) setContentView(binding.root) firebaseAuth = FirebaseAuth.getInstance() binding.backButton.setOnClickListener(){ val intent = Intent(this, MainActivity::class.java) startActivity(intent) } binding.loginButtonNext.setOnClickListener(){ val email = binding.userEmail.text.toString() val password = binding.userPassword.text.toString() if(!email.isNullOrBlank() && !password.isNullOrBlank()){ firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(){ if(it.isSuccessful){ val intent = Intent(this, MainActivity4::class.java) startActivity(intent) } else { Toast.makeText(this, it.exception.toString(), Toast.LENGTH_SHORT).show() } } }else{ Toast.makeText(this, "Please fill out all fields", Toast.LENGTH_SHORT).show() } } } }
import sqlite3 import pandas as pd from difflib import SequenceMatcher import numpy as np import math class president_converter: def __init__(self, conn): self.conn = conn # upload input df format of data to db as a Table # if same name exists in the db. Replace it. def upload_df_to_database(self, df: pd.DataFrame, name: str): df.to_sql(name, self.conn, if_exists='replace') def retrieve_df_from_db(self, table_name): query = """ SELECT * FROM {} """.format(table_name) df = pd.read_sql_query(query, self.conn) return df # dems_votes_year and gop_votes_year are added and shows only major candidates of each election(dems and gop candidates) def convert_database(self): query = """ DROP TABLE IF EXISTS name_modified_president; CREATE TABLE name_modified_president AS SELECT year, office, candidate, party_detailed, candidatevotes, CAST((CASE WHEN party_detailed = 'DEMOCRAT' THEN candidatevotes END) AS REAL) AS dems_votes_year, CAST ((CASE WHEN party_detailed = 'REPUBLICAN' THEN candidatevotes END) AS REAL) AS gop_votes_year FROM( SELECT year, office, candidate, party_detailed, sum(candidatevotes) as candidatevotes FROM ( SELECT year, office, candidate, party_detailed, sum(candidatevotes) as candidatevotes FROM from1976to2020_president GROUP BY year, party_detailed HAVING MAX(candidatevotes) ) GROUP By year, candidate HAVING MAX(candidatevotes) ); ALTER TABLE name_modified_president ADD COLUMN totalvotes; ALTER TABLE name_modified_president ADD COLUMN state_po; UPDATE name_modified_president SET dems_votes_year = ( SELECT subquery.dems_votes_year FROM( SELECT SUM(dems_votes_year) as dems_votes_year, year FROM name_modified_president GROUP BY year ) AS subquery WHERE subquery.year = name_modified_president.year), gop_votes_year = ( SELECT subquery.gop_votes_year FROM( SELECT SUM(gop_votes_year) as gop_votes_year, year FROM name_modified_president GROUP BY year ) AS subquery WHERE subquery.year = name_modified_president.year), totalvotes = ( SELECT subquery.totalvotes FROM ( SELECT year, SUM(candidatevotes) as totalvotes FROM name_modified_president GROUP BY year ) AS subquery WHERE subquery.year = name_modified_president.year), state_po = 'USA'; CREATE TABLE temp_name_modified_president AS SELECT * FROM name_modified_president WHERE party_detailed = 'DEMOCRAT' or party_detailed = 'REPUBLICAN'; DROP TABLE IF EXISTS name_modified_president; ALTER TABLE temp_name_modified_president RENAME TO name_modified_president; """ cursor = self.conn.cursor() cursor.executescript(query) # automatically assign names from hsall db to the names in the current name_modified_presdient database # using similarity. def auto_correct_names(self, df_error_names: pd.DataFrame, df_correct_names: pd.DataFrame, limit_similarity): for index, row in df_error_names.iterrows(): if row['office'] == 'US PRESIDENT': office = 'President' last_name = row['last_name'] first_name = row['first_name'] congress_no = ((row['year'] + 1 - 1789) / 2) + 1 df_error_names.at[index, 'congress'] = congress_no correct_rows = df_correct_names.loc[ (df_correct_names['congress'] == congress_no) & (df_correct_names['chamber'] == office)] for inner_index, inner_row in correct_rows.iterrows(): correct_name = inner_row['bioname'] error_name = row['candidate'] avg_similarity = 0 full_similarity = 0 if inner_row['first_name'] is not None and first_name is not None: first_similarity = SequenceMatcher(None, inner_row['first_name'], first_name).ratio() if inner_row['last_name'] is not None and last_name is not None: last_similarity = SequenceMatcher(None, inner_row['last_name'], last_name).ratio() if first_similarity is not None and last_similarity is not None: avg_similarity = (first_similarity * 0.3 + last_similarity * 0.7) if correct_name is not None and error_name is not None: full_similarity = SequenceMatcher(None, correct_name, error_name).ratio() similarity = max(avg_similarity, full_similarity) if similarity is not None and similarity > limit_similarity: df_error_names.at[index, 'candidate'] = inner_row['bioname'] df_error_names.at[index, 'first_name'] = inner_row['first_name'] df_error_names.at[index, 'last_name'] = inner_row['last_name'] df_error_names.at[index, 'bioguide_id'] = inner_row['bioguide_id'] df_error_names.at[index, 'match'] = 1 df_error_names = df_error_names.replace({np.nan: None}) return df_error_names # Interprete names and set first and last name according to the names. def interpret_names(self, df): error_df = pd.DataFrame() for index, row in df.iterrows(): name = row['candidate'] if name is not None: last_name_arr = name.split(',', 1) first_name_arr = last_name_arr[1].split() if len(last_name_arr) > 1 else None name_arr = [last_name_arr[0]] name_arr = name_arr + first_name_arr length = len(name_arr) new_name_arr = [] for i in range(length): if '(' in name_arr[i] or ')' in name_arr[i]: pass # new_name = name_arr[i].replace('(', "") # new_name = new_name.replace(')', "") # df.at[index, 'nickname'] = str(new_name).upper() elif "JR." == str(name_arr[i]).upper() or "SR." == str(name_arr[i]).upper() or "III" == str( name_arr[i]).upper() \ or "II" == str(name_arr[i]).upper() or "JR" == str(name_arr[i]).upper() or "SR" == str( name_arr[i]).upper(): # df.at[index, 'suffix'] = str(name_arr[i]).replace('.', "").upper() pass else: if ',' in name_arr[i]: name_element = name_arr[i].replace(',', "") else: name_element = name_arr[i] new_name_arr.append(name_element) if len(new_name_arr) == 1: error_df.append(row) else: df.at[index, 'last_name'] = str(new_name_arr[0]).upper() df.at[index, 'first_name'] = str(new_name_arr[1]).upper() return df
import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' import InputAccount from './InputAccount.vue' const user = userEvent.setup() test('fieldset のアクセシブルネームは、legend を引用している', () => { render(InputAccount) expect(screen.getByRole('group', { name: 'アカウント情報の入力' })).toBeInTheDocument() }) test('メールアドレス入力欄', async () => { render(InputAccount) const textbox = screen.getByRole('textbox', { name: 'メールアドレス' }) const value = '[email protected]' await user.type(textbox, value) expect(screen.getByDisplayValue(value)).toBeInTheDocument() }) test('パスワード入力欄', async () => { render(InputAccount) expect(() => screen.getByPlaceholderText('8文字以上で入力')).not.toThrow() expect(() => screen.getByRole('textbox', { name: 'パスワード' })).toThrow() }) test('パスワード入力欄', async () => { render(InputAccount) const password = screen.getByPlaceholderText('8文字以上で入力') const value = 'abcd1234' await user.type(password, value) expect(screen.getByDisplayValue(value)).toBeInTheDocument() }) test('Snapshot: アカウント情報の入力フォームが表示される', () => { const { container } = render(InputAccount) expect(container).toMatchSnapshot() })
package main import ( "fmt" "os" ) func main() { key := "DB_CONN" defValue := `postgres://as:[email protected]/pg? sslmode=verify-full` conn, err := SetEnv(key, defValue) if err != nil { fmt.Println(err) } else { fmt.Println("Set connection:", conn) } connStr := os.Getenv(key) fmt.Printf("Connection string: %s\n", connStr) if err = UnsetEnv(key); err != nil { fmt.Println(err) } conStr, err := GetenvDefault(key, defValue) if err != nil { fmt.Println(err) } else { fmt.Println("After unset connection:", conStr) } }
import React from 'react'; import { Box, Button, Flex, Image, Link, Spacer } from '@chakra-ui/react'; import Instagram from "./assets/social-media-icons/insta_32x32.png"; import Twitter from "./assets/social-media-icons/twitter_32x32.png"; import Email from "./assets/social-media-icons/email_32x32.png"; const NavBar = ({ accounts, setAccounts }) => { const isConnected = Boolean(accounts[0]); async function connectAccount() { if (window.ethereum) { const accounts = await window.ethereum.request({ method: "eth_requestAccounts", }); setAccounts(accounts); } } return ( <Flex justify="space-between" align="center" padding="30px"> {/* Left side - Social media icons */} <Flex justify="space-around" width="40%" padding="0 75px"> <Link href="https://www.instagram.com/frugs.io"> <Image src={Instagram} boxSize="42px" boxShadow="0 5px 5px #000000" margin="0 15px" /> </Link> <Link href="https://www.twitter.com/frugsnft"> <Image src={Twitter} boxSize="42px" boxShadow="0 5px 5px #000000" margin="0 15px" /> </Link> <Link href="https://discord.gg/Rq4zS3GM"> <Image src={Email} boxSize="42px" boxShadow="0 5px 5px #000000" margin="0 15px" /> </Link> </Flex> {/* Right side - Sections and connect */} <Flex justify="space-around" align="center" width="40%" padding="30px" textShadow="0 2px 2px #000000"> <Box margin="0 15px">About</Box> <Spacer /> <Box margin="0 15px">Mint</Box> <Spacer /> <Box margin="0 15px">Team</Box> <Spacer /> {/* Connect */} {isConnected ? ( <Box margin="0 15px">Connected</Box> ) : ( <Button backgroundColor="#3DE200" borderRadius="5px" boxShadow="0px 2px 2px 1px #0F0F0F" color="white" cursor="pointer" fontFamily="inherit" padding="15px" margin="0 15px" onClick={connectAccount} > Connect </Button> )} </Flex> </Flex> ); }; export default NavBar;
<article class="table-header"> <div> <h2 style="display:inline;" *ngIf="!viewMode">Prepare meal below:</h2> <h2 style="display:inline;" *ngIf="viewMode">Items in the prepared Menu:</h2> </div> <div *ngIf="!viewMode"> <button class="button-add-row" mat-raised-button (click)="addFromSaved()"> Add Items from saved Menus </button>&nbsp; <button class="button-add-row" mat-raised-button (click)="addRow()"> Add Item </button>&nbsp; <button mat-raised-button color="warn" (click)="removeSelectedRows()"> Remove Items </button> </div> </article> <div> <mat-error class="errorTextSize">{{previousAddOrEditExistsErrorMessage}}</mat-error> </div> <table mat-table [dataSource]="dataSource"> <ng-container [matColumnDef]="col.key" *ngFor="let col of columnsSchema"> <th mat-header-cell *matHeaderCellDef [ngSwitch]="col.key"> <span *ngSwitchCase="'isSelected'"> <mat-checkbox (change)="selectAll($event)" [checked]="isAllSelected()" [indeterminate]="!isAllSelected() && isAnySelected()" *ngIf="!viewMode"></mat-checkbox> </span> <span *ngSwitchDefault>{{ col.label }}</span> </th> <td mat-cell *matCellDef="let element"> <div [ngSwitch]="col.type" *ngIf="!element.isEdit"> <ng-container *ngSwitchCase="'isSelected'"> <mat-checkbox (change)="element.isSelected = $event.checked" [checked]="element.isSelected" *ngIf="!viewMode"></mat-checkbox> </ng-container> <div class="btn-edit" *ngSwitchCase="'isEdit'"> <span *ngIf="!viewMode"> <button mat-raised-button style="display:inline;background-color: #e6e600; color: black" (click)="editRow(element)"> <mat-icon>edit</mat-icon> </button>&nbsp; <button mat-button mat-raised-button style="display: inline; color: red" (click)="removeRow(element.itemName)"> <mat-icon>delete</mat-icon> </button> </span> </div> <span *ngSwitchCase="'date'"> {{ element[col.key] | date: 'mediumDate' }} </span> <span *ngSwitchDefault> {{ element[col.key] }} </span> </div> <div [ngSwitch]="col.type" *ngIf="element.isEdit"> <div *ngSwitchCase="'isSelected'"></div> <div class="btn-edit" *ngSwitchCase="'isEdit'"> <button mat-raised-button style="background-color: green; color: white" (click)="editCompletedRow(element)" [disabled]="disableSubmit(element.itemName)"> Done </button> </div> <mat-form-field class="form-input" *ngSwitchCase="'date'" appearance="fill"> <mat-label>Choose a date</mat-label> <input matInput [matDatepicker]="picker" [(ngModel)]="element[col.key]" /> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> <span *ngSwitchCase="'item'"> <mat-form-field class="form-input" appearance="fill" *ngIf="element.isAdd"> <!--<mat-label>Choose below</mat-label>--> <input [type]="col.type" [required]="col.required" [pattern]="col.pattern" matInput [formControl]="itemControl" [(ngModel)]="element[col.key]" [matAutocomplete]="auto" (change)="inputHandler($event, element.itemName, col.key)"> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)='selected($event.option.value)'> <mat-option *ngFor="let option of filteredOptions | async" [value]="option"> {{option.itemName}} </mat-option> </mat-autocomplete> </mat-form-field> <span *ngIf="!element.isAdd"> {{ element[col.key] }} </span> </span> <mat-form-field class="form-input" appearance="fill" *ngSwitchCase="'childItem'"> <mat-select multiple [required]="col.required" [pattern]="col.pattern" [(ngModel)]="element[col.key]" [(value)]="selectedChildItem" (change)="inputHandler($event, element.itemName, col.key)"> <mat-option *ngFor="let item of childItems" [value]="item.itemName"> {{item.itemName}} </mat-option> </mat-select> </mat-form-field> <mat-form-field class="form-input" appearance="fill" *ngSwitchCase="'itemUnit'"> <mat-select [required]="col.required" [pattern]="col.pattern" [(ngModel)]="element[col.key]" [(value)]="selectedUnit" (change)="inputHandler($event, element.itemName, col.key)"> <mat-option *ngFor="let lookup of itemLookupUnits" [value]="lookup"> {{lookup.unitLookupValue}} </mat-option> </mat-select> </mat-form-field> <mat-form-field class="form-input" *ngSwitchDefault> <input matInput [required]="col.required" [pattern]="col.pattern" [type]="col.type" [(ngModel)]="element[col.key]" (change)="inputHandler($event, element.itemName, col.key)" /> </mat-form-field> </div> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr> </table> <br /> <br />
package com.switchfully.digibooky.user.service; import com.switchfully.digibooky.user.domain.Member; import com.switchfully.digibooky.user.domain.userAttribute.Address; import com.switchfully.digibooky.user.service.dto.member.CreateMemberDto; import com.switchfully.digibooky.user.service.dto.member.MemberDto; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class UserMapperTest { private static final Address ADDRESS = new Address("rue Ferra", "3", "75013", "Paris"); private static final Member MEMBER = new Member("[email protected]", "lastName", "password", ADDRESS, "33A"); private static final CreateMemberDto CREATE_MEMBER_DTO = new CreateMemberDto( MEMBER.getEmail(), MEMBER.getLastname(), MEMBER.getFirstname(), MEMBER.getPassword(), MEMBER.getAddress(), MEMBER.getInss()); private static final MemberDto MEMBER_DTO = new MemberDto( MEMBER.getId(), MEMBER.getEmail(), MEMBER.getLastname(), MEMBER.getFirstname(), MEMBER.getAddress()); @Nested @DisplayName("UserMapper Test") class UserMapperTesting { UserMapper myMapper = new UserMapper(); @Test @DisplayName("CreateUserDTO to Member : return Member") void toMember_whenGivenCreateUserDTO_thenReturnMember() { //GIVEN //WHEN Member actualMember = myMapper.toMember(CREATE_MEMBER_DTO); //THEN Assertions.assertEquals(MEMBER.getEmail(), actualMember.getEmail()); } @Test @DisplayName("User to MemberDTO : return MemberDTO") void toMemberDto_whenUseGiven_thenReturnMemberDTO() { //GIVEN //WHEN MemberDto actualMemberDto = myMapper.toMemberDto(MEMBER); //THEN Assertions.assertEquals(MEMBER_DTO, actualMemberDto); } } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Store; class StoreController extends Controller { public function store(Request $request) { $request->validate([ 'name' => 'required', 'address' => 'required', 'active' => 'required|boolean', ]); $store = Store::create($request->all()); return response()->json([ 'message' => 'Store successfully create.' ], 200); } public function index() { $stores = Store::all(); return response()->json($stores); } public function show($id) { $store = Store::find($id); if (!$store) { return response()->json(['message' => 'Store not found'], 404); } return response()->json($store); } public function update(Request $request, $id) { $store = Store::find($id); if (!$store) { return response()->json(['message' => 'Store not found'], 404); } $request->validate([ 'name' => 'required', 'address' => 'required', 'active' => 'required|boolean', ]); $store->update($request->all()); return response()->json(['message' => 'Store successfully updated'], 200); } public function destroy($id) { $store = Store::find($id); if (!$store) { return response()->json(['message' => 'Store not found'], 404); } $store->delete(); return response()->json(['message' => 'Store successfully deleted'], 200); } }
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) 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. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. 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 org.firstinspires.ftc.teamcode.TestPrograms; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import org.firstinspires.ftc.robotcore.external.navigation.Acceleration; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.Position; import org.firstinspires.ftc.robotcore.external.navigation.Velocity; @Autonomous(name="Gyro Test", group ="Tester") @Disabled public class GyroTurnTest extends LinearOpMode { private DcMotor FrontLeftDrive = null; private DcMotor FrontRightDrive = null; private DcMotor BackLeftDrive = null; private DcMotor BackRightDrive = null; // The IMU sensor object BNO055IMU imu; // State used for updating telemetry Orientation angles; Acceleration gravity; @Override public void runOpMode() { BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); // Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port // on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU", // and named "imu". imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); telemetry.addData(">", "Press Play to start"); telemetry.update(); waitForStart(); imu.startAccelerationIntegration(new Position(), new Velocity(), 1000); while (opModeIsActive()) { turnToAngle(90); sleep(5000); } telemetry.addData("Running", "False"); telemetry.update(); } public void spinClockwise(double power) { FrontLeftDrive.setPower(power); BackLeftDrive.setPower(power); BackRightDrive.setPower(-power); FrontRightDrive.setPower(-power); } public void spinCounter(double power) { FrontLeftDrive.setPower(-power); BackLeftDrive.setPower(-power); BackRightDrive.setPower(power); FrontRightDrive.setPower(power); } public void turnToAngle(float angle) { float current; angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); current = angles.firstAngle; if (angle > current) { while (angle >= current + 5 && angle <= current -5) { spinClockwise(.75); current = angles.firstAngle; } } else { while (angle >= current + 5 && angle <= current -5) { spinCounter(.75); current = angles.firstAngle; } } } }
<template> <div class="register-container"> <!-- 注冊內容 --> <div class="register"> <h3>注冊新用戶 <span class="go">我有賬號,去 <a href="login.html" target="_blank">登陸</a> </span> </h3> <div class="content"> <label>手機號:</label> <!--name:要驗證的是哪一項 v-validate是否必須,驗證規則 --> <input placeholder="請輸入你的手機號" v-model="phone" name="phone" v-validate="{required:true,regex:/^09\d{8}$/}" :class="{invalid:errors.has('phone')}"> <span class="error-msg">{{errors.first("phone")}}</span> </div> <div class="content"> <label>驗證碼:</label> <input placeholder="請輸入驗證碼" v-model="code" name="code" v-validate="{required:true,regex:/^\d{6}$/}" :class="{invalid:errors.has('code')}"> <button style="width:100px;height:38px" @click="getCode">獲取驗證碼</button> <img ref="code" src="http://182.92.128.115/api/user/passport/code" alt="code"> <span class="error-msg">{{errors.first("code")}}</span> </div> <div class="content"> <label>登錄密碼:</label> <input placeholder="請輸入你的登入密碼" v-model="password" name="password" v-validate="{required:true,regex:/^[0-9A-Za-z]{8,20}$/}" :class="{invalid:errors.has('password')}"> <span class="error-msg">{{errors.first("password")}}</span> </div> <div class="content"> <label>確認密碼:</label> <input placeholder="請輸入確認密碼" v-model="password1" name="password1" v-validate="{required:true,is:password}" :class="{invalid:errors.has('password1')}"> <span class="error-msg">{{errors.first("password1")}}</span> </div> <div class="controls"> <input type="checkbox" v-model="agree" name="agree" v-validate="{required:true,'eunha':true}" :class="{invalid:errors.has('password1')}"> <span>同意協議並注冊《尚品匯用戶協議》</span> <span class="error-msg">{{errors.first("agree")}}</span> </div> <div class="btn"> <button @click="userRegister">完成注冊</button> </div> </div> <!-- 底部 --> <div class="copyright"> <ul> <li>關於我們</li> <li>聯系我們</li> <li>聯系客服</li> <li>商家入駐</li> <li>營銷中心</li> <li>手機尚品匯</li> <li>銷售聯盟</li> <li>尚品匯社區</li> </ul> <div class="address">地址:北京市昌平區宏福科技園綜合樓6層</div> <div class="beian">京ICP備19006430號 </div> </div> </div> </template> <script> export default { name: 'Register', data(){ return{ phone:'', //手機 code:'', //驗證碼 password:'', //密碼 password1:'', //密碼驗證 agree:true //同意 } }, methods:{ getCode(){ if(this.phone){ this.$store.dispatch('getCode',this.phone).then((res)=>{ if(res==1){ this.code=this.$store.state.user.code; //獲取驗證碼存起來 } }) } }, userRegister(){ //全不驗證通過才服務氣發請求 //回傳成功true/失敗false this.$validator.validateAll().then((res)=>{ if(res==true){ this.$router.push({ name:'login' }) }else{ alert('註冊失敗') } }); /*const {phone,code,password}=this; //都要不為空 if(phone&&code&&password){ this.$store.dispatch('userRegister',{phone,code,password}).then((res)=>{ if(res==1){ //註冊成功後跳到login this.$router.push({ name:'login' }) }else{ alert('註冊失敗') } }) } */ } } } </script> <style lang="less" scoped> .register-container { .register { width: 1200px; height: 445px; border: 1px solid rgb(223, 223, 223); margin: 0 auto; h3 { background: #ececec; margin: 0; padding: 6px 15px; color: #333; border-bottom: 1px solid #dfdfdf; font-size: 20.04px; line-height: 30.06px; span { font-size: 14px; float: right; a { color: #e1251b; } } } div:nth-of-type(1) { margin-top: 40px; } .content { padding-left: 390px; margin-bottom: 18px; position: relative; label { font-size: 14px; width: 96px; text-align: right; display: inline-block; } input { width: 270px; height: 38px; padding-left: 8px; box-sizing: border-box; margin-left: 5px; outline: none; border: 1px solid #999; } img { vertical-align: sub; } .error-msg { position: absolute; top: 100%; left: 495px; color: red; } } .controls { text-align: center; position: relative; input { vertical-align: middle; } .error-msg { position: absolute; top: 100%; left: 495px; color: red; } } .btn { text-align: center; line-height: 36px; margin: 17px 0 0 55px; button { outline: none; width: 270px; height: 36px; background: #e1251b; color: #fff !important; display: inline-block; font-size: 16px; } } } .copyright { width: 1200px; margin: 0 auto; text-align: center; line-height: 24px; ul { li { display: inline-block; border-right: 1px solid #e4e4e4; padding: 0 20px; margin: 15px 0; } } } } </style>
import mongoose from "mongoose"; import { destroyFromCloudinary } from "../utils/cloudinary.utils.js"; const commentSchema = mongoose.Schema({ text: { type: String, maxLength: [100, "length cannot exceed 100 characters"], default: "" }, media: { type: String, default: "" }, parent: { type: mongoose.Schema.Types.ObjectId, ref: "metaserver_comment", immutable: true, }, belongsTo: { type: mongoose.Schema.Types.ObjectId, ref: "metaserver_post", immutable: true, required: [true, "value is required"] }, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "metaserver_user", immutable: true, required: [true, "value is required"] }, }, { timestamps: true }); commentSchema.pre("deleteOne", { document: true, query: false }, async function (next) { const subComments = await CommentModel.find({ parent: this._id }); for (let subComment of subComments) { await subComment.deleteOne(); } if (this.media) { await destroyFromCloudinary(`comment-media-${this._id}`); } next(); }); const CommentModel = mongoose.model('metaserver_comment', commentSchema); export default CommentModel;
<template> <v-container grid-list-xs class="fontPrompt" v-if="!$store.state.loadingPage"> <v-row class="mt-10"> <v-spacer></v-spacer> <h1>ประกาศเกี่ยวกับ IT และซ่อมบำรุง</h1> <v-spacer></v-spacer> </v-row> <v-row v-if=" $store.getters.policyCode === '03' || $store.getters.policyCode === '02' " > <v-col cols="10"> <!-- <span>55</span> --> </v-col> <v-col cols="2"> <v-spacer></v-spacer> <v-btn @click="openPopNews = true" color="purple" dark >เพิ่มประกาศ</v-btn > <v-spacer></v-spacer> </v-col> </v-row> <v-row> <v-spacer></v-spacer> <v-col size="12"> <v-card elevation="9" outlined width="1000" v-for="item in dataShow" :key="item.ID" class="mt-10" v-bind:class="{ myImg: item.postStatus == '1' }" :loading="item.postStatus == '0'" > <v-card-actions class="justify-end backgroundGrey mb-n5"> <v-icon @click="deletePost(item.ID)" v-if="$store.getters.policyCode === '03'" >close</v-icon > <!-- </v-row> --> </v-card-actions> <v-card-title primary-title class="backgroundGrey"> <h2>{{ item.postHeader }}</h2> </v-card-title> <v-card-text class="pt-5"> <h3 class="ml-10">{{ item.postDes }}</h3> </v-card-text> <v-card-actions> <v-spacer></v-spacer> <span >ผู้เขียนประกาศ : {{ item.EmpFullName }} ({{ item.postDate | moment("DD/MM/YYYY") }})</span > <v-btn class="ml-5" color="pink" dark @click="disablePost(item)" v-if="$store.getters.policyCode === '03'" :disabled="item.postStatus == '1'" >ปิดการประกาศ</v-btn > </v-card-actions> </v-card> </v-col> <v-spacer></v-spacer> </v-row> <!-- Pop Create --> <v-dialog v-model="openPopNews" max-width="500"> <v-card class="pa-5"> <v-form @submit.prevent="submit"> <!-- Header--> <v-row> <v-col> <v-text-field v-model="newsData.postHeader" label="หัวข้อ" required outlined ></v-text-field> </v-col> </v-row> <v-row> <v-col> <v-text-field v-model="newsData.postDes" label="รายละเอียด" required outlined height="100" ></v-text-field> </v-col> </v-row> <v-row v-if="error.length" class="ml-5 mr-5 mt-5"> <div> <b class="red--text">Please correct the following error</b> <ul> <li v-for="error in error" :key="error.index" class="red--text"> {{ error }} </li> </ul> </div> </v-row> <v-row class="pt-10"> <v-spacer></v-spacer> <v-btn class="mr-4" @click="openPopNews = false">Cancel</v-btn> <v-btn color="success" type="submit">Confirm</v-btn> </v-row> </v-form> </v-card> </v-dialog> </v-container> </template> <script> import apiPostNews from "../services/apiPostnews"; import { updateEmpProcess } from "../services/apiProcess"; export default { name: "home", components: {}, async mounted() { this.$store.state.loadingPage = true; await this.loadData(); setTimeout(() => { this.$store.state.loadingPage = false; }, 200); // console.log(this.$store.getters.username) }, data() { return { error: [], newsData: { postHeader: "", postDes: "", postOwner: this.$store.getters.username, postStatus: "0", postDate: new Date(), }, openPopNews: false, dataShow: [], }; }, methods: { async submit() { const checkdata = this.checkFormDataCreate(); if (checkdata) { this.newsData.postOwner = this.$store.getters.username; // console.log(this.newsData); const result = await apiPostNews.createPost(this.newsData); if (result == "ok") { await this.loadData(); this.newsData = { postHeader: "", postDes: "", postOwner: this.$store.getters.username, postStatus: "0", postDate: new Date(), }; } this.openPopNews = false; } }, async loadData() { const result = await apiPostNews.getPostNews(); this.dataShow = result; // console.log(result) }, async deletePost(ID) { console.log(ID); const result = await apiPostNews.deletePost(ID); if (result == "ok") { alert("...........ลบประกาศแล้ว............"); await this.loadData(); } }, checkFormDataCreate() { this.error = []; if (this.newsData.postHeader !== "" && this.newsData.postDes !== "") { return true; } if (this.newsData.postHeader == "") { this.error.push("โปรดใส่ข้อมูลห้อข้อ"); } if (this.newsData.postDes == "") { this.error.push("โปรดใส่ข้อมูลรายละเอียด"); } }, async disablePost(item) { console.log(item.ID); const result = await apiPostNews.disablePost(item.ID); console.log(result); if (result == "ok") { alert("......ทำการปิดประกาศแล้ว....."); await this.loadData(); } }, }, }; </script> <style> .myImg { filter: brightness(50%); } .backgroundGrey { background-color: rgb(230, 230, 230); } </style>
/* eslint-disable react-hooks/exhaustive-deps */ import { useEffect, useState, memo, useRef } from "react"; import logo_desktop from "../../assets/logo.png"; import logo_mobile from "../../assets/logo-mobile.png"; import { Button, Login, Notification, SearchResult } from "../../components"; import { Link, NavLink, useNavigate } from "react-router-dom"; import { logout, clearMessage } from "../../store/user/userSlice"; import { useDispatch, useSelector } from "react-redux"; import icons from "../../utils/icons"; import Swal from "sweetalert2"; import { getCurrent } from "../../store/user/asyncAction"; import { apiGetComicWithTitle } from "../../apis"; import { toast } from "react-toastify"; const { IoNotifications, IoPersonOutline, CgLogOut, RiMoneyDollarCircleFill, FiSearch, IoClose, LuSwords, GiMoneyStack } = icons; const Header = () => { const inputSearch = useRef(null); const navigate = useNavigate(); const dispatch = useDispatch(); const [logo, setLogo] = useState(logo_desktop); const [isShow, setIsShow] = useState(false); const [active, setActive] = useState(); const [isShowOption, setIsShowOption] = useState(false); const [search, setSearch] = useState(""); const [isShowNotification, setIsShowNotification] = useState(false); const [comics, setComics] = useState([]); const [isLoading, setIsLoading] = useState(false); const { isLoggingIn, userData, errorMessage } = useSelector( (state) => state.user ); const [showInputMobile, setShowInputMobile] = useState(false); const showForm = () => { setIsShow(true); }; const fetchComic = async () => { try { const response = await apiGetComicWithTitle(search); setComics(response?.mes); } catch (error) { console.log(error); } finally { setIsLoading(false); } }; if (errorMessage) { toast.error(errorMessage); dispatch(clearMessage()); } useEffect(() => { if (isLoggingIn) { dispatch(getCurrent()); } if (window.innerWidth < 1024) setLogo(logo_mobile); else setLogo(logo_desktop); window.addEventListener("resize", handleResize); return () => { window.removeEventListener("reset", handleResize); }; }, []); useEffect(() => { if (search !== "") { setIsLoading(true); const handler = setTimeout(() => { fetchComic(); }, 500); return () => clearTimeout(handler); } else { setIsLoading(false); } }, [search]); const handleResize = () => { if (window.innerWidth < 1024) setLogo(logo_mobile); else setLogo(logo_desktop); }; return ( <header className="bg-headerBg h-[70px] text-[15px] fixed left-0 right-0 top-0 z-50 w-full px-[10px] min-[1300px]:p-0 "> {isShow && ( <Login setIsShow={setIsShow} active={active} setActive={setActive} /> )} <div className=" flex items-center h-full justify-between max-w-main mx-auto"> <div className={`flex justify-center items-center ${ showInputMobile ? "w-full" : "" }`} > <Link to={"/"}> <img src={logo} alt="" className={`h-[30px] w-auto ${showInputMobile ? "hidden" : ""}`} /> </Link> <div className={`rounded-full relative ml-5 min-w-6 min-h-6 border lg:p-0 lg:border-none ${ showInputMobile ? "border-none p-0 w-full mr-5" : "p-5" }`} > <input type="text" ref={inputSearch} placeholder="Bạn muốn tìm truyện gì" className={`rounded-full w-[400px] h-[44px] bg-inputBg pl-5 focus:outline-none lg:block ${ showInputMobile ? "block w-full" : "hidden" }`} value={search} onChange={(event) => { setSearch(event.target.value); }} /> {isLoading ? ( <div className={`text-main-text-color w-6 h-6 absolute top-1/2 right-1/2 lg:right-3 lg:top-1/2 -translate-y-1/2 translate-x-1/2 lg:translate-x-0 cursor-pointer ${ showInputMobile ? "right-5 translate-x-0" : "" }`} > <span className="loader-search"></span> </div> ) : ( <FiSearch size={24} className={`text-main-text-color absolute top-1/2 right-1/2 lg:right-3 lg:top-1/2 -translate-y-1/2 translate-x-1/2 lg:translate-x-0 cursor-pointer ${ showInputMobile ? "right-5 translate-x-0" : "" }`} onClick={() => { const width = window.innerWidth; if (width < 1024) { setShowInputMobile(true); } }} /> )} {search !== "" && <SearchResult data={comics} />} </div> {showInputMobile ? ( <div className="cursor-pointer" onClick={() => { setShowInputMobile(false); setSearch(""); inputSearch.current.focus(); }} > <IoClose size={30} /> </div> ) : null} </div> {!isLoggingIn ? ( <div className={`flex items-center ${showInputMobile ? "hidden" : ""}`} > <Button text={"Đăng ký"} css={"border-main hidden sm:block"} onClick={() => { showForm(); setActive(true); }} ></Button> <Button text={"Đăng nhập"} css={"bg-main border-main ml-5"} onClick={() => { showForm(); setActive(false); }} ></Button> </div> ) : ( <div className={`flex items-center h-full ${ showInputMobile ? "hidden" : "" }`} > <div className="relative"> <IoNotifications className="mx-5 cursor-pointer" size={26} onClick={() => { setIsShowNotification(!isShowNotification); }} /> {isShowNotification && <Notification />} </div> <div className="h-full w-auto py-3 flex items-center relative" onClick={() => { setIsShowOption(!isShowOption); }} > <img src={`${process.env.REACT_APP_API_IMAGE}${userData?.avatar}`} alt="avatar" className="h-full mr-2 cursor-pointer" /> <div> <p className="cursor-pointer font-semibold"> {userData?.fullname} </p> <p className="text-xs flex items-center ml-1"> {userData?.walletBalance}{" "} <RiMoneyDollarCircleFill color="yellow" className="ml-1" /> </p> </div> {isShowOption && ( <div className="absolute top-full right-0 py-2 bg-chapter-border-color flex flex-col justify-center translate-y-2 rounded-lg w-[250px] p-[10px]" onClick={() => {}} > <NavLink to={'/payment'} className="flex px-4 py-2 items-center cursor-pointer rounded-full hover:bg-main"> <GiMoneyStack className="mr-2" /> Nạp tiền </NavLink> <NavLink to={"/profile"} className="flex px-4 py-2 items-center cursor-pointer rounded-full hover:bg-main" > <IoPersonOutline className="mr-2" size={20} /> Trang cá nhân </NavLink> {userData?.role === "admin" && ( <NavLink to={"/admin"} className="flex px-4 py-2 items-center cursor-pointer rounded-full hover:bg-main" > <LuSwords className="mr-2" size={20} /> Quản lý </NavLink> )} <div className="flex px-4 py-2 items-center cursor-pointer rounded-full hover:bg-main" onClick={(event) => { Swal.fire({ icon: "question", title: "Bạn chắc chắn đăng xuất ?", showCancelButton: true, cancelButtonText: "Không", confirmButtonText: "Đăng xuất", showConfirmButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", }).then((result) => { console.log(result.isConfirmed); if (result.isConfirmed) { dispatch(logout()); navigate(0); } }); }} > <CgLogOut className="mr-2" size={20} /> Đăng xuất </div> </div> )} </div> </div> )} </div> </header> ); }; export default memo(Header);
from django.contrib import admin from . models import Client, Product, Order # @admin.action(description="Добавить скидку 15%") # def add_discount(modeladmin, request, queryset): # queryset.update(price=queryset.price * 0.85) class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'price', 'amount'] ordering = ['-amount'] list_filter = ['created_at'] search_fields = ['name'] search_fields_text = 'Поиск по названию продукта "name"' # actions = [add_discount] readonly_fields = ['amount', 'created_at'] fieldsets = [ ( 'Наименование и количество', { 'classes': ['wide'], 'fields': ['name', 'amount'], }, ), ( 'Подробности', { 'classes': ['collapse'], 'description': 'Подробности для продукта', 'fields': ['description', 'image'], }, ), ( 'Прочее', { 'fields': ['created_at'] }, ), ] admin.site.register(Client) admin.site.register(Product, ProductAdmin) admin.site.register(Order)
class Animal { action() { console.log('animal running'); } } class Dog extends Animal { action() { console.log('dog running'); } } class Fish extends Animal { action() { console.log('fish swimming'); } } // 多态的目的是为了写出更具备通用性的代码 // 父类引用指向子类对象 function makeActions(animals: Animal[]) { animals.forEach(animal => { animal.action(); }) } makeActions([new Dog(), new Fish()])
package com.zszuev.bookshelfsber.controllers; import com.fasterxml.jackson.databind.ObjectMapper; import com.zszuev.bookshelfsber.entities.Author; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.time.LocalDate; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @WebAppConfiguration public class AuthorControllerTest { @Autowired private WebApplicationContext context; private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testGetAllAuthors() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/authors") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } @Test public void testGetAuthor() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/authors/{authorId}", 1) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } @Test public void testGetAuthorNotFound() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/authors/{authorId}", 999) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test public void testCreateAuthor() throws Exception { Author newAuthor = new Author(1L, "John", "Middle", "Doe", LocalDate.of(1990, 1, 1).toString(), "Biography of John Doe"); String authorJson = new ObjectMapper().writeValueAsString(newAuthor); mockMvc.perform(MockMvcRequestBuilders.post("/api/authors") .contentType(MediaType.APPLICATION_JSON) .content(authorJson) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } @Test public void testUpdateAuthor() throws Exception { Author updatedAuthor = new Author(1L, "Updated", "Middle", "Author", LocalDate.of(1985, 5, 10).toString(), "Updated Biography"); String authorJson = new ObjectMapper().writeValueAsString(updatedAuthor); mockMvc.perform(MockMvcRequestBuilders.put("/api/authors/{authorId}", 1) .contentType(MediaType.APPLICATION_JSON) .content(authorJson) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } @Test public void testUpdateAuthorNotFound() throws Exception { Author updatedAuthor = new Author(1L, "Updated", "Middle", "Author", LocalDate.of(1985, 5, 10).toString(), "Updated Biography"); String authorJson = new ObjectMapper().writeValueAsString(updatedAuthor); mockMvc.perform(MockMvcRequestBuilders.put("/api/authors/{authorId}", 999) .contentType(MediaType.APPLICATION_JSON) .content(authorJson) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test public void testDeleteAuthor() throws Exception { mockMvc.perform(MockMvcRequestBuilders.delete("/api/authors/{authorId}", 1) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @Test public void testDeleteAuthorNotFound() throws Exception { mockMvc.perform(MockMvcRequestBuilders.delete("/api/authors/{authorId}", 999) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } }
import { addressWithMidEll, checkPrivateKey, isNumber, numberFormatter, timeSince, } from '../utils' describe('utils testing', () => { it('Should check private key of wallet', () => { expect(checkPrivateKey('mykeywrongforat')).toBe(false) expect( checkPrivateKey( '26d203424f24a19ce1e195bev5c08a853c2b22e5d4ebcab1d431ac7a7f23edb3' ) ).toBe(true) expect(checkPrivateKey('2d203424f24a19ce1e1bev5c08a')).toBe(false) }) it('Should check is provided value correct number', () => { expect(isNumber('sometext')).toBe(false) expect(isNumber(1)).toBe(true) expect(isNumber(0)).toBe(true) expect(isNumber('0')).toBe(false) }) it('Should add ellipses for long address in the middle of', () => { expect( addressWithMidEll('0xe4e174d0FC80dea9AC9A6C622BEBAA75C6B3EEa1') ).toBe('0xe4e174d0...75C6B3EEa1') expect(addressWithMidEll('0xe4e174d0FC80')).toBe('0xe4e174d0FC80') }) it('Should do formatting numbers in US formates', () => { expect(numberFormatter(1000000)).toBe('1,000,000') expect(numberFormatter(0.123456)).toBe('0.123') expect(numberFormatter(undefined as unknown as string)).toBe(undefined) }) it('Should get time period name since some time', () => { expect(timeSince(new Date().getTime() - 1000)).toBe('1 second(-s) ago') expect(timeSince(new Date().getTime() - 1000 * 61)).toBe( '1 minute(-s) ago' ) expect(timeSince(new Date().getTime() - 1000 * 61 * 60)).toBe( '1 hour(-s) ago' ) expect(timeSince(new Date().getTime() - 1000 * 61 * 60 * 24)).toBe( '1 day(-s) ago' ) expect(timeSince(new Date().getTime() - 1000 * 61 * 60 * 24 * 31)).toBe( '1 month(-s) ago' ) expect( timeSince(new Date().getTime() - 1000 * 61 * 60 * 24 * 31 * 12) ).toBe('1 year(-s) ago') }) })
require 'rails_helper' describe 'GET /articles/:article_id/comments', type: :request, comments: true, list: true do describe 'when user is non admin' do let(:user) { create(:user) } let(:article) { create(:article, published_at: DateTime.current) } let(:unpublished_article) { create(:article) } let!(:comment) { create(:comment, article: article) } let!(:child_comment1) { create(:comment, article: article, thread: comment, parent: comment) } let!(:child_comment2) { create(:comment, article: article, thread: comment, parent: comment) } before(:each) { sign_in(user) } it 'returns paginated response' do get article_comments_path(article), headers: { 'ACCEPT' => 'application/json' } body = JSON.parse(response.body) expect(body).to have_key('last_page') expect(body).to have_key('page') expect(body).to have_key('total') expect(body).to have_key('data') end it 'returns only root comments' do get article_comments_path(article), headers: { 'ACCEPT' => 'application/json' } body = JSON.parse(response.body) expect(body['total']).to be(1) expect(body['data'][0]['id']).to be(comment.id) end it 'cant view comments for unpublished articles' do get article_comments_path(unpublished_article), headers: { 'ACCEPT' => 'application/json' } expect(response).to have_http_status(:forbidden) end end describe 'when user is admin' do let(:user) { create(:user, admin: true) } let(:unpublished_article) { create(:article) } before(:each) { sign_in(user) } it 'can view comments for unpublished articles' do get article_comments_path(unpublished_article), headers: { 'ACCEPT' => 'application/json' } expect(response).to have_http_status(:success) end end end
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{% block title %}Welcome!{% endblock %}</title> <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> {# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #} {% block stylesheets %} {# {{ encore_entry_link_tags('app') }} #} <link rel="stylesheet" href="{{asset('style/header.css')}}"> {% endblock %} {% block javascripts %} {{ encore_entry_script_tags('app') }} {% endblock %} </head> <body> {% block body %} <!--Main Navigation--> <header> <nav class="navbar navbar-expand-sm navbar-dark bg-dark"> <div class="container-fluid text-center border-bottom"> <!-- Logo --> <a href="{{ path('Homepage') }}" class="navbar-brand"> <img src="{{asset('uploads/Shinrin.jpg')}}" style="width:50px" alt=""> </a> <!-- button toggler --> <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navmenu"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navmenu"> <!---left --> <div class="navbar-nav" > <a href="{{ path('app_product_index') }}" class="nav-link">All Product</a> <a href="{{ path('app_cart_index') }}" class="nav-link">Cart</a> <div class="dropdown"> <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown"> Categories</a> <div class ="dropdown-menu"> <li><a href="category.php?id=<?=$row['cid']?> "><?php echo$row["cname"]; ?></a></li> <li><a href="addcategory.php">&plus; New</a></li> </div> </div> </div> <!-- Search --> <!-- Right --> {# <div class="navbar-nav ms-auto"> <a href="#" class="nav-link">Welcom, <?=$_COOKIE['cc_usr']?></a> <a href="logout.php" class="nav-link">LogOut</a> </div> #} <div class="navbar-nav ms-auto"> <a href="Login.php" class="nav-link">Login</a> <a href="Register.php" class="nav-link">Register</a> </div> </div> </div> </nav> </header> {% endblock %} </body> </html>
package com.darkonnen.app.ws.ui.controller; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.darkonnen.app.ws.exceptions.UserServiceException; import com.darkonnen.app.ws.ui.models.request.UpdateUserDetailsRequestModel; import com.darkonnen.app.ws.ui.models.request.UserDetailsRequestModel; import com.darkonnen.app.ws.ui.models.response.UserRest; import com.darkonnen.app.ws.userservice.UserService; @RestController @RequestMapping("/users") public class UserController { // STORE USERS TEMPORARILY Map<String, UserRest> users; @Autowired UserService userService; @GetMapping("") public String getUsers(@RequestParam(value="page", defaultValue = "1") int page, @RequestParam(value="limit", defaultValue = "50") int limit, @RequestParam(value="sort", defaultValue = "desc", required = false) String sort) { return String.format("getUsers was called with page %s and limit %s and sort %s", page, limit, sort); } // @GetMapping(path="/{userId}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) // public UserRest getUser(@PathVariable("userId") String userId) { // UserRest returnValue = new UserRest(); // returnValue.setFirstName("Sergey"); // returnValue.setLastName("Kargopolov"); // returnValue.setEmail("[email protected]"); // return returnValue; // } @GetMapping(path="/{userId}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<UserRest> getUser(@PathVariable String userId){ // UserRest returnValue = new UserRest(); // returnValue.setFirstName("Sergey"); // returnValue.setLastName("Kargopolov"); // returnValue.setEmail("[email protected]"); // String firstName = null; // int firstNameLength = firstName.length(); if(true) throw new UserServiceException("A user service exception is thrown"); if(users.containsKey(userId)) { return new ResponseEntity<>(users.get(userId),HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } // return new ResponseEntity<UserRest>(HttpStatus.BAD_REQUEST); } @PostMapping(consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<UserRest> createUser(@Valid @RequestBody UserDetailsRequestModel userDetails) { // UserRest returnValue = new UserRest(); // returnValue.setFirstName(userDetails.getFirstName()); // returnValue.setLastName(userDetails.getLastName()); // returnValue.setEmail(userDetails.getEmail()); // // String userId = UUID.randomUUID().toString(); // returnValue.setUserID(userId); // // if(users == null) users = new HashMap<>(); // users.put(userId, returnValue); UserRest returnValue = userService.createUser(userDetails); return new ResponseEntity<UserRest>(returnValue,HttpStatus.OK); } @PutMapping(path="/{userId}", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public UserRest updateUser(@PathVariable("userId") String userId, @Valid @RequestBody UpdateUserDetailsRequestModel userDetails) { UserRest storedUserDetails = users.get(userId); storedUserDetails.setFirstName(userDetails.getFirstName()); storedUserDetails.setLastName(userDetails.getLastName()); users.put(userId, storedUserDetails); return storedUserDetails; } @DeleteMapping(path="/{userId}") public ResponseEntity<Void> deleteUser(@PathVariable("userId") String userId) { users.remove(userId); return ResponseEntity.noContent().build(); } }
import Id from "../../../@shared/domain/value-object/id.value-object"; import UseCaseInterface from "../../../@shared/usecase/use-case.interface"; import Client from "../../domain/client.entity"; import ClientGateway from "../../gateway/client.gateway"; import { AddClientInputDto, AddClientOutputDto } from "./add-client.usecase.dto"; export default class AddClientUseCase implements UseCaseInterface { constructor(private clientRepository: ClientGateway) {} async execute(input: AddClientInputDto): Promise<AddClientOutputDto> { const props = { id: new Id(input.id), name: input.name, email: input.email, document: input.document, street: input.street, city: input.city, state: input.state, number: input.number, complement: input.complement, zipCode: input.zipCode, } const client = new Client(props) this.clientRepository.add(client) return { id: client.id.value, name: client.name, email: client.email, document: client.document, street: client.street, city: client.city, state: client.state, number: client.number, complement: client.complement, zipCode: client.zipCode, createdAt: client.createdAt, updatedAt: client.updatedAt, } } }
package demo22_IP_UDP_TCP; import java.io.IOException; import java.net.*; /* 1.创建发送端的Socket对象(DatagramSocket) 2.创建数据,并把数据打包 3.调用DatagramSocket对象的方法发送数据 4.关闭发送端 * */ public class j2_UDP_send { public static void main(String[] args) throws IOException { //1.创建发送端的Socket对象(DatagramSocket) // DatagramSocket() 构造数据报套接字并将其绑定到本地主机上的任何可用端口 DatagramSocket ds = new DatagramSocket(); //2.创建数据,并把数据打包 byte[] bys = "hello,world".getBytes(); int len = bys.length; InetAddress address = InetAddress.getByName("211.83.104.118"); // 根据IP地址创建了对象 int port = 10086; // 端口号范围:0~65535,我们通常使用1024~65535; // 创建数据包对象 DatagramPacket dp = new DatagramPacket(bys, len, address, port); // 更简单地创建数据包对象 //DatagramPacket dp1 = new DatagramPacket(bys, bys.length, InetAddress.getByName("211.83.104.118"), 10086); //3.调用Socket对象的send()方法发送数据 ds.send(dp); //4.关闭Socket对象 ds.close(); } }
table = "visitors" my_db_file <- "visitor_log.sqlite" test <- as.data.frame(cbind("Name" = "Person, Test", "Phone" = "604-555-5555", "Email"= "[email protected]", "Reason4Visit" = "Other", "EntryDate" = as.character(today()), "EntryTime" = as.character(now()), "ExitTime" = NA)) # Create database saveData <- function(data) { require(dplyr) require(RSQLite) require(dbplyr) # Connect to the database db <- dbConnect(RSQLite::SQLite(), my_db_file) src_dbi(db) # Create data table # dbCreateTable(conn = db, name = "visitors", fields = as.data.frame(visitor) , row.names = NULL, temporary = FALSE) # Submit the update query and disconnect dbWriteTable(conn = db, name = "visitors", value = data, overwrite = FALSE, append = TRUE, temporary = FALSE) #copy_to(db, data, temporary = FALSE) #dbGetQuery(db, query) dbDisconnect(db) } loadData <- function() { require(dplyr) require(RSQLite) require(dbplyr) require(lubridate) # Connect to the database db <- dbConnect(RSQLite::SQLite(), my_db_file) src_dbi(db) # Construct the fetching query visitors <- tbl(db, table) %>% filter(EntryDate == as.character(today())) %>% filter(is.na(ExitTime)) %>% collect() #query <- sprintf("SELECT * FROM %s", table) # Submit the fetch query and disconnect #data <- dbGetQuery(db, query) dbDisconnect(db) return(visitors) } updateData <- function(name){ require(lubridate) update_query <- paste0("UPDATE visitors ", "SET ExitTime='", as.character(now()), "' WHERE Name='", name, "' AND EntryDate='", as.character(today()), "'") db <- dbConnect(RSQLite::SQLite(), my_db_file) src_dbi(db) dbExecute(db, update_query) dbDisconnect(db) } ## Now setup a scheduler so we don't have to remember to remove old entries from the database shiny.auto.delete <- function(table = table){ # 24 hours 60 minutes 60 seconds require(lubridate) db <- dbConnect(RSQLite::SQLite(), my_db_file) src_dbi(db) time <- today() - 30 visitors <- tbl(db, table) %>% filter(as.Date(EntryDate) > time) %>% collect() delete_query <- paste0( "DELETE FROM ", table, " WHERE EntryDate > ", time ) if (nrow(visitors) != 0){ dbExecute(db, delete_query) } dbDisconnect(db) }
import Image from "next/image"; import { useEffect, useRef, useState } from "react"; import AvatarEditor from 'react-avatar-editor' import { ImageSelectionProps } from "../types"; const CropImage = ({ imageSelected }: ImageSelectionProps) => { const [imgSrc, setImgSrc] = useState('/empty.png') const imageCroppedRef = useRef<any>(null); const [imgPreview, setImagePreview] = useState("") useEffect(() => { if (imageSelected) { const url = URL.createObjectURL(imageSelected) setImgSrc(url); } }, [imageSelected]) const handleCloseCropImage = () => { const closeModal = new CustomEvent("close-crop-image-modal"); window.dispatchEvent(closeModal); } const handleUploadImage = () => { const openModal = new CustomEvent("edit-image-upload-modal"); window.dispatchEvent(openModal); } const handlePreviewImage = async () => { if (imageCroppedRef.current) { try { const blob = await getCroppedImageBlob() as Blob; const newImage = new File([blob], "filename.jpeg", { type: blob.type, }); const image = URL.createObjectURL(newImage) const closeModal = new CustomEvent("open-preview-modal", { detail: { file: newImage, } }); window.dispatchEvent(closeModal); } catch (e) { console.log(e) } } } const getCroppedImageBlob = () => { return new Promise((resolve, reject) => { return imageCroppedRef.current.getImage().toBlob((blob: File) => { if (blob) { resolve(blob); } else { reject(new Error('Failed to get cropped image blob')); } }, 'image/jpeg'); // Specify the image format (e.g., 'image/jpeg') }); }; return ( <div className="overflow-auto h-screen"> <div className="mx-auto flex justify-between"> <div>{""}</div> <h1 className="modal__title text-center">Pan and crop image</h1> <button onClick={handleCloseCropImage}><Image src="/times.svg" width={40} height={40} alt="Close modal" /> </button> </div> <div className="bg-black p-10 mt-10"> <div className="flex justify-center mx-auto"> {/* <img src={imgSrc} alt="" width={384} height={498} style={{width: "100%"}} /> */} <AvatarEditor image={imgSrc} width={350} height={350} border={50} color={[255, 255, 255, 0.6]} // RGBA scale={1.2} rotate={0} ref={imageCroppedRef} disableHiDPIScaling={true} /> </div> {/* <div>preview here <img src={imgPreview} /> </div> */} </div> <div className="mx-auto text-center mt-5 mb-20"> <button className="button button__create text-white py-2 px-7" onClick={handlePreviewImage}>Done </button> <p className="mt-5">{" "}</p> <button className="button button__outline py-2 px-7" onClick={handleUploadImage}>Re-Upload Image </button> </div> <div className="py-10">{" "} </div> </div> ) } export default CropImage;
import { AfterViewInit, Component, ElementRef, EventEmitter, Inject, Input, OnChanges, Output, SimpleChanges, ViewChild, } from '@angular/core'; import { ErrorLogger, IErrorLogger } from '@sneat/logging'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import { Tabulator, SelectRowModule, MenuModule, InteractionModule, Module, RowContextMenuSignature, } from 'tabulator-tables'; import { IGridColumn } from '@sneat/grid'; import { TabulatorColumn, TabulatorOptions, } from '../../tabulator/tabulator-options'; class AdvertModule extends Module { public static override moduleName = 'advert'; constructor(table: Tabulator) { super(table); console.log('AdvertModule.constructor()'); } initialize() { console.log('AdvertModule.initialize()'); } } Tabulator.registerModule([ InteractionModule, SelectRowModule, AdvertModule, MenuModule, ]); // console.log('SelectRowModule', ); // export interface IGridDef { // columns: IGridColumn[], // rows?: unknown[], // groupBy?: string; // } // // export const getTabulatorCols = (cols: IGridColumn[]): any[] => cols.map(c => { // const v = {...c}; // delete v.dbType; // return v; // }); // // export interface IGridColumn { // field: string; // colName?: string; // dbType: string; // title: string; // tooltip?: (cell: any) => string; // formatter?: any; // hozAlign?: 'left' | 'right'; // widthShrink?: number; // widthGrow?: number; // width?: number | string; // } /** * This is a wrapper class for the tabulator JS library. * For more info see http://tabulator.info */ @Component({ selector: 'sneat-datagrid', template: ` <div id="tabulator" #tabulatorDiv></div> <p class="ion-margin-start">Rows: {{ data?.length }}</p> `, }) export class DataGridComponent implements AfterViewInit, OnChanges { @Input() layout?: 'fitData' | 'fitColumns' = 'fitColumns'; @Input() data?: unknown[] = []; @Input() columns?: IGridColumn[] = []; @Input() groupBy?: string; @Input() height?: string; @Input() maxHeight?: string | number; @Input() rowContextMenu?: RowContextMenuSignature; @ViewChild('tabulatorDiv', { static: true }) tabulatorDiv?: ElementRef; @Input() rowClick?: (event: Event, row: unknown) => void; @Output() readonly rowSelected = new EventEmitter<{ row: unknown; event?: Event; }>(); // private tab = document.createElement('div'); private tabulator?: Tabulator; @Input() public selectable?: boolean | number | 'highlight'; private tabulatorOptions?: TabulatorOptions; private clickEvent?: Event; constructor(@Inject(ErrorLogger) private readonly errorLogger: IErrorLogger) { console.log('DataGridComponent.constructor()'); } ngOnChanges(changes: SimpleChanges): void { console.log('DataGridComponent.ngOnChanges():', changes); try { if ( (changes['data'] && this.data && this.columns) || (changes['columns'] && this.columns) || (changes['rowClick'] && this.rowClick) ) { this.drawTable(); } } catch (ex) { this.errorLogger.logError( ex, 'Failed to process ngOnChanges in DataGridComponent', ); } } // ngOnDestroy(): void { // console.log('DataGridComponent.ngOnDestroy()', this.tabulator); // try { // TODO: destroy Tabulator // if (this.tabulator?.element) { // // noinspection TypeScriptValidateJSTypes // this.tabulator.element.tabulator('destroy'); // } // } catch (ex) { // this.errorLogger.logError(ex, 'Failed to destroy tabulator'); // } // } ngAfterViewInit(): void { if (this.tabulator) { try { this.tabulator.redraw(); } catch (e) { this.errorLogger.logError(e, 'Failed to redraw tabulator', { show: false, report: false, }); } } } private drawTable(): void { if (!this.data || !this.columns) { console.warn('drawTable()', 'columns:', this.columns, 'data:', this.data); return; } console.log( 'drawTable()', 'columns:', this.columns, 'groupBy:', this.groupBy, 'data:', this.data, ); try { if (!this.tabulatorDiv) { this.errorLogger.logError(new Error('!this.tabulatorDiv')); return; } if (this.tabulatorOptions) { this.tabulatorOptions = { ...this.tabulatorOptions, data: this.data }; this.tabulator?.setData(this.data); } else { this.createTabulatorGrid(); } // this.tabulatorDiv.nativeElement.appendChild(this.tab); // tabulator.redraw(); } catch (e) { this.errorLogger.logError(e, 'Failed to drawTable'); } } private createTabulatorGrid(): void { this.setTabulatorOptions(); if (!this.tabulator) { this.tabulatorOptions = { ...this.tabulatorOptions, // rowClick: function (e, row) { // console.log('rowClick1', row); // }, // rowSelect: function (row) { // console.log('rowSelect', row); // }, // rowDeselect: function (row) { // console.log('rowDeselect', row); // } }; console.log( 'createTabulatorGrid(): tabulatorOptions:', this.tabulatorOptions, ); this.tabulator = new Tabulator( this.tabulatorDiv?.nativeElement, this.tabulatorOptions, ); this.tabulator.on('rowClick', (event: Event, row: unknown) => { console.log('rowClick event', event, row); this.clickEvent = event; if (this.rowClick) { this.rowClick(event, row); } }); this.tabulator.on('rowSelected', (row: unknown) => this.rowSelected.emit({ row, event: this.clickEvent }), ); this.tabulator.on('rowDeselected', (row: unknown) => console.log('rowDeselected event', row), ); } } private setTabulatorOptions(): void { this.tabulatorOptions = { // tooltipsHeader: true, // enable header tooltips // tooltipGenerationMode: 'hover', rowContextMenu: this.rowContextMenu, selectable: this.selectable, data: this.data, // reactiveData: true, // enable data reactivity columns: this.columns?.map((c) => { const col: TabulatorColumn = { // TODO(help-wanted): Use strongly typed Tabulator col def field: c.field, title: c.title || c.field || c.title, // headerTooltip: () => // `${c.colName || c.title || c.field}: ${c.dbType}`, }; if (c.colName !== 'Id' && c.colName?.endsWith('Id')) { col.formatter = 'link'; col.formatterParams = { url: 'test-url', }; col.cellClick = (e: Event, cell: unknown) => { e.preventDefault(); e.stopPropagation(); console.log('cellClick', cell); }; } if (c.tooltip) { col.tooltip = c.tooltip; } if (c.formatter) { col.formatter = c.formatter; } if (c.hozAlign) { col.hozAlign = c.hozAlign; } if (c.headerHozAlign) { col.headerHozAlign = c.headerHozAlign; } if (c.widthGrow) { col.widthGrow = c.widthGrow; } if (c.widthShrink) { col.widthShrink = c.widthShrink; } if (c.width !== undefined) { col.width = c.width; } // console.log('col:', col); return col; }), layout: this.layout || 'fitColumns', }; if (this.height) { this.tabulatorOptions = { ...this.tabulatorOptions, height: this.height, }; } if (this.maxHeight) { this.tabulatorOptions = { ...this.tabulatorOptions, maxHeight: this.maxHeight, }; } if (this.groupBy) { this.tabulatorOptions = { ...this.tabulatorOptions, groupBy: this.groupBy, groupHeader: (value: unknown, count: number) => { // value - the value all members of this group share // count - the number of rows in this group // data - an array of all the row data objects in this group // group - the group component for the group // console.log('groupHeader', value); return `${ this.groupBy }: ${value} <span class="ion-margin-start">(${count} ${ count === 1 ? 'record' : 'records' })</span>`; }, }; } } }
// import 'package:flutter/material.dart'; // import 'package:flutter/widgets.dart'; // import 'package:jmessage_flutter/jmessage_flutter.dart'; // import 'package:modal_progress_hud/modal_progress_hud.dart'; // import 'main.dart'; // class ConversationManageView extends StatefulWidget { // @override // _ConversationManageViewState createState() => _ConversationManageViewState(); // } // class _ConversationManageViewState extends State<ConversationManageView> { // List<JMConversationInfo> dataList = []; // final _commonFont = const TextStyle(fontSize: 18.0); // bool _loading = false; // String _result = "请选择需要操作的会话"; // int selectIndex = -1; // JMConversationInfo selectConversationInfo; // @override // void initState() { // super.initState(); // demoGetConversationList(); // } // void addMessageEvent() async { // jmessage.addReceiveMessageListener((msg) { // //+ // print('listener receive event - message : ${msg.toJson()}'); // verifyMessage(msg); // setState(() { // _result = "【收到消息】${msg.toJson()}"; // }); // }); // } // @override // Widget build(BuildContext context) { // return new Scaffold( // appBar: AppBar( // title: new Text("会话列表", style: TextStyle(fontSize: 20)), // leading: IconButton( // icon: new Image.asset("assets/nav_close.png"), // onPressed: () { // Navigator.maybePop(context); // }), // ), // body: ModalProgressHUD(inAsyncCall: _loading, child: _buildContentView()), // ); // } // Widget _buildContentView() { // return new Column( // children: <Widget>[ // new Container( // margin: EdgeInsets.fromLTRB(5, 5, 5, 0), // color: Colors.brown, // child: Text(_result), // width: double.infinity, // height: 120, // ), // new Row( // mainAxisAlignment: MainAxisAlignment.start, // children: <Widget>[ // new Text(" "), // new CustomButton(title: "发送文本消息", onPressed: demoSendTextMessage), // new Text(" "), // new CustomButton(title: "获取历史消息", onPressed: demoGetHistorMessage), // new Text(" "), // new CustomButton( // title: "刷新会话列表", // onPressed: () { // demoGetConversationList(); // }), // ], // ), // Expanded( // child: new Container( // color: Colors.grey, // margin: EdgeInsets.fromLTRB(5, 5, 5, 5), // child: new ListView.builder( // itemCount: dataList.length * 2, // itemBuilder: (context, i) { // if (i.isOdd) return new Divider(); // final index = i ~/ 2; // return _buildRow(dataList[index], index); // }), // ), // ), // ], // ); // } // Widget _buildRow(JMConversationInfo object, int index) { // String title = // "【${getStringFromEnum(object.conversationType)}】${object.title}"; // return new Container( // height: 60, // child: new ListTile( // //dense: true, // //leading: CircleAvatar(backgroundImage: NetworkImage(url)), // //trailing: Icon(Icons.keyboard_arrow_right), // contentPadding: EdgeInsets.symmetric(horizontal: 10.0), //设置内容边距,默认是 16 // title: new Text(title), // subtitle: new Text(object.latestMessage.toString()), // selected: selectIndex == index, // onTap: () { // print("点击了第【${index + 1}】行"); // setState(() { // selectIndex = index; // _result = "【选择的会话】\n ${object.toJson()}"; // }); // selectConversationInfo = object; // }, // ), // ); // } // /// 获取公开群列表 // void demoGetConversationList() async { // print("demoGetConversationList"); // setState(() { // selectIndex = -1; // selectConversationInfo = null; // _result = "请选择需要操作的会话"; // _loading = true; // }); // List<JMConversationInfo> conversations = await jmessage.getConversations(); // setState(() { // _loading = false; // dataList = conversations; // }); // for (JMConversationInfo info in conversations) { // print('会话:${info.toJson()}'); // } // } // int textIndex = 0; // void demoSendTextMessage() async { // print("demoSendTextMessage"); // if (selectConversationInfo == null) { // setState(() { // _result = "请选着需要操作的会话"; // }); // return; // } // setState(() { // _loading = true; // }); // JMTextMessage msg = await selectConversationInfo.sendTextMessage( // text: "send msg queen index $textIndex"); // setState(() { // _loading = false; // _result = "【文本消息】${msg.toJson()}"; // }); // textIndex++; // } // // 历史消息 // void demoGetHistorMessage() async { // print("demoGetHistorMessage"); // if (selectConversationInfo == null) { // setState(() { // _result = "请选着需要操作的会话"; // }); // return; // } // setState(() { // _loading = true; // }); // selectConversationInfo // .getHistoryMessages(from: 0, limit: 20) // .then((msgList) { // for (JMNormalMessage msg in msgList) { // print("get conversation history msg : ${msg.toJson()}"); // } // setState(() { // _loading = false; // _result = "【消息列表】${msgList.toString()}"; // }); // }); // } // }
use chrono::{DateTime, Local}; use clap::{arg, command, value_parser, ArgAction}; use dirs::{config_dir, home_dir}; use rev_lines::RevLines; use serde::{Deserialize, Serialize}; use std::fs::{read_to_string, write, File, OpenOptions}; use std::io::Write; use std::path::PathBuf; use toml; #[derive(Serialize, Deserialize, Debug)] #[serde(default)] struct Config { default_log_file: PathBuf, style: String, } impl Default for Config { fn default() -> Self { Self { default_log_file: default_log_file_path().into(), style: "markdown".to_string(), } } } fn default_log_file_path() -> std::ffi::OsString { home_dir() .expect("Couldn't get home directory") .join("rlg.md") .into_os_string() } fn canonicalize_log_file_path(mut config: Config) -> Config { let first = config .default_log_file .components() .collect::<Vec<_>>() .first() .unwrap() .as_os_str(); if first == "~" { config.default_log_file = home_dir() .expect("Couldn't get home directory") .join(config.default_log_file.strip_prefix("~").unwrap()) .canonicalize() .unwrap(); } else if first == "$HOME" { config.default_log_file = home_dir() .expect("Couldn't get home directory") .join(config.default_log_file.strip_prefix("$HOME").unwrap()) .canonicalize() .unwrap(); } config } fn get_config() -> Config { let binding = config_dir() .expect("Couldn't get config directory") .join("rlg.toml"); let config_path = binding.as_os_str().to_str().unwrap(); match read_to_string(config_path) { Ok(config_file_path) => match toml::from_str::<Config>(&config_file_path.to_string()) { Ok(config) => canonicalize_log_file_path(config), Err(e) => { eprintln!("Unable to parse config: {}", e); Config::default() } }, Err(_) => { println!( "No config file found, creating default config at {}", config_path ); match write( config_path, toml::to_string_pretty::<Config>(&Config::default()).unwrap(), ) { Ok(_) => {} Err(e) => eprintln!("Unable to write default config: {}", e), } Config::default() } } } fn year_header(datetime: DateTime<Local>) -> String { format!("\n## {}", datetime.format("%Y")) } fn day_header(datetime: DateTime<Local>) -> String { format!("\n\n### {}\n", datetime.format("%Y-%m-%d")) } fn determine_headers(path: &File, datetime: DateTime<Local>) -> String { let mut headers = String::new(); let year = datetime.format("%Y").to_string(); let day = datetime.format("%Y-%m-%d").to_string(); for line in RevLines::new(path) { match line { Ok(line) => { if line.trim().is_empty() { continue; } if line.starts_with(format!("- {}", day).as_str()) { return headers; } if !line.starts_with(format!("- {}", year).as_str()) { headers.push_str(&year_header(datetime)); } headers.push_str(&day_header(datetime)); return headers; } // We don't have a valid log line at this point??? Err(e) => { eprintln!("Error reading line: {}", e); return headers; } } } if headers.is_empty() { headers.push_str("# Lab Log\n"); headers.push_str(&year_header(datetime)); headers.push_str(&day_header(datetime)); } return headers; } fn print_last_n_lines(path: File, log_file_path_arg: &str, num_lines: usize) { println!( num_lines, log_file_path_arg ); let lines = RevLines::new(path).take(num_lines).collect::<Vec<_>>(); for line in lines.into_iter().rev() { match line { Ok(line) => println!("{}", line), Err(e) => eprintln!("Error reading line: {}", e), } } } fn append_to_file(mut path: &File, text: String) { if let Err(e) = writeln!(path, "{}", text) { eprintln!("Couldn't write to file: {}", e); } } fn main() { let config = get_config(); // Parse the command line args let args = command!() .arg( arg!([file] "Optional file to save the new log entry to") .short('f') .long("file") .value_name("file") .required(false) .default_value(config.default_log_file.into_os_string()) .value_parser(value_parser!(PathBuf)), ) .arg( arg!([text] "Text to save to the log" ) .value_name("text") .required(false) .default_value("testing!") .trailing_var_arg(true) .action(ArgAction::Append) .value_parser(value_parser!(String)), ) .get_matches(); let text_arg: String = args .get_many::<String>("text") .expect("No text provided") .cloned() .collect::<Vec<String>>() .join(" "); let log_file_path_arg = args.get_one::<PathBuf>("file").expect("Invalid file"); // Set our datetime let datetime_now = Local::now(); let datetime_str = datetime_now.format("%Y-%m-%d %H:%M:%S").to_string(); let mut log_entry = String::new().to_owned(); // Open and write the log entry to the file let file = OpenOptions::new() .read(true) .append(true) .create(true) .open(log_file_path_arg); match file { Ok(f) => { log_entry.push_str(determine_headers(&f, datetime_now).as_str()); log_entry.push_str(&format!("- {}: {}", datetime_str, text_arg)); append_to_file(&f, log_entry); } Err(e) => { println!("Unable to open file: {}", e); } } // Finally, provide feedback on what was just added to the log with context print_last_n_lines( OpenOptions::new() .read(true) .open(log_file_path_arg) .expect("Unable to read log file"), &log_file_path_arg.display().to_string(), 6, ); } /* * TODO: * - [ ] If no args are provided, spit out the last n-lines of the log * - [ ] Create a minimal TUI * - [ ] Add creation of new log lines * - [ ] Add view of existing log lines * - [ ] Add deletion of existing log lines * - [x] Create a default config if one isn't found. Let the user know. * - [x] Add a ~/.config/rlg.toml config file allowing a custom default log file location * - [x] Create a new file with appropriate headers if one doesn't exist * - [x] Only open the file once and pass it around * - [x] Get default log file working * - [x] Reverse the printout of last lines * - [x] Append text to file * - [x] Add timestamp to file * - [x] Add day header whenever the day changes * - [x] Add year header whenever the year changes */
<template> <div class="chart-frame"> <canvas ref="lineChartCanvas" height="252"></canvas> </div> <div class="category-container"> <div class="category-frame" @click="selectTab('수입')"> <div class="category-icon"> <CategoryIcon :class="{ 'selected-tab-image': selectedTab === '수입' }" :category="incomeTab.category" :width="60" /> </div> <div class="category-name" :class="{ 'selected-tab-text': selectedTab === '수입' }" > {{ incomeTab.category }} </div> </div> <div class="divide-bar"></div> <div class="category-frame" v-for="(tab, index) in outcomeList" :key="index" @click="selectTab(tab.category)" > <div class="category-icon"> <CategoryIcon :class="{ 'selected-tab-image': selectedTab === tab.category }" :category="tab.category" :width="60" /> </div> <div :class="{ 'selected-tab-text': selectedTab === tab.category }" class="category-name" > {{ tab.category }} </div> </div> </div> <div class="monthlyinout"> <div class="june"> <div>이전 달 대비</div> <div> <select v-model="month" class="month-select"> <option value="1">1월</option> <option value="2">2월</option> <option value="3">3월</option> <option value="4">4월</option> <option value="5">5월</option> <option value="6">6월</option> </select> <i class="fa-solid fa-caret-down"></i> </div> </div> <div class="inout"> <div class="income">수입</div> <div> <div class="times">{{ comparisonPrev.incomeCountDiff }}회</div> <div class="total" :class="greenOrRed(comparisonPrev.incomeSumDiff)"> {{ addPlusComma(comparisonPrev.incomeSumDiff) }}원 </div> <div class="total" :class="greenOrRed(comparisonPrev.incomeSumDiff)"> {{ addPlusComma(comparisonPrev.incomeGrowthRate) }}% </div> </div> </div> <div class="inout"> <div class="income">지출</div> <div> <div class="times">{{ comparisonPrev.outcomeCountDiff }}회</div> <div class="total" :class="redOrGreen(comparisonPrev.outcomeSumDiff)"> {{ addPlusComma(comparisonPrev.outcomeSumDiff) }}원 </div> <div class="total" :class="redOrGreen(comparisonPrev.outcomeSumDiff)"> {{ addPlusComma(comparisonPrev.outcomeGrowthRate) }}% </div> </div> </div> <div class="detail-container" :style="hideDetail ? { height: '0px' } : { height: '404px' }" > <div class="inout" v-for="category in comparisonPrev.categoryComparison"> <div class="income">{{ category.category }}</div> <div> <div class="times">{{ category.countDiff }}회</div> <div class="total" :class="redOrGreen(category.sumDiff)"> {{ addPlusComma(category.sumDiff) }}원 </div> <div class="total" :class="redOrGreen(category.growthRate)"> {{ addPlusComma(category.growthRate) }}% </div> </div> </div> </div> <div class="inout-detail"> <div v-if="hideDetail"> <span class="detail" @click="handleDetail(false)">자세히 &nbsp;</span> <i class="fa-solid fa-caret-down"></i> </div> <div v-else> <span class="detail" @click="handleDetail(true)">간략히 &nbsp;</span> <i class="fa-solid fa-caret-up"></i> </div> </div> </div> </template> <script setup> import { ref, onMounted, watch } from 'vue'; import { Chart, registerables } from 'chart.js'; import { useHistoryStore } from '@/stores/history'; import CategoryIcon from './CategoryIcon.vue'; const date = new Date(); const month = ref(date.getMonth() + 1); const selectedTab = ref('noTab'); const hideDetail = ref(true); const handleDetail = (val) => { hideDetail.value = val; }; const incomeTab = ref({ category: '수입', selected: false, }); const outcomeList = ref([ { category: '지출 전체', selected: false, }, { category: '식비', selected: false, }, { category: '교통', selected: false, }, { category: '문화', selected: false, }, { category: '통신', selected: false, }, { category: '기타', selected: false, }, ]); const historyStore = useHistoryStore(); const { getAmountsByMonthAndCategory, getComparisonWithPreviousMonth, addPlusComma, } = historyStore; const amountsByMonthAndCategory = ref(getAmountsByMonthAndCategory()); const comparisonPrev = ref(getComparisonWithPreviousMonth(month.value)); const greenOrRed = (num) => { if (num >= 0) { return 'text-green'; } else { return 'text-red'; } }; const redOrGreen = (num) => { if (num < 0) { return 'text-green'; } else { return 'text-red'; } }; watch(month, () => { comparisonPrev.value = getComparisonWithPreviousMonth(month.value); }); Chart.register(...registerables); const lineChartCanvas = ref(null); let chart = null; const selectTab = (tab) => { selectedTab.value = selectedTab.value === tab ? 'noTab' : tab; }; const getDatasetsArray = () => { const categoryMap = { noTab: { data: [ amountsByMonthAndCategory.value.income, amountsByMonthAndCategory.value.outcome, ], colors: ['#FFCA67', '#CF55EE'], labels: ['수입', '지출 전체'], }, 수입: { data: [amountsByMonthAndCategory.value.income], colors: ['#FFCA67'], labels: ['수입'], }, '지출 전체': { data: [amountsByMonthAndCategory.value.outcome], colors: ['#CF55EE'], labels: ['지출 전체'], }, 식비: { data: [amountsByMonthAndCategory.value.식비], colors: ['#44c4a1'], labels: ['식비'], }, 교통: { data: [amountsByMonthAndCategory.value.교통], colors: ['#ff553e'], labels: ['교통'], }, 문화: { data: [amountsByMonthAndCategory.value.문화], colors: ['#eeae55'], labels: ['문화'], }, 통신: { data: [amountsByMonthAndCategory.value.통신], colors: ['#64798a'], labels: ['통신'], }, 기타: { data: [amountsByMonthAndCategory.value.기타], colors: ['#569ddf'], labels: ['기타'], }, }; const selectedCategory = categoryMap[selectedTab.value]; return selectedCategory.data.map((data, index) => ({ label: selectedCategory.labels[index], data: data, borderColor: selectedCategory.colors[index], backgroundColor: selectedCategory.colors[index], tension: 0.4, fill: false, })); }; watch(selectedTab, () => { createChart(getDatasetsArray()); }); const createChart = (data) => { if (chart) { chart.destroy(); } const ctx = lineChartCanvas.value.getContext('2d'); chart = new Chart(ctx, { type: 'line', data: { labels: ['1월', '2월', '3월', '4월', '5월', '6월'], datasets: data, }, options: { responsive: true, plugins: { legend: { position: 'bottom', display: true, labels: { color: '#727272', boxWidth: 8, boxHeight: 8, padding: 24, font: { family: 'Pretendard', size: 14, weight: 500, }, }, }, title: { display: false, text: '', }, tooltip: { enabled: false, }, datalabels: { display: false, }, }, scales: { x: { ticks: { color: '#727272', font: { family: 'Pretendard', size: 14, weight: 400, }, }, }, y: { beginAtZero: false, ticks: { color: '#727272', font: { family: 'Pretendard', size: 11, weight: 400, }, }, }, }, }, }); }; onMounted(() => { createChart(getDatasetsArray()); }); </script> <style scoped> .chart-frame { background-color: var(--white); height: 320px; padding: 0 5.56%; display: flex; justify-content: center; align-items: center; } .category-container { background-color: var(--white); margin-top: 16px; padding: 16px 5.56%; display: flex; gap: 16px; overflow-x: scroll; align-items: center; } .category-frame { width: 64px; display: flex; flex-direction: column; align-items: center; justify-content: center; cursor: pointer; } .category-icon { width: 60px; height: 60px; border-radius: 100%; background-color: var(--white); display: flex; justify-content: center; align-items: center; overflow: hidden; margin-bottom: 8px; box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.12); } .category-name { font-size: 12px; } .selected-tab-image { filter: brightness(0.88); transform: scale(1.1); transition: transform 0.2s ease; } .selected-tab-text { font-weight: 650; } .divide-bar { width: 1px; height: 56px; margin: 0 2px; border-right: 1px solid var(--gray); } .monthlyinout { margin: 16px 0; background-color: var(--white); padding-bottom: 16px; font-size: 16px; } .june { border-bottom: 1px solid var(--gray); height: 40px; display: flex; align-items: center; padding: 0 4.5% 0 5.56%; justify-content: space-between; } .inout { width: 100%; display: flex; justify-content: space-between; padding: 0 5.56%; margin-top: 16px; } .outout { width: 100%; display: flex; justify-content: space-between; padding: 0 24px; margin-top: 16px; } .times { text-align: right; font-weight: 400; } .total { text-align: right; font-size: 13px; font-weight: 400; } .text-green { color: var(--green); } .text-red { color: var(--red); } .month-select { background-color: transparent; border: 0 none; outline: 0 none; color: var(--black) !important; -webkit-appearance: none; -moz-appearance: none; appearance: none; margin-right: 4px; } .inout-detail { width: 100%; display: flex; justify-content: end; align-items: center; padding: 0 5.56%; margin-top: 16px; color: var(--dark-gray); font-size: 14px; } .detail-container { transition: height 0.8s ease; position: relative; overflow: hidden; } i { color: var(--black); font-size: 14px; } </style>
\documentclass[12pt]{otsreport} % Uncomment the following line to disable hyphenation. %\usepackage[none]{hyphenat} \usepackage{ots} \usepackage{ots-sectioning} \usepackage{amsmath} \usepackage{setspace} % to control TOC spacing % This package gives us \RaggedRight to use in place of \raggedright. % Doing so solves the problem of our big Archetype comparison chart % (which is implement as a longtable) not being ragged-right in cells. % For more details, see section 2.1 on page 351 of Klaus Höppner's % "Typesetting tables with LaTeX" at % https://www.tug.org/TUGboat/tb28-3/tb90hoeppner.pdf. \usepackage{ragged2e} % For coloring individual cells in tables. \usepackage[table]{xcolor} % Define colors used in this document here. latexcolor.com may help. \definecolor{tableheader}{rgb}{0.63, 0.79, 0.95} \definecolor{rowheaderleft}{rgb}{0.6, 0.73, 0.89} \definecolor{plainwhite}{rgb}{1, 1, 1} % Some good blue-y colors Karl found, FWIW: % % Eton blue #96C8A2 {0.59, 0.78, 0.64} % Carolina blue #99BADD {0.6, 0.73, 0.89} % Baby blue eyes #A1CAF1 {0.63, 0.79, 0.95} % % Less sure about these green ones, but they might work together: % % Moss green #ADDFAD {0.68, 0.87, 0.68} % Olivine #9AB973 {0.6, 0.73, 0.45} % Turquoise green #A0D6B4 {0.63, 0.84, 0.71} % Without this, a multiline footnote has its first line (including the % footnote's identifying number) indented by quite a bit inside the % margin, but then subsequent lines start at the margin, which just % looks weird IMHO. With this, the numbers start at the margin, and % all the lines of text line up with each other, indented slightly. % % See https://www.ctan.org/pkg/footmisc?lang=en \usepackage[hang,flushmargin]{footmisc} % This TOC depth causes the table of contents to provide a high-level % overview of the document, instead of distracting the reader with % subsection titles and such. \setcounter{tocdepth}{1} \usepackage{enumerate} \usepackage{enumitem} \ifxetex \usepackage[setpagesize=false, % page size defined by xetex unicode=false, % unicode breaks when used with xetex xetex]{hyperref} \else \usepackage[unicode=true]{hyperref} \fi \hypersetup{breaklinks=true, pdfborder={0 0 0}} \setlength{\parindent}{0pt} \setlength{\parskip}{7pt plus 2pt minus 1pt} \setcounter{secnumdepth}{0} \usepackage[margin=1in]{geometry} \usepackage{changepage} \usepackage{hyperref} \usepackage{mdframed} % For an inset box of text % For logo and accompanying contact info. \usepackage{graphicx} \usepackage{float} \usepackage{color} \definecolor{dkgreen}{RGB}{50, 109, 72} \definecolor{dkergreen}{RGB}{0, 100, 0} \DeclareFixedFont{\viiisf}{OT1}{cmss}{m}{n}{8} \newcommand{\circlesep}{\raisebox{1.7em}{\hspace{1.8em}\includegraphics[clip, trim=0cm 11cm 19.3cm 11cm, scale=0.05]{otslogo.pdf}\hspace{1.8em}}} % Rename the table of contents label \renewcommand*\contentsname{\vspace{-1em}} \begin{document} \otsheader % Must happen after \otsheader so that the header displays correctly. \RaggedRight \begin{center} \LARGE{Open Source Archetypes: \\ A Framework For Purposeful Open Source} \vspace{.5em} \normalsize{\otsurl{https://opentechstrategies.com/archetypes}} \vspace{.5em} \large{Version 2.0} \vspace{1em} \normalsize{28 October 2019} \end{center} % The grouping with the \addtocontents and \addvspace bits below are % to reduce the vertical spacing in the TOC. More information here: % https://tex.stackexchange.com/questions/111243/lyx-reduce-spacing-in-toc \begingroup % \addtocontents{toc}{\protect\setstretch{0.80}} % \def\addvspace#1{} \tableofcontents \endgroup \newpage \input{preface.ltx} \newpage \input{v1-v2.ltx} \newpage \input{introduction.ltx} \input{how-to-use.ltx} \input{goals.ltx} % Start the main section on its own page \newpage \input{arch-intro.ltx} \filbreak \input{arch-b2b.ltx} \filbreak \input{arch-multi-vendor-infra.ltx} \filbreak \input{arch-rocket-ship-to-mars.ltx} \filbreak \input{arch-houseplant.ltx} \filbreak \input{arch-controlled-ecosystem.ltx} \filbreak \input{arch-wide-open.ltx} \filbreak \input{arch-mass-market.ltx} \filbreak \input{arch-specialty-library.ltx} \filbreak \input{arch-trusted-vendor.ltx} \filbreak \input{arch-upstream-dependency.ltx} \filbreak \input{arch-bathwater.ltx} \input{archetypes-chart.ltx} \input{contributor-expectations.ltx} \input{metrics.ltx} \input{ecosystem-mapping.ltx} \input{business-models.ltx} \input{transitions.ltx} \input{choosing-archetype-checklist.ltx} \input{closing.ltx} \newpage % page break before starting the appendices \input{appdx-open-source-licensing-basics.ltx} % Not including these for now. % % \newpage % \input{appdx-worksheet-goals.ltx} % \newpage % \input{appdx-worksheet-ecosystem-map.ltx} % \newpage \input{appdx-openness-work.ltx} \input{copyright.ltx} \end{document}