text
stringlengths
184
4.48M
from django.shortcuts import render,HttpResponseRedirect,HttpResponse from django.contrib import messages from .validators import * from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from user_auth.models import CourseCreatorProfile,CourseUserProfile from home.validators import get_user_type # Create your views here. def sign_up(request): if request.method=="POST": username=request.POST["username"] pass_1=request.POST["pass-1"] pass_2=request.POST["pass-2"] email=request.POST["email"] is_student=request.POST.get("student",None) is_creator=request.POST.get("creator",None) is_password_valid,error_type =validator_password(pass_1,pass_2) #----------------------VALIDATORS------------------------------ #passowrd validation if(not is_password_valid): messages.error(request,error_type) return HttpResponseRedirect('/auth/sign-up/') if(is_student==None and is_creator==None): messages.error(request,"please select any single profession") return HttpResponseRedirect('/auth/sign-up/') if(is_student and is_creator): messages.error(request,"please select any single profession") return HttpResponseRedirect('/auth/sign-up/') # check user allready exist or not if_email_exists=User.objects.filter(email=email) if_username_exists=User.objects.filter(username=username) if((if_username_exists.count()!=0) or (if_email_exists.count()!=0)): messages.error(request,"user Allready exists") return HttpResponseRedirect('/auth/sign-up/') user=User.objects.create(username=username,email=email,password=pass_1) user.save() #creating profile for the user if(is_student): create_profile(user,"student") if(is_creator): create_profile(user,"creator") messages.success(request,"account created successfully !!!") return HttpResponseRedirect('/auth/sign-in/') return render(request,"signup.html") def sign_in(request): # i will create sign in using sesions creation if (request.method=="POST"): username=request.POST["username"] password=request.POST["password"] try: user=User.objects.get(username=username,password=password) if user: login(request,user) print(request.user) return HttpResponseRedirect('/home/') except: messages.error(request,"user does not exists") return HttpResponseRedirect('/auth/sign-up/') return render(request,"signin.html") @login_required(login_url='/auth/sign-in') def log_out(request): logout(request) messages.success(request,"Logged out successfully !!") return HttpResponseRedirect('/auth/sign-in/') def update_profile(request,username): if request.user.username!=username: return HttpResponse("permission denied") #getting the type of user user_type,user_object=get_user_type(request) user_profile=user_object if request.method=="POST": full_name=request.POST["full_name"] college_name=request.POST["college_name"] github_id=request.POST["github_id"] sex=request.POST["sex"] linkedin_id=request.POST["linkedin_id"] if(user_type=="creator"): creator_profile=user_object creator_profile.full_name=full_name or creator_profile.full_name creator_profile.sex=sex or creator_profile.sex creator_profile.github_id=github_id or creator_profile.github_id creator_profile.college_name=college_name or creator_profile.college_name creator_profile.linkedin_id=linkedin_id or creator_profile.linkedin_id creator_profile.save() print("saved") elif(user_type=="student"): student_profile=user_object student_profile.full_name=full_name or student_profile.full_name student_profile.sex=sex or student_profile.sex student_profile.github_id=github_id or student_profile.github_id student_profile.linkedin_id=linkedin_id or student_profile.linkedin_id student_profile.college_name=college_name or student_profile.college_namor student_profile.save() print("saved") return HttpResponseRedirect(f'/auth/{username}/update-profile') context={"user_profile":user_profile,"user_type":user_type} return render(request,"user-profile-settings.html",context) def error_page(request): return render(request,'404.html')
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router"; import guest from '~/middleware/guest'; import auth from '~/middleware/auth'; import { ActionTypes } from "~/store/modules/action-types"; import middlewarePipeline from "~/middleware/middlewarePipeline"; import store from '~/store'; import LocalStorageService from "~/utils/LocalStorageService"; import { EntryPoint, Login, MainPage, Registration, Test, NamazWidgetPage, Gallery, UniqueImagePage } from "~/view"; const routes: Array<RouteRecordRaw> = [ { name: 'gallery', path: '/', component: Gallery }, { name: 'favourite', path: '/favourite', component: Gallery }, { name: 'uniqueImage', path: '/:imageId',component: UniqueImagePage, meta: { middleware: [ guest ], layout: 'MainLayout' } }, // sensitive: true // { // name: 'additionals', path: '/additionals', component: NamazWidgetPage // }, // { // name: 'entry', path: '', // component: EntryPoint, // redirect: '/login', // children: [ // { name: 'registration', path: 'registration', component: Registration, // }, // { name: 'login', path: 'login', component: Login, // } // ] // }, // { // name: 'entry', path: '/entry', component: EntryPoint // }, // { // name: 'test', path: '/test', component: Test, // } // children: [ // { // name: 'bot', path: 'bot', component: BotPage, // meta: { middleware: [ auth ] } // }, // { // name: 'create-bot', path: 'create-bot', component: CreateBotPage, // meta: { // middleware: [ auth ], title: 'Создать Бота', layout: 'MainLayout' // } // }, // { // name: 'error-page', path: 'error-page', component: ErrorPage // } // ] // }, ] const router = createRouter({ history: createWebHistory(), routes, strict: true, }) router.beforeEach(function (to, from, next) { if(!to.meta.middleware) { return next() } const middleware: any = to.meta.middleware ; if(!store.state.initialized){ store.dispatch(ActionTypes.INITIALIZE_APP) } const authToken = LocalStorageService.getToken(); const context = { to, from, next, store, authToken } return middleware[0]({ ...context, next: middlewarePipeline( context, middleware, 1 ) }) }) export default router
--- // Assets Imports - info & Icons import { include } from '../constants/index' import { services } from '../constants/index' import { Home, Pizza, Dumbbell } from 'lucide-react' // Astro Imports - Components import TrainingCard from './TrainingCard.astro' import Header from './layout/Header.astro' // Translation Imports import { getLangFromUrl, useTranslations } from '../i18n/utils' const lang = getLangFromUrl(Astro.url) const t = useTranslations(lang) --- <section class="flex flex-col items-center justify-center gap-10 bg-primary/10 pt-8" id="entrenamientos" > <Header title={t('services-title')} subtitle={t('services-subtitle')} /> <div class="flex max-w-[1680px] flex-col items-center justify-center gap-10 p-10 md:flex-row md:gap-14" > <!-- Services List --> { services.map(({ title, description, image, info, price }) => ( <TrainingCard {title} {description} {image} {info} {price} /> )) } </div> <hr class="h-2 w-2/3" /> <div class="w-full max-w-[1680px] space-y-10 p-10"> <h2 class="text-center text-sm uppercase text-accent md:text-lg"> {t('training-title')} </h2> <div class="flex w-full flex-col items-center justify-center gap-10 md:flex-row" > <!-- Include List --> { include.map(({ title, description }) => { // Function to get an icon with the title function getIcon(training) { switch (training) { case 'A Domicilio': return <Home width="30px" height="30px" /> case 'At Home': return <Home width="30px" height="30px" /> case 'Personalizado': return <Dumbbell width="30px" height="30px" /> case 'Personalized': return <Dumbbell width="30px" height="30px" /> case 'Asesoría Nutricional': return <Pizza width="30px" height="30px" /> case 'Nutritional Counseling': return <Pizza width="30px" height="30px" /> default: return <div /> } } return ( <div class="flex flex-col items-start gap-3"> <div class="flex items-center justify-center gap-3"> {getIcon(title[lang])} <h3 class="text-lg font-bold">{title[lang]}</h3> </div> <p class="text-sm text-muted-foreground">{description[lang]}</p> </div> ) }) } </div> </div> <hr class="h-2 w-full" /> </section>
/********************************************************************* * * Software License Agreement * * Copyright (c) 2023, * TU Dortmund University, Institute of Control Theory and System Engineering * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * Authors: Maximilian Krämer * Maintainer(s)/Modifier(s): Heiko Renz *********************************************************************/ #ifndef UR_COLLISION_H #define UR_COLLISION_H #include <mhp_robot/robot_collision/robot_collision.h> #include <ur_utilities/ur_kinematic/ur_kinematic.h> namespace mhp_robot { namespace robot_collision { class URCollision : public RobotCollision { public: using Ptr = std::shared_ptr<URCollision>; using UPtr = std::unique_ptr<URCollision>; URCollision(); RobotCollision::UPtr createUniqueInstance() const override; RobotCollision::Ptr createSharedInstance() const override; // Robot - Robot bool getSelfCollisionDistances(Eigen::Ref<Eigen::Matrix<double, -1, 1>> d) const override; bool getSelfCollisionDistances(Eigen::Ref<Eigen::Matrix<double, -1, 1>> d, Eigen::Ref<Eigen::Matrix<double, 3, -1>> start_points, Eigen::Ref<Eigen::Matrix<double, 3, -1>> end_points) const override; // Robot - Obstacle bool getObstacleDistances(const robot_misc::Obstacle& obstacle, Eigen::Ref<Eigen::Matrix<double, -1, 1>> d, double t = 0, double t_radius = 0) const override; bool getObstacleDistances(const robot_misc::Obstacle& obstacle, Eigen::Ref<Eigen::Matrix<double, -1, 1>> d, Eigen::Ref<Eigen::Matrix<double, 3, -1>> start_points, Eigen::Ref<Eigen::Matrix<double, 3, -1>> end_points, double t = 0, double t_radius = 0) const override; // Robot - Uncertainty Obstacle bool getUncertaintyObstacleDistances(const robot_misc::Obstacle& obstacle, Eigen::Ref<Eigen::Matrix<double, -1, 1>> d, double t = 0, int iterator = 0) const override; bool getUncertaintyObstacleDistances(const robot_misc::Obstacle& obstacle, Eigen::Ref<Eigen::Matrix<double, -1, 1>> d, Eigen::Ref<Eigen::Matrix<double, 3, -1>> start_points, Eigen::Ref<Eigen::Matrix<double, 3, -1>> end_points, double t = 0, int iterator = 0) const override; // Robot - Plane bool getPlaneCollisionDistances(const robot_misc::Plane& plane, Eigen::Ref<Eigen::Matrix<double, -1, 1>> d) const override; bool getPlaneCollisionDistances(const robot_misc::Plane& plane, Eigen::Ref<Eigen::Matrix<double, -1, 1>> d, Eigen::Ref<Eigen::Matrix<double, 3, -1>> start_points, Eigen::Ref<Eigen::Matrix<double, 3, -1>> end_points) const override; }; } // namespace robot_collision } // namespace mhp_robot #endif // UR_COLLISION_H
## 22. loops `while` ```java while(condition){ // statements } ``` `do-while` ```java do{ // statements }while(condition) ``` The only difference between the while and do-while loop is that do-while loop runs at least once even though the condition is not satisfied. `while` loop evaluates the condition and runs the body while `do-while` runs the body statements and evaluates condition. `for-loop` ```java for(initialization;condition;iteration){ // body } ``` `enhanced for-loop` or `for-each` - available JDK 5 and onwards syntax: `for(type value: collection)` ```java public class Solution{ public static void main(String[] args){ int[] nums = {1,2,3,4,5,6,7,8,9,10}; for(int x: nums){ System.out.println(x); } } } ```
import json import pandas as pd class HostGuestPlanner: """ ReplicationPlanner class for generating chemspeed workflow instructions from screening experiment results. Args: - screening_data (str): Path to the JSON file containing screening experiment results. - predicted_ms (str): Path to the JSON file containing predicted masses of complexes. - import_file (str): Path to the CSV file for importing chemspeed workflow data. Attributes: - screening_data (str): Path to the JSON file containing screening e xperiment results. - predicted_ms (str): Path to the JSON file containing predicted masses of complexes. - df (pd.DataFrame): DataFrame for chemspeed workflow data. """ def __init__(self, replication_data, import_file): self.replication_data = replication_data self.df = pd.read_csv(import_file) def data_loader(self): """Load screening and mass data from specified JSON files.""" with open(f"{self.replication_data}", "r") as f: self.data = json.load(f) def identification_successful_experiments(self): """ Identify experiments selected for replication. Returns: - List[str]: List of experiment IDs selected for replication. """ self.replication_list = [ exp for exp in self.data if self.data[exp]["REPLICATED"] ] return self.replication_list def generate_nmr_dict(self): """ Create a dictionary of NMR experiments containing the nature of the complex being replicated and the type of nmr experiment to be run. Returns: - Dict[int, Dict[str, Any]]: Dictionary with experiment indices and NMR experiment details. """ self.replication_list = self.identification_successful_experiments() nmr_dict = {} counter = 0 for exp in self.replication_list: # might need changing for _ in range(6): counter += 1 nmr_dict[counter] = { "sample_info": {"screening_id": exp}, "solvent": "CH3CN", "nmr_experiments": ["MULTISUPPDC70_f"], } return nmr_dict def update_chemspeed_dataframe(self): """Update chemspeed DataFrame with replication information.""" self.df.loc[self.df["Experiment"] == 1, ["Program"]] = 3 def generate_chemspeed_csv(self, csv_path): """ Generate and save chemspeed CSV file. Args: - csv_path (str): Path to save the generated CSV file. """ self.update_chemspeed_dataframe() self.df.to_csv(csv_path, index=False) def generate(self, csv_path): """ Generate all necessary files for the replication workflow. Args: - csv_path (str): Path to save the generated chemspeed CSV file. - ms_path (str): Path to save the generated MS peaks JSON file. - nmr_path (str): Path to save the generated NMR experiments JSON file. """ self.generate_chemspeed_csv(csv_path)
主旨要求:传输层面(减少请求数,降低请求量)执行层面(减少重绘&回流) 传输层面的从来都是优化的核心点,而这个层面的优化要对浏览器有一个基本的认识,比如: ① 网页自上而下的解析渲染,边解析边渲染,页面内CSS文件会阻塞渲染,异步CSS文件会导致回流 ② 浏览器在document下载结束会检测静态资源,新开线程下载(有并发上限),在带宽限制的条件下,无序并发会导致主资源速度下降,从而影响首屏渲染 ③ 浏览器缓存可用时会使用缓存资源,这个时候可以避免请求体的传输,对性能有极大提高 衡量性能的重要指标为首屏载入速度(指页面可以看见,不一定可交互),影响首屏的最大因素为请求,所以请求是页面真正的杀手,一般来说我们会做这些优化: 减少请求数 ① 合并样式、脚本文件 ② 合并背景图片 ③ CSS3图标、Icon Font 降低请求量 ① 开启GZip ② 优化静态资源,jQuery->Zepto、阉割IScroll、去除冗余代码 ③ 图片无损压缩 ④ 图片延迟加载 ⑤ 减少Cookie携带 采用类似“时间换空间、空间换时间”的做法,比如: ① 缓存为王,对更新较缓慢的资源&接口做缓存(浏览器缓存、localsorage、application cache这个坑多) ② 按需加载,先加载主要资源,其余资源延迟加载,对非首屏资源滚动加载 ③ fake页技术,将页面最初需要显示Html&Css内联,在页面所需资源加载结束前至少可看,理想情况是index.html下载结束即展示(2G 5S内) ④ CDN
package com.aviary.android.feather.widget; import it.sephiroth.android.library.imagezoom.easing.Easing; import it.sephiroth.android.library.imagezoom.easing.Expo; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.RemoteViews.RemoteView; // TODO: Auto-generated Javadoc /** * Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or * content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and * provides various display options such as scaling and tinting. * * @attr ref android.R.styleable#ImageView_adjustViewBounds * @attr ref android.R.styleable#ImageView_src * @attr ref android.R.styleable#ImageView_maxWidth * @attr ref android.R.styleable#ImageView_maxHeight * @attr ref android.R.styleable#ImageView_tint * @attr ref android.R.styleable#ImageView_scaleType * @attr ref android.R.styleable#ImageView_cropToPadding */ @RemoteView public class AdjustImageView extends View { /** The Constant LOG_TAG. */ static final String LOG_TAG = "rotate"; // settable by the client /** The m uri. */ private Uri mUri; /** The m resource. */ private int mResource = 0; /** The m matrix. */ private Matrix mMatrix; /** The m scale type. */ private ScaleType mScaleType; /** The m adjust view bounds. */ private boolean mAdjustViewBounds = false; /** The m max width. */ private int mMaxWidth = Integer.MAX_VALUE; /** The m max height. */ private int mMaxHeight = Integer.MAX_VALUE; // these are applied to the drawable /** The m color filter. */ private ColorFilter mColorFilter; /** The m alpha. */ private int mAlpha = 255; /** The m view alpha scale. */ private int mViewAlphaScale = 256; /** The m color mod. */ private boolean mColorMod = false; /** The m drawable. */ private Drawable mDrawable = null; /** The m state. */ private int[] mState = null; /** The m merge state. */ private boolean mMergeState = false; /** The m level. */ private int mLevel = 0; /** The m drawable width. */ private int mDrawableWidth; /** The m drawable height. */ private int mDrawableHeight; /** The m draw matrix. */ private Matrix mDrawMatrix = null; /** The m rotate matrix. */ private Matrix mRotateMatrix = new Matrix(); /** The m flip matrix. */ private Matrix mFlipMatrix = new Matrix(); // Avoid allocations... /** The m temp src. */ private RectF mTempSrc = new RectF(); /** The m temp dst. */ private RectF mTempDst = new RectF(); /** The m crop to padding. */ private boolean mCropToPadding; /** The m baseline. */ private int mBaseline = -1; /** The m baseline align bottom. */ private boolean mBaselineAlignBottom = false; /** The m have frame. */ private boolean mHaveFrame; /** The m easing. */ private Easing mEasing = new Expo(); /** View is in the reset state. */ boolean isReset = false; /** reset animation time. */ int resetAnimTime = 200; /** * Sets the reset anim duration. * * @param value the new reset anim duration */ public void setResetAnimDuration( int value ) { resetAnimTime = value; } /** * The listener interface for receiving onReset events. * The class that is interested in processing a onReset * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addOnResetListener<code> method. When * the onReset event occurs, that object's appropriate * method is invoked. * * @see OnResetEvent */ public interface OnResetListener { /** * On reset complete. */ void onResetComplete(); } /** The m reset listener. */ private OnResetListener mResetListener; /** * Sets the on reset listener. * * @param listener the new on reset listener */ public void setOnResetListener( OnResetListener listener ) { mResetListener = listener; } /** The Constant sScaleTypeArray. */ @SuppressWarnings("unused") private static final ScaleType[] sScaleTypeArray = { ScaleType.MATRIX, ScaleType.FIT_XY, ScaleType.FIT_START, ScaleType.FIT_CENTER, ScaleType.FIT_END, ScaleType.CENTER, ScaleType.CENTER_CROP, ScaleType.CENTER_INSIDE }; /** * Instantiates a new adjust image view. * * @param context the context */ public AdjustImageView( Context context ) { super( context ); initImageView(); } /** * Instantiates a new adjust image view. * * @param context the context * @param attrs the attrs */ public AdjustImageView( Context context, AttributeSet attrs ) { this( context, attrs, 0 ); } /** * Instantiates a new adjust image view. * * @param context the context * @param attrs the attrs * @param defStyle the def style */ public AdjustImageView( Context context, AttributeSet attrs, int defStyle ) { super( context, attrs, defStyle ); initImageView(); /* * TypedArray a = context.obtainStyledAttributes( attrs, com.android.internal.R.styleable.ImageView, defStyle, 0 ); * * Drawable d = a.getDrawable( com.android.internal.R.styleable.ImageView_src ); if ( d != null ) { setImageDrawable( d ); } * * mBaselineAlignBottom = a.getBoolean( com.android.internal.R.styleable.ImageView_baselineAlignBottom, false ); * * mBaseline = a.getDimensionPixelSize( com.android.internal.R.styleable.ImageView_baseline, -1 ); * * setAdjustViewBounds( a.getBoolean( com.android.internal.R.styleable.ImageView_adjustViewBounds, false ) ); * * setMaxWidth( a.getDimensionPixelSize( com.android.internal.R.styleable.ImageView_maxWidth, Integer.MAX_VALUE ) ); * * setMaxHeight( a.getDimensionPixelSize( com.android.internal.R.styleable.ImageView_maxHeight, Integer.MAX_VALUE ) ); * * int index = a.getInt( com.android.internal.R.styleable.ImageView_scaleType, -1 ); if ( index >= 0 ) { setScaleType( * sScaleTypeArray[index] ); } * * int tint = a.getInt( com.android.internal.R.styleable.ImageView_tint, 0 ); if ( tint != 0 ) { setColorFilter( tint ); } * * int alpha = a.getInt( com.android.internal.R.styleable.ImageView_drawableAlpha, 255 ); if ( alpha != 255 ) { setAlpha( * alpha ); } * * mCropToPadding = a.getBoolean( com.android.internal.R.styleable.ImageView_cropToPadding, false ); * * a.recycle(); */ // need inflate syntax/reader for matrix } /** * Sets the easing. * * @param value the new easing */ public void setEasing( Easing value ) { mEasing = value; } /** * Inits the image view. */ private void initImageView() { mMatrix = new Matrix(); mScaleType = ScaleType.FIT_CENTER; } /* (non-Javadoc) * @see android.view.View#verifyDrawable(android.graphics.drawable.Drawable) */ @Override protected boolean verifyDrawable( Drawable dr ) { return mDrawable == dr || super.verifyDrawable( dr ); } /* (non-Javadoc) * @see android.view.View#invalidateDrawable(android.graphics.drawable.Drawable) */ @Override public void invalidateDrawable( Drawable dr ) { if ( dr == mDrawable ) { /* * we invalidate the whole view in this case because it's very hard to know where the drawable actually is. This is made * complicated because of the offsets and transformations that can be applied. In theory we could get the drawable's bounds * and run them through the transformation and offsets, but this is probably not worth the effort. */ invalidate(); } else { super.invalidateDrawable( dr ); } } /* (non-Javadoc) * @see android.view.View#onSetAlpha(int) */ @Override protected boolean onSetAlpha( int alpha ) { if ( getBackground() == null ) { int scale = alpha + ( alpha >> 7 ); if ( mViewAlphaScale != scale ) { mViewAlphaScale = scale; mColorMod = true; applyColorMod(); } return true; } return false; } /** * Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable. * * @param adjustViewBounds * Whether to adjust the bounds of this view to presrve the original aspect ratio of the drawable * * @attr ref android.R.styleable#ImageView_adjustViewBounds */ public void setAdjustViewBounds( boolean adjustViewBounds ) { mAdjustViewBounds = adjustViewBounds; if ( adjustViewBounds ) { setScaleType( ScaleType.FIT_CENTER ); } } /** * An optional argument to supply a maximum width for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been set * to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT. * * <p> * Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image * to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)} * to determine how to fit the image within the bounds. * </p> * * @param maxWidth * maximum width for this view * * @attr ref android.R.styleable#ImageView_maxWidth */ public void setMaxWidth( int maxWidth ) { mMaxWidth = maxWidth; } /** * An optional argument to supply a maximum height for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been * set to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT. * * <p> * Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image * to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)} * to determine how to fit the image within the bounds. * </p> * * @param maxHeight * maximum height for this view * * @attr ref android.R.styleable#ImageView_maxHeight */ public void setMaxHeight( int maxHeight ) { mMaxHeight = maxHeight; } /** * Return the view's drawable, or null if no drawable has been assigned. * * @return the drawable */ public Drawable getDrawable() { return mDrawable; } /** * Sets a drawable as the content of this ImageView. * * <p class="note"> * This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using * * @param resId the resource identifier of the the drawable * {@link #setImageDrawable(android.graphics.drawable.Drawable)} or {@link #setImageBitmap(android.graphics.Bitmap)} and * {@link android.graphics.BitmapFactory} instead. * </p> * @attr ref android.R.styleable#ImageView_src */ public void setImageResource( int resId ) { if ( mUri != null || mResource != resId ) { updateDrawable( null ); mResource = resId; mUri = null; resolveUri(); requestLayout(); invalidate(); } } /** * Sets the content of this ImageView to the specified Uri. * * <p class="note"> * This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using * * @param uri The Uri of an image * {@link #setImageDrawable(android.graphics.drawable.Drawable)} or {@link #setImageBitmap(android.graphics.Bitmap)} and * {@link android.graphics.BitmapFactory} instead. * </p> */ public void setImageURI( Uri uri ) { if ( mResource != 0 || ( mUri != uri && ( uri == null || mUri == null || !uri.equals( mUri ) ) ) ) { updateDrawable( null ); mResource = 0; mUri = uri; resolveUri(); requestLayout(); invalidate(); } } /** * Sets a drawable as the content of this ImageView. * * @param drawable * The drawable to set */ public void setImageDrawable( Drawable drawable ) { if ( mDrawable != drawable ) { mResource = 0; mUri = null; int oldWidth = mDrawableWidth; int oldHeight = mDrawableHeight; updateDrawable( drawable ); if ( oldWidth != mDrawableWidth || oldHeight != mDrawableHeight ) { requestLayout(); } invalidate(); } } /** * Sets a Bitmap as the content of this ImageView. * * @param bm * The bitmap to set */ public void setImageBitmap( Bitmap bm ) { // if this is used frequently, may handle bitmaps explicitly // to reduce the intermediate drawable object setImageDrawable( new BitmapDrawable( getContext().getResources(), bm ) ); } /** * Sets the image state. * * @param state the state * @param merge the merge */ public void setImageState( int[] state, boolean merge ) { mState = state; mMergeState = merge; if ( mDrawable != null ) { refreshDrawableState(); resizeFromDrawable(); } } /* (non-Javadoc) * @see android.view.View#setSelected(boolean) */ @Override public void setSelected( boolean selected ) { super.setSelected( selected ); resizeFromDrawable(); } /** * Sets the image level, when it is constructed from a {@link android.graphics.drawable.LevelListDrawable}. * * @param level * The new level for the image. */ public void setImageLevel( int level ) { mLevel = level; if ( mDrawable != null ) { mDrawable.setLevel( level ); resizeFromDrawable(); } } /** * Options for scaling the bounds of an image to the bounds of this view. */ public enum ScaleType { /** * Scale using the image matrix when drawing. The image matrix can be set using {@link ImageView#setImageMatrix(Matrix)}. From * XML, use this syntax: <code>android:scaleType="matrix"</code>. */ MATRIX( 0 ), /** * Scale the image using {@link Matrix.ScaleToFit#FILL}. From XML, use this syntax: <code>android:scaleType="fitXY"</code>. */ FIT_XY( 1 ), /** * Scale the image using {@link Matrix.ScaleToFit#START}. From XML, use this syntax: <code>android:scaleType="fitStart"</code> * . */ FIT_START( 2 ), /** * Scale the image using {@link Matrix.ScaleToFit#CENTER}. From XML, use this syntax: * <code>android:scaleType="fitCenter"</code>. */ FIT_CENTER( 3 ), /** * Scale the image using {@link Matrix.ScaleToFit#END}. From XML, use this syntax: <code>android:scaleType="fitEnd"</code>. */ FIT_END( 4 ), /** * Center the image in the view, but perform no scaling. From XML, use this syntax: <code>android:scaleType="center"</code>. */ CENTER( 5 ), /** * Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will * be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view. * From XML, use this syntax: <code>android:scaleType="centerCrop"</code>. */ CENTER_CROP( 6 ), /** * Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will * be equal to or less than the corresponding dimension of the view (minus padding). The image is then centered in the view. * From XML, use this syntax: <code>android:scaleType="centerInside"</code>. */ CENTER_INSIDE( 7 ); /** * Instantiates a new scale type. * * @param ni the ni */ ScaleType( int ni ) { nativeInt = ni; } /** The native int. */ final int nativeInt; } /** * Controls how the image should be resized or moved to match the size of this ImageView. * * @param scaleType * The desired scaling mode. * * @attr ref android.R.styleable#ImageView_scaleType */ public void setScaleType( ScaleType scaleType ) { if ( scaleType == null ) { throw new NullPointerException(); } if ( mScaleType != scaleType ) { mScaleType = scaleType; setWillNotCacheDrawing( mScaleType == ScaleType.CENTER ); requestLayout(); invalidate(); } } /** * Return the current scale type in use by this ImageView. * * @return the scale type * @see ImageView.ScaleType * @attr ref android.R.styleable#ImageView_scaleType */ public ScaleType getScaleType() { return mScaleType; } /** * Return the view's optional matrix. This is applied to the view's drawable when it is drawn. If there is not matrix, this * method will return null. Do not change this matrix in place. If you want a different matrix applied to the drawable, be sure * to call setImageMatrix(). * * @return the image matrix */ public Matrix getImageMatrix() { return mMatrix; } /** * Sets the image matrix. * * @param matrix the new image matrix */ public void setImageMatrix( Matrix matrix ) { // collaps null and identity to just null if ( matrix != null && matrix.isIdentity() ) { matrix = null; } // don't invalidate unless we're actually changing our matrix if ( matrix == null && !mMatrix.isIdentity() || matrix != null && !mMatrix.equals( matrix ) ) { mMatrix.set( matrix ); configureBounds(); invalidate(); } } /** * Resolve uri. */ private void resolveUri() { if ( mDrawable != null ) { return; } Resources rsrc = getResources(); if ( rsrc == null ) { return; } Drawable d = null; if ( mResource != 0 ) { try { d = rsrc.getDrawable( mResource ); } catch ( Exception e ) { Log.w( LOG_TAG, "Unable to find resource: " + mResource, e ); // Don't try again. mUri = null; } } else if ( mUri != null ) { String scheme = mUri.getScheme(); if ( ContentResolver.SCHEME_ANDROID_RESOURCE.equals( scheme ) ) { } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) || ContentResolver.SCHEME_FILE.equals( scheme ) ) { try { d = Drawable.createFromStream( getContext().getContentResolver().openInputStream( mUri ), null ); } catch ( Exception e ) { Log.w( LOG_TAG, "Unable to open content: " + mUri, e ); } } else { d = Drawable.createFromPath( mUri.toString() ); } if ( d == null ) { System.out.println( "resolveUri failed on bad bitmap uri: " + mUri ); // Don't try again. mUri = null; } } else { return; } updateDrawable( d ); } /* (non-Javadoc) * @see android.view.View#onCreateDrawableState(int) */ @Override public int[] onCreateDrawableState( int extraSpace ) { if ( mState == null ) { return super.onCreateDrawableState( extraSpace ); } else if ( !mMergeState ) { return mState; } else { return mergeDrawableStates( super.onCreateDrawableState( extraSpace + mState.length ), mState ); } } /** * Update drawable. * * @param d the d */ private void updateDrawable( Drawable d ) { if ( mDrawable != null ) { mDrawable.setCallback( null ); unscheduleDrawable( mDrawable ); } mDrawable = d; if ( d != null ) { d.setCallback( this ); if ( d.isStateful() ) { d.setState( getDrawableState() ); } d.setLevel( mLevel ); mDrawableWidth = d.getIntrinsicWidth(); mDrawableHeight = d.getIntrinsicHeight(); applyColorMod(); configureBounds(); } else { mDrawableWidth = mDrawableHeight = -1; } } /** * Resize from drawable. */ private void resizeFromDrawable() { Drawable d = mDrawable; if ( d != null ) { int w = d.getIntrinsicWidth(); if ( w < 0 ) w = mDrawableWidth; int h = d.getIntrinsicHeight(); if ( h < 0 ) h = mDrawableHeight; if ( w != mDrawableWidth || h != mDrawableHeight ) { mDrawableWidth = w; mDrawableHeight = h; requestLayout(); } } } /** The Constant sS2FArray. */ private static final Matrix.ScaleToFit[] sS2FArray = { Matrix.ScaleToFit.FILL, Matrix.ScaleToFit.START, Matrix.ScaleToFit.CENTER, Matrix.ScaleToFit.END }; /** * Scale type to scale to fit. * * @param st the st * @return the matrix. scale to fit */ private static Matrix.ScaleToFit scaleTypeToScaleToFit( ScaleType st ) { // ScaleToFit enum to their corresponding Matrix.ScaleToFit values return sS2FArray[st.nativeInt - 1]; } /* (non-Javadoc) * @see android.view.View#onLayout(boolean, int, int, int, int) */ @Override protected void onLayout( boolean changed, int left, int top, int right, int bottom ) { super.onLayout( changed, left, top, right, bottom ); if ( changed ) { mHaveFrame = true; configureBounds(); } } /* (non-Javadoc) * @see android.view.View#onMeasure(int, int) */ @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { resolveUri(); int w; int h; // Desired aspect ratio of the view's contents (not including padding) float desiredAspect = 0.0f; // We are allowed to change the view's width boolean resizeWidth = false; // We are allowed to change the view's height boolean resizeHeight = false; final int widthSpecMode = MeasureSpec.getMode( widthMeasureSpec ); final int heightSpecMode = MeasureSpec.getMode( heightMeasureSpec ); if ( mDrawable == null ) { // If no drawable, its intrinsic size is 0. mDrawableWidth = -1; mDrawableHeight = -1; w = h = 0; } else { w = mDrawableWidth; h = mDrawableHeight; if ( w <= 0 ) w = 1; if ( h <= 0 ) h = 1; // We are supposed to adjust view bounds to match the aspect // ratio of our drawable. See if that is possible. if ( mAdjustViewBounds ) { resizeWidth = widthSpecMode != MeasureSpec.EXACTLY; resizeHeight = heightSpecMode != MeasureSpec.EXACTLY; desiredAspect = (float) w / (float) h; } } int pleft = getPaddingLeft(); int pright = getPaddingRight(); int ptop = getPaddingTop(); int pbottom = getPaddingBottom(); int widthSize; int heightSize; if ( resizeWidth || resizeHeight ) { /* * If we get here, it means we want to resize to match the drawables aspect ratio, and we have the freedom to change at * least one dimension. */ // Get the max possible width given our constraints widthSize = resolveAdjustedSize( w + pleft + pright, mMaxWidth, widthMeasureSpec ); // Get the max possible height given our constraints heightSize = resolveAdjustedSize( h + ptop + pbottom, mMaxHeight, heightMeasureSpec ); if ( desiredAspect != 0.0f ) { // See what our actual aspect ratio is float actualAspect = (float) ( widthSize - pleft - pright ) / ( heightSize - ptop - pbottom ); if ( Math.abs( actualAspect - desiredAspect ) > 0.0000001 ) { boolean done = false; // Try adjusting width to be proportional to height if ( resizeWidth ) { int newWidth = (int) ( desiredAspect * ( heightSize - ptop - pbottom ) ) + pleft + pright; if ( newWidth <= widthSize ) { widthSize = newWidth; done = true; } } // Try adjusting height to be proportional to width if ( !done && resizeHeight ) { int newHeight = (int) ( ( widthSize - pleft - pright ) / desiredAspect ) + ptop + pbottom; if ( newHeight <= heightSize ) { heightSize = newHeight; } } } } } else { /* * We are either don't want to preserve the drawables aspect ratio, or we are not allowed to change view dimensions. Just * measure in the normal way. */ w += pleft + pright; h += ptop + pbottom; w = Math.max( w, getSuggestedMinimumWidth() ); h = Math.max( h, getSuggestedMinimumHeight() ); widthSize = resolveSize( w, widthMeasureSpec ); heightSize = resolveSize( h, heightMeasureSpec ); } setMeasuredDimension( widthSize, heightSize ); } /** * Resolve adjusted size. * * @param desiredSize the desired size * @param maxSize the max size * @param measureSpec the measure spec * @return the int */ private int resolveAdjustedSize( int desiredSize, int maxSize, int measureSpec ) { int result = desiredSize; int specMode = MeasureSpec.getMode( measureSpec ); int specSize = MeasureSpec.getSize( measureSpec ); switch ( specMode ) { case MeasureSpec.UNSPECIFIED: /* * Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves. */ result = Math.min( desiredSize, maxSize ); break; case MeasureSpec.AT_MOST: // Parent says we can be as big as we want, up to specSize. // Don't be larger than specSize, and don't be larger than // the max size imposed on ourselves. result = Math.min( Math.min( desiredSize, specSize ), maxSize ); break; case MeasureSpec.EXACTLY: // No choice. Do what we are told. result = specSize; break; } return result; } /** * Configure bounds. */ private void configureBounds() { if ( mDrawable == null || !mHaveFrame ) { return; } int dwidth = mDrawableWidth; int dheight = mDrawableHeight; int vwidth = getWidth() - getPaddingLeft() - getPaddingRight(); int vheight = getHeight() - getPaddingTop() - getPaddingBottom(); boolean fits = ( dwidth < 0 || vwidth == dwidth ) && ( dheight < 0 || vheight == dheight ); if ( dwidth <= 0 || dheight <= 0 || ScaleType.FIT_XY == mScaleType ) { /* * If the drawable has no intrinsic size, or we're told to scaletofit, then we just fill our entire view. */ mDrawable.setBounds( 0, 0, vwidth, vheight ); mDrawMatrix = null; } else { // We need to do the scaling ourself, so have the drawable // use its native size. mDrawable.setBounds( 0, 0, dwidth, dheight ); if ( ScaleType.MATRIX == mScaleType ) { // Use the specified matrix as-is. if ( mMatrix.isIdentity() ) { mDrawMatrix = null; } else { mDrawMatrix = mMatrix; } } else if ( fits ) { // The bitmap fits exactly, no transform needed. mDrawMatrix = null; } else if ( ScaleType.CENTER == mScaleType ) { // Center bitmap in view, no scaling. mDrawMatrix = mMatrix; mDrawMatrix.setTranslate( (int) ( ( vwidth - dwidth ) * 0.5f + 0.5f ), (int) ( ( vheight - dheight ) * 0.5f + 0.5f ) ); } else if ( ScaleType.CENTER_CROP == mScaleType ) { mDrawMatrix = mMatrix; float scale; float dx = 0, dy = 0; if ( dwidth * vheight > vwidth * dheight ) { scale = (float) vheight / (float) dheight; dx = ( vwidth - dwidth * scale ) * 0.5f; } else { scale = (float) vwidth / (float) dwidth; dy = ( vheight - dheight * scale ) * 0.5f; } mDrawMatrix.setScale( scale, scale ); mDrawMatrix.postTranslate( (int) ( dx + 0.5f ), (int) ( dy + 0.5f ) ); } else if ( ScaleType.CENTER_INSIDE == mScaleType ) { mDrawMatrix = mMatrix; float scale; float dx; float dy; if ( dwidth <= vwidth && dheight <= vheight ) { scale = 1.0f; } else { scale = Math.min( (float) vwidth / (float) dwidth, (float) vheight / (float) dheight ); } dx = (int) ( ( vwidth - dwidth * scale ) * 0.5f + 0.5f ); dy = (int) ( ( vheight - dheight * scale ) * 0.5f + 0.5f ); mDrawMatrix.setScale( scale, scale ); mDrawMatrix.postTranslate( dx, dy ); } else { // Generate the required transform. mTempSrc.set( 0, 0, dwidth, dheight ); mTempDst.set( 0, 0, vwidth, vheight ); mDrawMatrix = mMatrix; mDrawMatrix.setRectToRect( mTempSrc, mTempDst, scaleTypeToScaleToFit( mScaleType ) ); mCurrentScale = getMatrixScale( mDrawMatrix )[0]; Matrix tempMatrix = new Matrix( mMatrix ); RectF src = new RectF(); RectF dst = new RectF(); src.set( 0, 0, dheight, dwidth ); dst.set( 0, 0, vwidth, vheight ); tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) ); mVerticalScale = getValue( tempMatrix, Matrix.MSCALE_X ); Log.d( LOG_TAG, "current scale: " + mCurrentScale ); Log.d( LOG_TAG, "vertical scale: " + mVerticalScale ); tempMatrix = new Matrix( mDrawMatrix ); tempMatrix.invert( tempMatrix ); float invertScale = getMatrixScale( tempMatrix )[0]; Log.d( LOG_TAG, "inverted scale: " + invertScale ); Log.d( LOG_TAG, "diff: " + ( invertScale - mCurrentScale ) ); mDrawMatrix.postScale( invertScale, invertScale, vwidth / 2, vheight / 2 ); mRotateMatrix.postScale( mCurrentScale, mCurrentScale, vwidth / 2, vheight / 2 ); Log.d( LOG_TAG, "now matrix scale: " + getMatrixScale( mDrawMatrix )[0] ); } } } /* (non-Javadoc) * @see android.view.View#drawableStateChanged() */ @Override protected void drawableStateChanged() { super.drawableStateChanged(); Drawable d = mDrawable; if ( d != null && d.isStateful() ) { d.setState( getDrawableState() ); } } /* (non-Javadoc) * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override protected void onDraw( Canvas canvas ) { super.onDraw( canvas ); if ( mDrawable == null ) { return; // couldn't resolve the URI } if ( mDrawableWidth == 0 || mDrawableHeight == 0 ) { return; // nothing to draw (empty bounds) } final int mPaddingTop = getPaddingTop(); final int mPaddingLeft = getPaddingLeft(); final int mPaddingBottom = getPaddingBottom(); final int mPaddingRight = getPaddingRight(); if ( mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0 ) { mDrawable.draw( canvas ); } else { int saveCount = canvas.getSaveCount(); canvas.save(); if ( mCropToPadding ) { final int scrollX = getScrollX(); final int scrollY = getScrollY(); canvas.clipRect( scrollX + mPaddingLeft, scrollY + mPaddingTop, scrollX + getRight() - getLeft() - mPaddingRight, scrollY + getBottom() - getTop() - mPaddingBottom ); } canvas.translate( mPaddingLeft, mPaddingTop ); if ( mFlipMatrix != null ) { canvas.concat( mFlipMatrix ); } if ( mRotateMatrix != null ) { canvas.concat( mRotateMatrix ); } if ( mDrawMatrix != null ) { canvas.concat( mDrawMatrix ); } mDrawable.draw( canvas ); canvas.restoreToCount( saveCount ); } } /** * <p> * Return the offset of the widget's text baseline from the widget's top boundary. * </p> * * @return the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported. */ @Override public int getBaseline() { if ( mBaselineAlignBottom ) { return getMeasuredHeight(); } else { return mBaseline; } } /** * <p> * Set the offset of the widget's text baseline from the widget's top boundary. This value is overridden by the * * @param baseline The baseline to use, or -1 if none is to be provided. * {@link #setBaselineAlignBottom(boolean)} property. * </p> * @see #setBaseline(int) * @attr ref android.R.styleable#ImageView_baseline */ public void setBaseline( int baseline ) { if ( mBaseline != baseline ) { mBaseline = baseline; requestLayout(); } } /** * Set whether to set the baseline of this view to the bottom of the view. Setting this value overrides any calls to setBaseline. * * @param aligned * If true, the image view will be baseline aligned with based on its bottom edge. * * @attr ref android.R.styleable#ImageView_baselineAlignBottom */ public void setBaselineAlignBottom( boolean aligned ) { if ( mBaselineAlignBottom != aligned ) { mBaselineAlignBottom = aligned; requestLayout(); } } /** * Return whether this view's baseline will be considered the bottom of the view. * * @return the baseline align bottom * @see #setBaselineAlignBottom(boolean) */ public boolean getBaselineAlignBottom() { return mBaselineAlignBottom; } /** * Set a tinting option for the image. * * @param color * Color tint to apply. * @param mode * How to apply the color. The standard mode is {@link PorterDuff.Mode#SRC_ATOP} * * @attr ref android.R.styleable#ImageView_tint */ public final void setColorFilter( int color, PorterDuff.Mode mode ) { setColorFilter( new PorterDuffColorFilter( color, mode ) ); } /** * Set a tinting option for the image. Assumes {@link PorterDuff.Mode#SRC_ATOP} blending mode. * * @param color * Color tint to apply. * @attr ref android.R.styleable#ImageView_tint */ public final void setColorFilter( int color ) { setColorFilter( color, PorterDuff.Mode.SRC_ATOP ); } /** * Clear color filter. */ public final void clearColorFilter() { setColorFilter( null ); } /** * Apply an arbitrary colorfilter to the image. * * @param cf * the colorfilter to apply (may be null) */ public void setColorFilter( ColorFilter cf ) { if ( mColorFilter != cf ) { mColorFilter = cf; mColorMod = true; applyColorMod(); invalidate(); } } /** * Sets the alpha. * * @param alpha the new alpha */ public void setAlpha( int alpha ) { alpha &= 0xFF; // keep it legal if ( mAlpha != alpha ) { mAlpha = alpha; mColorMod = true; applyColorMod(); invalidate(); } } /** * Apply color mod. */ private void applyColorMod() { // Only mutate and apply when modifications have occurred. This should // not reset the mColorMod flag, since these filters need to be // re-applied if the Drawable is changed. if ( mDrawable != null && mColorMod ) { mDrawable = mDrawable.mutate(); mDrawable.setColorFilter( mColorFilter ); mDrawable.setAlpha( mAlpha * mViewAlphaScale >> 8 ); } } /** The m handler. */ protected Handler mHandler = new Handler(); /** The m rotation. */ protected int mRotation = 0; /** The m current scale. */ protected float mCurrentScale = 0; /** The m vertical scale. */ protected float mVerticalScale = 0; /** The m running. */ protected boolean mRunning = false; /** * Rotate90. * * @param cw the cw * @param durationMs the duration ms */ public void rotate90( boolean cw, int durationMs ) { rotateTo( cw, durationMs ); } /** * Rotate to. * * @param cw the cw * @param durationMs the duration ms */ protected void rotateTo( final boolean cw, final int durationMs ) { if ( mRunning ) { return; } mRunning = true; final float destRotation = mRotation + 90; Log.i( LOG_TAG, "rotateCW > " + destRotation ); final long startTime = System.currentTimeMillis(); final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight(); final int vheight = getHeight() - getPaddingTop() - getPaddingBottom(); final int centerX = vwidth / 2; final int centerY = vheight / 2; Log.d( LOG_TAG, "currentScale: " + mCurrentScale ); Log.d( LOG_TAG, "destScale: " + mVerticalScale ); mRotateMatrix.setRotate( mRotation, centerX, centerY ); mRotateMatrix.setScale( mCurrentScale, mCurrentScale, centerX, centerY ); mHandler.post( new Runnable() { @SuppressWarnings("unused") float old_scale = 0; @SuppressWarnings("unused") float old_rotation = 0; @Override public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min( durationMs, now - startTime ); float new_rotation = (float) mEasing.easeInOut( currentMs, 0, cw ? 90 : -90, durationMs ); float new_scale = (float) mEasing.easeInOut( currentMs, 0, ( mVerticalScale - mCurrentScale ), durationMs ); mRotateMatrix.setScale( mCurrentScale + new_scale, mCurrentScale + new_scale, centerX, centerY ); mRotateMatrix.postRotate( mRotation + new_rotation, vwidth / 2, vheight / 2 ); old_scale = new_scale; old_rotation = new_rotation; invalidate(); if ( currentMs < durationMs ) { mHandler.post( this ); } else { mRotation += cw ? 90 : -90; mRotation = mRotation % 360; if ( mRotation < 0 ) mRotation = 360 + mRotation; float t = mVerticalScale; mVerticalScale = mCurrentScale; mCurrentScale = t; mRotateMatrix.setRotate( mRotation, centerX, centerY ); mRotateMatrix.postScale( mCurrentScale, mCurrentScale, centerX, centerY ); invalidate(); printDetails(); mRunning = false; if ( isReset ) { onReset(); } } } } ); } /** * Prints the details. */ public void printDetails() { Log.i( LOG_TAG, "details:" ); Log.d( LOG_TAG, " flip horizontal: " + ( ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt ) ); Log.d( LOG_TAG, " flip vertical: " + ( ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt ) ); Log.d( LOG_TAG, " rotation: " + mRotation ); Log.d( LOG_TAG, "--------" ); } /** * Flip. * * @param horizontal the horizontal * @param durationMs the duration ms */ public void flip( boolean horizontal, int durationMs ) { flipTo( horizontal, durationMs ); } /** The m camera enabled. */ private boolean mCameraEnabled; /** * Sets the camera enabled. * * @param value the new camera enabled */ public void setCameraEnabled( final boolean value ) { if ( android.os.Build.VERSION.SDK_INT >= 14 && value ) mCameraEnabled = value; else mCameraEnabled = false; } /** * Flip to. * * @param horizontal the horizontal * @param durationMs the duration ms */ protected void flipTo( final boolean horizontal, final int durationMs ) { if ( mRunning ) { return; } mRunning = true; final long startTime = System.currentTimeMillis(); final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight(); final int vheight = getHeight() - getPaddingTop() - getPaddingBottom(); final float centerx = vwidth / 2; final float centery = vheight / 2; final Camera camera = new Camera(); mHandler.post( new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); double currentMs = Math.min( durationMs, now - startTime ); if ( mCameraEnabled ) { float degrees = (float) ( 0 + ( ( -180 - 0 ) * ( currentMs / durationMs ) ) ); camera.save(); if ( horizontal ) { camera.rotateY( degrees ); } else { camera.rotateX( degrees ); } camera.getMatrix( mFlipMatrix ); camera.restore(); mFlipMatrix.preTranslate( -centerx, -centery ); mFlipMatrix.postTranslate( centerx, centery ); } else { double new_scale = mEasing.easeInOut( currentMs, 1, -2, durationMs ); if ( horizontal ) mFlipMatrix.setScale( (float) new_scale, 1, centerx, centery ); else mFlipMatrix.setScale( 1, (float) new_scale, centerx, centery ); } invalidate(); if ( currentMs < durationMs ) { mHandler.post( this ); } else { boolean isRotate = mRotation % 180 == 90; if ( horizontal ) { mFlipType ^= isRotate ? FlipType.FLIP_VERTICAL.nativeInt : FlipType.FLIP_HORIZONTAL.nativeInt; if ( mRotation % 180 == 0 ) mDrawMatrix.postScale( -1, 1, centerx, centery ); else mDrawMatrix.postScale( 1, -1, centerx, centery ); } else { mFlipType ^= isRotate ? FlipType.FLIP_HORIZONTAL.nativeInt : FlipType.FLIP_VERTICAL.nativeInt; if ( mRotation % 180 == 0 ) mDrawMatrix.postScale( 1, -1, centerx, centery ); else mDrawMatrix.postScale( -1, 1, centerx, centery ); } mFlipMatrix.reset(); invalidate(); printDetails(); mRunning = false; if ( isReset ) { onReset(); } } } } ); } /** The m matrix values. */ protected final float[] mMatrixValues = new float[9]; /** * Gets the value. * * @param matrix the matrix * @param whichValue the which value * @return the value */ protected float getValue( Matrix matrix, int whichValue ) { matrix.getValues( mMatrixValues ); return mMatrixValues[whichValue]; } /** * Gets the matrix scale. * * @param matrix the matrix * @return the matrix scale */ protected float[] getMatrixScale( Matrix matrix ) { float[] result = new float[2]; result[0] = getValue( matrix, Matrix.MSCALE_X ); result[1] = getValue( matrix, Matrix.MSCALE_Y ); return result; } /** The m flip type. */ protected int mFlipType = FlipType.FLIP_NONE.nativeInt; /** * The Enum FlipType. */ public enum FlipType { /** The FLI p_ none. */ FLIP_NONE( 1 << 0 ), /** The FLI p_ horizontal. */ FLIP_HORIZONTAL( 1 << 1 ), /** The FLI p_ vertical. */ FLIP_VERTICAL( 1 << 2 ); /** * Instantiates a new flip type. * * @param ni the ni */ FlipType( int ni ) { nativeInt = ni; } /** The native int. */ public final int nativeInt; } /* (non-Javadoc) * @see android.view.View#getRotation() */ public float getRotation() { return mRotation; } /** * Gets the horizontal flip. * * @return the horizontal flip */ public boolean getHorizontalFlip() { if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) { if ( mRotation % 180 == 90 ) { return ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt; } else { return ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt; } } return false; } /** * Gets the vertical flip. * * @return the vertical flip */ public boolean getVerticalFlip() { if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) { if ( mRotation % 180 == 90 ) { return ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt; } else { return ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt; } } return false; } /** * Gets the flip type. * * @return the flip type */ public int getFlipType() { return mFlipType; } /** * Checks if is running. * * @return true, if is running */ public boolean isRunning() { return mRunning; } /** * Reset the image to the original state. */ public void reset() { Log.i( LOG_TAG, "reset" ); isReset = true; onReset(); } /** * On reset. */ private void onReset() { if ( isReset ) { Log.d( LOG_TAG, "onReset. rotation: " + mRotation + ", hflip: " + getHorizontalFlip() + ", vflip: " + getVerticalFlip() ); final boolean hflip = getHorizontalFlip(); final boolean vflip = getVerticalFlip(); boolean handled = false; switch ( mRotation ) { case 0: if ( hflip ) { flip( true, resetAnimTime ); handled = true; } else if ( vflip ) { flip( false, resetAnimTime ); handled = true; } break; case 90: rotate90( false, resetAnimTime ); handled = true; break; case 180: if ( hflip && vflip ) { handled = false; } else { if ( !hflip && !vflip ) { flip( false, resetAnimTime ); handled = true; } else if ( vflip ) { flip( true, resetAnimTime ); handled = true; } else if ( hflip ) { flip( false, resetAnimTime ); handled = true; } } break; case 270: rotate90( true, resetAnimTime ); handled = true; break; } if ( !handled ) { fireOnResetComplete(); } } } /** * Fire on reset complete. */ private void fireOnResetComplete() { Log.w( LOG_TAG, "onResetComplete" ); if ( mResetListener != null ) { mResetListener.onResetComplete(); } } }
describe('Post Moderation Tests', () => { beforeEach(() => { // Seed the database before each test cy.exec("node ../server/init.js"); }); afterEach(() => { // Clear the database after each test cy.exec("node ../server/destroy.js"); }); it('Show error page for non-admin user', () => { cy.visit('http://localhost:3000'); cy.contains('Login').click(); cy.get('#loginEmailInput').type('john@email.com'); cy.get('#loginPasswordInput').type('WXYZ123'); cy.get('#loginButton').click(); cy.contains('All Questions'); // should take you to home page cy.get("#postModerationButton").click(); cy.contains('Oops!'); // Error message on screen if non-admin user logged in }) it('Show flagged content for admin user', () => { cy.visit('http://localhost:3000'); cy.contains('Login').click(); cy.get('#loginEmailInput').type('sammy@email.com'); cy.get('#loginPasswordInput').type('GHJK543'); cy.get('#loginButton').click(); cy.contains('All Questions'); // should take you to home page cy.get("#postModerationButton").click(); cy.contains('Flagged Questions'); // If admin user logged in, flagged content will be shown to review cy.contains('Flagged Answers'); }) it('Shows the reset and delete buttons', () => { cy.visit('http://localhost:3000'); cy.contains('Login').click(); cy.get('#loginEmailInput').type('sammy@email.com'); cy.get('#loginPasswordInput').type('GHJK543'); cy.get('#loginButton').click(); cy.contains('All Questions'); // should take you to home page cy.get("#postModerationButton").click(); cy.contains("Reset"); cy.contains("Delete"); }) it('Resets answer vote count to 0 if reset button clicked', () => { cy.visit('http://localhost:3000'); cy.contains('Login').click(); cy.get('#loginEmailInput').type('sammy@email.com'); cy.get('#loginPasswordInput').type('GHJK543'); cy.get('#loginButton').click(); cy.contains('All Questions'); // should take you to home page cy.get("#postModerationButton").click(); cy.contains("Best pizza in Boston?"); cy.contains("-16 votes"); cy.get("#resetBtnQ").click(); // if you click the reset button, question removed from flagged content (reverses flag, sets vote count to 0) cy.contains("No flagged questions to review"); cy.get("#menu_question").click(); cy.contains("All Questions"); cy.contains("Best pizza in Boston?").click(); cy.contains('0'); // vote count reset to 0 to reverse flag }) it("Deletes answer from database and decrements answer count on question", () => { cy.visit('http://localhost:3000'); cy.contains('Login').click(); cy.get('#loginEmailInput').type('sammy@email.com'); cy.get('#loginPasswordInput').type('GHJK543'); cy.get('#loginButton').click(); cy.contains('All Questions'); // should take you to home page cy.contains("Quick question about storage on android").click(); cy.contains("2 answers"); // before question deleted cy.get("#postModerationButton").click(); cy.contains("Blah blah blah blah blah"); cy.contains("-15 votes"); cy.get("#deleteBtnA").click(); // if you click the delete button, answer removed from DB cy.contains("No flagged answers to review"); cy.get("#menu_question").click(); cy.contains("Quick question about storage on android").click(); cy.contains("1 answers"); // question deleted }) })
import React from 'react' import { screen, fireEvent } from '@testing-library/react' import { render } from '@/utils/helpers/testUtils' import '@testing-library/jest-dom' import ToastMessage, { ToastMessageProps } from '.' import theme from '@/styles/lightTheme' const mockOnRemoveMessage = jest.fn() const mockMessage: ToastMessageProps['message'] = { id: 1, text: 'Test Message', type: 'default', duration: 5000 } const setup = (message: ToastMessageProps['message'] = mockMessage) => { return render( <ToastMessage onRemoveMessage={mockOnRemoveMessage} message={message} /> ) } describe('ToastMessage', () => { afterEach(() => { jest.clearAllMocks() }) it('renders ToastMessage correctly', () => { setup() expect(screen.getByRole('button')).toBeInTheDocument() expect(screen.getByText('Test Message')).toBeInTheDocument() }) it('calls onRemoveMessage when clicked', () => { setup() fireEvent.click(screen.getByRole('button')) expect(mockOnRemoveMessage).toHaveBeenCalledWith(1) }) it('should render default styles', () => { const { container } = setup() expect(container.firstChild).toHaveStyle(` color: #fff; box-shadow: 0 2rem 2rem -1.6rem rgba(0, 0, 0, 0.25); background: ${theme.colors.primary.main}; padding: ${theme.spacings.xsmall} ${theme.spacings.medium}; border-radius: ${theme.border.radius}; display: flex; align-items: center; justify-content: center; cursor: pointer; `) }) it('should render warning styles', () => { const { container } = setup({ ...mockMessage, type: 'warning' }) expect(container.firstChild).toHaveStyle(` background: ${theme.colors.warning.main}; `) }) it('should render sucess styles', () => { const { container } = setup({ ...mockMessage, type: 'success' }) expect(container.firstChild).toHaveStyle(` background: ${theme.colors.success.main}; `) }) it('should render danger styles', () => { const { container } = setup({ ...mockMessage, type: 'danger' }) expect(container.firstChild).toHaveStyle(` background: ${theme.colors.danger.main}; `) }) })
import jwt from "jsonwebtoken"; import bcrypt from "bcrypt"; import User from "../models/users.js"; export const registerUser = async (req, res) => { const { email, password } = req.body; try { // Check if the user already exists const existingUser = await User.findOne({ email }); if (existingUser) { return res.status(400).json({ error: "User already exists" }); } // Hash the password const hashedPassword = await bcrypt.hash(password, 10); // Create a new user with the hashed password const newUser = new User({ email, password: hashedPassword }); // Save the user to the database await newUser.save(); // Return the token return res.status(201).json({ message: "User created successfully!" }); } catch (error) { console.error(error); return res.status(500).json({ error: "Something went wrong" }); } }; export const loginUser = async (req, res) => { const { email, password } = req.body; try { // Check if the user exists const user = await User.findOne({ email }); if (!user) { return res.status(401).json({ error: "Invalid credentials" }); } const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(401).json({ error: "Invalid credentials" }); } // Generate a token const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" }); // Return the token return res.json({ token }); } catch (error) { console.error(error); return res.status(500).json({ error: "Something went wrong" }); } };
#BUTTONS /** * This is an example component. Extend inuitcss by building your own components * that make up your UI. Component classes are prefixed with a `c-`. */ /** * 1. Allow us to style box model properties. * 2. Line different sized buttons up a little nicer. * 3. Make buttons inherit font styles (often necessary when styling `input`s as * buttons). * 4. Reset/normalize some styles. * 5. Force all button-styled elements to appear clickable. */ .o-btn { height:55px; display: inline-block; /* [1] */ vertical-align: middle; /* [2] */ font: inherit; /* [3] */ text-align: center; /* [4] */ margin: 0; /* [4] */ cursor: pointer; /* [5] */ padding: $inuit-global-spacing-unit-small $inuit-global-spacing-unit; transition: $global-transition; border-radius: $global-radius; border:0; text-decoration:none; color:#fff; line-height: 32px; ////// ???? } /* Style variants .o-btn--primary { background-color: $red; &, &:hover, &:active{ //text-transform:uppercase; } &:hover{ background-color: darken($red, 10%); } } .o-btn--secondary { background-color: $mid; &, &:hover, &:active{ //text-transform:uppercase; } &:hover{ background-color: darken($mid, 10%); } } .o-btn--tertiary { background-color: $dark; &, &:hover, &:active{ //text-transform:uppercase; } &:hover{ background-color: darken($dark, 10%); } } .o-btn--blue { background-color: $blue; &, &:hover, &:active{ //text-transform:uppercase; } &:hover{ background-color: darken($blue, 10%); } } /* Size variants .o-btn--small { height:auto; padding: inuit-rem($inuit-global-spacing-unit-tiny) inuit-rem($inuit-global-spacing-unit-small); line-height:1.5em; } .o-btn--large { height:auto; padding: inuit-rem($inuit-global-spacing-unit) inuit-rem($inuit-global-spacing-unit-large); } /* Other variants .o-btn--white-text { color:#fff; } .o-btn--disabled { color:rgba(255,255,255,.5); cursor:not-allowed; &.o-btn--primary { background-color: lighten($red,10%); } &.o-btn--secondary { background-color: lighten($mid,10%); } &.o-btn--tertiary { background-color: lighten($dark,10%); } &:hover,&:focus { } } .o-btn--iconLeft { .icon { margin-top:-4px; margin-right:7px; vertical-align:middle; } } .o-btn--iconRight { .icon { margin-left:3px; vertical-align:middle; } } .o-btn--outline { border:1px solid; &.o-btn--primary { border-color: lighten($red,10%); } &.o-btn--secondary { border-color: lighten($mid,10%); } &.o-btn--tertiary { border-color: lighten($dark,10%); } } .o-btn--icon { padding-right:.5rem; padding-left:.5rem; } .o-btn--straight { border-radius:0; } @-webkit-keyframes pulse { 0% { background-color: lighten($red,10%); } 50% { background-color: $red; box-shadow:0px 0px 10px $red; } 100% { background-color: lighten($red,10%); } } @keyframes pulse { 0% { background-color: lighten($red,10%); } 50% { background-color: $red; box-shadow:0px 0px 10px $red; } 100% { background-color: lighten($red,10%); } } .o-btn--pulse { -webkit-animation: pulse 2s infinite; animation: pulse 2s infinite; } /* Ghost buttons /** * Ghost buttons have see-through backgrounds and are bordered. */ $btn-ghost-border-width: 2px; .o-btn--ghost { border: $btn-ghost-border-width solid #fff; //padding: ($inuit-global-spacing-unit-small - $btn-ghost-border-width) ($inuit-global-spacing-unit - $btn-ghost-border-width); line-height:1.6; &, &:hover, &:active { background: none; } &:hover { background: #fff; color:$dark; } &.o-btn--small { padding: ($inuit-global-spacing-unit-tiny - $btn-ghost-border-width) ($inuit-global-spacing-unit-small - $btn-ghost-border-width); } &.o-btn--large { padding: ($inuit-global-spacing-unit - $btn-ghost-border-width) ($inuit-global-spacing-unit-large - $btn-ghost-border-width); } &.o-btn--primary { color: #4a8ec2; &:hover{ color: #3774a2; } } &.o-btn--secondary { border-color:#2f4054; color: #2f4054; &:hover { border-color:#fff; color: #1d2733; } } &.o-btn--tertiary { color: #fff; &:hover{ color: #fff; } } }
package com.bobking.leetcode.training; import java.util.ArrayList; import java.util.List; public class Number51 { List<List<String>> res = new ArrayList<List<String>>(); // 参考:https://leetcode-cn.com/problems/n-queens/solution/hui-su-suan-fa-xiang-jie-by-labuladong/ public List<List<String>> solveNQueens(int n) { if (n < 1) return res; List<StringBuilder> track = new ArrayList<StringBuilder>(); for (int i = 0; i < n; i++) { StringBuilder str = new StringBuilder(); for (int j = 0; j < n; j++) str.append("."); track.add(str); } brackTrace(track, 0); return res; } // 按行递归 private void brackTrace(List<StringBuilder> track, int row) { if (row == track.size()) { List<String> list = new ArrayList<String>(); for (StringBuilder sb : track) list.add(sb.toString()); res.add(list); return; } // 即把当前行的每一列都尝试一遍 for (int col = 0; col < track.get(row).length(); col++) { if (!isValid(track, row, col)) continue; track.get(row).setCharAt(col, 'Q'); brackTrace(track, row + 1); // 回溯 track.get(row).setCharAt(col, '.'); } } private boolean isValid(List<StringBuilder> track, int row, int col) { // 不可能会有行冲突,因为是按行递归的 // 检查列是否有冲突 for (int i = 0; i < track.size(); i++) { if (track.get(i).charAt(col) == 'Q') return false; } // 检查右上方是否有冲突 for (int i = row - 1, j = col + 1; i >= 0 && j < track.size(); i--, j++) { if (track.get(i).charAt(j) == 'Q') return false; } // 检查左上方是否有冲突 for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (track.get(i).charAt(j) == 'Q') return false; } return true; } }
import { HttpCode, HttpStatus, Injectable, NotFoundException, BadRequestException, } from '@nestjs/common'; import { Track } from './track.interface'; const BASE_URL = 'http://localhost:3030/tracks/'; @Injectable() export class TrackService { async getTracks(): Promise<Track[]> { const res = await fetch(BASE_URL); const parsed = await res.json(); return parsed; } async getTrackByArtist(artist: string): Promise<any> { const res = await fetch(BASE_URL); if (!res.ok) throw new BadRequestException(); const allTracks = await res.json(); const track = allTracks.filter((track: Track) => track.artist.toLocaleLowerCase().includes(artist.toLocaleLowerCase()), ); console.log(track); if (!track.length) throw new NotFoundException(`Ninguna pista de ${artist}.`); return track; } async getTrackById(id: number): Promise<Track> { const res = await fetch(BASE_URL + id); const parsed = await res.json(); //track existe: lo retornamos al controller if (Object.keys(parsed).length) return parsed; //track no existe: lanzamos una excepción al controller throw new NotFoundException(`Track con id ${id} no existe`); } async createTrack(track: Track) { const id = await this.setId(); const newTrack = { ...track, id }; await fetch(BASE_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(newTrack), }); } async deleteTrackById(id: number): Promise<any> { const res = await fetch(BASE_URL + id, { method: 'DELETE', }); const parsed = await res.json(); return parsed; } async updateTrackById(id: number, body: Track): Promise<void> { const isTrack = await this.getTrackById(id); if (!Object.keys(isTrack).length) return; //early return const updatedTrack = { ...body, id }; await fetch(BASE_URL + id, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(updatedTrack), }); } private async setId(): Promise<number> { const tracks = await this.getTracks(); const id = tracks.pop().id + 1; return id; } }
/// <summary> /// Declarations and inline definitions for ReactionAttributed. /// </summary> #pragma once #include "Reaction.h" #include "EventMessageAttributed.h" namespace FIEAGameEngine { class ReactionAttributed : public Reaction { RTTI_DECLARATIONS(ReactionAttributed, Reaction); public: /// <summary> /// The constructor for a ReactionAttributed /// </summary> /// <param name="name">The name of this ReactioAttributed</param> ReactionAttributed(const std::string& name = "", std::string subtype = ""); /// <summary> /// A copy constructor for a ReactionAttributed that performs a deep copy during construction. /// </summary> /// <param name="other">The ReactionAttributed to copy</param> ReactionAttributed(const ReactionAttributed& rhs) = default; /// <summary> /// The move constructor for ReactionAttributed. /// </summary> /// <param name="rhs">The ReactionAttributed to move data from</param> ReactionAttributed(ReactionAttributed&& rhs) noexcept = default; /// <summary> /// The copy assignment operator for an ReactionAttributed that first clears the existing elements and then performs a deep copy. /// </summary> /// <param name="rhs">The ReactionAttributed to copy</param> /// <returns>A reference to the updated ReactionAttributed</returns> ReactionAttributed& operator=(const ReactionAttributed& rhs) = default; /// <summary> /// The move assignment operator for a ReactionAttributed that first clears the existing elements and then performs a move assignment. /// </summary> /// <param name="rhs">The ReactionAttributed to copy</param> /// <returns>A reference to the updated ReactionAttributed</returns> ReactionAttributed& operator=(ReactionAttributed&& rhs) noexcept = default; /// <summary> /// The destructor for a ReactionAttributed. /// </summary> virtual ~ReactionAttributed(); /// <summary> /// The cloneable function of an ReactionAttributed, made pure virtual because you cannot have a concreate ReactionAttributed. /// </summary> /// <returns>A gsl::owner indicating ownership of the enclosed pointer to the new ReactionAttributed.</returns> [[nodiscard]] gsl::owner<ReactionAttributed*> Clone() const override; /// <summary> /// Get the signatures of all the prescribed attributes for this Attributed object to auto populate its scope. /// </summary> /// <returns>A Vector of all the signatures of the prescribed attributes for this object.</returns> static FIEAGameEngine::Vector<FIEAGameEngine::Signature> Signatures(); /// <summary> /// Update this ReactionAttributed. /// </summary> /// <param name="gameTime">The current time of the game</param> virtual void Update(const GameTime& gameTime) override; /// <summary> /// The "notification response" function of this ReactionAttributed; /// </summary> /// <param name="eventPublisher">The event that occured.</param> virtual void Notify(EventPublisher& eventPublisher); /// <summary> /// Overriden RTTI functionality - Compare the equality of this ReactionAttributed with another object. /// </summary> /// <returns>A bool representing the equality of these two RTTI.</returns> bool Equals(const RTTI* rhs) const override; /// <summary> /// Getter function for the subtype of this ReactionAttributed. /// </summary> /// <returns>A const reference to the subtype of this ReactionAttributed.</returns> inline const std::string& Subtype() const { return _subtype; }; /// <summary> /// A setter for the gameState of this ReactionAttributed. /// </summary> /// <param name="newGameState">The new subtype.</param> inline void SetSubtype(std::string newSubtype) { _subtype = std::move(newSubtype); }; protected: /// <summary> /// Constructor for a ReactionAttributed that takes a derived class RTTI type ID. /// </summary> /// <param name="typeID">The actual typeID of this instance.</param> /// <param name="name">The name of this ReactionAttributed.</param> explicit ReactionAttributed(RTTI::IdType typeID, const std::string& name = "", std::string subtype = ""); /// <summary> /// A helper function to copy in the "parameters" of an EventMessage Attributed object. /// </summary> /// <param name="eventMessage"></param> void CopyInParameters(const EventMessageAttributed& eventMessage); /// <summary> /// The subtype this ReactionAttributed matches to. /// </summary> std::string _subtype{ "" }; /// <summary> /// The delegate object that will subscribe to events. /// </summary> Delegate notificationDelegate{ std::bind(&ReactionAttributed::Notify, this, _1) }; }; /// <summary> /// The generated concrete factory class that produces ReactionAttributeds. /// </summary> CONCRETE_FACTORY(ReactionAttributed, FIEAGameEngine::Scope) }
<?php namespace App\Http\Controllers; use App\Models\BankCard; use Illuminate\Http\Request; class BankCardController extends Controller { public function index() { $cards = BankCard::all(); return response()->json($cards); } public function store(Request $request) { $validatedData = $request->validate([ 'cardNumber' => 'required|digits:16|unique:bank_cards,number', 'expirationDateMM' => 'required', 'expirationDateYY' => 'required', 'cvv' => 'required|digits:3', ]); $validatedData['number'] = $request->cardNumber; $validatedData['expiry_date_month'] = $request->expirationDateMM; $validatedData['expiry_date_year'] = $request->expirationDateYY; $validatedData['cvv'] = $request->cvv; $card = BankCard::create($validatedData); return response()->json($card, 201); } public function show(BankCard $card) { return response()->json($card); } public function update(Request $request, BankCard $card) { $validatedData = $request->validate([ 'cardNumber' => 'required|digits:16|unique:bank_cards,number,' . $card->id, 'expirationDateMM' => 'required', 'expirationDateYY' => 'required', 'cvv' => 'required|digits:3', ]); $validatedData['number'] = $request->cardNumber; $validatedData['expiry_date_month'] = $request->expirationDateMM; $validatedData['expiry_date_year'] = $request->expirationDateYY; $validatedData['cvv'] = $request->cvv; $card->update($validatedData); return response()->json($card); } public function destroy(BankCard $card) { $card->delete(); return response()->json(null, 204); } }
import React, { useState } from 'react'; import "./AppicationForm.css"; import ReCAPTCHA from "react-google-recaptcha"; const Form = () => { const [image, setImage] = useState(null); const [fileName, setFilename] = useState("No selected file"); const [formData, setFormData] = useState({ firstName: '', lastName: '', course: '', dob: '', gender:'', education: [], email: '', phoneNumber: '', streetAddress: '', addressLine2: '', city: '', state: '', pincode: '', fileName: null, // documents: null, captcha: '', }); const handleInputChange = (event) => { const { name, value, type, checked, files} = event.target; if (type === 'checkbox') { const updatedEducation = formData.education.includes(value) ? formData.education.filter(edu => edu !== value) : [...formData.education, value]; setFormData({ ...formData, education: updatedEducation, }); } else if (type === 'file') { setFormData({ ...formData, [name]: files[0], }); files[0] && setFilename(files[0].name); if (files) { setImage(URL.createObjectURL(files[0])); } } else { setFormData({ ...formData, [name]: type === 'checkbox' ? checked : value, }); } }; const handleSubmit = (event) => { event.preventDefault(); console.log('Form Data:', formData); }; return ( <> <form className="form" onSubmit={handleSubmit}> <h1>Application Form</h1> {/* Candidate Name */} <div className="name-div"> <lable htmlFor="username" className="name-label"> Candidate Name </lable> <div className="name"> <input className="firstname" placeholder="FistName" type="text" name="firstName" onChange={handleInputChange} value={formData.firstName} required /> <input className="firstname" placeholder="LastName" type="text" name="lastName" onChange={handleInputChange} value={formData.lastName} required /> </div> </div> {/* Course Applying For */} <div className="course-div"> <label className="usercourse">Which Course Are You Applying For:</label> <div className="course-option"> <div className="course"> <input type="radio" name="course" value="web" onChange={handleInputChange} required /> <label className="course-span">Web Development</label> </div> <div className="course"> <input type="radio" name="course" value="mobile" onChange={handleInputChange} /> <label className="course-span">Mobile App Development</label> </div> <div className="course"> <input type="radio" name="course" value="data" onChange={handleInputChange} /> <label className="course-span">Data Science</label> </div> </div> </div> {/* Date of Birth */} <div className="course-div"> <label className="usercourse" >Date of Birth:</label> <input style={{ color: "#7a9449", fontSize: "medium", fontFamily: "sans-serif", width: "200px", height: "3vh", outline:"none", borderRadius: "4px", border: "1px solid #dee2e6", }} className="dob" type="date" name="dob" onChange={handleInputChange} value={formData.dob} required /> </div> {/* gender */} <div className="course-div"> <label className="usercourse">Gender</label> <div className="course-option"> <div className="course"> <input type="radio" name="gender" value="male" onChange={handleInputChange} required /> <label className="course-span">Male</label> </div> <div className="course"> <input type="radio" name="gender" value="female" onChange={handleInputChange} /> <label className="course-span">Female</label> </div> <div className="course"> <input type="radio" name="gender" value="other" onChange={handleInputChange} /> <label className="course-span">Others</label> </div> </div> </div> {/* Education */} <div className="course-div"> <label className="usercourse">Education:</label> <div className="education"> <div> <input type="checkbox" name="education" value="school" onChange={handleInputChange} checked={formData.education.includes('school')} /> <label style={{ marginLeft: "5px" }}>School</label> </div> <div> <input type="checkbox" name="education" value="college" onChange={handleInputChange} checked={formData.education.includes('college')} /> <label style={{ marginLeft: "5px" }}>College</label> </div> <div> <input type="checkbox" name="education" value="university" onChange={handleInputChange} checked={formData.education.includes('university')} /> <label style={{ marginLeft: "5px" }}>University</label> </div> </div> </div> {/* Email */} <div className="course-div"> <label className="usercourse">Email:</label> <input style={{ color: "#7a9449", fontSize: "medium", fontFamily: "sans-serif", outline:"none" }} placeholder="abc@example.com" className="mail-input" type="email" name="email" onChange={handleInputChange} value={formData.email} required /> </div> {/* Phone Number */} <div className="course-div"> <label className="usercourse">Phone Number:</label> <input className="mail-input" style={{ color: "#7a9449", fontSize: "medium", fontFamily: "sans-serif", outline:"none", }} type="tel" name="phoneNumber" onChange={handleInputChange} value={formData.phoneNumber} required /> </div> {/* Address */} <div> <div className="mb-3"> <label className=" usercourse">Address:</label> <input placeholder="Street Address" className="form-control" type="text" name="streetAddress" onChange={handleInputChange} value={formData.streetAddress} required /> </div> <div className="mb-3"> <input className="form-control" type="text" placeholder="Street Address Line 2" name="addressLine2" onChange={handleInputChange} value={formData.addressLine2} /> </div> <div className="mb-3 d-flex "> <input className="form-control" placeholder="City" type="text" name="city" onChange={handleInputChange} value={formData.city} required /> <input placeholder="State / Province" className="form-control" type="text" name="state" onChange={handleInputChange} value={formData.state} required /> </div> <div className="mb-3"> <input placeholder="Postal / Zip Code" className="form-control" type="text" name="pincode" onChange={handleInputChange} value={formData.pincode} required /> </div> </div> {/* File Uploads */} <div> <label className="usercourse">File Upload*</label> <div className="image-load" onClick={() => document.querySelector(".input-field").click()} > <input hidden className="input-field" type="file" name="fileName" accept="image/*" onChange={handleInputChange} /> {image ? ( <img src={image} width={150} height={150} alt={fileName} /> ) : ( <> <i className="fa-solid fa-cloud-arrow-up" style={{ color: "#7a9449", fontSize: "xxx-large" }} ></i> <p>Browse File to Upload</p> </> )} </div> </div> <div className='Captcha'> <label className="usercourse">Please verify that you are human</label> <ReCAPTCHA className='inr-captcha' name="captcha" sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI" value={formData.captcha} onChange={handleInputChange} required /> </div> {/* Submit Button */} <button type="submit">Submit</button> </form> </> ); }; export default Form;
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random; public class GamePanel extends JPanel implements ActionListener{ static final int SCREEN_WIDTH = 600; static final int SCREEN_HEIGHT = 600; static final int UNIT_SIZE = 25; static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/ (UNIT_SIZE*UNIT_SIZE); static final int DELAY = 75; final int x[] = new int[GAME_UNITS]; final int y[] = new int[GAME_UNITS]; int bodyParts = 6; int applesEaten; int appleX; int appleY; char direction = 'R'; boolean running = false; Timer timer; Random random; GamePanel(){ random = new Random(); this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT)); this.setBackground(Color.black); this.setFocusable(true); this.addKeyListener(new MyKeyAdapter()); startGame(); } public void startGame(){ newApple(); running = true; timer = new Timer(DELAY, this); timer.start(); } public void paintComponent(Graphics g){ super.paintComponent(g); draw(g); } public void draw(Graphics g){ if(running) { // This is to draw a grid of 24x24 // for (int i = 0; i < SCREEN_HEIGHT / UNIT_SIZE; i++) { // g.drawLine(i * UNIT_SIZE, 0, i * UNIT_SIZE, SCREEN_HEIGHT); // g.drawLine(0, i * UNIT_SIZE, SCREEN_WIDTH, i * UNIT_SIZE); // } g.setColor(Color.red); g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE); for (int i = 0; i < bodyParts; i++) { if (i == 0) { g.setColor(Color.green); g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); } else { g.setColor(new Color(45, 180, 0)); g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); } g.setColor(Color.red); g.setFont(new Font("Serif", Font.BOLD, 40)); FontMetrics metrics = getFontMetrics(g.getFont()); g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize()); } }else{ gameOver(g); } } public void newApple(){ appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE; appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE; } public void move(){ for(int i = bodyParts; i>0; i--) { x[i] = x[i - 1]; y[i] = y[i - 1]; } switch(direction){ case 'U': y[0] = y[0] - UNIT_SIZE; break; case 'D': y[0] = y[0] + UNIT_SIZE; break; case 'L': x[0] = x[0] - UNIT_SIZE; break; case 'R': x[0] = x[0] + UNIT_SIZE; break; } } public void checkApple(){ if((x[0] == appleX) && y[0] == appleY){ bodyParts++; applesEaten++; newApple(); } } public void checkCollisions(){ // checks if head collides with body. for(int i = bodyParts; i>0; i--){ if(x[0] == x[i] && y[0] == y[i]) { running = false; } } //checks if head collides with the left border. if(x[0] < 0){ running = false; } //checks if head collides with the right border. if(x[0] > SCREEN_WIDTH){ running = false; } //checks if head collides with the top border. if(y[0] < 0){ running = false; } //checks if head collides with the bottom border. if(y[0] > SCREEN_HEIGHT){ running = false; } if(!running){ timer.stop(); } } public void gameOver(Graphics g){ g.setColor(Color.red); g.setFont(new Font("Serif", Font.BOLD, 75)); FontMetrics metrics1 = getFontMetrics(g.getFont()); g.drawString("Game Over", (SCREEN_WIDTH - metrics1.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2); g.setColor(Color.red); g.setFont(new Font("Serif", Font.BOLD, 40)); FontMetrics metrics2 = getFontMetrics(g.getFont()); g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics2.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize()); } @Override public void actionPerformed(ActionEvent e){ if(running){ move(); checkApple(); checkCollisions(); } repaint(); } public class MyKeyAdapter extends KeyAdapter{ @Override public void keyPressed(KeyEvent e){ switch(e.getKeyCode()){ case KeyEvent.VK_LEFT : if(direction != 'R'){ direction = 'L'; }break; case KeyEvent.VK_RIGHT: if(direction != 'L') { direction = 'R'; }break; case KeyEvent.VK_UP: if(direction != 'D'){ direction = 'U'; }break; case KeyEvent.VK_DOWN: if(direction != 'U'){ direction = 'D'; }break; } } } }
# Copyright 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import sys import fixtures import mock from oslotest import base as test_base import six from ironicclient.common import cliutils class ValidateArgsTest(test_base.BaseTestCase): def test_lambda_no_args(self): cliutils.validate_args(lambda: None) def _test_lambda_with_args(self, *args, **kwargs): cliutils.validate_args(lambda x, y: None, *args, **kwargs) def test_lambda_positional_args(self): self._test_lambda_with_args(1, 2) def test_lambda_kwargs(self): self._test_lambda_with_args(x=1, y=2) def test_lambda_mixed_kwargs(self): self._test_lambda_with_args(1, y=2) def test_lambda_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_lambda_with_args) def test_lambda_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_lambda_with_args, 1) def test_lambda_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_lambda_with_args, y=2) def _test_lambda_with_default(self, *args, **kwargs): cliutils.validate_args(lambda x, y, z=3: None, *args, **kwargs) def test_lambda_positional_args_with_default(self): self._test_lambda_with_default(1, 2) def test_lambda_kwargs_with_default(self): self._test_lambda_with_default(x=1, y=2) def test_lambda_mixed_kwargs_with_default(self): self._test_lambda_with_default(1, y=2) def test_lambda_positional_args_all_with_default(self): self._test_lambda_with_default(1, 2, 3) def test_lambda_kwargs_all_with_default(self): self._test_lambda_with_default(x=1, y=2, z=3) def test_lambda_mixed_kwargs_all_with_default(self): self._test_lambda_with_default(1, y=2, z=3) def test_lambda_with_default_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_lambda_with_default) def test_lambda_with_default_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_lambda_with_default, 1) def test_lambda_with_default_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_lambda_with_default, y=2) def test_lambda_with_default_missing_args4(self): self.assertRaises(cliutils.MissingArgs, self._test_lambda_with_default, y=2, z=3) def test_function_no_args(self): def func(): pass cliutils.validate_args(func) def _test_function_with_args(self, *args, **kwargs): def func(x, y): pass cliutils.validate_args(func, *args, **kwargs) def test_function_positional_args(self): self._test_function_with_args(1, 2) def test_function_kwargs(self): self._test_function_with_args(x=1, y=2) def test_function_mixed_kwargs(self): self._test_function_with_args(1, y=2) def test_function_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_function_with_args) def test_function_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_function_with_args, 1) def test_function_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_function_with_args, y=2) def _test_function_with_default(self, *args, **kwargs): def func(x, y, z=3): pass cliutils.validate_args(func, *args, **kwargs) def test_function_positional_args_with_default(self): self._test_function_with_default(1, 2) def test_function_kwargs_with_default(self): self._test_function_with_default(x=1, y=2) def test_function_mixed_kwargs_with_default(self): self._test_function_with_default(1, y=2) def test_function_positional_args_all_with_default(self): self._test_function_with_default(1, 2, 3) def test_function_kwargs_all_with_default(self): self._test_function_with_default(x=1, y=2, z=3) def test_function_mixed_kwargs_all_with_default(self): self._test_function_with_default(1, y=2, z=3) def test_function_with_default_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_function_with_default) def test_function_with_default_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_function_with_default, 1) def test_function_with_default_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_function_with_default, y=2) def test_function_with_default_missing_args4(self): self.assertRaises(cliutils.MissingArgs, self._test_function_with_default, y=2, z=3) def test_bound_method_no_args(self): class Foo(object): def bar(self): pass cliutils.validate_args(Foo().bar) def _test_bound_method_with_args(self, *args, **kwargs): class Foo(object): def bar(self, x, y): pass cliutils.validate_args(Foo().bar, *args, **kwargs) def test_bound_method_positional_args(self): self._test_bound_method_with_args(1, 2) def test_bound_method_kwargs(self): self._test_bound_method_with_args(x=1, y=2) def test_bound_method_mixed_kwargs(self): self._test_bound_method_with_args(1, y=2) def test_bound_method_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_bound_method_with_args) def test_bound_method_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_bound_method_with_args, 1) def test_bound_method_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_bound_method_with_args, y=2) def _test_bound_method_with_default(self, *args, **kwargs): class Foo(object): def bar(self, x, y, z=3): pass cliutils.validate_args(Foo().bar, *args, **kwargs) def test_bound_method_positional_args_with_default(self): self._test_bound_method_with_default(1, 2) def test_bound_method_kwargs_with_default(self): self._test_bound_method_with_default(x=1, y=2) def test_bound_method_mixed_kwargs_with_default(self): self._test_bound_method_with_default(1, y=2) def test_bound_method_positional_args_all_with_default(self): self._test_bound_method_with_default(1, 2, 3) def test_bound_method_kwargs_all_with_default(self): self._test_bound_method_with_default(x=1, y=2, z=3) def test_bound_method_mixed_kwargs_all_with_default(self): self._test_bound_method_with_default(1, y=2, z=3) def test_bound_method_with_default_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_bound_method_with_default) def test_bound_method_with_default_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_bound_method_with_default, 1) def test_bound_method_with_default_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_bound_method_with_default, y=2) def test_bound_method_with_default_missing_args4(self): self.assertRaises(cliutils.MissingArgs, self._test_bound_method_with_default, y=2, z=3) def test_unbound_method_no_args(self): class Foo(object): def bar(self): pass cliutils.validate_args(Foo.bar, Foo()) def _test_unbound_method_with_args(self, *args, **kwargs): class Foo(object): def bar(self, x, y): pass cliutils.validate_args(Foo.bar, Foo(), *args, **kwargs) def test_unbound_method_positional_args(self): self._test_unbound_method_with_args(1, 2) def test_unbound_method_kwargs(self): self._test_unbound_method_with_args(x=1, y=2) def test_unbound_method_mixed_kwargs(self): self._test_unbound_method_with_args(1, y=2) def test_unbound_method_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_unbound_method_with_args) def test_unbound_method_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_unbound_method_with_args, 1) def test_unbound_method_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_unbound_method_with_args, y=2) def _test_unbound_method_with_default(self, *args, **kwargs): class Foo(object): def bar(self, x, y, z=3): pass cliutils.validate_args(Foo.bar, Foo(), *args, **kwargs) def test_unbound_method_positional_args_with_default(self): self._test_unbound_method_with_default(1, 2) def test_unbound_method_kwargs_with_default(self): self._test_unbound_method_with_default(x=1, y=2) def test_unbound_method_mixed_kwargs_with_default(self): self._test_unbound_method_with_default(1, y=2) def test_unbound_method_with_default_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_unbound_method_with_default) def test_unbound_method_with_default_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_unbound_method_with_default, 1) def test_unbound_method_with_default_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_unbound_method_with_default, y=2) def test_unbound_method_with_default_missing_args4(self): self.assertRaises(cliutils.MissingArgs, self._test_unbound_method_with_default, y=2, z=3) def test_class_method_no_args(self): class Foo(object): @classmethod def bar(cls): pass cliutils.validate_args(Foo.bar) def _test_class_method_with_args(self, *args, **kwargs): class Foo(object): @classmethod def bar(cls, x, y): pass cliutils.validate_args(Foo.bar, *args, **kwargs) def test_class_method_positional_args(self): self._test_class_method_with_args(1, 2) def test_class_method_kwargs(self): self._test_class_method_with_args(x=1, y=2) def test_class_method_mixed_kwargs(self): self._test_class_method_with_args(1, y=2) def test_class_method_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_class_method_with_args) def test_class_method_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_class_method_with_args, 1) def test_class_method_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_class_method_with_args, y=2) def _test_class_method_with_default(self, *args, **kwargs): class Foo(object): @classmethod def bar(cls, x, y, z=3): pass cliutils.validate_args(Foo.bar, *args, **kwargs) def test_class_method_positional_args_with_default(self): self._test_class_method_with_default(1, 2) def test_class_method_kwargs_with_default(self): self._test_class_method_with_default(x=1, y=2) def test_class_method_mixed_kwargs_with_default(self): self._test_class_method_with_default(1, y=2) def test_class_method_with_default_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_class_method_with_default) def test_class_method_with_default_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_class_method_with_default, 1) def test_class_method_with_default_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_class_method_with_default, y=2) def test_class_method_with_default_missing_args4(self): self.assertRaises(cliutils.MissingArgs, self._test_class_method_with_default, y=2, z=3) def test_static_method_no_args(self): class Foo(object): @staticmethod def bar(): pass cliutils.validate_args(Foo.bar) def _test_static_method_with_args(self, *args, **kwargs): class Foo(object): @staticmethod def bar(x, y): pass cliutils.validate_args(Foo.bar, *args, **kwargs) def test_static_method_positional_args(self): self._test_static_method_with_args(1, 2) def test_static_method_kwargs(self): self._test_static_method_with_args(x=1, y=2) def test_static_method_mixed_kwargs(self): self._test_static_method_with_args(1, y=2) def test_static_method_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_static_method_with_args) def test_static_method_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_static_method_with_args, 1) def test_static_method_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_static_method_with_args, y=2) def _test_static_method_with_default(self, *args, **kwargs): class Foo(object): @staticmethod def bar(x, y, z=3): pass cliutils.validate_args(Foo.bar, *args, **kwargs) def test_static_method_positional_args_with_default(self): self._test_static_method_with_default(1, 2) def test_static_method_kwargs_with_default(self): self._test_static_method_with_default(x=1, y=2) def test_static_method_mixed_kwargs_with_default(self): self._test_static_method_with_default(1, y=2) def test_static_method_with_default_missing_args1(self): self.assertRaises(cliutils.MissingArgs, self._test_static_method_with_default) def test_static_method_with_default_missing_args2(self): self.assertRaises(cliutils.MissingArgs, self._test_static_method_with_default, 1) def test_static_method_with_default_missing_args3(self): self.assertRaises(cliutils.MissingArgs, self._test_static_method_with_default, y=2) def test_static_method_with_default_missing_args4(self): self.assertRaises(cliutils.MissingArgs, self._test_static_method_with_default, y=2, z=3) class _FakeResult(object): def __init__(self, name, value): self.name = name self.value = value class PrintResultTestCase(test_base.BaseTestCase): def setUp(self): super(PrintResultTestCase, self).setUp() self.mock_add_row = mock.MagicMock() self.useFixture(fixtures.MonkeyPatch( "prettytable.PrettyTable.add_row", self.mock_add_row)) self.mock_get_string = mock.MagicMock(return_value="") self.useFixture(fixtures.MonkeyPatch( "prettytable.PrettyTable.get_string", self.mock_get_string)) self.mock_init = mock.MagicMock(return_value=None) self.useFixture(fixtures.MonkeyPatch( "prettytable.PrettyTable.__init__", self.mock_init)) # NOTE(dtantsur): won't work with mocked __init__ self.useFixture(fixtures.MonkeyPatch( "prettytable.PrettyTable.align", mock.MagicMock())) def test_print_list_sort_by_str(self): objs = [_FakeResult("k1", 1), _FakeResult("k3", 2), _FakeResult("k2", 3)] cliutils.print_list(objs, ["Name", "Value"], sortby_index=0) self.assertEqual(self.mock_add_row.call_args_list, [mock.call(["k1", 1]), mock.call(["k3", 2]), mock.call(["k2", 3])]) self.mock_get_string.assert_called_with(sortby="Name") self.mock_init.assert_called_once_with(["Name", "Value"]) def test_print_list_sort_by_integer(self): objs = [_FakeResult("k1", 1), _FakeResult("k2", 3), _FakeResult("k3", 2)] cliutils.print_list(objs, ["Name", "Value"], sortby_index=1) self.assertEqual(self.mock_add_row.call_args_list, [mock.call(["k1", 1]), mock.call(["k2", 3]), mock.call(["k3", 2])]) self.mock_get_string.assert_called_with(sortby="Value") self.mock_init.assert_called_once_with(["Name", "Value"]) def test_print_list_sort_by_none(self): objs = [_FakeResult("k1", 1), _FakeResult("k3", 3), _FakeResult("k2", 2)] cliutils.print_list(objs, ["Name", "Value"], sortby_index=None) self.assertEqual(self.mock_add_row.call_args_list, [mock.call(["k1", 1]), mock.call(["k3", 3]), mock.call(["k2", 2])]) self.mock_get_string.assert_called_with() self.mock_init.assert_called_once_with(["Name", "Value"]) def test_print_list_dict(self): objs = [{'name': 'k1', 'value': 1}, {'name': 'k2', 'value': 2}] cliutils.print_list(objs, ["Name", "Value"], sortby_index=None) self.assertEqual(self.mock_add_row.call_args_list, [mock.call(["k1", 1]), mock.call(["k2", 2])]) self.mock_get_string.assert_called_with() self.mock_init.assert_called_once_with(["Name", "Value"]) def test_print_dict(self): cliutils.print_dict({"K": "k", "Key": "Value"}) cliutils.print_dict({"K": "k", "Key": "Long\\nValue"}) self.mock_add_row.assert_has_calls([ mock.call(["K", "k"]), mock.call(["Key", "Value"]), mock.call(["K", "k"]), mock.call(["Key", "Long"]), mock.call(["", "Value"])], any_order=True) def test_print_list_field_labels(self): objs = [_FakeResult("k1", 1), _FakeResult("k3", 3), _FakeResult("k2", 2)] field_labels = ["Another Name", "Another Value"] cliutils.print_list(objs, ["Name", "Value"], sortby_index=None, field_labels=field_labels) self.assertEqual(self.mock_add_row.call_args_list, [mock.call(["k1", 1]), mock.call(["k3", 3]), mock.call(["k2", 2])]) self.mock_init.assert_called_once_with(field_labels) def test_print_list_field_labels_sort(self): objs = [_FakeResult("k1", 1), _FakeResult("k3", 3), _FakeResult("k2", 2)] field_labels = ["Another Name", "Another Value"] cliutils.print_list(objs, ["Name", "Value"], sortby_index=0, field_labels=field_labels) self.assertEqual(self.mock_add_row.call_args_list, [mock.call(["k1", 1]), mock.call(["k3", 3]), mock.call(["k2", 2])]) self.mock_init.assert_called_once_with(field_labels) self.mock_get_string.assert_called_with(sortby="Another Name") def test_print_list_field_labels_too_many(self): objs = [_FakeResult("k1", 1), _FakeResult("k3", 3), _FakeResult("k2", 2)] field_labels = ["Another Name", "Another Value", "Redundant"] self.assertRaises(ValueError, cliutils.print_list, objs, ["Name", "Value"], sortby_index=None, field_labels=field_labels) class PrintResultStringTestCase(test_base.BaseTestCase): def test_print_list_string(self): objs = [_FakeResult("k1", 1)] field_labels = ["Another Name", "Another Value"] orig = sys.stdout sys.stdout = six.StringIO() cliutils.print_list(objs, ["Name", "Value"], sortby_index=0, field_labels=field_labels) out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = orig expected = '''\ +--------------+---------------+ | Another Name | Another Value | +--------------+---------------+ | k1 | 1 | +--------------+---------------+ ''' self.assertEqual(expected, out) def test_print_list_string_json(self): objs = [_FakeResult("k1", 1)] field_labels = ["Another Name", "Another Value"] orig = sys.stdout sys.stdout = six.StringIO() cliutils.print_list(objs, ["Name", "Value"], sortby_index=0, field_labels=field_labels, json_flag=True) out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = orig expected = [{"name": "k1", "value": 1}] self.assertEqual(expected, json.loads(out)) def test_print_dict_string(self): orig = sys.stdout sys.stdout = six.StringIO() cliutils.print_dict({"K": "k", "Key": "Value"}) out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = orig expected = '''\ +----------+-------+ | Property | Value | +----------+-------+ | K | k | | Key | Value | +----------+-------+ ''' self.assertEqual(expected, out) def test_print_dict_string_json(self): orig = sys.stdout sys.stdout = six.StringIO() cliutils.print_dict({"K": "k", "Key": "Value"}, json_flag=True) out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = orig expected = {"K": "k", "Key": "Value"} self.assertEqual(expected, json.loads(out)) def test_print_dict_string_custom_headers(self): orig = sys.stdout sys.stdout = six.StringIO() cliutils.print_dict({"K": "k", "Key": "Value"}, dict_property='Foo', dict_value='Bar') out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = orig expected = '''\ +-----+-------+ | Foo | Bar | +-----+-------+ | K | k | | Key | Value | +-----+-------+ ''' self.assertEqual(expected, out) def test_print_dict_string_sorted(self): orig = sys.stdout sys.stdout = six.StringIO() cliutils.print_dict({"Foo": "k", "Bar": "Value"}) out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = orig expected = '''\ +----------+-------+ | Property | Value | +----------+-------+ | Bar | Value | | Foo | k | +----------+-------+ ''' self.assertEqual(expected, out) class DecoratorsTestCase(test_base.BaseTestCase): def test_arg(self): func_args = [("--image", ), ("--flavor", )] func_kwargs = [dict(default=None, metavar="<image>"), dict(default=None, metavar="<flavor>")] @cliutils.arg(*func_args[1], **func_kwargs[1]) @cliutils.arg(*func_args[0], **func_kwargs[0]) def dummy_func(): pass self.assertTrue(hasattr(dummy_func, "arguments")) self.assertEqual(len(dummy_func.arguments), 2) for args_kwargs in zip(func_args, func_kwargs): self.assertIn(args_kwargs, dummy_func.arguments) def test_unauthenticated(self): def dummy_func(): pass self.assertFalse(cliutils.isunauthenticated(dummy_func)) dummy_func = cliutils.unauthenticated(dummy_func) self.assertTrue(cliutils.isunauthenticated(dummy_func)) class EnvTestCase(test_base.BaseTestCase): def test_env(self): env = {"alpha": "a", "beta": "b"} self.useFixture(fixtures.MonkeyPatch("os.environ", env)) self.assertEqual(env["beta"], cliutils.env("beta")) self.assertEqual(env["beta"], cliutils.env("beta", "alpha")) self.assertEqual(env["alpha"], cliutils.env("alpha", "beta")) self.assertEqual(env["beta"], cliutils.env("gamma", "beta")) self.assertEqual("", cliutils.env("gamma")) self.assertEqual("c", cliutils.env("gamma", default="c")) class GetPasswordTestCase(test_base.BaseTestCase): def setUp(self): super(GetPasswordTestCase, self).setUp() class FakeFile(object): def isatty(self): return True self.useFixture(fixtures.MonkeyPatch("sys.stdin", FakeFile())) def test_get_password(self): self.useFixture(fixtures.MonkeyPatch("getpass.getpass", lambda prompt: "mellon")) self.assertEqual("mellon", cliutils.get_password()) def test_get_password_verify(self): env = {"OS_VERIFY_PASSWORD": "True"} self.useFixture(fixtures.MonkeyPatch("os.environ", env)) self.useFixture(fixtures.MonkeyPatch("getpass.getpass", lambda prompt: "mellon")) self.assertEqual("mellon", cliutils.get_password()) def test_get_password_verify_failure(self): env = {"OS_VERIFY_PASSWORD": "True"} self.useFixture(fixtures.MonkeyPatch("os.environ", env)) self.useFixture(fixtures.MonkeyPatch("getpass.getpass", lambda prompt: prompt)) self.assertIsNone(cliutils.get_password())
package dk.sdu.mmmi.cbse.main; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import dk.sdu.mmmi.cbse.common.data.Entity; import dk.sdu.mmmi.cbse.common.data.GameData; import dk.sdu.mmmi.cbse.common.data.World; import dk.sdu.mmmi.cbse.beans.EntityProcessingService; import dk.sdu.mmmi.cbse.beans.GamePluginService; import dk.sdu.mmmi.cbse.beans.PostEntityProcessingService; import dk.sdu.mmmi.cbse.managers.GameInputProcessor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; @Component public class Game implements ApplicationListener { private static OrthographicCamera cam; private final GameData gameData = new GameData(); private ShapeRenderer sr; private World world = new World(); private AnnotationConfigApplicationContext applicationContext; public Game() { this.applicationContext = new AnnotationConfigApplicationContext(); this.applicationContext.scan("dk.sdu.mmmi.cbse.beans"); this.applicationContext.refresh(); } @Override public void create() { gameData.setDisplayWidth(Gdx.graphics.getWidth()); gameData.setDisplayHeight(Gdx.graphics.getHeight()); cam = new OrthographicCamera(gameData.getDisplayWidth(), gameData.getDisplayHeight()); cam.translate(gameData.getDisplayWidth() / 2f, gameData.getDisplayHeight() / 2f); cam.update(); sr = new ShapeRenderer(); Gdx.input.setInputProcessor( new GameInputProcessor(gameData) ); ((GamePluginService) applicationContext.getBean("gamePluginService")).start(gameData, world); } @Override public void render() { // clear screen to black Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); gameData.setDelta(Gdx.graphics.getDeltaTime()); update(); draw(); gameData.getKeys().update(); } private void update() { // Update ((EntityProcessingService) applicationContext.getBean("entityProcessingService")).process(gameData, world); ((PostEntityProcessingService) applicationContext.getBean("postEntityProcessingService")).process(gameData, world); } private void draw() { for (Entity entity : world.getEntities()) { sr.begin(ShapeRenderer.ShapeType.Line); float[] shapex = entity.getShapeX(); float[] shapey = entity.getShapeY(); for (int i = 0, j = shapex.length - 1; i < shapex.length; j = i++) { sr.line(shapex[i], shapey[i], shapex[j], shapey[j]); } sr.end(); } } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } }
<!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>Document</title> </head> <body> <h2>Arrays</h2> <script> console.error("일반적인 배열 사용"); /* JS에서 배열을 사용하는 가장 일반적인 방법은 크기만큼 반복하고 인덱스를 통해 접근한다. */ var arr = [1, 2, 3]; for(var i=0; i<arr.length; i++) { console.log('arr['+i+']', arr[i]); } /* pop() : 배열의 마지막 부분에 원소 삭제 push() : 마지막 부분에 원소 추가 shift() : 첫번째 부분에 원소 삭제 unshift() : 첫번째 부분에 원소 추가 */ console.error("pop()/push() 와 shift()/unshift()"); var arr2 = [10, 20, 30]; arr2.pop(); // arr2에서 마지막 원소 삭제 arr2.push("end"); // 마지막 부분에 문자열 추가 console.log(arr2); arr2.shift(); // arr2 에서 첫번째 원소 삭제 arr2.unshift("start"); // 첫번째 부분에 문자열 추가 console.log(arr2); /* splice() : 저장한 인덱스의 원소를 삭제하거나, 삽입하는 2가지 기능을 모두 가지고 있는 함수 형식] splice(시작인덱스, 삭제할원소의갯수, 추가할원소1, 원소2, ..., 원소N) */ console.error("splite() 함수 사용하기"); let arr3 = [1, 5, 7]; //인덱스 1부터 원소 3개(2,3,4) 추가 arr3.splice(1, 0, 2, 3, 4); console.log(arr3); // 인덱스 1부터 원소 2개를 삭제한다. arr3.splice(1, 2); console.log(arr3); // 인덱스 0부터 원소2개(50, 51)를 추가한다. arr3.splice(0, 0, 50, 51); console.log(arr3); // 인덱스 2부터 원소 4개를 추가한다. arr3.splice(2, 0, 52, 53, 54, 55); console.log(arr3); /* Array.from() : 기존의 배열을 새로운 배열로 복사하거나, 함수에서 사용하는 경우 인자를 통해 생성된 유사배열을 실제 배열로 변경해주는 역할을 한다. */ console.error("Array.from() 사용하기"); function fromFunction() { /* arguments : 인자로 전달되는 값을 묶어서 생성되는 유사배열객체 배열과 비슷하지만 실제 배열은 아니므로 배열함수를 사용하면 에러가 발생한다. */ console.log('arguments', arguments); //arguments.push(101); // 실제 배열이 아니므로 에러가 발생 // 유사배열을 실제 배열로 변경한다. var newArr1 = Array.from(arguments); newArr1.push(101); console.log('newArr1', newArr1); } fromFunction(98, 99, 100); // 기존의 배열을 복사한다. let newArr2 = Array.from(arr); console.log('newArr2', newArr2); /* concat() : 일반적으로 2개의 문자열을 연결할때 사용하지만, 2개의 배열을 하나로 합쳐주는 역할도 한다. */ console.error("concat() 사용하기"); var newArr3 = arr.concat([66,77,88]); console.log('newArr3', newArr3); /* Array.isArray() : 인수로 전달받은 객체가 배열일떄 true를 반환한다. */ console.error("Array.isArray() 사용하기"); console.log(Array.isArray([21,22,23])); console.log(Array.isArray({f1:21, f2:22, f3:23})); </script> </body> </html>
import { RecaptchaVerifier, signInWithPhoneNumber } from 'firebase/auth'; import { auth } from '../firebase'; import { Box, Input, Button ,Text,useToast, Stack, AlertDialog, AlertDialogBody, AlertDialogFooter, AlertDialogHeader, AlertDialogContent, AlertDialogOverlay, useDisclosure, } from '@chakra-ui/react'; import { useRef, useState } from 'react'; import { MDBInput } from 'mdb-react-ui-kit'; import { Navigate, NavLink } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import { get_error, get_loading, get_suceess } from '../Redux App/action'; const InitState={ first_name:"", last_name:"", email:"", password:"", phone_number:"" } const SignUpPage=()=>{ const { isOpen, onOpen, onClose } = useDisclosure() const cancelRef = useRef() const { loading }=useSelector((state)=>state) const dispatch=useDispatch(); const [values,setValues]=useState(InitState); const toast = useToast(); const handleChange=(e)=>{ const {name,value}=e.target; setValues({...values,[name]:value}) } const [nav,setNav]=useState(false); const [show, setShow] = useState(false) const [otp,setOtp]=useState(""); const showClick= () => setShow(!show) const [code,setRes]=useState(""); // const [refresh,setRefresh]=useState(false); if(nav){ return <Navigate to='/login' /> } // if(refresh){ // return <Navigate to='/signup' /> // } const handleChangeotp=(e)=>{ setOtp(e.target.value); } const handleClick=async(e)=>{ e.preventDefault(); dispatch( get_loading() ); let res1=await fetch(' https://boat-lifestyle.herokuapp.com/users') let res2=await res1.json(); let flag=false; res2.forEach((elem)=>{ if(elem.email===values.email || elem.phone_number===values.phone_number ){ flag=true; } }) // res2.map((elem)=>{ // if(elem.email===values.email || elem.phone_number===values.phone_number ){ // flag=true; // } // }) if(flag===false){ let recaptcha=new RecaptchaVerifier('recaptcha-container', {}, auth); recaptcha.render(); let number=`+91${values.phone_number}` let res= await signInWithPhoneNumber(auth,number,recaptcha); setRes(res); onOpen(); // }).catch((err)=>{ // dispatch(get_error()) // console.log(err) // toast({ // title: "Server Error", // for server error // description: "Something went wrong", // status: 'error', // duration: 4000, // isClosable: true, // }) // return; // }) console.log(values); }else{ alert("user Already Exists !!") dispatch(get_error()); } // window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {}, auth); } const verify=()=>{ if(code==null) return; code.confirm(otp).then(function(res){ console.log(res.user,'user'); fetch('https://boat-lifestyle.herokuapp.com/users',{ method:'POST', body: JSON.stringify(values), headers : { 'content-type': 'application/json' } }) dispatch(get_suceess(false)); setNav(true); //for navigation toast({ // for sucess title: 'Account Created.', description: "We've created your account for you.", status: 'success', duration: 4000, isClosable: true, position:"top" }) }).catch((err)=>{ dispatch(get_error()) console.log(err) toast({ title: "WRONG OTP", //for wrong otp description: "Try Again", status: 'error', duration: 4000, isClosable: true, position:"top" }) // setRefresh(true); setValues(InitState); return; }) setValues(InitState); } const handleVerify=()=>{ onClose(); verify(); } // if(loading){ // return <h1>...loading...</h1> // } // if(error){ // return <h1>...error..</h1> // } return ( <> <Box width={ {base:"90%", sm:"90%" , md:"60%",lg:"30%"} } margin='auto' marginTop="100px" mb={10}> <Stack marginBottom='30px' > <Text textAlign="center" fontSize='5xl'>Register</Text> <Text textAlign="center" fontSize='xl'>Please fill in the fields </Text> </Stack> <form onSubmit={handleClick} > <Stack spacing="10px" > <MDBInput label="First Name" size='lg' name='first_name' value={values.first_name} onChange={handleChange} required /> <MDBInput label="Last Name" size='lg' name='last_name' value={values.last_name} onChange={handleChange} required /> <MDBInput label="Email" value={values.email} name='email' size='lg' id='typeEmail' type='email' onChange={handleChange} required /> <MDBInput label="Phone Number" value={values.phone_number} size='lg' name='phone_number' id='typeNumber' type='number' onChange={handleChange} required /> <Box width='100%' position='relative' > <MDBInput width='100%' label="Password" id='typePassword' size='lg' name='password' type={show ? 'text' : 'password'} value={values.password} onChange={handleChange} maxLength='8' /> <Button h='1.75rem' size='sm' right='2' top='2' position='absolute' onClick={showClick}> {show ? 'Hide' : 'Show'} </Button> </Box> <Box width='100%' id='recaptcha-container' ></Box> <Button width='100%' isLoading={loading} type='submit' height='50px' style={{ backgroundColor:"red", padding:"20px", textAlign:"center" }} variant="contained" color='#ffff' >CREATE ACCOUNT</Button> <Text textAlign="center" fontSize='lg'>Already have an account <NavLink style={{ color:'red'}} className='hover-underline-animation' to='/login' >Login</NavLink> </Text> </Stack> </form> </Box> <AlertDialog isOpen={isOpen} leastDestructiveRef={cancelRef} onClose={onClose} > <AlertDialogOverlay> <AlertDialogContent> <AlertDialogHeader fontSize='lg' fontWeight='bold'> OTP </AlertDialogHeader> <AlertDialogBody> <Input placeholder='OTP' onChange={ handleChangeotp } ></Input> </AlertDialogBody> <AlertDialogFooter> <Button colorScheme='red' onClick={handleVerify} ml={3}> verify </Button> </AlertDialogFooter> </AlertDialogContent> </AlertDialogOverlay> </AlertDialog> </> ) } export default SignUpPage
# language ES6 JavaScript module for looking up [ISO 639-1 language code](https://en.wikipedia.org/wiki/ISO_639-1) info. ## Importing this library `import { Language } from "https://esm.sh/gh/doga/language@1.0.2/mod.mjs";` ## Usage _Tip: Run the following example by typing this in your terminal (requires [Deno](https://deno.land)):_ ```shell deno run \ --allow-net --allow-run --allow-env --allow-read \ https://deno.land/x/mdrb@2.0.0/mod.ts \ --dax=false --mode=isolated \ https://raw.githubusercontent.com/doga/language/main/README.md ``` <details data-mdrb> <summary>Print out language info for some language codes.</summary> <pre> description = ''' Running this example is safe, it will not read or write anything to your filesystem. ''' </pre> </details> ```javascript import { Language } from "https://esm.sh/gh/doga/language@1.0.2/mod.mjs"; ['en', 'fr', 'de', 'tr'].forEach(iso639_1 => { const lang = Language.fromCode(iso639_1); if(!lang)return; console.info(`Language info for ${lang}:`); console.info(` ISO 639-1: ${lang.iso639_1}`); console.info(` ISO 639-2: ${lang.iso639_2}`); console.info(` Name: ${lang.name}`); console.info(` Native name: ${lang.nativeName}`); console.info(` Family: ${lang.family}`); console.info(` Wiki URL: ${lang.wikiUrl}`); }); ``` Sample output for the code above: ```text Language info for en: ISO 639-1: "en" ISO 639-2: "eng" Name: "English" Native name: "English" Family: "Indo-European" Wiki URL: "https://en.wikipedia.org/wiki/English_language" Language info for fr: ISO 639-1: "fr" ISO 639-2: "fra" Name: "French" Native name: "français, langue française" Family: "Indo-European" Wiki URL: "https://en.wikipedia.org/wiki/French_language" Language info for de: ISO 639-1: "de" ISO 639-2: "deu" Name: "German" Native name: "Deutsch" Family: "Indo-European" Wiki URL: "https://en.wikipedia.org/wiki/German_language" Language info for tr: ISO 639-1: "tr" ISO 639-2: "tur" Name: "Turkish" Native name: "Türkçe" Family: "Turkic" Wiki URL: "https://en.wikipedia.org/wiki/Turkish_language" ``` ∎
What's New ========== 1. Due to the active state of the ZoneMinder project, we now recommend granting ALL permission to the ZoneMinder mysql account. This change must be done manually before ZoneMinder will run. See the installation steps below. 2. This package uses the HTTPS protocol by default to access the web portal. Requests using HTTP will auto-redirect to HTTPS. See README.https for more information. 3. The php package that ships with CentOS 6 does not support the new ZoneMinder API. If you require API functionality (such as using a mobile app) then you should consider an upgrade to CentOS 7 or use Fedora. New installs 1. Unless you are already using MySQL server, you need to ensure that the server is confired to start during boot and properly secured by running: sudo service mysqld start /usr/bin/mysql_secure_installation sudo chkconfig mysqld on 2. Using the password for the root account set during the previous step, you will need to create the ZoneMinder database and configure a database account for ZoneMinder to use: mysql -uroot -p < /usr/share/zoneminder/db/zm_create.sql mysql -uroot -p -e "grant all on zm.* to \ 'zmuser'@localhost identified by 'zmpass';" mysqladmin -uroot -p reload The database account credentials, zmuser/zmpass, are arbitrary. Set them to anything that suits your environment. 3. If you have chosen to change the zoneminder mysql credentials to something other than zmuser/zmpass then you must now edit /etc/zm.conf. Change ZM_DB_USER and ZM_DB_PASS to the values you created in the previous step. 4. Edit /etc/php.ini, uncomment the date.timezone line, and add your local timezone. PHP will complain loudly if this is not set, or if it is set incorrectly, and these complaints will show up in the zoneminder logging system as errors If you are not sure of the proper timezone specification to use, look at http://php.net/date.timezone 5. Install mod_ssl or configure /etc/httpd/conf.d/zoneminder.conf to meet your needs. This package comes preconfigured for HTTPS using the default self signed certificate on your system. The recommended way to complete this step is to simply install mod_ssl: sudo yum install mod_ssl If this does not meet your needs, then read README.https to learn about alternatives. When in doubt, install mod_ssl. 6. Configure the web server to start automatically: sudo chkconfig httpd on sudo service httpd start 7. This package will automatically configure and install an SELinux policy called local_zoneminder. A copy of this policy is in the documentation folder. It is still possible to run into SELinux issues, however. If this is case, you can disable SELinux permanently by editing the following: /etc/selinux/conf Change SELINUX line from "enforcing" to "disabled". This change will not take effect until a reboot, however. To avoid a reboot, execute the following from the commandline: sudo setenforce 0 8. Finally, you may start the ZoneMinder service: sudo service zoneminder start Then point your web browser to http://<machine name or ip>/zm Upgrades ======== 1. Verify /etc/zm.conf. If zm.conf was manually edited before running the upgrade, the installation may not overwrite it. In this case, it will create the file /etc/zm.conf.rpmnew. For example, this will happen if you are using database account credentials other than zmuser/zmpass. Compare /etc/zm.conf to /etc/zm.conf.rpmnew. Verify that zm.conf contains any new config settings that may be in zm.conf.rpmnew. 2. Verify permissions of the zmuser account. Over time, the database account permissions required for normal operation have increased. Verify the zmuser database account has been granted all permission to the ZoneMinder database: mysql -uroot -p -e "show grants for zmuser@localhost;" See step 2 of the Installation section to add missing permissions. 3. Verify the ZoneMinder Apache configuration file in the folder /etc/httpd/conf.d. You will have a file called "zoneminder.conf" and there may also be a file called "zoneminder.conf.rpmnew". If the rpmnew file exists, inspect it and merge anything new in that file with zoneminder.conf. Verify the SSL REquirements meet your needs. Read README.https if necessary. 4. Upgrade the database before starting ZoneMinder. Most upgrades can be performed by executing the following command: sudo zmupdate.pl Recent versions of ZoneMinder don't require any parameters added to the zmupdate command. However, if ZoneMinder complains, you may need to call zmupdate in the following manner: sudo zmupdate.pl --user=root --pass=<mysql_root_pwd> --version=<from version> 5. Now start zoneminder: sudo service zoneminder start
using Jobberwocky.GeometryAlgorithms.Source.Core; using Jobberwocky.GeometryAlgorithms.Source.Algorithms.Triangulation2D; using Jobberwocky.GeometryAlgorithms.Source.Algorithms.Triangulation3D; using UnityEngine; using System; using Jobberwocky.GeometryAlgorithms.Source.Parameters; namespace Jobberwocky.GeometryAlgorithms.Source.API { public class TriangulationAPI : ThreadingAPI { /// <summary> /// Creates a 2D triangulation of the given input points + parameters. /// The points input should not include the boundary and holes points. /// </summary> /// <param name="parameters"></param> /// <returns>Geometry</returns> public Geometry Triangulate2DRaw(Triangulation2DParameters parameters) { var triWrapper2D = new Triangulation2DWrapper(); return triWrapper2D.Triangulate2D(parameters); } /// <summary> /// Creates a 2D triangulation of the given input points + parameters. /// The points input should not include the boundary and holes points. /// </summary> /// <param name="parameters"></param> /// <returns>Triangulated Unity mesh</returns> public Mesh Triangulate2D(Triangulation2DParameters parameters) { // Create triangulation Geometry geometry = Triangulate2DRaw(parameters); return geometry.ToUnityMesh(); } /// <summary> /// Creates a 2D triangulation using threading /// </summary> /// <param name="callback"></param> /// <param name="parameters"></param> public void Triangulate2DAsync(Action<Geometry> callback, Triangulation2DParameters parameters = null) { StartWorker((IParameters param, Action<Geometry> callbackResult) => { var triWrapper = new Triangulation2DWrapper(); var geometry = triWrapper.Triangulate2D((Triangulation2DParameters)param); return new ThreadingResult(callbackResult, geometry); }, parameters, callback); } /// <summary> /// Creates a 3D triangulation of the given input points. /// Note that this method assumes that the 3D shape is convex and without holes. /// This means that concave shapes are triangulated to a convex shape and holes are removed. /// </summary> /// <param name="parameters"></param> /// <returns>Unity mesh</returns> public Mesh Triangulate3D(Triangulation3DParameters parameters) { var geometry = Triangulate3DRaw(parameters); return geometry.ToUnityMesh(); } /// <summary> /// Creates a 3D triangulation of the given input points. /// Note that this method assumes that the 3D shape is convex and without holes. /// This means that concave shapes are triangulated to a convex shape and holes are removed. /// </summary> /// <param name="parameters"></param> /// <returns>Geometry</returns> public Geometry Triangulate3DRaw(Triangulation3DParameters parameters) { var triWrapper3D = new Triangulation3DWrapper(); return triWrapper3D.Triangulate3D(parameters); } /// <summary> /// Creates a 3D convex triangulation using threading /// </summary> /// <param name="callback"></param> /// <param name="points"></param> /// <param name="parameters"></param> public void Triangulation3DThreading(Action<Geometry> callback, Triangulation3DParameters parameters) { StartWorker( (IParameters param, Action<Geometry> callbackResult) => { var triWrapper = new Triangulation3DWrapper(); var geometry = triWrapper.Triangulate3D(parameters); return new ThreadingResult(callbackResult, geometry); }, parameters, callback); } } }
import XCTest @testable import Validation final class ValidateTests: XCTestCase { func testValidate_Valid() { let predicate1 = Predicate<String> { $0.contains("a") } let predicate2 = Predicate<String> { $0.count == 5 } let validate = Validate { predicate1 predicate2 } assertValid(validate.validate("abcde")) { XCTAssertEqual($0, "abcde") } } func testValidate_Invalid() { let predicate1 = Predicate<String> { $0.contains("a") } let predicate2 = Predicate<String> { $0.count == 5 } let validate = Validate { predicate1 predicate2 } assertInvalid(validate.validate("abc")) { XCTAssertEqual($0.count, 1) } assertInvalid(validate.validate("bcdef")) { XCTAssertEqual($0.count, 1) } assertInvalid(validate.validate("bcd")) { XCTAssertEqual($0.count, 2) } } }
package cloudlogin.eats.estrategiamovilmx.cloudlogin; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.cloudrail.si.CloudRail; import com.eats.estrategiamovilmx.cloudlogin.R; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.OptionalPendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import cloudlogin.eats.estrategiamovilmx.enums.SocialMediaProvider; import cloudlogin.eats.estrategiamovilmx.service.LoginService; public class MainActivity extends AppCompatActivity implements View.OnClickListener,GoogleApiClient.OnConnectionFailedListener{ private static final String TAG = "MainActivity"; private SocialMediaProvider mProfile; private static final int RC_SIGN_IN = 007; private GoogleApiClient mGoogleApiClient; private ProgressDialog mProgressDialog; private SignInButton btnSignIn; private Button btnSignOut, btnRevokeAccess; private LinearLayout llProfileLayout; private ImageView imgProfilePic; private TextView txtName, txtEmail; private static final String BROWSABLE = "android.intent.category.BROWSABLE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1 CloudRail.setAppKey(getString(R.string.app_key)); //other impl btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in); btnSignOut = (Button) findViewById(R.id.btn_sign_out); btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access); llProfileLayout = (LinearLayout) findViewById(R.id.llProfile); imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic); txtName = (TextView) findViewById(R.id.txtName); txtEmail = (TextView) findViewById(R.id.txtEmail); btnSignIn.setOnClickListener(this); btnSignOut.setOnClickListener(this); btnRevokeAccess.setOnClickListener(this); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // Customizing G+ button btnSignIn.setSize(SignInButton.SIZE_STANDARD); btnSignIn.setScopes(gso.getScopeArray()); } public void performFacebookLogin(View view) { //2 mProfile = SocialMediaProvider.FACEBOOK; //3 performLogin(); } public void performTwitterLogin(View view) { mProfile = SocialMediaProvider.TWITTER; performLogin(); } public void performGooglePlusLogin(View view) { mProfile = SocialMediaProvider.GOOGLE_PLUS; performLogin(); } public void performInstagramLogin(View view) { mProfile = SocialMediaProvider.INSTAGRAM; performLogin(); } public void performLinkedInLogin(View view) { mProfile = SocialMediaProvider.LINKED_IN; performLogin(); } public void performYahooLogin(View view) { mProfile = SocialMediaProvider.YAHOO; performLogin(); } public void performWindowsLiveLogin(View view) { mProfile = SocialMediaProvider.WINDOWS_LIVE; performLogin(); } public void performGitHubLogin(View view) { mProfile = SocialMediaProvider.GITHUB; performLogin(); } //4 public void performLogin() { Intent intent = new Intent(this, LoginService.class); intent.putExtra(LoginService.EXTRA_PROFILE, mProfile); this.startService(intent); } @Override protected void onNewIntent(Intent intent) { if(intent.getCategories().contains(BROWSABLE)) { // Here we pass the response to the SDK which will automatically // complete the authentication process CloudRail.setAuthenticationResponse(intent); } super.onNewIntent(intent); } /********************************** other ********************************************/ private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { updateUI(false); } }); } private void revokeAccess() { Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { updateUI(false); } }); } private void handleSignInResult(GoogleSignInResult result) { Log.d(TAG, "handleSignInResult:" + result.isSuccess()); if (result.isSuccess()) { Log.d(TAG,"isSuccess ...."); // Signed in successfully, show authenticated UI. GoogleSignInAccount acct = result.getSignInAccount(); Log.e(TAG, "display name: " + acct.getDisplayName()); String personName = acct.getDisplayName()!=null?acct.getDisplayName():""; String personPhotoUrl = acct.getPhotoUrl()!=null?acct.getPhotoUrl().toString():""; String email = acct.getEmail(); Log.e(TAG, "Name: " + personName + ", email: " + email + ", Image: " + personPhotoUrl); txtName.setText(personName); txtEmail.setText(email); if (!personPhotoUrl.isEmpty()) { Glide.with(getApplicationContext()).load(personPhotoUrl) .thumbnail(0.5f) .crossFade() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imgProfilePic); } updateUI(true); } else { // Signed out, show unauthenticated UI. Log.d(TAG, "Signed out....show unauthenticated UI"); updateUI(false); } } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.btn_sign_in: signIn(); break; case R.id.btn_sign_out: signOut(); break; case R.id.btn_revoke_access: revokeAccess(); break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); Log.d(TAG,"CASO 1"); handleSignInResult(result); }else{ Log.d(TAG,"onActivityResult....requestCode.......ELSE"); } } @Override public void onStart() { super.onStart(); Log.d(TAG, "onStart...."); OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); if (opr.isDone()) { // If the user's cached credentials are valid, the OptionalPendingResult will be "done" // and the GoogleSignInResult will be available instantly. Log.d(TAG, "Got cached sign-in"); GoogleSignInResult result = opr.get(); Log.d(TAG,"CASO 2"); handleSignInResult(result); } else { // If the user has not previously signed in on this device or the sign-in has expired, // this asynchronous branch will attempt to sign in the user silently. Cross-device // single sign-on will occur in this branch. Log.d(TAG, "attempt to sign in the user silently"); showProgressDialog(); opr.setResultCallback(new ResultCallback<GoogleSignInResult>() { @Override public void onResult(GoogleSignInResult googleSignInResult) { hideProgressDialog(); Log.d(TAG, "CASO 3"); handleSignInResult(googleSignInResult); } }); } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); } private void showProgressDialog() { Log.d(TAG,"showProgressDialog..."); if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setIndeterminate(true); } mProgressDialog.show(); } private void hideProgressDialog() { Log.d(TAG,"hideProgressDialog..."); if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.hide(); } } private void updateUI(boolean isSignedIn) { Log.d(TAG,"updateUI isSignedIn:"+isSignedIn); if (isSignedIn) { btnSignIn.setVisibility(View.GONE); btnSignOut.setVisibility(View.VISIBLE); btnRevokeAccess.setVisibility(View.VISIBLE); llProfileLayout.setVisibility(View.VISIBLE); } else { btnSignIn.setVisibility(View.VISIBLE); btnSignOut.setVisibility(View.GONE); btnRevokeAccess.setVisibility(View.GONE); llProfileLayout.setVisibility(View.GONE); } } }
@extends('admin') @section('title', $viewData["title"]) @section('content') <!-- Form per inserire i prodotti --> <div class="card mb-4"> <div class="card-header">Crea Nuovo Prodotto</div> <div class="card-body"> @if ($errors->any()) <ul class="alert alert-danger list-unstyled"> @foreach ($errors->all() as $error) <li>- {{ $error }}</li> @endforeach </ul> @endif <form method="POST" action="{{ route('admin.product.store') }}" enctype="multipart/form-data"> @csrf <div class="row"> <div class="col"> <div class="mb-3 row"> <label class="col-lg-2 col-md-6 col-sm-12 col-form-label">Name:</label> <div class="col-lg-10 col-md-6 col-sm-12"> <input type="text" name="name" class="form-control" value="{{ old('name') }}"> </div> </div> </div> <div class="col"> <div class="mb-3 row"> <label class="col-lg-2 col-md-6 col-sm-12 col-form-label">Price:</label> <div class="col-lg-10 col-md-6 col-sm-12"> <input type="number" name="price" class="form-control" value="{{ old('price') }}"> </div> </div> </div> </div> <div class="row"> <div class="col"> <div class="mb-3 row"> <label class="col-lg-2 col-md6 col-sm12 col-form-label">Image:</label> <div class="col-lg-10 col-md-6 col-sm-12"> <input type="file" name="image" class="form-control"> </div> </div> </div> </div> <div class="mb-3"> <label class="col-lg2 col-md6 col-sm-12">Description</label> <textarea class="form-control" name="description" rows="3">{{ old('description') }}</textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> <!-- FINE Form per inserire i prodotti --> <div class="card"> <div class="card-header">Manage Products</div> <div class="card-body"> <table class="table table-bordered table-striped"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> @foreach ($viewData["products"] as $product) <tr> <td>{{ $product->getId() }}</td> <td>{{ $product->getName() }}</td> <td> <a class="btn btn-primary" href="{{route('admin.product.edit', ['id'=> $product->getId()])}}"> <i class="bi-pencil"></i> </a> </td> <td> <form action="{{ route('admin.product.delete', $product->getId())}}" method="POST"> @csrf @method('DELETE') <button class="btn btn-danger"> <i class="bi-trash"></i> </button> </form> </td> </tr> @endforeach </tbody> </table> </div> </div> @endsection
cd paradise_hotel py manage.py runserver venv\Scripts\activate.bat 5. pip freeze проверяем правильность установки 6. django-admin startproject mysite 7. py manage.py runserver 8. ctrl c закрыть сервер 9. py manage.py startapp и далее имя файла login admin Password: FytT75FbfF87 from django.db.models import Q from django.views.generic import ListView, DetailView from django.shortcuts import render from .models import BrowseCategories, CollectionBanner, Color, Product, Category, ProductBrand, informationblock class HomeView(ListView): model = Product paginate_by = 3 template_name = "eister_shop/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['products_all'] = Product.objects.all() context['collection_banners'] = CollectionBanner.objects.all()[:1] context['information_blocks'] = informationblock.objects.all() context['products'] = Product.objects.all()[:3] return context class ProductView(ListView): model = Product template_name = "eister_shop/product.html" context_object_name = 'product_info' slug_url_kwarg = 'post_slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['products_info'] = Product.objects.all() context['browse_categories'] = BrowseCategories.objects.all() context['brands'] = ProductBrand.objects.all() context['productcolors'] = Color.objects.all() context['category_name'] = Category.objects.all() return context def get_queryset(self): queryset = super().get_queryset() category = self.request.GET.get('category') brand = self.request.GET.get('brand') color = self.request.GET.get('color') min_price = self.request.GET.get('min_price') max_price = self.request.GET.get('max_price') filters = Q() if category: filters &= Q(category__name=category) if brand: filters &= Q(productbrand__name=brand) if color: filters &= Q(color__name=color) if min_price: filters &= Q(price__gte=min_price) if max_price: filters &= Q(price__lte=max_price) queryset = queryset.filter(filters) return queryset class ProductDetailView(DetailView): model = Product slug_url_kwarg = 'product_slug' template_name = 'eister_shop/include/product_info.html' class FilteredProductView(ListView): model = Product template_name = "eister_shop/filtered_product.html" context_object_name = 'filtered_products' paginate_by = 10 def get_queryset(self): queryset = super().get_queryset() category = self.request.GET.get('category') brand = self.request.GET.get('brand') color = self.request.GET.get('color') min_price = self.request.GET.get('min_price') max_price = self.request.GET.get('max_price') filters = Q() if category: filters &= Q(category__name=category) if brand: filters &= Q(productbrand__name=brand) if color: filters &= Q(color__name=color) if min_price: filters &= Q(price__gte=min_price) if max_price: filters &= Q(price__lte=max_price) queryset = queryset.filter(filters) return queryset class CardView(DetailView): model = Product paginate_by = 3 template_name = "eister_shop/card.html" def get(self, request): products = Product.objects.all() return render(request, 'eister_shop/card.html', {"card": products}) class OrderTrackingView(DetailView): model = Product paginate_by = 3 template_name = "eister_shop/order_tracking.html" def get(self, request): order_trackings = Product.objects.all() return render(request, 'eister_shop/order_tracking', {"order_tracking": order_trackings}) class ContactView(ListView): model = CollectionBanner paginate_by = 3 template_name = "eister_shop/contact.html" def get(self, request): contacts = CollectionBanner.objects.all() return render(request, 'eister_shop/contact.html', {"contact": contacts}) {% extends 'base.html' %} {% block product %} <div class="container"> <div class="row flex-row-reverse"> <div class="col-lg-9"> <div class="product_top_bar"> <div class="left_dorp"> <select class="sorting"> <option value="1">Default sorting</option> <option value="2">Default sorting 01</option> <option value="4">Default sorting 02</option> </select> <select class="show"> <option value="1">Show 12</option> <option value="2">Show 14</option> <option value="4">Show 16</option> </select> </div> </div> <div class="latest_product_inner"> <div class="row"> {% for product in product_info %} <div class="col-lg-4 col-md-6"> <div class="single-product"> <div class="product-img"> <a href="{{ product.Images.url }}" class="enlarge-image"> <img class="img-fluid w-100" src="{{ product.Images.url }}" alt="" /> <div class="overlay"></div> </a> <div class="p_icon"> <a href="{{ product.Images.url }}" class="enlarge-image"> <i class="ti-eye"></i> </a> <a href="#"> <i class="ti-heart"></i> </a> <a href="{% url 'gift-card' %}"> <i class="ti-shopping-cart"></i> </a> </div> </div> <div class="product-btm"> <a href="{{ product.slug }}" class="d-block"> <h4>{{ product.title }}</h4> </a> <div class="mt-3"> <span class="mr-4">${{ product.price }}</span> <del>${{ product.pricewithoutdiscount }}</del> </div> </div> </div> </div> {% endfor %} </div> </div> </div> <div class="col-lg-3"> <div class="left_sidebar_area"> <form class="left_widgets p_filter_widgets" method="GET" action="{% url 'product' %}"> <aside class="left_widgets p_filter_widgets"> <div class="l_w_title"> <h3>Browse Categories</h3> </div> <div class="widgets_inner"> <select name="category"> <option value="">All Categories</option> {% for category in browse_categories %} <option value="{{ category.name }}">{{ category.name }}</option> {% endfor %} </select> </div> </aside> <aside class="left_widgets p_filter_widgets"> <div class="l_w_title"> <h3>Product Brand</h3> </div> <div class="widgets_inner"> <select name="brand"> <option value="">All Brands</option> {% for brand in brands %} <option value="{{ brand.name }}">{{ brand.name }}</option> {% endfor %} </select> </div> </aside> <aside class="left_widgets p_filter_widgets"> <div class="l_w_title"> <h3>Color Filter</h3> </div> <div class="widgets_inner"> <select name="color"> <option value="">All Colors</option> {% for color in productcolors %} <option value="{{ color.name }}">{{ color.name }}</option> {% endfor %} </select> </div> </aside> <aside class="left_widgets p_filter_widgets"> <div class="l_w_title"> <h3>Price Filter</h3> </div> <div class="widgets_inner"> <div class="range_item"> <div id="slider-range"></div> <div class=""> <input type="number" id="min_price" name="min_price" step="1" placeholder="Min Price" value="{{ request.GET.min_price }}"> <input type="number" id="max_price" name="max_price" step="1" placeholder="Max Price" value="{{ request.GET.max_price }}"> <div><button class="mt-40" type="submit">Filter</button></div> </div> </div> </div> </aside> </form> </div> </div> </div> </div> </section> {% endblock product %}
## CS412 Group Project: Predicting Homework Scores with ChatGPT This project consists of a ML model that tries to predict the homework scores of a student based on the ChatGPT history which they used while doing the homework. By analyzing the interactions between students and ChatGPT, we explore the potential correlation between the assistance interactions and homework grades. ## Extracting and Storing Data - The code firstly processes the ChatGPT histories stored as HTML files and puts them in a dictionary. The dictionary stores them with the students’ ids as keys and the prompts and answers as values. - The code then creates a separate disctionary to store just the user prompts, for easier integration into functions. - It also stores the document names on a list for easy access later on. - We then create a separate list with the document names of students who got perfect scores. - Using the stored document names, we extract text from the GPT responses, seperately storing those the belong to students with a perfect score. - Finally, the code extracts our main labels, the student scores. ## Preprocessing - Preprocessing is applied to both the questions and user prompts to clean the data consisting of words. Tabs, newlines, non-ASCII words, words that only have numbers, data paths and multiple spaces are removed. - The words that only occur once are also removed. - The words then have Stemming and Lemitization applied to them. - A word frequency matrix is then formed by using TF-IDF vectorizer. - We then identify the student chats where the student score is outside of mean ± standart deviation. This is done to get rid of outliers that might harm the data. We also remove values directly equal to 100, as we use those values as the “golden standart” of one our features. ## Feature Engineering - Code similarity: Calculated by finding the similarity between all students and those who got perfect scores. - Question similarity: Calculated by finding the similarity of each student’s prompt with the questions of the assignment. This is given as a separate feature for each question. - Average characters per prompt/response: Calculated by counting the total number of characters in a prompt/response and then at the end divided by the number of prompts/responses. - Keyword Occurrence: Calculated by counting the number of times each keyword is found. The list of keywords is given below: ![Aspose Words 92108f4f-65b0-468b-8f6e-6114b7f94085 001](https://github.com/Orkataru/CS412_Project/assets/91630525/61016bce-651f-47c4-a6b2-a842149ef83e) - Joy and Anger: Obtained by implementing a sentiment analysis tool. - Intelligence Scored: An abstract value that represents the overall intelligence of the student, as best as possible given just the text data, uses the following metrics to get close to an objective rating: - Vocabulary Complexity - Curiosity and Inquiry - Engagement with Diverse Topics - Logical Consistency - Problem-Solving Skills - Learning and Adaptation ## Finalizing the data. - The code inserts all the data into the DataFrame - The code then filters out the students that were marked to be filtered out. (Outliers and perfect scorers) - DataFrame is then finalized and is merged with the rest of the featured. ## Applying Upsampling and running the model. - The code applies Manual Upsampling to the DataFrame to prevent certain small classes from being underrepresented. - The code then uses stratified K fold to obtain a more accurate test result. Hyperparameter tuning is used alongside the K fold to get the best parameters for all the folds. - The model is then run for all the folds, using a variety of Regression models, and is compared to the accuracies of the model initially given to us also ran with the same models. - The table of the results can be found below. ## Results ![image](https://github.com/Orkataru/CS412_Project/assets/81559141/104bd65a-37a1-401f-b129-1fb373c582ff) Authors Bilgehan Bilgin (00030902) <br /> Sadiq Qara (00030410) <br /> Zeynep Özgür Gün (00029502) <br /> Beste Bayhan (00028863)
import get from 'lodash.get' import { AssetsTablePerYear } from 'types/index' import getDeltaPercentage from './getDeltaPercentage' import getDiff from './getDiff' type GetNetWorth = { data: AssetsTablePerYear } export default function getNetWorth({ data }: GetNetWorth): AssetsTablePerYear { return Object.keys(data).reduce((yearAcc, year) => { if (!data[year].CASH) { return yearAcc } const netWorthList = data[year].CASH.TOTAL.map((cashCell, index) => { const cash = cashCell.value as number const pensionFund = data[year].PENSION_FUND.TOTAL[index].value as number const pensionFundPrivate = data[year].PENSION_FUND_PRIVATE.TOTAL[index] .value as number return cash + pensionFund + pensionFundPrivate }) // the data from the last year isn't available in the array of this year // we need to prepend it to calculate the delta const netWorthValuesFromPreviousYear = get( yearAcc, `${parseInt(year, 10) - 1}.NET_WORTH.TOTAL`, ) const lastSavingsValueFromThePreviousYear = netWorthValuesFromPreviousYear ? netWorthValuesFromPreviousYear[ netWorthValuesFromPreviousYear.length - 1 ].value : 0 const netWorthDelta = getDiff([ lastSavingsValueFromThePreviousYear, ...netWorthList, ]) return { ...yearAcc, [year]: { ...data[year], NET_WORTH: { ...data[year].CASH_SAVINGS, TOTAL: netWorthList.map((value, index) => ({ label: index, value, })), DELTA: netWorthDelta.map((value, index) => ({ label: index, value, })), DELTA_PERCENTAGE: getDeltaPercentage({ deltaArray: netWorthDelta, totalValuesArray: netWorthList, }), }, }, } }, {}) }
/* Copyright (C) 2015-2019, Wazuh Inc. * Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public * License (version 2) as published by the FSF - Free Software * Foundation */ #ifndef VALIDATE_H #define VALIDATE_H /* IP structure */ typedef struct _os_ip { char *ip; unsigned int ip_address; unsigned int netmask; } os_ip; /** * @brief Get the netmask based on the integer value. * * @param[in] mask Integer value of the netmask. * @param[out] strmask Pointer to array where the value will be stored. * @param[in] size Size of the array. * @return Returns 1. */ int getNetmask(unsigned int mask, char *strmask, size_t size) __attribute__((nonnull)); /* Run-time definitions */ int getDefine_Int(const char *high_name, const char *low_name, int min, int max) __attribute__((nonnull)); /** * @brief Check if IP_address is present at that_ip * * @param ip_address IP address. * @param that_ip Struct os_ip to check. * @return Returns 1 on success or 0 on failure. */ int OS_IPFound(const char *ip_address, const os_ip *that_ip) __attribute__((nonnull)); /** * @brief Check if IP_address is present at that_ip * * @param ip_address IP address. * @param list_of_ips List of os_ip struct to check. * @return Returns 1 on success or 0 on failure. */ int OS_IPFoundList(const char *ip_address, os_ip **list_of_ips);// __attribute__((nonnull)); /** * @brief Validate if an IP address is in the right format * * @param ip_address [in] IP address. * @param final_ip [out] Struct os_ip with the given IP address. * @return Returns 0 if doesn't match or 1 if it does (or 2 if it has a CIDR). */ int OS_IsValidIP(const char *ip_address, os_ip *final_ip); /** * @brief Validate if a time is in an acceptable format. * * Acceptable formats: * hh:mm - hh:mm (24 hour format) * !hh:mm - hh:mm (24 hour format) * hh - hh (24 hour format) * hh:mm am - hh:mm pm (12 hour format) * hh am - hh pm (12 hour format) * * @param time_str Time to be validated. * @return Returns 0 if doesn't match or a valid string in success. */ char *OS_IsValidTime(const char *time_str); /** * @brief Validate if a time is in an acceptable format, but only accepts a unique time, not a range. * * @param time_str Time to be validated. * @return Returns 0 if doesn't match or a valid string in success. */ char *OS_IsValidUniqueTime(const char *time_str) __attribute__((nonnull)); /** * @brief Validate if a time is in on a specied time interval. * Must be a valid string, called after OS_IsValidTime(). * @param time_str Time to be validated. * @param ossec_time Time interval. * @return Returns 1 on success or 0 on failure. */ int OS_IsonTime(const char *time_str, const char *ossec_time) __attribute__((nonnull)); /** * @brief Checks if time is the same or has passed a specified one. * Must be a valid string, called after OS_IsValidTime(). * @param time_str Time to be validated. * @param ossec_time Time interval. * @return Returns 1 on success or 0 on failure. */ int OS_IsAfterTime(const char *time_str, const char *ossec_time) __attribute__((nonnull)); /** * @brief Checks if time is the same or has passed a specified one. * Acceptable formats: * weekdays, weekends, monday, tuesday, thursday,.. * monday,tuesday * mon,tue wed * @param day_str Day to be validated. * @return Returns 0 if doesn't match or a valid string in success. */ char *OS_IsValidDay(const char *day_str); /** * @brief Check if the specified week day is in the range. * * @param week_day Day of the week. * @param ossec_day Interval. * @return Returns 1 on success or 0 on failure. */ int OS_IsonDay(int week_day, const char *ossec_day) __attribute__((nonnull)); /** * @brief Convert a CIDR into string: aaa.bbb.ccc.ddd[/ee] * * @param ip [in] IP to be converted. * @param string [out] Allocated string to store the IP. * @param size [in] Size of the allocated string. * @return Returns 0 on success or -1 on failure. */ int OS_CIDRtoStr(const os_ip * ip, char * string, size_t size); /** * @brief Validate the day of the week set and retrieve its corresponding integer value. * * @param day_str Day of the week. * @return Return day of the week. If not found, -1 is returned. */ int w_validate_wday(const char * day_str); /** * @brief Validate a given time. * Acceptable format: hh:mm (24 hour format) * * @param time_str Time to be validated. * @return Returns NULL on error or a valid string in success. */ char * w_validate_time(const char * time_str); /** * @brief Validate if the specified interval is multiple of weeks or days. * * @param interval Interval to be validated. * @param force Set to 0 to check if it is multiple of days or 1 for weeks. * @return Returns 0 if the interval is multiple, -1 otherwise. */ int w_validate_interval(int interval, int force); /* Macros */ /* Check if the IP is a single host, not a network with a netmask */ #define isSingleHost(x) (x->netmask == 0xFFFFFFFF) #endif /* VALIDATE_H */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace StaticDelegate { class DBConnection { protected static int NextConnectionNbr = 1; protected string connectionName; public string ConnectionName { get { return connectionName; } } public DBConnection() { connectionName = "Database Connection " + DBConnection.NextConnectionNbr++; } } class DBManger { protected ArrayList activeConnections; public DBManger() { activeConnections = new ArrayList(); for (int i = 0; i < 6; i++) { activeConnections.Add(new DBConnection()); } } public delegate void EnumConnectionsCallback(DBConnection connection); public void EnumConnections(EnumConnectionsCallback callback) { foreach (DBConnection connection in activeConnections) { callback(connection); } } } class Program { static DBManger.EnumConnectionsCallback printConnections = new DBManger.EnumConnectionsCallback(printConnections); public static void PrintConnections(DBConnection connection) { Console.WriteLine("[StaticDelegate.PrintConnections] {0}", connection.ConnectionName); } static void Main(string[] args) { DBManger dbManager = new DBManger(); Console.WriteLine("[Main] Calling EnumConnections " + "- passing the delegate"); dbManager.EnumConnections(printConnections); Console.ReadLine(); } } }
/*---------------------- Copyright (C): Henri Payno, Axel Delsol, Laboratoire de Physique de Clermont UMR 6533 CNRS-UCA This software is distributed under the terms of the GNU Lesser General Public Licence (LGPL) See LICENSE.md for further details ----------------------*/ #ifndef ELEMENT_MANAGER_HH #define ELEMENT_MANAGER_HH #include "G4Element.hh" #include <map> #include <QString> /// \brief define the element manager /// \warning elements are defined from the G4Element definition /// @author Henri Payno class ElementManager { public: /// \brief constructor ElementManager(); /// \brief destructor ~ElementManager(); /// \brief return the ElementManager singleton static ElementManager* getInstance(); /// \brief return the requested element G4Element* getElement(QString); /// \brief register the G4Element* bool registerElement(G4Element*); /// \brief unregister the G4Element void unregisterElement(QString); private: /// \brief define some basic elements void generateStandardElements(); /// \brief the map registred elements std::map<QString, G4Element*> elementsMap; }; #endif // ELEMENT_MANAGER_HH
use super::{ build_traits::SubContainer, dataflow::{DFGBuilder, DFGWrapper}, handle::BuildHandle, BasicBlockID, BuildError, CfgID, Container, Dataflow, HugrBuilder, Wire, }; use crate::ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}; use crate::{ extension::{ExtensionRegistry, ExtensionSet}, types::FunctionType, }; use crate::{hugr::views::HugrView, types::TypeRow}; use crate::Node; use crate::{hugr::HugrMut, type_row, Hugr}; /// Builder for a [`crate::ops::CFG`] child control /// flow graph. /// /// These builder methods should ensure that the first two children of a CFG /// node are the entry node and the exit node. /// /// # Example /// ``` /// /* Build a control flow graph with the following structure: /// +-----------+ /// | Entry | /// +-/-----\---+ /// / \ /// / \ /// / \ /// / \ /// +-----/----+ +--\-------+ /// | Branch A | | Branch B | /// +-----\----+ +----/-----+ /// \ / /// \ / /// \ / /// \ / /// +-\-------/--+ /// | Exit | /// +------------+ /// */ /// use hugr::{ /// builder::{BuildError, CFGBuilder, Container, Dataflow, HugrBuilder}, /// extension::{prelude, ExtensionSet}, /// ops, type_row, /// types::{FunctionType, SumType, Type}, /// Hugr, /// }; /// /// const NAT: Type = prelude::USIZE_T; /// /// fn make_cfg() -> Result<Hugr, BuildError> { /// let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; /// /// // Outputs from basic blocks must be packed in a sum which corresponds to /// // which successor to pick. We'll either choose the first branch and pass /// // it a NAT, or the second branch and pass it nothing. /// let sum_variants = vec![type_row![NAT], type_row![]]; /// /// // The second argument says what types will be passed through to every /// // successor, in addition to the appropriate `sum_variants` type. /// let mut entry_b = /// cfg_builder.entry_builder(sum_variants.clone(), type_row![NAT], ExtensionSet::new())?; /// /// let [inw] = entry_b.input_wires_arr(); /// let entry = { /// // Pack the const "42" into the appropriate sum type. /// let left_42 = ops::Value::sum( /// 0, /// [prelude::ConstUsize::new(42).into()], /// SumType::new(sum_variants.clone()), /// )?; /// let sum = entry_b.add_load_value(left_42); /// /// entry_b.finish_with_outputs(sum, [inw])? /// }; /// /// // This block will be the first successor of the entry node. It takes two /// // `NAT` arguments: one from the `sum_variants` type, and another from the /// // entry node's `other_outputs`. /// let mut successor_builder = cfg_builder.simple_block_builder( /// FunctionType::new(type_row![NAT, NAT], type_row![NAT]), /// 1, // only one successor to this block /// )?; /// let successor_a = { /// // This block has one successor. The choice is denoted by a unary sum. /// let sum_unary = successor_builder.add_load_const(ops::Value::unary_unit_sum()); /// /// // The input wires of a node start with the data embedded in the variant /// // which selected this block. /// let [_forty_two, in_wire] = successor_builder.input_wires_arr(); /// successor_builder.finish_with_outputs(sum_unary, [in_wire])? /// }; /// /// // The only argument to this block is the entry node's `other_outputs`. /// let mut successor_builder = cfg_builder /// .simple_block_builder(FunctionType::new(type_row![NAT], type_row![NAT]), 1)?; /// let successor_b = { /// let sum_unary = successor_builder.add_load_value(ops::Value::unary_unit_sum()); /// let [in_wire] = successor_builder.input_wires_arr(); /// successor_builder.finish_with_outputs(sum_unary, [in_wire])? /// }; /// let exit = cfg_builder.exit_block(); /// cfg_builder.branch(&entry, 0, &successor_a)?; // branch 0 goes to successor_a /// cfg_builder.branch(&entry, 1, &successor_b)?; // branch 1 goes to successor_b /// cfg_builder.branch(&successor_a, 0, &exit)?; /// cfg_builder.branch(&successor_b, 0, &exit)?; /// let hugr = cfg_builder.finish_prelude_hugr()?; /// Ok(hugr) /// }; /// #[cfg(not(feature = "extension_inference"))] /// assert!(make_cfg().is_ok()); /// ``` #[derive(Debug, PartialEq)] pub struct CFGBuilder<T> { pub(super) base: T, pub(super) cfg_node: Node, pub(super) inputs: Option<TypeRow>, pub(super) exit_node: Node, pub(super) n_out_wires: usize, } impl<B: AsMut<Hugr> + AsRef<Hugr>> Container for CFGBuilder<B> { #[inline] fn container_node(&self) -> Node { self.cfg_node } #[inline] fn hugr_mut(&mut self) -> &mut Hugr { self.base.as_mut() } #[inline] fn hugr(&self) -> &Hugr { self.base.as_ref() } } impl<H: AsMut<Hugr> + AsRef<Hugr>> SubContainer for CFGBuilder<H> { type ContainerHandle = BuildHandle<CfgID>; #[inline] fn finish_sub_container(self) -> Result<Self::ContainerHandle, BuildError> { Ok((self.cfg_node, self.n_out_wires).into()) } } impl CFGBuilder<Hugr> { /// New CFG rooted HUGR builder pub fn new(signature: FunctionType) -> Result<Self, BuildError> { let cfg_op = ops::CFG { signature: signature.clone(), }; let base = Hugr::new(cfg_op); let cfg_node = base.root(); CFGBuilder::create(base, cfg_node, signature.input, signature.output) } } impl HugrBuilder for CFGBuilder<Hugr> { fn finish_hugr( mut self, extension_registry: &ExtensionRegistry, ) -> Result<Hugr, crate::hugr::ValidationError> { self.base.update_validate(extension_registry)?; Ok(self.base) } } impl<B: AsMut<Hugr> + AsRef<Hugr>> CFGBuilder<B> { pub(super) fn create( mut base: B, cfg_node: Node, input: TypeRow, output: TypeRow, ) -> Result<Self, BuildError> { let n_out_wires = output.len(); let exit_block_type = OpType::ExitBlock(ExitBlock { cfg_outputs: output, }); let exit_node = base .as_mut() // Make the extensions a parameter .add_node_with_parent(cfg_node, exit_block_type); Ok(Self { base, cfg_node, n_out_wires, exit_node, inputs: Some(input), }) } /// Return a builder for a non-entry [`DataflowBlock`] child graph with `inputs` /// and `outputs` and the variants of the branching Sum value /// specified by `sum_rows`. /// /// # Errors /// /// This function will return an error if there is an error adding the node. pub fn block_builder( &mut self, inputs: TypeRow, sum_rows: impl IntoIterator<Item = TypeRow>, extension_delta: ExtensionSet, other_outputs: TypeRow, ) -> Result<BlockBuilder<&mut Hugr>, BuildError> { self.any_block_builder(inputs, sum_rows, other_outputs, extension_delta, false) } fn any_block_builder( &mut self, inputs: TypeRow, sum_rows: impl IntoIterator<Item = TypeRow>, other_outputs: TypeRow, extension_delta: ExtensionSet, entry: bool, ) -> Result<BlockBuilder<&mut Hugr>, BuildError> { let sum_rows: Vec<_> = sum_rows.into_iter().collect(); let op = OpType::DataflowBlock(DataflowBlock { inputs: inputs.clone(), other_outputs: other_outputs.clone(), sum_rows, extension_delta, }); let parent = self.container_node(); let block_n = if entry { let exit = self.exit_node; // TODO: Make extensions a parameter self.hugr_mut().add_node_before(exit, op) } else { // TODO: Make extensions a parameter self.hugr_mut().add_node_with_parent(parent, op) }; BlockBuilder::create(self.hugr_mut(), block_n) } /// Return a builder for a non-entry [`DataflowBlock`] child graph with `inputs` /// and `outputs` and a UnitSum type: a Sum of `n_cases` unit types. /// /// # Errors /// /// This function will return an error if there is an error adding the node. pub fn simple_block_builder( &mut self, signature: FunctionType, n_cases: usize, ) -> Result<BlockBuilder<&mut Hugr>, BuildError> { self.block_builder( signature.input, vec![type_row![]; n_cases], signature.extension_reqs, signature.output, ) } /// Return a builder for the entry [`DataflowBlock`] child graph with `inputs` /// and `outputs` and the variants of the branching Sum value /// specified by `sum_rows`. /// /// # Errors /// /// This function will return an error if an entry block has already been built. pub fn entry_builder( &mut self, sum_rows: impl IntoIterator<Item = TypeRow>, other_outputs: TypeRow, extension_delta: ExtensionSet, ) -> Result<BlockBuilder<&mut Hugr>, BuildError> { let inputs = self .inputs .take() .ok_or(BuildError::EntryBuiltError(self.cfg_node))?; self.any_block_builder(inputs, sum_rows, other_outputs, extension_delta, true) } /// Return a builder for the entry [`DataflowBlock`] child graph with `inputs` /// and `outputs` and a UnitSum type: a Sum of `n_cases` unit types. /// /// # Errors /// /// This function will return an error if there is an error adding the node. pub fn simple_entry_builder( &mut self, outputs: TypeRow, n_cases: usize, extension_delta: ExtensionSet, ) -> Result<BlockBuilder<&mut Hugr>, BuildError> { self.entry_builder(vec![type_row![]; n_cases], outputs, extension_delta) } /// Returns the exit block of this [`CFGBuilder`]. pub fn exit_block(&self) -> BasicBlockID { self.exit_node.into() } /// Set the `branch` index `successor` block of `predecessor`. /// /// # Errors /// /// This function will return an error if there is an error connecting the blocks. pub fn branch( &mut self, predecessor: &BasicBlockID, branch: usize, successor: &BasicBlockID, ) -> Result<(), BuildError> { let from = predecessor.node(); let to = successor.node(); self.hugr_mut().connect(from, branch, to, 0); Ok(()) } } /// Builder for a [`DataflowBlock`] child graph. pub type BlockBuilder<B> = DFGWrapper<B, BasicBlockID>; impl<B: AsMut<Hugr> + AsRef<Hugr>> BlockBuilder<B> { /// Set the outputs of the block, with `branch_wire` carrying the value of the /// branch controlling Sum value. `outputs` are the remaining outputs. pub fn set_outputs( &mut self, branch_wire: Wire, outputs: impl IntoIterator<Item = Wire>, ) -> Result<(), BuildError> { Dataflow::set_outputs(self, [branch_wire].into_iter().chain(outputs)) } fn create(base: B, block_n: Node) -> Result<Self, BuildError> { let block_op = base.get_optype(block_n).as_dataflow_block().unwrap(); let signature = block_op.inner_signature(); let db = DFGBuilder::create_with_io(base, block_n, signature)?; Ok(BlockBuilder::from_dfg_builder(db)) } /// [Set outputs](BlockBuilder::set_outputs) and [finish](`BlockBuilder::finish_sub_container`). pub fn finish_with_outputs( mut self, branch_wire: Wire, outputs: impl IntoIterator<Item = Wire>, ) -> Result<<Self as SubContainer>::ContainerHandle, BuildError> where Self: Sized, { self.set_outputs(branch_wire, outputs)?; self.finish_sub_container() } } impl BlockBuilder<Hugr> { /// Initialize a [`DataflowBlock`] rooted HUGR builder pub fn new( inputs: impl Into<TypeRow>, sum_rows: impl IntoIterator<Item = TypeRow>, other_outputs: impl Into<TypeRow>, extension_delta: ExtensionSet, ) -> Result<Self, BuildError> { let inputs = inputs.into(); let sum_rows: Vec<_> = sum_rows.into_iter().collect(); let other_outputs = other_outputs.into(); let op = DataflowBlock { inputs: inputs.clone(), other_outputs: other_outputs.clone(), sum_rows, extension_delta, }; let base = Hugr::new(op); let root = base.root(); Self::create(base, root) } /// [Set outputs](BlockBuilder::set_outputs) and [finish_hugr](`BlockBuilder::finish_hugr`). pub fn finish_hugr_with_outputs( mut self, branch_wire: Wire, outputs: impl IntoIterator<Item = Wire>, extension_registry: &ExtensionRegistry, ) -> Result<Hugr, BuildError> { self.set_outputs(branch_wire, outputs)?; self.finish_hugr(extension_registry) .map_err(BuildError::InvalidHUGR) } } #[cfg(test)] pub(crate) mod test { use crate::builder::{DataflowSubContainer, ModuleBuilder}; use crate::hugr::validate::InterGraphEdgeError; use crate::hugr::ValidationError; use crate::{builder::test::NAT, type_row}; use cool_asserts::assert_matches; use super::*; #[test] fn basic_module_cfg() -> Result<(), BuildError> { let build_result = { let mut module_builder = ModuleBuilder::new(); let mut func_builder = module_builder .define_function("main", FunctionType::new(vec![NAT], type_row![NAT]).into())?; let _f_id = { let [int] = func_builder.input_wires_arr(); let cfg_id = { let mut cfg_builder = func_builder.cfg_builder( vec![(NAT, int)], type_row![NAT], ExtensionSet::new(), )?; build_basic_cfg(&mut cfg_builder)?; cfg_builder.finish_sub_container()? }; func_builder.finish_with_outputs(cfg_id.outputs())? }; module_builder.finish_prelude_hugr() }; assert_eq!(build_result.err(), None); Ok(()) } #[test] fn basic_cfg_hugr() -> Result<(), BuildError> { let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; build_basic_cfg(&mut cfg_builder)?; assert_matches!(cfg_builder.finish_prelude_hugr(), Ok(_)); Ok(()) } pub(crate) fn build_basic_cfg<T: AsMut<Hugr> + AsRef<Hugr>>( cfg_builder: &mut CFGBuilder<T>, ) -> Result<(), BuildError> { let sum2_variants = vec![type_row![NAT], type_row![NAT]]; let mut entry_b = cfg_builder.entry_builder(sum2_variants.clone(), type_row![], ExtensionSet::new())?; let entry = { let [inw] = entry_b.input_wires_arr(); let sum = entry_b.make_sum(1, sum2_variants, [inw])?; entry_b.finish_with_outputs(sum, [])? }; let mut middle_b = cfg_builder .simple_block_builder(FunctionType::new(type_row![NAT], type_row![NAT]), 1)?; let middle = { let c = middle_b.add_load_const(ops::Value::unary_unit_sum()); let [inw] = middle_b.input_wires_arr(); middle_b.finish_with_outputs(c, [inw])? }; let exit = cfg_builder.exit_block(); cfg_builder.branch(&entry, 0, &middle)?; cfg_builder.branch(&middle, 0, &exit)?; cfg_builder.branch(&entry, 1, &exit)?; Ok(()) } #[test] fn test_dom_edge() -> Result<(), BuildError> { let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; let sum_tuple_const = cfg_builder.add_constant(ops::Value::unary_unit_sum()); let sum_variants = vec![type_row![]]; let mut entry_b = cfg_builder.entry_builder(sum_variants.clone(), type_row![], ExtensionSet::new())?; let [inw] = entry_b.input_wires_arr(); let entry = { let sum = entry_b.load_const(&sum_tuple_const); entry_b.finish_with_outputs(sum, [])? }; let mut middle_b = cfg_builder.simple_block_builder(FunctionType::new(type_row![], type_row![NAT]), 1)?; let middle = { let c = middle_b.load_const(&sum_tuple_const); middle_b.finish_with_outputs(c, [inw])? }; let exit = cfg_builder.exit_block(); cfg_builder.branch(&entry, 0, &middle)?; cfg_builder.branch(&middle, 0, &exit)?; assert_matches!(cfg_builder.finish_prelude_hugr(), Ok(_)); Ok(()) } #[test] fn test_non_dom_edge() -> Result<(), BuildError> { let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; let sum_tuple_const = cfg_builder.add_constant(ops::Value::unary_unit_sum()); let sum_variants = vec![type_row![]]; let mut middle_b = cfg_builder .simple_block_builder(FunctionType::new(type_row![NAT], type_row![NAT]), 1)?; let [inw] = middle_b.input_wires_arr(); let middle = { let c = middle_b.load_const(&sum_tuple_const); middle_b.finish_with_outputs(c, [inw])? }; let mut entry_b = cfg_builder.entry_builder(sum_variants.clone(), type_row![NAT], ExtensionSet::new())?; let entry = { let sum = entry_b.load_const(&sum_tuple_const); // entry block uses wire from middle block even though middle block // does not dominate entry entry_b.finish_with_outputs(sum, [inw])? }; let exit = cfg_builder.exit_block(); cfg_builder.branch(&entry, 0, &middle)?; cfg_builder.branch(&middle, 0, &exit)?; assert_matches!( cfg_builder.finish_prelude_hugr(), Err(ValidationError::InterGraphEdgeError( InterGraphEdgeError::NonDominatedAncestor { .. } )) ); Ok(()) } }
# go-storage-like-redis like redis but written by me on Golang. Just Key-Value storage. ## Requirements 1) Go version 1.21 or above ## Install 1) Copy repository via `git clone` or other method 2) Install necessary modules via `go mod tidy` (inside project folder) ## Run ### 1) Via Docker 1) Set up configuration 2) Add necessary flags to Dockerfile (if you want use non-default config) 3) `docker build -t image-name .` 4) `docker run -p port:port image-name` ### 2) Manual 1) Set up configuration 2) `go run cmd/main.go -config=pathToConfig` ## Flags 1) `-config` - set up path to your configuration ## Configuration struct 1) `server` - server settings 1) `host` - server host 2) `port` - server port 3) `read_timeout_in_ms` - timeout for read requests 4) `write_timeout_in_ms` - timeout for write requests 5) `auth` - optional, if you want BaseAuth for server 1) `user` - username 2) `pass` - password 2) `storage` - storage settings 1) `ttl_in_seconds` - default TTL for objects 2) `max_collections_count` - max collections count 3) `refresh_time_in_seconds` - refreshing time for collections ## Requests ### 1) POST if you want to create new collection or set objects into collection you should use this request #### Struct: 1) `type` - type of request: 1) use "collection" for creating new collection 2) use "object" for setting object into collection 2) `collection` - optional, name of collection which you want to create or where you want to set object. If field is empty, object will set into `default` collection 3) `objects` - map [`key`] `object` settings, leave empty if you want to add new collection 1) `key` - key for setting object into collection. 2) `object` - object settings. 4) `objects_without_keys` - array of objects settings. Service generate new keys and return in response. > request should have `objects` OR/AND `objects_without_keys` #### Struct of object settings 1) `data` - binary object data 2) `timeout` - object TTL 3) `deadline` - object will expire in deadline 4) `timeless` - object will never expire > Don't use options together, priority of options is timeout -> deadline -> timeless > If options is empty, object TTL will be default. ### 2) GET if you want to get collection or objects you should use this request #### Struct: 1) `type` - type of request: 1) use "collection" for get all objects from collection 2) use "object" for get object from collection 2) `collection` - optional, name of collection. If field is empty, objects will get from `default` collection 3) `keys` - optional, keys for getting objects from collection. If you want to get collection just leave empty. ### 2) DELETE if you want to delete collection or objects you should use this request #### Struct: 1) `type` - type of request: 1) use "collection" for delete collection 2) use "object" for delete object from collection 2) `collection` - name of collection. If field is empty, object will delete from `default` collection 3) `keys` - optional, keys for delete objects from collection. If you want to delete collection just leave empty. > Don't request to delete default collection. ## Response All request has one struct of response ### Struct: 1) `data` - binary data 1) for `POST` request - key of added object 2) for `GET` request - object data 2) `success` - is request successful 3) `error` - is request has some error 1) `message` - error message of details 2) `code` - http code > For POST/GET/DELETE objects requests response will be array of responses ## Client simple client (not fully functional) >See example of using client in client/example ## Tests Project has integration tests and unit tests for `storage`, `object`, `config` packages > All tests - PASS ## TODO or what can be added in future updates 1) Add metrics like Prometheus for analysis how well the service works 2) Add refreshing objects (object should refresh his data after it expire) 3) Something else...
=== JGit (((jgit)))(((Java))) Če želite uporabljati Git znotraj programa Java, je na voljo lastnosti polna knjižnica Git imenovana JGit. JGit je relativno lastnosti polna implementacija Gita napisanega izvorno v Javi in je široko uporabljena v skupnosti Java. Projekt JGit je pod okriljem Eclipse in njegov dom je moč najti na https://www.eclipse.org/jgit/[^]. ==== Nastavitve Na voljo je število načinov za povezavo vašega projekta z JGit in začetkov pisanja kode z njim. Verjetno najenostavnejši je uporaba Mavena -- integracija je dosežena z dodajanjem sledečih odrezkov znački `<dependencies>` v vaši datoteki `pom.xml`: [source,xml] ---- <dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>3.5.0.201409260305-r</version> </dependency> ---- `version` se bo sčasoma najverjetneje povečala, ko to berete; preverite https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit[^] za posodobljene informacije repozitorija. Ko je to enkrat narejeno, bo Maven avtomatično zahteval in uporabljal knjižnice JGit, ki jih boste potrebovali. Če bi raje upravljali binarne odvisnosti sami, so vnaprej zgrajene zagonske datoteke JGit na voljo na https://www.eclipse.org/jgit/download[^]. Vgradite jih lahko v svoj projekt z naslednjim pogonom ukaza: [source,console] ---- $ javac -cp .:org.eclipse.jgit-3.5.0.201409260305-r.jar App.java $ java -cp .:org.eclipse.jgit-3.5.0.201409260305-r.jar App ---- ==== Napeljava JGit ima dva osnovna nivoja API-ja: napeljavo in keramiko. Terminologija za to dvoje prihaja iz samega Gita in JGit je v grobem razdeljen na iste vrste področij: API-ji keramike so prijazno ospredje za pogoste akcije na nivoju uporabnika (vrsta stvari, ki bi jih običajni uporabnik uporabil za orodje ukazne vrstice Git), medtem ko so API-ji napeljave namenjeni neposredni interakciji z objekti repozitorija nižjega nivoja. Začetna točka za večino sej JGit je razred `Repository` in prva stvar, ki jo boste želeli narediti, je ustvariti instanco iz njega. Za repozitorij na osnovi datotečnega sistema (da, JGit omogoča ostale modele shranjevanja) je to urejeno z uporabo `FileRepositoryBuilder`: [source,java] ---- // Create a new repository Repository newlyCreatedRepo = FileRepositoryBuilder.create( new File("/tmp/new_repo/.git")); newlyCreatedRepo.create(); // Open an existing repository Repository existingRepo = new FileRepositoryBuilder() .setGitDir(new File("my_repo/.git")) .build(); ---- Graditelj ima učinkovit API za ponujanje vseh stvari, ki jih potrebuje, da najde repozitorij Git, če vaš program točno ve ali pa ne, kje je lociran. Uporablja lahko spremenljivke okolja (`.readEnvironment()`), začne iz mesta v delovnem direktoriju in išče (`.setWorkTree(…).findGitDir()`), ali pa samo odpre znani direktorij `.git` kot zgoraj. Ko imate enkrat instanco `Repository`, lahko z njo naredite vse vrste stvari. Tu je hiter primer: [source,java] ---- // Get a reference Ref master = repo.getRef("master"); // Get the object the reference points to ObjectId masterTip = master.getObjectId(); // Rev-parse ObjectId obj = repo.resolve("HEAD^{tree}"); // Load raw object contents ObjectLoader loader = repo.open(masterTip); loader.copyTo(System.out); // Create a branch RefUpdate createBranch1 = repo.updateRef("refs/heads/branch1"); createBranch1.setNewObjectId(masterTip); createBranch1.update(); // Delete a branch RefUpdate deleteBranch1 = repo.updateRef("refs/heads/branch1"); deleteBranch1.setForceUpdate(true); deleteBranch1.delete(); // Config Config cfg = repo.getConfig(); String name = cfg.getString("user", null, "name"); ---- Tu se dogaja kar veliko, torej pojdimo skozi razdelke po enega na enkrat. Prva vrstica dobi kazalec na referenco `master`. JGit avtomatično vzame _dejanski_ ref `master`, ki domuje v `refs/heads/master` in vrne objekt, ki vam omogoča pridobiti informacije o referenci. Dobite lahko ime (`getName()`) in bodisi tarčo objekta neposredne reference (`.getObjectId()`) ali pa referenco, ki kaže na simbolični ref (`.getTarget()`). Objekti ref so uporabljeni tudi, da predstavljajo reference oznak in objektov, tako da lahko vprašate, če je oznaka »olupljena« (angl. _peeled_), kar pomeni, da kaže na končno tarčo (potencialno dolgega) niza objektov oznake. Druga vrstica dobi tarčo reference `master`, ki je vrnjena kot instanca ObjectId. ObjectId predstavlja zgoščeno vrednost SHA-1 objekta, ki lahko obstaja ali pa ne v objektni podatkovni bazi Git. Tretja vrstica je podobna, vendar prikazuje, kako JGit upravlja s sintakso rev-parse (za več o tem, glejte razdelek <<ch07-git-tools#_branch_references>>); lahko podate katerokoli določilo objekta, ki ga Git razume, in JGit bo vrnil veljavni ObjectId za ta objekt ali pa `null`. Naslednji dve vrstici prikazujeta, kako naložiti golo vsebino objekta. V tem primeru kličemo `ObjectLoader.copyTo()`, da pretoči vsebine objekta neposredno v stdout, vendar ObjectLoader ima tudi metode za pisanje tipa in velikosti objekta, kot tudi vrne bajtno polje. Za velike objekte (kjer `.isLarge()` vrne `true`), lahko kličete `.openStream()`, da dobite InputStreamu podoben objekt, ki lahko prebere surovi objekt podatkov, ne da povleče vse naenkrat v spomin. Naslednjih nekaj vrstic prikazuje, kaj vzame, da ustvari novo vejo. Ustvarimo instanco RefUpdate, nastavimo nekaj parametrov in kličemo `.update()`, da sprožimo spremembo. Neposredno temu kar sledi, je koda za izbris te iste veje. Pomnite, da je `.setForceUpdate(true)` obvezen, da to deluje; drugače bo `.delete()` klic vrnil `REJECTED` in nič se ne bo zgodilo. Zadnji primer prikazuje, kako pridobiti vrednost `user.name` iz nastavitvenih datotek Git. Instanca Config uporablja repozitorij, ki smo ga prej odprli za lokalne nastavitve, vendar bo avtomatično odkril globalne in sistemske nastavitvene datoteke in prebral vrednosti tudi iz njih. To je samo majhen primer celotnega API-ja napeljave; na voljo je veliko več metod in razredov. Kar tu ni prikazano, je tudi način, kako JGit upravlja z napakami, kar je z uporabo izjem. API-ji JGita včasih vržejo standardne izjeme Java (kot je `IOException`), vendar je ponujena cela množica določenih tipov izjem JGIT (kot so `NoRemoteRepositoryException`, `CorruptObjectException` in `NoMergeBaseException`). ==== Keramika API-ji napeljave so nekoliko zaključeni, vendar jih je lahko težavno nizati skupaj, da se dosežejo skupni cilji, kot je dodajanje datoteke indeksu ali ustvarjanje nove potrditve. JGit ponuja skupek višje nivojskih API-jev, da vam pri tem pomaga, in vnosna točka tem API-jem je razred `Git`: [source,java] ---- Repository repo; // construct repo... Git git = new Git(repo); ---- Razred Git ima lep skupek visoko nivojskih metod v stilu _gradnje_, ki so lahko uporabljene za konstrukcijo nekega lepega kompleksnega obnašanja. Poglejmo primer -- narediti nekaj, kot je `git ls-remote`: [source,java] ---- CredentialsProvider cp = new UsernamePasswordCredentialsProvider("username", "p4ssw0rd"); Collection<Ref> remoteRefs = git.lsRemote() .setCredentialsProvider(cp) .setRemote("origin") .setTags(true) .setHeads(false) .call(); for (Ref ref : remoteRefs) { System.out.println(ref.getName() + " -> " + ref.getObjectId().name()); } ---- To je pogosti vzorec z razredom Git; metode vrnejo objekt ukaza, ki vam omogoča verižiti klice metod, da nastavijo parametre, ki so izvedeni, ko kličete `.call()`. V tem primeru sprašujemo daljavo `origin` za oznake, vendar ne pa za glave. Bodite pozorni tudi na uporabo objekta za overjanje `CredentialsProvider`. Mnogi ostali ukazi so na voljo preko razreda Git, vključno z `add`, `blame`, `commit`, `clean`, `push`, `rebase`, `revert` in `reset`, vendar niso omejeni le na te. ==== Nadaljnje branje To je samo majhen primer JGitove polne zmožnosti. Če vas zanima in želite izvedeti več, poglejte tu za informacije in navdih: * Uradna dokumentacija JGit API je na voljo na spletu na https://www.eclipse.org/jgit/documentation[^]. To so standardni Javadoc, tako da jih bo vaš priljubljeni JVM IDE tudi zmožen namestiti lokalno. * Knjiga receptov JGit na https://github.com/centic9/jgit-cookbook[^] ima mnoge primere, kako narediti določena opravila z JGitom.
import * as React from "react" import { State, pushNotification, NOTIFICATION_SUCCESS, NOTIFICATION_ERROR, NOTIFICATION_WARNING } from "../../store" import { connect } from "react-redux" import { trxPlaceBidMarket } from "../../utils/eos" import Modal from "../shared/Modal" import { MonsterProps } from "../monsters/monsters" interface Props { closeModal: (doUpdate: boolean) => void, scatter: any, dispatchPushNotification: any, monsters: MonsterProps[], initialName?: string, initialMonster?: MonsterProps, initialAmount?: number } interface ReactState { monstername: string, amount: number, monster: MonsterProps | undefined } /** * Bid is Off for now due to monsters autocomplete. * no way to select all monsters in memory? demux to the rescue */ class NewBidModal extends React.Component<Props, {}> { public state: ReactState = { monstername: this.props.initialMonster ? this.props.initialMonster.name: "", amount: this.props.initialAmount ? this.props.initialAmount : 0, monster: this.props.initialMonster } public render() { const { closeModal, monsters } = this.props const { monstername, amount, monster } = this.state const footerButtons = [ <button key="submit" className="button is-success" onClick={this.createBid}> Submit </button>, <button key="cancel" className="button is-light" onClick={() => closeModal(false)}> Cancel </button> ] const title = this.props.initialMonster ? "Update Bid" : "Create a New Bid" return ( <Modal title={title} close={() => closeModal(false)} footerButtons={footerButtons}> <div> <div className="field"> <label className="label is-large">Monster Name</label> <div className="control has-icons-left has-icons-right"> <datalist id="mymonsters"> {monsters.map((m) => <option key={m.name} value={m.name} /> )} </datalist> <input className="input is-large" placeholder="Bubble" type="text" list="mymonsters" onChange={this.handleChangeMonster} value={monstername} /> <span className="icon is-left"> <i className="fa fa-paw" /> </span> {monster && <span className="label"> #{monster.id} </span>} </div> </div> <div className="field"> <label className="label is-large">Value in EOS</label> <div className="control has-icons-left has-icons-right"> <input className="input is-large" placeholder="0.0000" type="number" min="0.0000" step="0.0001" onChange={this.handleChangeValue} value={amount / 10000.0}/> <span className="icon is-left"> <i className="fa fa-money" /> </span> </div> </div> </div> </Modal> ) } private handleChangeMonster = (event: any) => { const monsterName = event.target.value const {dispatchPushNotification, monsters} = this.props const monstersWithName = monsters.filter((monster:MonsterProps) => monster.name === monsterName) if (monstersWithName.length > 0) { if (monstersWithName.length > 1) { dispatchPushNotification(`More than one monster found with this name. Using the first one`, NOTIFICATION_WARNING) } // tslint:disable-next-line:no-console console.log("monsters found:" + monstersWithName) this.setState({monstername:monsterName, monster: monstersWithName[0]}) } else { this.setState({monstername:monsterName, monster: undefined}) } } private handleChangeValue = (event: any) => { if (event.target.value) { this.setState({amount: Math.floor(event.target.value * 10000.0)}) } } private createBid = () => { const { scatter, closeModal, dispatchPushNotification } = this.props const { amount, monster } = this.state if (!monster) { return dispatchPushNotification(`Monster is required to make a bid`, NOTIFICATION_ERROR) } if (amount && amount < 0 ) { return dispatchPushNotification(`Invalid amount for offer`, NOTIFICATION_ERROR) } trxPlaceBidMarket(scatter, monster.id, amount) .then((res: any) => { console.info(`Bid for pet ${monster.id} was created successfully`, res) dispatchPushNotification(`Bid for ${monster.name} was created successfully`, NOTIFICATION_SUCCESS) closeModal(true) }).catch((err: any) => { dispatchPushNotification(`Fail to place a bid for ${monster.name} ${err.eosError}`, NOTIFICATION_ERROR) }) } } const mapStateToProps = (state: State) => { // const eosAccount = getEosAccount(state.scatter.identity) return { scatter: state.scatter, monsters: state.myMonsters // state.monsters.filter((m:MonsterProps) => m.owner !== eosAccount) } } const mapDispatchToProps = { dispatchPushNotification: pushNotification } export default connect(mapStateToProps, mapDispatchToProps)(NewBidModal)
/** * Name: MStop * Description: defines the MStop species and its related constantes, variables, and methods. * A MStop agent represents a location where buses can take or drop off people. * Authors: Laatabi * For the i-Maroc project. */ model MStop import "MLine.gaml" import "PDUZone.gaml" import "Individual.gaml" global { float STOP_NEIGHBORING_DISTANCE <- 400#m; list<MStop> first_intersecting_stops (list<MStop> li1, list<MStop> li2) { if empty(li1) or empty(li2) { return []; } list<MStop> lisa <- []; bool sstop <- false; loop elem1 over: li1 { list<MStop> inters <- elem1.stop_neighbors inter li2; if !empty(inters) { if length(inters) = 1 and first(inters) = elem1{ lisa <<+ elem1.stop_neighbors; } else { lisa <<+ elem1.stop_neighbors inter (li2 closest_to elem1).stop_neighbors; } sstop <- true; } if sstop { break; } } return remove_duplicates(lisa); } list<MStop> closest_stops (list<MStop> li1, list<MStop> li2) { if empty(li1) or empty(li2) { return []; } MStop stop1; MStop stop2; MStop clos; float min_dist <- #max_float; float ddst; loop stp over: li1 { if li2 contains stp { clos <- stp; ddst <- 0.0; } else { clos <- li2 closest_to stp; ddst <- stp distance_to clos; } if ddst < min_dist { min_dist <- ddst; stop1 <- stp; stop2 <- clos; } } return [stop1,stop2]; } } /*******************************/ /******* BusStop Species ******/ /*****************************/ species MStop schedules: [] parallel: true { int stop_id; string stop_name; PDUZone stop_zone; list<Individual> stop_waiting_people <- []; list<Individual> stop_transited_people <- []; list<Individual> stop_arrived_people <- []; list<MStop> stop_neighbors <- []; // list of line/direction that pass by the stop list<pair<MLine,int>> stop_lines <- []; // for each stop, the taxi lines (+direction) that an Individual can take + closest line on the taxiline to the stop list<pair<TaxiLine,int>> stop_connected_taxi_lines <- []; map<pair<MLine,int>,float> stop_last_vehicle_depart_time <-[]; bool stop_is_busy <- false; // if a vehicle is taking/dropping individuals at a stop, make it busy to prevent other vehicles from working //list<MVehicle> stop_current_stopping_vehicles <- []; } species BusStop parent: MStop { geometry shape <- circle(40#meter); aspect default { draw circle(40#meter) color: #gamablue; draw circle(20#meter) color: #white; } } species BRTStop parent: MStop { geometry shape <- circle(40#meter); aspect default { draw circle(40#meter) color: #darkred; draw circle(20#meter) color: #white; } } species TaxiStop parent: MStop{ geometry shape <- circle(40#meter); aspect default { draw circle(40#meter) color: #darkorange; draw circle(20#meter) color: #white; } } /*** end of species definition ***/
package lot.flightmanager; import lot.flightmanager.Models.Passenger; import lot.flightmanager.Models.PassengerRepository; import lot.flightmanager.Models.Status; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.test.annotation.Rollback; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @Rollback(value = false) public class PassengerRepositoryTests { @Autowired private PassengerRepository repo; @Test public void testAddNew() { Passenger passenger = new Passenger(); passenger.setName("John"); passenger.setSurname("Doe"); passenger.setPhone(123456789); passenger.setStatus(Status.NORMAL); Passenger savedPassenger = repo.save(passenger); assertThat(savedPassenger).isNotNull(); assertThat(savedPassenger.getId_Passenger()).isGreaterThan(0); } @Test public void testListAll() { List<Passenger> passengers = repo.findAll(); assertThat(passengers).isNotEmpty(); for (Passenger p : passengers) { System.out.println(p); } } @Test public void testUpdate() { Integer idPassenger = 1; // assuming this is a valid passenger ID Optional<Passenger> optionalPassenger = repo.findById(idPassenger); if (optionalPassenger.isPresent()) { Passenger passenger = optionalPassenger.get(); passenger.setStatus(Status.GOLD); Passenger updatedPassenger = repo.save(passenger); assertThat(updatedPassenger).isNotNull(); assertThat(updatedPassenger.getStatus()).isEqualTo(Status.GOLD); } else { throw new AssertionError("Passenger not found with id: " + idPassenger); } } @Test public void testDelete() { Integer idPassenger = 1; // assuming this is a valid passenger ID repo.deleteById(idPassenger); Optional<Passenger> optionalPassenger = repo.findById(idPassenger); assertThat(optionalPassenger).isNotPresent(); } }
import React, { useState } from "react"; import { useDispatch } from "react-redux"; import { addTodo } from "../features/todo/operation"; function AddTodo() { const dispatch = useDispatch(); const [Todo, setTodo] = useState({ sub: "", body: "" }); const onChange = (e) => { setTodo({ ...Todo, [e.target.name]: e.target.value }); }; const addTodoHandler = (e) => { e.preventDefault(); dispatch(addTodo(Todo)); setTodo({ sub: "", body: "" }); }; return ( <div className="container"> <h1 className="my-3">Create a Todo</h1> <form onSubmit={addTodoHandler} className="space-x-3 mt-12 border p-3 rounded card shadow"> <div class="form-group"> <label for="exampleInputEmail1">Todo Subject</label> <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter a Subject of Todo" name="sub" onChange={onChange} value={Todo.sub} /> </div> <div class="form-group"> <label for="exampleInputPassword1">Todo Body</label> <input type="text" class="form-control" id="exampleInputPassword1" placeholder="Enter a Body of Todo" name="body" onChange={onChange} value={Todo.body} /> </div> <button type="submit" class="btn btn-primary mt-3" disabled={Todo.body.length < 3 || Todo.sub.length < 3} > Add Todo </button> </form> </div> ); } export default AddTodo;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.initModels = exports.Restaurant = void 0; const sequelize_1 = require("sequelize"); class Restaurant extends sequelize_1.Model { } exports.Restaurant = Restaurant; const initModels = (sequelize) => { Restaurant.init({ id: { type: sequelize_1.DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, }, name: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, logo: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, address: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, longitude: { type: sequelize_1.DataTypes.FLOAT, allowNull: false, }, latitude: { type: sequelize_1.DataTypes.FLOAT, allowNull: false, }, type: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, rating: { type: sequelize_1.DataTypes.FLOAT, allowNull: false, }, reviews: { type: sequelize_1.DataTypes.INTEGER, allowNull: false, }, phone: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, email: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, facebookMobile: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, facebookWeb: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, InstagramMobile: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, InstagramWeb: { type: sequelize_1.DataTypes.STRING, allowNull: false, }, }, { sequelize, tableName: 'restaurants', timestamps: true, underscored: true, }); return { Restaurant, }; }; exports.initModels = initModels; // import { Sequelize, Model, DataTypes, Optional } from 'sequelize'; // interface RestaurantAttributes { // id: number; // name: string; // description: string; // imageUrl: string; // } // interface RestaurantCreationAttributes extends Optional<RestaurantAttributes, 'id'> {} // class Restaurant extends Model<RestaurantAttributes, RestaurantCreationAttributes> implements RestaurantAttributes { // public id!: number; // public name!: string; // public description!: string; // public imageUrl!: string; // public readonly createdAt!: Date; // public readonly updatedAt!: Date; // } // export function initRestaurantModel(sequelize: Sequelize): void { // Restaurant.init( // { // id: { // type: DataTypes.INTEGER.UNSIGNED, // autoIncrement: true, // primaryKey: true, // }, // name: { // type: DataTypes.STRING(128), // allowNull: false, // }, // description: { // type: DataTypes.TEXT, // allowNull: true, // }, // imageUrl: { // type: DataTypes.STRING(255), // allowNull: true, // }, // }, // { // tableName: 'restaurant', // sequelize, // timestamps: true, // }, // ); // } // export default Restaurant;
#include <iostream> using namespace std; class Player { int x, y; public: Player() { x = 0; y = 0; } Player(int xx, int yy) { cout << "Parametric Constructor!" << endl; x = xx; y = yy; } void setx(int xx) { x = xx; } int getX() const { return x; } void setY(int yy) { y = yy; } int getY() const { return y; } ~Player() { cout << x << " " << "Destroyed!" << endl; } Player(const Player &obj) { cout << "Copy Constructor!" << endl; x = obj.x; y = obj.y; } void init() { x = 0; y = 0; } void print() const { cout << x << " " << y << endl; } }; void print(const Player &obj) { obj.print(); // cout << obj.getX() << " " << obj.getY() << endl; } int main() { const Player p1(2, 3), p2(p1); // p1 = p2; // No Copy Constructor bcz p1 and p2 are already made // p1.init(); // p1.print(); // p1.~Player(); // p1.print(); // p1.setx(10); // p1.print(); // print(p1); // global function // p1.print(); // p1.print(&p1); // matlb k andar kuch ni hota to to LHS ka reference hi hota hy jo this catch krta hy // Player* ptr1 = &p1; int x = 10; int *ptr = &x; cout << x << endl; cout << &x << endl; cout << ptr << endl; // ptr mn x ka address hy (ptr = *x) cout << *ptr << endl; // *ptr mn x ki value hy means dereferencing (*ptr = x) cout << &ptr << endl; // &ptr mn ptr ka apna address hy // x = 20; // *ptr = 20; return 0; }
#! /usr/bin/python # -*- coding: utf-8 -*- """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Title: loop Author: David Leclerc Version: 0.2 Date: 29.10.2018 License: GNU General Public License, Version 3 (http://www.gnu.org/licenses/gpl.html) Overview: ... Notes: ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # LIBRARIES import datetime import traceback import numpy as np import matplotlib.pyplot as plt # USER LIBRARIES import lib import fmt import errors import logger import reporter import exporter import uploader import calculator import idc from CGM import cgm from Stick import stick from Pump import pump from Profiles import bg, basal, net, isf, csf, iob, cob, targets # Define instances Logger = logger.Logger("loop") Exporter = exporter.Exporter() Uploader = uploader.Uploader() # CLASSES class Loop(object): def __init__(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INIT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Initialize start/end times self.t0 = None self.t1 = None # Give the loop devices self.stick = stick.Stick() self.cgm = cgm.CGM() self.pump = pump.Pump(self.stick) # Initialize profile dict self.profiles = {} # Initialize TB recommendation self.recommendation = None # Define report self.report = None def do(self, task, branch, *args): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Execute a task and increment its corresponding branch in the loop logs, in order to keep track of loop's performance. """ # Do task task(*args) # Update loop log self.report.increment(branch) self.report.store() def tryAndCatch(self, task, *args): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TRYANDCATCH ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Try to execute a given task and give back trace, in case it fails, as well as boolean indicating whether the execution was successful or not. """ # Try task try: task(*args) return True # Ignore all errors, but log them except: Logger.error("\n" + traceback.format_exc()) return False def start(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ START ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The loop is only considered started after the devices have been initialized and are ready to receive orders. """ # Info Logger.info("Started loop.") # Define starting time self.t0 = datetime.datetime.now() # Get current day today = self.t0.date() # Get report self.report = reporter.getReportByType(reporter.LoopReport, today, strict = False) # Update loop stats self.report.set(lib.formatTime(self.t0), ["Loop", "Last Time"], True) self.report.increment(["Loop", "Start"]) self.report.store() def stop(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STOP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Define ending time self.t1 = datetime.datetime.now() # Get loop duration duration = (self.t1 - self.t0).seconds # Update loop stats self.report.set(duration, ["Loop", "Last Duration"], True) self.report.increment(["Loop", "End"]) self.report.store() # Info Logger.info("Ended loop.") def readCGM(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ READCGM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Read BGs (last 24 hours) self.do(self.cgm.dumpBG, ["CGM", "BG"], 10) # Read battery self.do(self.cgm.battery.read, ["CGM", "Battery"]) # Read sensor events self.do(self.cgm.databases["Sensor"].read, ["CGM", "Sensor"]) def readPump(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ READPUMP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Read battery level self.do(self.pump.battery.read, ["Pump", "Battery"]) # Read remaining amount of insulin self.do(self.pump.reservoir.read, ["Pump", "Reservoir"]) # Read pump settings self.do(self.pump.settings.read, ["Pump", "Settings"]) # Read ISF self.do(self.pump.ISF.read, ["Pump", "ISF"]) # Read CSF self.do(self.pump.CSF.read, ["Pump", "CSF"]) # Read BG targets self.do(self.pump.BGTargets.read, ["Pump", "BG Targets"]) # Read basal self.do(self.pump.basal.read, ["Pump", "Basal"], "Standard") # Update history self.do(self.pump.history.update, ["Pump", "History"]) def buildProfiles(self, now, dt = 5.0 / 60.0): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BUILDPROFILES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ dt: step size """ # Get DIA DIA = reporter.getPumpReport().get(["Settings", "DIA"]) # Define PIA (peak of insulin action) PIA = 1.25 # Define past/future reference times past = now - datetime.timedelta(hours = DIA) future = now + datetime.timedelta(hours = DIA) # Instanciate profiles self.profiles = {"IDC": idc.ExponentialIDC(DIA, PIA), "Basal": basal.Basal(), "Net": net.Net(), "BGTargets": targets.BGTargets(), "FutureISF": isf.FutureISF(), "FutureCSF": csf.FutureCSF(), "PastIOB": iob.PastIOB(), "FutureIOB": iob.FutureIOB(), "PastBG": bg.PastBG(), "FutureBG": bg.FutureBG()} # Build net insulin profile self.profiles["Net"].build(past, now) # Build past profiles self.profiles["Basal"].build(past, now) self.profiles["PastIOB"].build(past, now) self.profiles["PastBG"].build(past, now) # Build daily profiles self.profiles["BGTargets"].build(now, future) self.profiles["FutureISF"].build(now, future) #self.profiles["FutureCSF"].build(now, future) # Build future profiles self.profiles["FutureIOB"].build( self.profiles["Net"], self.profiles["IDC"], dt) self.profiles["FutureBG"].build( self.profiles["PastBG"], self.profiles["Net"], self.profiles["IDC"], self.profiles["FutureISF"], dt) def computeTB(self, now): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ COMPUTETB ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Build profiles self.buildProfiles(now) # Get current IOB IOB = self.profiles["FutureIOB"].y[0] # Compute BG dynamics BGDynamics = calculator.computeBGDynamics( self.profiles["PastBG"], self.profiles["FutureBG"], self.profiles["BGTargets"], self.profiles["FutureIOB"], self.profiles["FutureISF"]) # Store TB recommendation self.recommendation = calculator.recommendTB( BGDynamics, self.profiles["Basal"], self.profiles["FutureISF"], self.profiles["IDC"], IOB) def enactTB(self, TB): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ENACTTB ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # If no TB is required if TB is None: # Get current TB self.pump.TB.read() # If TB currently set: cancel it if self.pump.TB.value["Duration"] != 0: self.do(self.pump.TB.cancel, ["Pump", "TB"]) # Otherwise, enact TB recommendation else: self.do(self.pump.TB.set, ["Pump", "TB"], TB) # Re-update history self.pump.history.update() def export(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EXPORT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Export preprocessed treatments self.do(Exporter.run, ["Loop", "Export"], self.t0) # Upload stuff self.do(Uploader.run, ["Loop", "Upload"]) def plot(self, now): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PLOT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Build profiles self.buildProfiles(now) # Profiles defined? if self.profiles: # Prepare plot lib.initPlot() # Build graph 1 (basals) self.profiles["Basal"].plot(1, [4, 1], False, None, "purple") self.profiles["Net"].plot(1, [4, 1], False, "Basals", "orange") # Build graph 2 (ISFs) self.profiles["FutureISF"].plot(2, [4, 1], False, "ISFs", "red") # Build graph 3 (IOBs) self.profiles["PastIOB"].plot(3, [4, 1], False, None, "#99e500") self.profiles["FutureIOB"].plot(3, [4, 1], False, "IOBs") # Build graph 4 (BGs) self.profiles["PastBG"].plot(4, [4, 1], False, None, "pink") self.profiles["FutureBG"].plot(4, [4, 1], True, "BGs") def run(self): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RUN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ # Start isStarted = {"Loop": self.tryAndCatch(self.start), "Stick": self.tryAndCatch(self.stick.start), "CGM": self.tryAndCatch(self.cgm.start), "Pump": self.tryAndCatch(self.pump.start)} # Read isRead = {"CGM": isStarted["CGM"] and self.tryAndCatch(self.readCGM), "Pump": isStarted["Pump"] and self.tryAndCatch(self.readPump)} # BG data is always necessary if isRead["CGM"]: # If pump was successfully read if isRead["Pump"]: # Compute and enact necessary TB if self.tryAndCatch(self.computeTB, self.t0): self.tryAndCatch(self.enactTB, self.recommendation) # Export recent treatments self.tryAndCatch(self.export) # Stop isStopped = {"Pump": self.tryAndCatch(self.pump.stop), "CGM": self.tryAndCatch(self.cgm.stop), "Stick": self.tryAndCatch(self.stick.stop), "Loop": self.tryAndCatch(self.stop)} def main(): """ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~­ """ # Get current time now = datetime.datetime.now() # Instanciate a loop loop = Loop() # Loop loop.run() # Plot #loop.plot(now) # Run this when script is called from terminal if __name__ == "__main__": main()
// 对于 axios进行二次封装 import axios from "axios"; //引入nprogress 进度条 import nprogress from "nprogress"; // //引入进度条样式 import 'nprogress/nprogress.css' //start 进度条开始 done 进度条结束 //1:利用axios对象的方法create,去创建一个axios实例 //2:request 就是axios 只不过稍微配置一下 const requests = axios.create({ //配置对象 //基础路径,发请求的时候。路径当前会出现api baseURL:'/mock', //代表请求超时时间5秒 timeouts:5000, }); //请求拦截器:在发请求之前。请求拦截器可以检测到。可以在请求发出去前做一些事情 requests.interceptors.request.use((config)=>{ nprogress.start();//进度条开始动 return config;//config:配置对象。对象里面有一个属性很重要,headers请求头 }) //响应拦截器 requests.interceptors.response.use((res)=>{ nprogress.done();//进度条结束 return res.data;//成功的回调函数:服务器相应数据回来以后,响应式拦截器可以检测到,可以做一些事情 }),(error)=>{ //响应失败的回调函数 return Promise.reject(new error('faile')); }; //对外暴露 export default requests;
import React, { useState } from 'react' import '../header/header.css' import { FaShoppingCart } from 'react-icons/fa' import Order from '../order/Order' const showOrders = (props) => { let summa = 0 props.orders.forEach(el => summa += Number.parseFloat(el.price)) return(<div> {props.orders.map(el => ( <Order onDelete={props.onDelete} key={el.id} item={el}/> ))} <p className='summa'>Sum: {new Intl.NumberFormat().format(summa)}$</p> </div>) } const showNothing = () => { return(<div className='empty'><h2>No items</h2></div>) } export default function Header(props) { let [cartOpen, setCartOpen] = useState(false) return ( <header> <div> <span className="logo">House Staff</span> <ul className="nav"> <li>About us</li> <li>Contacts</li> <li>Cabinet</li> </ul> <FaShoppingCart onClick={() => setCartOpen(cartOpen = !cartOpen)} className={`shop-cart-button ${cartOpen && 'active'}`}/> {cartOpen && ( <div className='shop-cart'> {props.orders.length > 0 ? showOrders(props) : showNothing()} </div> )} </div> <div className="presentation"></div> </header> ) }
<!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"> <meta name="description" content=""> <meta name="author" content=""> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Bootstrap Core CSS --> <link href="modern-business/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="modern-business/css/modern-business.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="modern-business/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <!-- Scripts --> <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?> </script> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Banco Amigo</a> </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 navbar-right"> <li> <a href="{{url('/')}}">Inicio</a> </li> <li> <a href="{{url('/service')}}">Servicios</a> </li> <li> <a href="{{url('/contact')}}">Contactanos</a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Banca por Internet <b class="caret"></b></a> <ul class="dropdown-menu"> @if (Auth::guest()) <li><a href="{{url('/login')}}">Ingresar</a></li> <li><a href="{{url('/register')}}">Crear Cuenta</a></li> @else <li><a href="{{url('/home')}}">Panel Principal</a></li> <li> <a href="{{ url('/logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Cerrar Sesión </a> <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </li> @endif </ul> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> @yield('carousel') <!-- Page Content --> <div class="container"> @yield('marketing') <hr> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <p>Copyright &copy; Banco Amigo 2017</p> </div> </div> </footer> </div> <!-- /.container --> <!-- jQuery --> <script src="modern-business/js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="modern-business/js/bootstrap.min.js"></script> <!-- Script to Activate the Carousel --> <script> $('.carousel').carousel({ interval: 5000 //changes the speed }) </script> </body> </html>
*this is the fourth entry in an n-part [series explaining the compilation techniques of Clojure](http://blog.fogus.me/tag/clj-compilation). translations: [[日本語](http://ykomatsu.akaumigame.org/compiling-clojure-to-javascript-pt-3-the-himera-model-ja.html)]* When [ClojureScript](http://github.com/clojure/clojurescript) was first announced there was much gnashing of teeth over the fact that it provided neither `eval`, nor runtime macros. In response, I did [tackle the matter of `eval`](http://blog.fogus.me/2011/07/29/compiling-clojure-to-javascript-pt-2-why-no-eval/), but code speaks louder than words, so I therefore present [Himera](http://github.com/fogus/himera), a ClojureScript compilation web-service. I have a deployment of [Himera on Heroku](http://himera.herokuapp.com/index.html) (shown below -- caveat emptor) if you'd like to play with it. Additionally, the [Himera source code is available on Github](http://github.com/fogus/himera). <a href="http://himera.herokuapp.com/index.html"> ![himera-ws](http://farm8.staticflickr.com/7188/6874829058_0694d746c4_d.jpg "Click to visit Himera") </a> ## What Himera is Himera[^band] (Russian: Химера, pronounced Hee-mera with a trill) is an experiment in slicing and dicing the typical REPL model of Lisp computation, providing a modularized web service for ClojureScript compilation. [^band]: Химера was a Russian band that I liked very much as a younger man. ## REPL Lisps, and Clojure is no exception, provide a unique programming experience via the REPL. The canonical representation of the REPL described as source is summarized simply as: (loop (print (eval (read)))) You've probably seen this contrivance, but what exactly does it mean? The diagram below is a graphical representation of the same idea: ![repl-vanilla](http://farm8.staticflickr.com/7272/6872246852_6e1f3775b8_n_d.jpg "REPL 10000ft") That is, a REPL is a composition of three repeating functions: `read`, `eval`, and `print`. The read step takes a string (or maybe an input buffer) and produces a Lisp data structure representing the program in hand[^ast-not]. This data structure is then fed into the `eval` function and executed as a program. Finally, the result of the evaluation step (another Lisp data structure) is printed to the user. [^ast-not]: A popular view of a Lisp program is that its data structure, syntax, and abstract syntax tree are equivalent. The fact of the matter is that these three things are very very different... the subject of a future post. This model of the REPL is highly simplistic, but it serves as representational for most cases. However, because of a lot of historical baggage, the typical conception of this model is often limited to that of a single process, as in the image below: ![repl-1-proc](http://farm8.staticflickr.com/7271/7018375589_3394d31528_n_d.jpg "The REPL as single process") But this is an outmoded ideal, whether it be at a console REPL: ![repl-console](http://farm8.staticflickr.com/7250/6872327792_04a2833c9d_n_d.jpg "REPL in da console") ... a browser: ![repl-browser](http://farm8.staticflickr.com/7109/6872327840_f047cfa2a9_n_d.jpg "REPL in da browser") ... or a phone: ![repl-phone](http://farm8.staticflickr.com/7272/6872328064_9d19f52a10_n_d.jpg "REPL in da iPhone") It simply does not need to be configured in such a way. The very nature of Lisp and its furcated architecture allows many different ways to arrange the components of a REPL. ## An exploded view of the REPL Before I can talk about various ways to slice up the REPL into bits and pieces I should mention that the canonical image above is way too simplistic. Instead, the ClojureScript compiler is modularized along much finer dimensions than the Lispy trinity. Observe the following: ![cljs-compiler-anatomy](http://farm8.staticflickr.com/7280/7018455969_e35f4bfffc_z_d.jpg "ClojureScript's compiler anatomy") The constituent parts of the ClojureScript anatomy are as follows: ### Input Some input device reads a string of characters and feeds it into the reader as a true string datatype or some input buffer. ### Reader The reader consumes the string from the input device and transforms it into a Clojure data structure. In other words, the raw string: "(vector :thx (-> 1138 - str))" Is converted into a Clojure persistent list data structure of three elements: 1) the symbol `vector`, 2) the keyword `:thx`, and 3) another persistent list of three elements a symbol `->`, `1138`, a symbol `-` and another symbol `str`. The source view of this data structure is described in Clojure as: (list 'vector :thx (list '-> 1138 '- 'str)) The result of the Reader is always a Clojure data structure, Java instance, or an error. ### Macro expansion (macro-xp) The raw Clojure data structures produced by the Reader are then processed for macro-expansion to some fixed point (i.e. they are expanded until the input equals the output). In the case of the structure listed above, the macro `->` would be expanded into the following: (vector :thx (str (- 1138))) This is where Clojure's idea of (and Lisp in general) code as data diverges from the syntactic representation. ### Analyzer The analysis phase of ClojureScript compilation builds an abstract syntax tree (AST) that represents the program itself, divorced from syntactic matters. That is, the tree structure defines logical groupings along branches, binding contexts alongs tree depth, etc. This is where Clojure's (and Lisp in general) code as data diverges from its parse form. The analysis phase also marks the end of the the first phase in ClojureScript's 2-phase compilation process. ### Emitter This is where ClojureScript's AST is walked and transformed into JavaScript. This is the beginning and end of the second phase of ClojureScript's 2-phase compilation process. This is also where you would typically deploy your ClojureScript application. However, in the context of a REPL layout, two more elements are missing. ### Eval (or runtime) The JavaScript that is produced by the ClojureScript compiler is evaluated. The original code `(vector :thx (str (- 1138)))` under examination above would result in what in Clojure would look like the following: [:thx "-1138"] However, it would be JavaScript and therefore an instance of `cljs.core.Vector` containing two strings.[^kw-str] [^kw-str]: Keywords in ClojureScript are compiled down to JavaScript strings prefixed with some magic unicode character. ### Print The result of the JavaScript is "printed" via the appropriate means. Taking this exploded view of the ClojureScript compiler to heart, imagine how the traditional REPL model might look differently under various operational constraints. Below I will illustrate a few. ## The Browser-connected REPL Because ClojureScript has neither runtime evaluation nor compilation elements, the [Clojure/core](http://clojure.com) team had to devise a way to provide an agile development experience that Clojure programmers were accustomed to. The initial release of ClojureScript packaged [Rhino](http://www.mozilla.org/rhino/) and used it as the evaluation engine of the emitted JavaScript, however, this was less than optimal for numerous reasons outside of the scope of this post. Eventually, it was decided that the evaluation engine should instead be that of a browser, as shown below: ![bc-repl](http://farm8.staticflickr.com/7051/6873346498_f822daa961_d.jpg "Browser-connected REPL")
import React, { Suspense } from 'react'; import { BrowserRouter, Route, Routes } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; // Create a client const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, retry: 1, staleTime: 10000, }, }, }); const loading = ( <div className="pt-3 text-center"> <div className="sk-spinner sk-spinner-pulse"></div> </div> ); // react lazy 코드 스플리팅 const AppContent = React.lazy(() => import('./components/layouts/app/AppContent')); const App = () => { return ( <QueryClientProvider client={queryClient}> <BrowserRouter> <Suspense fallback={loading}> <Routes> <Route path="*" element={<AppContent />} /> </Routes> <ReactQueryDevtools initialIsOpen={false} position="bottom-left" /> </Suspense> </BrowserRouter> </QueryClientProvider> ); }; export default App;
<?php namespace App\Controller\Front; use App\Entity\User; use App\Entity\UserMessage; use App\Form\UserMessageType; use App\Security\Handler\UserConversationHandlerInterface; use App\Service\Paginator\ConversationPaginator; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Http\Attribute\IsGranted; #[Route('/message-prive', name: 'app_conversation_')] class UserConversationController extends AbstractController { public const MESSAGE_PER_PAGE = 10; #[Route('', name: 'index', methods: ['GET'])] public function index(): Response { return $this->render('front/userConversation/index.html.twig', [ 'controller_name' => 'UserConversationController', ]); } #[Route('/ma-discussion/check', name: 'check', methods: ['GET'])] public function checkUser(): Response { $user = $this->getUser(); if ($user) { return $this->redirectToRoute('app_conversation_chat', [ 'id' => $user->getId(), 'token' => $user->getUserConversation()->getToken(), ]); } return $this->redirectToRoute('app_login'); } #[Route('/ma-discussion/{id}/{token}', name: 'chat', methods: ['GET', 'POST'])] #[IsGranted('ROLE_USER')] #[IsGranted('', subject: 'user')] public function chat( User $user, Request $request, UserConversationHandlerInterface $userConversationHandler, ConversationPaginator $conversationPaginator ): Response { $userMessage = new UserMessage(); $form = $this->createForm(UserMessageType::class, $userMessage); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $userConversationHandler($user, $userMessage); return $this->redirectToRoute('app_conversation_chat', [ 'id' => $user->getId(), 'token' => $user->getUserConversation()->getToken(), ]); } return $this->render('front/userConversation/chat.html.twig', [ 'user' => $user, 'messages' => $conversationPaginator($userMessage, $user, self::MESSAGE_PER_PAGE), 'form' => $form, ]); } }
package org.CCristian.Api_Stream.EJEMPLOS; import org.CCristian.Api_Stream.MODELS.Usuario; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class Ejemplo_Stream_ListToStream { public static void main(String[] args) { List<Usuario> lista_usuarios = new ArrayList<>(); lista_usuarios.add(new Usuario("Andrés","Guzmán")); lista_usuarios.add(new Usuario("Luci","Martínez")); lista_usuarios.add(new Usuario("Pepe","Fernández")); lista_usuarios.add(new Usuario("Cata", "Pérez")); lista_usuarios.add(new Usuario("Lalo","Mena")); lista_usuarios.add(new Usuario("Exequiel","Doe")); lista_usuarios.add(new Usuario("Bruce","Lee")); lista_usuarios.add(new Usuario("Bruce","Willis")); System.out.println("-------------------List<Usuario> lista_usuarios-------------------"); lista_usuarios.forEach(System.out::println); System.out.println("-------------------Stream lista_usuarios (Usuario ---> String)-------------------"); Stream<String> stream_nombres = lista_usuarios.stream() .map(u -> u.getNombre().toUpperCase() .concat(" ").concat(u.getApellido().toUpperCase())) .flatMap(nombre -> { /*Filtrando usando 'flatMap'*/ if (nombre.contains("bruce".toUpperCase())){ return Stream.of(nombre); } return Stream.empty(); }) .map(String::toLowerCase) .peek(u -> System.out.println("peak ---> " + u)); System.out.println("stream_nombres.count() ---> " + stream_nombres.count()); } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.18; import {IStrategy} from "@tokenized-strategy/interfaces/IStrategy.sol"; interface IStrategyInterface is IStrategy { struct Player { bool activated; bool payed; bool couped; } struct TicTacToe { address player1; address player2; uint256 buyIn; address turn; uint8[9] board; } function lendingPool() external view returns (address); function aToken() external view returns (address); function start() external view returns (uint256); function end() external view returns (uint256); function winner() external view returns (address); function players(address) external view returns (Player memory); // List of all players who registerd and payed function playerList(uint256) external view returns (address); // Amount required to buy in. function buyIn() external view returns (uint256); // Storage for Games. function TicTacToeGames(bytes32) external view returns (TicTacToe memory); // Number of players that have couped against // The current managment. function couped() external view returns (uint256); function activateNewPlayer(address _player) external; function winnerWinnerChickenDinner(address _winner) external; function startNewTicTacToeGame( address _player1, address _player2, uint256 _buyIn ) external; function acceptNewTicTacToeGame(bytes32 _id) external; function makeMove(bytes32 _gameId, uint8 _spot) external; function getGameId( address _player1, address _player2, uint256 _buyIn ) external pure returns (bytes32); /** * The board is repersented as an array where each index * or `spot` corresponds to the diagram below. * * [0] [1] [2] * * [3] [4] [5] * * [6] [7] [8] * */ function getBoard(bytes32 _gameId) external view returns (uint8[9] memory); function getNextPlayer(bytes32 _gameId) external view returns (address); function stageACoup() external; }
# 🎫 CBT - Crime Bound Token Track Criminal Records using Non transferrable ERC721 Tokens (Inspired By: SBT- Soul Bound Token) <p align="center"> Make Sure you have React installed for local setup of this project <br /> <a href="https://reactjs.org/"><strong>Learn more about React »</strong></a> <br /> <a href="https://github.com/dhananjaypai08/CrimeBoundToken/issues">Report Bug</a> <br /> <a href="https://github.com/dhananjaypai08/CrimeBoundToken">Project Link</a> </p> ## ✍️ Table of Contents - [About the Project](#about-the-project) - [Project Breakdown](#project-breakdown) - [Built With](#built-with) - [Getting Started](#getting-started) - [Installation](#installation) - [Usage](#usage) - [Contributions](#contributions) ## 💻 About The Project ### 📰 Introduction: - Cops within the chain can easily track criminal records by sending non-transferrable NFT token, which is the CrimeBound Token. No need of storing the data in centralized way where criminals can behave anyhow they want to erase their data. Blockchain nodes are available by all the cop stations along the city. Thus every station knows what CBT has been received by a particular criminal. While punishing and investigating a culprit police can have a look at his CBT profile. That is checking his past criminal records along with its metadata which is integrated using IPFS distributed system for storing the metadata of the NFT. - SBT(Soul Bound Token) for Crime Records - Owner of the contract can mint the CBT to an address and can also add metadata which will be stored on IPFS - CBT is a simple ERC721 token which is non transferrable and can not be burnt, thus acting as an identity token - Deployed on Goerli Testnet ## 🔨 Project Breakdown - Developing ERC721 contract. Making changes to this contract and giving it the Sould Bound properties. Changing the before token transfer and after token transfer phases. - Deploying the contract using hardhat on goerli test network. - Using Ethers JS for smart contract interaction and safely minting the CBT. - Using IPFS for setting up the IPFS http client on the development server and adding metadata to the IPFS and receiving the IPFS hash for the CBT data. - Using ReactJS for setting up IPFS infura client node, ethers.js and also for providing the development server. ### 🔧 Built With - Frontend: - HTML - React - Ethers - JavaScript - IPFS HTTP Client - Contract: - Solidity - Remix - Metamask - Hardhat ## 🚀 Getting Started To get a local copy up and running follow these simple steps. ### 🔨 Installation 1. Clone the repo ```sh git clone https://github.com/hrishi0102/Certify.git ``` 2. Installing dependencies and requirements ```sh cd CrimeBoundToken npm install ethers npm install ipfs-http-client ``` 3. Running the APP ```sh npm start ``` ## 🧠 Usage Built version: - npm v8.1.2 - Node v16.13.2 The Basic goal is to make criminal records for police accessible and easy to fetch for investigations. Reliable and data once minted cannot be deleted or erased which happens in centralized systems. ## 🤠 Contributions Open for contributions. Just clone and follow the installation. Make changes and raise a PR detailing about the changes made.
require "globals" require "utils" function open_nes_file(file) local bytes = open_file(file) if (bytes[1] ~= 78 or bytes[2] ~= 69 or bytes[3] ~= 83 or bytes[4] ~= 26) then error("file is not a .nes file") end return bytes end function get_chr_banks_start_index(bytes) local prg_size_kb = bytes[5] local chr_size_kb = bytes[6] if (chr_size_kb == 0) then error("this rom has no CHR banks") end local has_trainer = bytes[7] & 8 has_trainer = has_trainer >> 3 local header_size = 16 local trainer_size = 512 * has_trainer local prg_size = prg_size_kb * 16384 local chr_size = chr_size_kb * 8192 return header_size + trainer_size + prg_size + 1, chr_size_kb end function create_chr_files(bytes, chr_bank_start) local chr_size = bytes[6] - 1 for i = 0, chr_size do local this_bank_start = chr_bank_start + i * 8192 local filename = string.format("chr-%d.chr", i) local f = io.open(filename, "wb") io.output(f) for j = 0, 8191 do io.write(string.char(bytes[this_bank_start + j])) end io.close(f) end end function get_char_bank(bytes, chr_bank_start) local buffer = {} local this_bank_start = chr_bank_start - 1 for j = 1, 8192 do buffer[j] = bytes[this_bank_start + j] end return buffer; end function import_nes(filename) local bytes = open_nes_file(filename) local chr_bank_start, chr_size = get_chr_banks_start_index(bytes) for i = 1, chr_size do local chr = get_char_bank(bytes, chr_bank_start + (i - 1) * 8192) local buffer = chr_to_raw_bmp_data_255(chr) local image = Image(gImageSpec) image.bytes = table.concat(buffer) local sprite = Sprite(gImageSpec) sprite.filename = string.format("bank-%d", i - 1) sprite:setPalette(gPalette) sprite:newCel(sprite.layers[1], 1, image, Point(0, 0)) end end function import_nes_as_layers(filename) local sprite sprite = Sprite(gImageSpec) sprite:setPalette(gPalette) local bytes = open_nes_file(filename) local chr_bank_start, chr_size = get_chr_banks_start_index(bytes) for i = 1, chr_size do local chr = get_char_bank(bytes, chr_bank_start + (i - 1) * 8192) local buffer = chr_to_raw_bmp_data_255(chr) local image = Image(gImageSpec) image.bytes = table.concat(buffer) local layer = i == 1 and sprite.layers[1] or sprite:newLayer() layer.isVisible = i == 1 layer.name = string.format("bank-%d", i - 1) sprite:newCel(layer, 1, image, Point(0, 0)) end end function import_nes_first_bank(filename) local sprite local bytes = open_nes_file(filename) local chr_bank_start = get_chr_banks_start_index(bytes) local chr = get_char_bank(bytes, chr_bank_start) local buffer = chr_to_raw_bmp_data_255(chr) local image = Image(gImageSpec) image.bytes = table.concat(buffer) local sprite = Sprite(gImageSpec) sprite.filename = "bank-0" sprite:setPalette(gPalette) sprite:newCel(sprite.layers[1], 1, image, Point(0, 0)) end
# 图片预加载 ## 背景 大家有没有遇到这样的场景,有一个页面全部都是有图片组成,但有部分图片很关键,如果没有下载完成或者下载失败,这时候不应该显示页面内容,继续显示加载组件(比如蚂蚁庄园,就会有一个加载中的覆盖层),否则会带给用户不好的体验。这时候就需要对关键图片进行预加载,等图片下载完成后,再关闭加载组件,再对图片进行渲染。 ## 实现 针对图片预加载这个需求,可以封装一个图片预加载方法: ```javascript /** * 图片预加载,加载成功返回图片链接,失败返回 undefined * @param url 图片链接 */ export function prefetch(url: string): Promise<string | undefined> { return new Promise((resolve) => { // 加载图片 const virtualImage = new Image(); virtualImage.src = url; // 图片被加载完成过,这时候complete会为true if (virtualImage.complete) { return resolve(url); } // 加载完成 virtualImage.onload = (): void => { resolve(url); }; // 加载失败 virtualImage.onerror = (): void => { resolve(); }; }); } ``` 如果想同时预加载多个图片,且成功返回 `true` ,失败返回 `false` : ```javascript /** * 成功,返回true,失败返回 false * @param urls 图片链接数组 */ export async function prefetchAll(urls: string[]): Promise<boolean> { for (let index = 0; index < urls.length; index++) { // 有一个失败,则返回false if (!(await prefetch(urls[index]))) { return false; } } // 全部成功,返回true return true; } ``` 上面这种实现方式会串行去请求图片资源,如果图片都能请求成功,效率低一些,不能充分利用网络,不过如果不是最后一张图片请求失败,可以节约流量🤦‍♂️。 下面用类似 `promise all` 的方式,先批量发请求,有一个失败则直接 `resolve(false)` ```javascript /** * 成功,返回true,失败返回 false * @param urls 图片链接数组 */ export function prefetchAll2(urls: string[]): Promise<boolean> { return new Promise((resolve) => { const length = urls.length; const results = []; const thenFn = (url?: string): void => { // 有一个失败,则返回false if (!url) { resolve(false); } // 成功则加入results results.push(url); // 全部加载成功 if (results.length === length) { resolve(true); } }; // 先触发请求 for (let index = 0; index < length; index++) { prefetch(urls[index]).then(thenFn); } }); } ``` 上面使用Promise 的 then来触发回调,可以在一个失败的时候,不用等待其他图片加载结束 如果想同时预加载多个图片,不管成功还是失败,返回图片链接数组(加载成功的返回链接,失败的返回undefined,以便于区分哪一张失败或者过滤掉失败的图片): ```javascript /** * 全部加载完,不管成功或者失败,返回图片链接数组(加载成功的返回链接,失败的返回undefined) * @param urls 图片链接数组 */ export async function prefetchAllSettled(urls: string[]): Promise<(undefined | string)[]> { const result: (undefined | string)[] = []; for (let index = 0; index < urls.length; index++) { result.push(await prefetch(urls[index])); } return result; } ``` 上面这种实现方式也会串行去请求图片资源,不能充分利用网络。 下面用类似 `promise allSettled` 的方式,先批量发请求,再等待所有请求结果 ```javascript /** * 全部加载完,不管成功或者失败,返回图片链接数组(加载成功的返回链接,失败的返回undefined) * @param urls 图片链接数组 */ export async function prefetchAllSettled2(urls: string[]): Promise<(undefined | string)[]> { const length = urls.length; const result: (undefined | string)[] = []; const promises = []; // 先触发请求 for (let index = 0; index < length; index++) { promises.push(prefetch(urls[index])); } // 等待所有结果 for (let index = 0; index < length; index++) { result.push(await promises[index]); } return result; } ``` `prefetchAll2` 和 `prefetchAllSettled2` 两个方法模拟了 `promise` 的 `all` 和 `allSettled` 的简单实现
<?php declare(strict_types=1); namespace Jikan\JikanPHP\Endpoint; use Jikan\JikanPHP\Exception\GetClubsSearchBadRequestException; use Jikan\JikanPHP\Model\ClubsSearch; use Jikan\JikanPHP\Runtime\Client\BaseEndpoint; use Jikan\JikanPHP\Runtime\Client\Endpoint; use Jikan\JikanPHP\Runtime\Client\EndpointTrait; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Serializer\SerializerInterface; class GetClubsSearch extends BaseEndpoint implements Endpoint { /** * @param array $queryParameters { * * @var int $page * @var int $limit * @var string $q * @var string $type * @var string $category * @var string $order_by * @var string $sort * @var string $letter Return entries starting with the given letter * } */ public function __construct(array $queryParameters = []) { $this->queryParameters = $queryParameters; } use EndpointTrait; public function getMethod(): string { return 'GET'; } public function getUri(): string { return '/clubs'; } public function getBody(SerializerInterface $serializer, $streamFactory = null): array { return [[], null]; } protected function getExtraHeaders(): array { return ['Accept' => ['application/json']]; } protected function getQueryOptionsResolver(): OptionsResolver { $optionsResolver = parent::getQueryOptionsResolver(); $optionsResolver->setDefined(['page', 'limit', 'q', 'type', 'category', 'order_by', 'sort', 'letter']); $optionsResolver->setRequired([]); $optionsResolver->setDefaults([]); $optionsResolver->setAllowedTypes('page', ['int']); $optionsResolver->setAllowedTypes('limit', ['int']); $optionsResolver->setAllowedTypes('q', ['string']); $optionsResolver->setAllowedTypes('type', ['string']); $optionsResolver->setAllowedTypes('category', ['string']); $optionsResolver->setAllowedTypes('order_by', ['string']); $optionsResolver->setAllowedTypes('sort', ['string']); $optionsResolver->setAllowedTypes('letter', ['string']); return $optionsResolver; } /** * {@inheritdoc} * * @throws GetClubsSearchBadRequestException * * @return null|ClubsSearch */ protected function transformResponseBody(string $body, int $status, SerializerInterface $serializer, ?string $contentType = null) { if (!is_null($contentType) && (200 === $status && false !== mb_strpos($contentType, 'application/json'))) { return $serializer->deserialize($body, ClubsSearch::class, 'json'); } if (400 === $status) { throw new GetClubsSearchBadRequestException(); } } public function getAuthenticationScopes(): array { return []; } }
import { AriaComponent } from "../../../core/AriaComponent"; import { AriaVec3, AriaVec3C } from "../../../core/arithmetic/AriaVector"; export enum AriaPhyParticleIntegrator{ APP_INTEGRATOR_EUCLID = "eculid", APP_INTEGRATOR_VERLET = "verlet" } export class AriaPhyParticle extends AriaComponent{ protected _lastPosition:AriaVec3 = AriaVec3.create() protected _position:AriaVec3 = AriaVec3.create() protected _velocity:AriaVec3 = AriaVec3.create() protected _acceleration:AriaVec3 = AriaVec3.create() protected _damping:number = 0.995 protected _mass:number = 1 public _forceAccum:AriaVec3 = AriaVec3.create() private _integrator:string = AriaPhyParticleIntegrator.APP_INTEGRATOR_VERLET constructor(){ super("AriaPhy/Particle") } public integrate(duration:number){ if(this._integrator==AriaPhyParticleIntegrator.APP_INTEGRATOR_EUCLID){ this._lastPosition.fromArray(this.position) this.position.addScaled_(this.velocity,duration) let accu = AriaVec3.create() accu.fromArray(this.acceleration) accu.addScaled_(this._forceAccum,this.inverseMass) this.position.addScaled_(accu,duration*duration) this.velocity.addScaled_(accu,duration) this.velocity.mul_(Math.pow((1-this.damping),duration)) this.clearForceAccum() }else if(this._integrator==AriaPhyParticleIntegrator.APP_INTEGRATOR_VERLET){ let lastPos = AriaVec3.create() lastPos.fromArray(this._lastPosition) this._lastPosition.fromArray(this.position) let accu = AriaVec3.create() accu.fromArray(this.acceleration) accu.addScaled_(this._forceAccum,this.inverseMass) this.position.addScaled_(this._lastPosition.sub(lastPos),(1-this.damping)) this.position.addScaled_(accu,duration*duration) this.velocity.fromArray(this.position.sub(this._lastPosition).div(duration)) this.clearForceAccum() }else{ this._logError("aria.phy.particle: integrator not supported yet") } } public addForce(force:AriaVec3){ this._forceAccum.add_(force) } public clearForceAccum(){ this._forceAccum.fromArray([0,0,0]) } public setIntegrator(x:AriaPhyParticleIntegrator){ this._integrator = x } public get lastPosition(){ return this._lastPosition } public get position(){ return this._position } public set position(x:AriaVec3){ this._lastPosition.fromArray(x) this._position.fromArray(x) } public set positionAdjusted(x:AriaVec3){ this._position.fromArray(x) } public get velocity(){ return this._velocity } public set velocity(x:AriaVec3){ this._velocity.fromArray(x) } public get acceleration(){ return this._acceleration } public get totalAcceleration(){ let ret = AriaVec3.create() ret.fromArray(this.acceleration) ret.addScaled_(this._forceAccum,this.inverseMass) return ret } public set acceleration(x:AriaVec3){ this._acceleration.fromArray(x) } public get mass(){ return this._mass } public set mass(x:number){ this._mass = x } public get damping(){ return this._damping } public set damping(x:number){ this._damping = x } public get inverseMass(){ return 1/this._mass } }
'use strict'; import { QueryInterface, BOOLEAN, Model, INTEGER } from "sequelize"; export default { up(queryInterface: QueryInterface) { return queryInterface.createTable<Model>('matches', { id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, }, homeTeamId: { primaryKey: true, type: INTEGER, allowNull: false, field: 'home_team_id', onUpdate: 'CASCADE', onDelete: 'CASCADE', references: { model: 'teams', key: 'id' } }, homeTeamGoals: { type: INTEGER, allowNull: false, field: 'home_team_goals', }, awayTeamId: { primaryKey: true, type: INTEGER, allowNull: false, field: 'away_team_id', onUpdate: 'CASCADE', onDelete: 'CASCADE', references: { model: 'teams', key: 'id' } }, awayTeamGoals: { type: INTEGER, allowNull: false, field: 'away_team_goals', }, inProgress: { type: BOOLEAN, allowNull: false, defaultValue: false, field: 'in_progress' }, }) }, down(queryInterface: QueryInterface) { return queryInterface.dropTable('matches'); }, };
use std::ops::{Add, Div, Mul, Neg, Sub}; // todo: determine how to implement this without copy/clone (troubleshoot 'cannot move' error) #[derive(Copy, Clone)] struct Vec3 { x: f32, y: f32, z: f32, } impl Neg for Vec3 { type Output = Self; fn neg(self) -> Self::Output { self * -1.0 } } impl Add for Vec3 { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Vec3 { x: self.x + rhs.x, y: self.y + rhs.y, z: self.z + rhs.z, } } } impl Sub for Vec3 { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { self + -rhs } } impl Mul<f32> for Vec3 { type Output = Self; fn mul(self, rhs: f32) -> Self::Output { Vec3 { x: self.x * rhs, y: self.y * rhs, z: self.z * rhs, } } } impl Div<f32> for Vec3 { type Output = Self; fn div(self, rhs: f32) -> Self::Output { self * 1.0 / rhs } } impl Mul for Vec3 { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { Vec3 { x: self.x * rhs.x, y: self.y * rhs.y, z: self.z * rhs.z, } } } impl Vec3 { pub fn cross(self, rhs: Self) -> Self { Vec3 { x: self.y * rhs.z - self.z * rhs.y, y: self.x * rhs.z - self.z * rhs.x, z: self.x * rhs.y - self.y * rhs.x, } } pub fn dot(self, rhs: Self) -> f32 { self.x * rhs.x + self.y * rhs.y + self.z * rhs.z } pub fn length(self) -> f32 { self.length_squared().sqrt() } pub fn length_squared(self) -> f32 { self.x.powi(2) + self.y.powi(2) + self.z.powi(2) } pub fn unit_vector(self) -> Self { self.div(self.length()) } } type Point = Vec3; type Color = Vec3; fn write_color(color: Color) { let r = color.x; let g = color.y; let b = color.z; let rbyte = (255.999 * r) as usize; let gbyte = (255.999 * g) as usize; let bbyte = (255.999 * b) as usize; println!("{} {} {}", rbyte, gbyte, bbyte); } fn main() { // Image let image_width = 256; let image_height = 256; println!("P3\n{} {}\n255", image_width, image_height); // Render (0..image_height).for_each(|y| { eprintln!("Scanlines remaining: {}", image_height - y); (0..image_width).for_each(|x| { let pixel_color = Color { x: x as f32 / (image_width - 1) as f32, y: y as f32 / (image_height - 1) as f32, z: 0f32, }; write_color(pixel_color); }) }); eprintln!("Done"); }
import React, { useState, useEffect } from 'react'; import { View, Text, StyleSheet, ActivityIndicator } from 'react-native'; import axios from 'axios'; import { auth } from './Firebase'; const Weather = () => { const [weatherData, setWeatherData] = useState(null); useEffect(() => { if (!auth.currentUser) { console.log('Aucun utilisateur connecté.'); return; } const API_KEY = "6635d8752f8af79f658bac4beeff5bfb"; const url = `https://api.openweathermap.org/data/2.5/weather?q=Tarbes&appid=${API_KEY}&units=metric`; const fetchWeatherData = async () => { try { const response = await axios.get(url); setWeatherData(response.data); } catch (error) { console.error(error); } }; fetchWeatherData(); }, []); if (!weatherData) return <ActivityIndicator size="large" color="#0000ff" />; return ( <View style={styles.container}> <Text style={styles.title}>Météo à Tarbes</Text> <Text>Température: {weatherData.main.temp}°C</Text> <Text>Humidité: {weatherData.main.humidity}%</Text> <Text>Description: {weatherData.weather[0].description}</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { fontSize: 20, fontWeight: 'bold', marginBottom: 20, }, }); export default Weather;
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>single-products</title> <link rel="shortcut icon" href="favicon.ico"> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;600;700&display=swap" rel="stylesheet"> <script src="https://kit.fontawesome.com/af1f9ad13b.js" crossorigin="anonymous"></script> </head> <body> <div class="container"> <!-- ***********NAVBAR WHICH IS TOP SECTION LOGO AND HOME PRODUCT ......********* --> <div class="navbar"> <div class="logo"> <a href="index.html"><img src="images/logo.png" alt="logo" width="125px"></a> </div> <ul id="MenuItem"> <li><a href="index.html">HOME</a></li> <li><a href="products.html">PRODUCT</a></li> <li><a href="#">ABOUT</a></li> <li><a href="#">CONTACT</a></li> <li><a href="account.html">ACCOUNT</a></li> </ul> <div class="icons"> <a href="cart.html"><img class="cart" src="images/cart.png" height="30px" width="30px"></a> <img class="menu-icon" src="images/menu.png" width="28px" onclick="menu()"> </div> </div> <!-- **************************************************************** --> <!-- SINGLE PRODUCT DETAILS --> <div class="small-container singleproduct"> <div class="row"> <div class="col-2"> <img id="ProductImg" src="images/gallery-1.jpg" width="100%" > <div class="small-img-row" > <div class="small-img-col"> <img class="small-img" src="images/gallery-1.jpg" > </div> <div class="small-img-col"> <img class="small-img" src="images/gallery-2.jpg"> </div> <div class="small-img-col"> <img class="small-img" src="images/gallery-3.jpg"> </div> <div class="small-img-col"> <img class="small-img" src="images/gallery-4.jpg"> </div> </div> </div> <div class="col-2"> <p>Home/T-Shirt</p> <h1>Red Printed T-Shirt by HRX</h1> <h4>$50.00</h4> <select> <option>Select size</option> <option>XXL</option> <option>XL</option> <option>LARGE</option> <option>MEDIUM</option> <option>SMALL</option> </select> <input type="number" value="1"> <a href=""class="btn">Add to cart</a> <h3>Product Details <i class="fas fa-indent"></i></h3><br> <p>Give your Summer wardobe a new style with this fabulous red color HRX printed Tshirt BY Hrithik Roshan</p> </div> </div> </div> <div class="small-container"> <div class="row row-2"> <h2>Related Products</h2> <p>view more</p> </div> </div> <div class="small-container"> <div class="row"> <div class="col-4"> <img src="images/product-9.jpg" width="100%"> <h4>Sports Watch</h4> <div class="rating"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="far fa-star"></i> </div> <p>$50.00</p> </div> <div class="col-4"> <img src="images/product-10.jpg" width="100%"> <h4>Running Shoes</h4> <div class="rating"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="far fa-star"></i> </div> <p>$50.00</p> </div> <div class="col-4"> <img src="images/product-11.jpg" width="100%"> <h4>Casual Shoes</h4> <div class="rating"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="far fa-star"></i> </div> <p>$50.00</p> </div> <div class="col-4"> <img src="images/product-12.jpg" width="100%"> <h4>Trousers</h4> <div class="rating"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="far fa-star"></i> </div> <p>$50.00</p> </div> </div> </div> </div> <!-- FOOTER SECTION --> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download our app</h3> <p>Download our app for android and ios device.</p> <div class="app-logo"> <img src="images/play-store.png" > <img src="images/app-store.png" > </div> </div> <div class="footer-col-2"> <img src="images/logo-white.png" > <p>our purpose is to sustainably make the pleasure of sports accessories to many.</p> </div> <div class="footer-col-3"> <h3>useful links</h3> <ul> <li>BlogPost</li> <li>Coupons</li> <li>Return Policy</li> <li>Join Affiliate</li> </ul> </div> <div class="footer-col-4"> <h3>Follow us</h3> <ul> <li>Facebook</li> <li>Instagram</li> <li>Twitter</li> <li>Youtube</li> </ul> </div> </div> <hr> <p class="copyright"> copyright © 2021-Ninja</p> </div> </div> <script > var MenuItem=document.getElementById('MenuItem'); MenuItem.style.maxHeight="0px"; function menu(){ if(MenuItem.style.maxHeight=="0px") MenuItem.style.maxHeight="200px"; else MenuItem.style.maxHeight="0px"; } </script> </body> </html>
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.action.admin.cluster.allocation; import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder; import org.elasticsearch.client.internal.ElasticsearchClient; /** * Builder for requests to explain the allocation of a shard in the cluster */ public class ClusterAllocationExplainRequestBuilder extends MasterNodeOperationRequestBuilder< ClusterAllocationExplainRequest, ClusterAllocationExplainResponse, ClusterAllocationExplainRequestBuilder> { public ClusterAllocationExplainRequestBuilder(ElasticsearchClient client) { super(client, TransportClusterAllocationExplainAction.TYPE, new ClusterAllocationExplainRequest()); } /** The index name to use when finding the shard to explain */ public ClusterAllocationExplainRequestBuilder setIndex(String index) { request.setIndex(index); return this; } /** The shard number to use when finding the shard to explain */ public ClusterAllocationExplainRequestBuilder setShard(int shard) { request.setShard(shard); return this; } /** Whether the primary or replica should be explained */ public ClusterAllocationExplainRequestBuilder setPrimary(boolean primary) { request.setPrimary(primary); return this; } /** Whether to include "YES" decider decisions in the response instead of only "NO" decisions */ public ClusterAllocationExplainRequestBuilder setIncludeYesDecisions(boolean includeYesDecisions) { request.includeYesDecisions(includeYesDecisions); return this; } /** Whether to include information about the gathered disk information of nodes in the cluster */ public ClusterAllocationExplainRequestBuilder setIncludeDiskInfo(boolean includeDiskInfo) { request.includeDiskInfo(includeDiskInfo); return this; } /** * Requests the explain API to explain an already assigned replica shard currently allocated to * the given node. */ public ClusterAllocationExplainRequestBuilder setCurrentNode(String currentNode) { request.setCurrentNode(currentNode); return this; } /** * Signal that the first unassigned shard should be used */ public ClusterAllocationExplainRequestBuilder useAnyUnassignedShard() { request.setIndex(null); request.setShard(null); request.setPrimary(null); return this; } }
// // Authentication.swift // ITunesOmega // // Created by Андрей Гавриков on 24.02.2022. // import Foundation import UIKit import CoreData class Authentication { static var shared = Authentication() static private var salt = 4 // choosen by fair dice roll private var container: NSPersistentContainer { // swiftlint:disable force_cast (UIApplication.shared.delegate as! AppDelegate).persistentContainer // swiftlint:enable force_cast } private func hashedPassword(_ pass: String) -> Int64 { Int64(pass.hashValue + Authentication.salt) } private(set) var currentUser: User? private init() { } // swiftlint:disable function_parameter_count func createUser(name: String, surname: String, age: Date, phone: String, email: String, password: String) -> Bool { let newUser = User(context: container.viewContext) newUser.name = name newUser.surname = surname newUser.age = age newUser.phone = phone newUser.email = email.lowercased() newUser.password = hashedPassword(password) if container.viewContext.hasChanges { do { try container.viewContext.save() } catch { print("Error while saving: \(error.localizedDescription)") return false } } return true } // swiftlint:enable function_parameter_count func signIn(email: String, password: String) -> Bool { let request = User.createFetchRequest() let predicate = NSPredicate(format: "email == %@ AND password == %lld", email.lowercased(), hashedPassword(password)) request.predicate = predicate do { let users = try self.container.viewContext.fetch(request) if users.count > 0 { currentUser = users[0] return true } } catch { print(error.localizedDescription) } return false } func signOut() { currentUser = nil } }
/* * Created on Thu Feb 02 2023 * * This file is a part of Skytable * Skytable (formerly known as TerrabaseDB or Skybase) is a free and open-source * NoSQL database written by Sayan Nandan ("the Author") with the * vision to provide flexibility in data modelling without compromising * on performance, queryability or scalability. * * Copyright (c) 2023, Sayan Nandan <ohsayan@outlook.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ use { super::syn::{self, DictFoldState, ExpandedField}, crate::{ engine::{ core::EntityIDRef, data::DictGeneric, error::{QueryError, QueryResult}, ql::{ ast::{QueryData, State}, lex::{Ident, Token}, }, }, util::compiler, }, }; #[derive(Debug, PartialEq)] /// An alter space query with corresponding data pub struct AlterSpace<'a> { pub space_name: Ident<'a>, pub updated_props: DictGeneric, } impl<'a> AlterSpace<'a> { #[cfg(test)] pub fn new(space_name: Ident<'a>, updated_props: DictGeneric) -> Self { Self { space_name, updated_props, } } #[inline(always)] /// Parse alter space from tokens fn parse<Qd: QueryData<'a>>(state: &mut State<'a, Qd>) -> QueryResult<Self> { if compiler::unlikely(state.remaining() <= 3) { return compiler::cold_rerr(QueryError::QLUnexpectedEndOfStatement); } let space_name = state.fw_read(); state.poison_if_not(space_name.is_ident()); state.poison_if_not(state.cursor_eq(Token![with])); state.cursor_ahead(); // ignore errors state.poison_if_not(state.cursor_eq(Token![open {}])); state.cursor_ahead(); // ignore errors if compiler::unlikely(!state.okay()) { return Err(QueryError::QLInvalidSyntax); } let space_name = unsafe { // UNSAFE(@ohsayan): We just verified that `space_name` is an ident space_name.uck_read_ident() }; let mut d = DictGeneric::new(); syn::rfold_dict(DictFoldState::CB_OR_IDENT, state, &mut d); if state.okay() { Ok(AlterSpace { space_name, updated_props: d, }) } else { Err(QueryError::QLInvalidCollectionSyntax) } } } #[derive(Debug, PartialEq)] pub struct AlterModel<'a> { pub(in crate::engine) model: EntityIDRef<'a>, pub(in crate::engine) kind: AlterKind<'a>, } impl<'a> AlterModel<'a> { #[inline(always)] pub fn new(model: EntityIDRef<'a>, kind: AlterKind<'a>) -> Self { Self { model, kind } } } #[derive(Debug, PartialEq)] /// The alter operation kind pub enum AlterKind<'a> { Add(Box<[ExpandedField<'a>]>), Remove(Box<[Ident<'a>]>), Update(Box<[ExpandedField<'a>]>), } impl<'a> AlterModel<'a> { #[inline(always)] /// Parse an [`AlterKind`] from the given token stream fn parse<Qd: QueryData<'a>>(state: &mut State<'a, Qd>) -> QueryResult<Self> { // alter model mymodel remove x if state.remaining() <= 2 || !state.cursor_has_ident_rounded() { return compiler::cold_rerr(QueryError::QLInvalidSyntax); // FIXME(@ohsayan): bad because no specificity } let model_name = state.try_entity_ref_result()?; let kind = match state.fw_read() { Token![add] => AlterKind::alter_add(state), Token![remove] => AlterKind::alter_remove(state), Token![update] => AlterKind::alter_update(state), _ => Err(QueryError::QLExpectedStatement), }; kind.map(|kind| AlterModel::new(model_name, kind)) } } impl<'a> AlterKind<'a> { #[inline(always)] /// Parse the expression for `alter model <> add (..)` fn alter_add<Qd: QueryData<'a>>(state: &mut State<'a, Qd>) -> QueryResult<Self> { ExpandedField::parse_multiple(state).map(Self::Add) } #[inline(always)] /// Parse the expression for `alter model <> add (..)` fn alter_update<Qd: QueryData<'a>>(state: &mut State<'a, Qd>) -> QueryResult<Self> { ExpandedField::parse_multiple(state).map(Self::Update) } #[inline(always)] /// Parse the expression for `alter model <> remove (..)` fn alter_remove<Qd: QueryData<'a>>(state: &mut State<'a, Qd>) -> QueryResult<Self> { const DEFAULT_REMOVE_COL_CNT: usize = 4; /* WARNING: No trailing commas allowed <remove> ::= <ident> | <openparen> (<ident> <comma>)*<closeparen> */ if compiler::unlikely(state.exhausted()) { return compiler::cold_rerr(QueryError::QLUnexpectedEndOfStatement); } let r = match state.fw_read() { Token::Ident(id) => Box::new([*id]), Token![() open] => { let mut stop = false; let mut cols = Vec::with_capacity(DEFAULT_REMOVE_COL_CNT); while state.loop_tt() && !stop { match state.fw_read() { Token::Ident(ref ident) => { cols.push(*ident); let nx_comma = state.cursor_rounded_eq(Token![,]); let nx_close = state.cursor_rounded_eq(Token![() close]); state.poison_if_not(nx_comma | nx_close); stop = nx_close; state.cursor_ahead_if(state.okay()); } _ => { state.cursor_back(); state.poison(); break; } } } state.poison_if_not(stop); if state.okay() { cols.into_boxed_slice() } else { return Err(QueryError::QLInvalidSyntax); } } _ => return Err(QueryError::QLInvalidSyntax), }; Ok(Self::Remove(r)) } } mod impls { use { super::{AlterModel, AlterSpace}, crate::engine::{ error::QueryResult, ql::ast::{traits::ASTNode, QueryData, State}, }, }; impl<'a> ASTNode<'a> for AlterModel<'a> { const MUST_USE_FULL_TOKEN_RANGE: bool = true; const VERIFIES_FULL_TOKEN_RANGE_USAGE: bool = false; fn __base_impl_parse_from_state<Qd: QueryData<'a>>( state: &mut State<'a, Qd>, ) -> QueryResult<Self> { Self::parse(state) } } impl<'a> ASTNode<'a> for AlterSpace<'a> { const MUST_USE_FULL_TOKEN_RANGE: bool = true; const VERIFIES_FULL_TOKEN_RANGE_USAGE: bool = false; fn __base_impl_parse_from_state<Qd: QueryData<'a>>( state: &mut State<'a, Qd>, ) -> QueryResult<Self> { Self::parse(state) } } }
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Upgradeable} from "@openzeppelin-contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {MathUpgradeable} from "@openzeppelin-contracts-upgradeable/math/MathUpgradeable.sol"; import {SafeMathUpgradeable} from "@openzeppelin-contracts-upgradeable/math/SafeMathUpgradeable.sol"; import {SafeERC20Upgradeable} from "@openzeppelin-contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import {BaseStrategy} from "@badger-finance/BaseStrategy.sol"; import {IVault} from "../interfaces/badger/IVault.sol"; import {IAsset} from "../interfaces/balancer/IAsset.sol"; import {IBalancerVault, JoinKind} from "../interfaces/balancer/IBalancerVault.sol"; import {IAuraToken} from "../interfaces/aura/IAuraToken.sol"; import {IBaseRewardPool} from "../interfaces/aura/IBaseRewardPool.sol"; import {IVirtualBalanceRewardPool} from "../interfaces/aura/IVirtualBalanceRewardPool.sol"; contract AuraBalStakerStrategy is BaseStrategy { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; bool public claimRewardsOnWithdrawAll; uint256 public balEthBptToAuraBalMinOutBps; uint256 public minBbaUsdHarvest; IBaseRewardPool public constant AURABAL_REWARDS = IBaseRewardPool(0x00A7BA8Ae7bca0B10A32Ea1f8e2a1Da980c6CAd2); IVault public constant GRAVIAURA = IVault(0xBA485b556399123261a5F9c95d413B4f93107407); IBalancerVault public constant BALANCER_VAULT = IBalancerVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8); IAuraToken public constant AURA = IAuraToken(0xC0c293ce456fF0ED870ADd98a0828Dd4d2903DBF); IERC20Upgradeable public constant AURABAL = IERC20Upgradeable(0x616e8BfA43F920657B3497DBf40D6b1A02D4608d); IERC20Upgradeable public constant WETH = IERC20Upgradeable(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20Upgradeable public constant BAL = IERC20Upgradeable(0xba100000625a3754423978a60c9317c58a424e3D); IERC20Upgradeable public constant BALETH_BPT = IERC20Upgradeable(0x5c6Ee304399DBdB9C8Ef030aB642B10820DB8F56); IERC20Upgradeable public constant BB_A_USD = IERC20Upgradeable(0xA13a9247ea42D743238089903570127DdA72fE44); IERC20Upgradeable public constant BB_A_USDC = IERC20Upgradeable(0x82698aeCc9E28e9Bb27608Bd52cF57f704BD1B83); IERC20Upgradeable public constant USDC = IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); bytes32 public constant BAL_ETH_POOL_ID = 0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014; bytes32 public constant AURABAL_BALETH_BPT_POOL_ID = 0x3dd0843a028c86e0b760b1a76929d1c5ef93a2dd000200000000000000000249; bytes32 public constant BB_A_USD_POOL_ID = 0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d; bytes32 public constant BB_A_USDC_POOL_ID = 0x82698aecc9e28e9bb27608bd52cf57f704bd1b83000000000000000000000336; bytes32 public constant USDC_WETH_POOL_ID = 0x96646936b91d6b9d7d0c47c496afbf3d6ec7b6f8000200000000000000000019; /// @dev Initialize the Strategy with security settings as well as tokens /// @notice Proxies will set any non constant variable you declare as default value /// @dev add any extra changeable variable at end of initializer as shown function initialize(address _vault) public initializer { require(IVault(_vault).token() == address(AURABAL)); __BaseStrategy_init(_vault); want = address(AURABAL); claimRewardsOnWithdrawAll = true; balEthBptToAuraBalMinOutBps = 9500; // max 5% slippage minBbaUsdHarvest = 1000e18; // ~$1000 AURABAL.safeApprove(address(AURABAL_REWARDS), type(uint256).max); BAL.safeApprove(address(BALANCER_VAULT), type(uint256).max); WETH.safeApprove(address(BALANCER_VAULT), type(uint256).max); BALETH_BPT.safeApprove(address(BALANCER_VAULT), type(uint256).max); BB_A_USD.approve(address(BALANCER_VAULT), type(uint256).max); AURA.approve(address(GRAVIAURA), type(uint256).max); } function setClaimRewardsOnWithdrawAll(bool _claimRewardsOnWithdrawAll) external { _onlyGovernanceOrStrategist(); claimRewardsOnWithdrawAll = _claimRewardsOnWithdrawAll; } function setBalEthBptToAuraBalMinOutBps(uint256 _minOutBps) external { _onlyGovernanceOrStrategist(); require(_minOutBps <= MAX_BPS, "Invalid minOutBps"); balEthBptToAuraBalMinOutBps = _minOutBps; } function setMinBbaUsdHarvest(uint256 _minBbaUsd) external { _onlyGovernanceOrStrategist(); minBbaUsdHarvest = _minBbaUsd; } /// @dev Return the name of the strategy function getName() external pure override returns (string memory) { return "AuraBalStakerStrategy"; } /// @dev Return a list of protected tokens /// @notice It's very important all tokens that are meant to be in the strategy to be marked as protected /// @notice this provides security guarantees to the depositors they can't be sweeped away function getProtectedTokens() public view virtual override returns (address[] memory) { address[] memory protectedTokens = new address[](4); protectedTokens[0] = want; // AURABAL protectedTokens[1] = address(AURA); protectedTokens[2] = address(BAL); protectedTokens[3] = address(BB_A_USD); return protectedTokens; } /// @dev Deposit `_amount` of want, investing it to earn yield function _deposit(uint256 _amount) internal override { // Add code here to invest `_amount` of want to earn yield AURABAL_REWARDS.stake(_amount); } /// @dev Withdraw all funds, this is used for migrations, most of the time for emergency reasons function _withdrawAll() internal override { uint256 poolBalance = balanceOfPool(); if (poolBalance > 0) { AURABAL_REWARDS.withdrawAll(claimRewardsOnWithdrawAll); } } /// @dev Withdraw `_amount` of want, so that it can be sent to the vault / depositor /// @notice just unlock the funds and return the amount you could unlock function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 wantBalance = balanceOfWant(); if (wantBalance < _amount) { uint256 toWithdraw = _amount.sub(wantBalance); AURABAL_REWARDS.withdraw(toWithdraw, false); } return MathUpgradeable.min(_amount, balanceOfWant()); } /// @dev Does this function require `tend` to be called? function _isTendable() internal pure override returns (bool) { return false; // Change to true if the strategy should be tended } function _harvest() internal override returns (TokenAmount[] memory harvested) { AURABAL_REWARDS.getReward(); // Rewards are handled like this: // BB_A_USD --> AURABAL (autocompounded) // BAL --> BAL/ETH BPT --> AURABAL (autocompounded) // AURA --> GRAVIAURA (emitted) harvested = new TokenAmount[](2); harvested[0].token = address(AURABAL); harvested[1].token = address(GRAVIAURA); // BB_A_USD --> WETH uint256 bbaUsdBalance = BB_A_USD.balanceOf(address(this)); uint256 wethEarned; if (bbaUsdBalance > minBbaUsdHarvest) { IAsset[] memory assets = new IAsset[](4); assets[0] = IAsset(address(BB_A_USD)); assets[1] = IAsset(address(BB_A_USDC)); assets[2] = IAsset(address(USDC)); assets[3] = IAsset(address(WETH)); int256[] memory limits = new int256[](4); limits[0] = int256(bbaUsdBalance); IBalancerVault.BatchSwapStep[] memory swaps = new IBalancerVault.BatchSwapStep[](3); // BB_A_USD --> BB_A_USDC swaps[0] = IBalancerVault.BatchSwapStep({ poolId: BB_A_USD_POOL_ID, assetInIndex: 0, assetOutIndex: 1, amount: bbaUsdBalance, userData: new bytes(0) }); // BB_A_USDC --> USDC swaps[1] = IBalancerVault.BatchSwapStep({ poolId: BB_A_USDC_POOL_ID, assetInIndex: 1, assetOutIndex: 2, amount: 0, // 0 means all from last step userData: new bytes(0) }); // USDC --> WETH swaps[2] = IBalancerVault.BatchSwapStep({ poolId: USDC_WETH_POOL_ID, assetInIndex: 2, assetOutIndex: 3, amount: 0, // 0 means all from last step userData: new bytes(0) }); IBalancerVault.FundManagement memory fundManagement = IBalancerVault .FundManagement({ sender: address(this), fromInternalBalance: false, recipient: payable(address(this)), toInternalBalance: false }); int256[] memory assetBalances = BALANCER_VAULT.batchSwap( IBalancerVault.SwapKind.GIVEN_IN, swaps, assets, fundManagement, limits, type(uint256).max ); wethEarned = uint256(-assetBalances[assetBalances.length - 1]); } // BAL --> BAL/ETH BPT --> AURABAL uint256 balBalance = BAL.balanceOf(address(this)); uint256 auraBalEarned; if (balBalance > 0) { // Deposit BAL --> BAL/ETH BPT IAsset[] memory assets = new IAsset[](2); assets[0] = IAsset(address(BAL)); assets[1] = IAsset(address(WETH)); uint256[] memory maxAmountsIn = new uint256[](2); maxAmountsIn[0] = balBalance; maxAmountsIn[1] = wethEarned; BALANCER_VAULT.joinPool( BAL_ETH_POOL_ID, address(this), address(this), IBalancerVault.JoinPoolRequest({ assets: assets, maxAmountsIn: maxAmountsIn, userData: abi.encode( JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, maxAmountsIn, 0 // minOut ), fromInternalBalance: false }) ); // Swap BAL/ETH BPT --> AURABAL uint256 balEthBptBalance = IERC20Upgradeable(BALETH_BPT).balanceOf( address(this) ); // Swap BAL/ETH BPT --> auraBal IBalancerVault.FundManagement memory fundManagement = IBalancerVault .FundManagement({ sender: address(this), fromInternalBalance: false, recipient: payable(address(this)), toInternalBalance: false }); IBalancerVault.SingleSwap memory singleSwap = IBalancerVault .SingleSwap({ poolId: AURABAL_BALETH_BPT_POOL_ID, kind: IBalancerVault.SwapKind.GIVEN_IN, assetIn: IAsset(address(BALETH_BPT)), assetOut: IAsset(address(AURABAL)), amount: balEthBptBalance, userData: new bytes(0) }); uint256 minOut = (balEthBptBalance * balEthBptToAuraBalMinOutBps) / MAX_BPS; auraBalEarned = BALANCER_VAULT.swap( singleSwap, fundManagement, minOut, type(uint256).max ); harvested[0].amount = auraBalEarned; } // AURA --> graviAURA uint256 auraBalance = AURA.balanceOf(address(this)); if (auraBalance > 0) { GRAVIAURA.deposit(auraBalance); uint256 graviAuraBalance = GRAVIAURA.balanceOf(address(this)); harvested[1].amount = graviAuraBalance; _processExtraToken(address(GRAVIAURA), graviAuraBalance); } // Report harvest _reportToVault(auraBalEarned); // Stake whatever is earned if (auraBalEarned > 0) { _deposit(auraBalEarned); } } // Example tend is a no-op which returns the values, could also just revert function _tend() internal override returns (TokenAmount[] memory tended) { revert("no op"); } /// @dev Return the balance (in want) that the strategy has invested somewhere function balanceOfPool() public view override returns (uint256) { // Change this to return the amount of want invested in another protocol return AURABAL_REWARDS.balanceOf(address(this)); } /// @dev Return the balance of rewards that the strategy has accrued /// @notice Used for offChain APY and Harvest Health monitoring function balanceOfRewards() external view override returns (TokenAmount[] memory rewards) { uint256 numExtraRewards = AURABAL_REWARDS.extraRewardsLength(); rewards = new TokenAmount[](numExtraRewards + 2); uint256 balEarned = AURABAL_REWARDS.earned(address(this)); rewards[0] = TokenAmount(address(BAL), balEarned); rewards[1] = TokenAmount( address(AURA), getMintableAuraRewards(balEarned) ); for (uint256 i; i < numExtraRewards; ++i) { IVirtualBalanceRewardPool extraRewardPool = IVirtualBalanceRewardPool( address(AURABAL_REWARDS.extraRewards(i)) ); rewards[i + 2] = TokenAmount( extraRewardPool.rewardToken(), extraRewardPool.earned(address(this)) ); } } /// @notice Returns the expected amount of AURA to be minted given an amount of BAL rewards /// @dev ref: https://etherscan.io/address/0xc0c293ce456ff0ed870add98a0828dd4d2903dbf#code#F1#L86 function getMintableAuraRewards(uint256 _balAmount) public view returns (uint256 amount) { // NOTE: Only correct if AURA.minterMinted() == 0 // minterMinted is a private var in the contract, so we can't access it directly uint256 emissionsMinted = AURA.totalSupply() - AURA.INIT_MINT_AMOUNT(); uint256 cliff = emissionsMinted.div(AURA.reductionPerCliff()); uint256 totalCliffs = AURA.totalCliffs(); if (cliff < totalCliffs) { uint256 reduction = totalCliffs.sub(cliff).mul(5).div(2).add(700); amount = _balAmount.mul(reduction).div(totalCliffs); uint256 amtTillMax = AURA.EMISSIONS_MAX_SUPPLY().sub( emissionsMinted ); if (amount > amtTillMax) { amount = amtTillMax; } } } }
Name: ln Type: function Syntax: the ln of <number> Syntax: ln(<number>) Summary: <return|Returns> the natural logarithm of a number. Introduced: 1.0 OS: mac, windows, linux, ios, android Platforms: desktop, server, mobile Example: ln(1) -- returns zero Example: ln(0.15) -- returns -1.89712 Example: ln(10) -- returns 2.302585 Parameters: number: A positive number, or an expression that evaluates to a positive number. Returns: The <ln> <function> <return|returns> a number. Description: Use the <ln> function to obtain a base e logarithm. The natural logarithm of a <number> is the power to which e must be raised to obtain the <number>. The transcendental number e appears in many mathematical formulas. To find the logarithm of a number in any base, use the following function: function logarithm theBase,theNumber return ln(theNumber)/ln(theBase) end logarithm If a math operation on finite inputs produces a non-finite output, an execution error is thrown. See <math operation|math operations> for more information. References: function (control structure), ln1 (function), exp (function), return (glossary), math operation (glossary) Tags: math
class Solution { /* o: int - how many distinct ways can climb to the top i: int - how many steps c: e: n = 0 -> 0 n = 1 -> 1 n = 2 -> 2 n = 3 -> dp[n] = dp[n - 1] + dp[n - 2]; */ public int climbStairs(int n) { if (n == 1) return 1; int[] dp = new int[n + 1]; dp[1] = 1; dp[2] = 2; for (int i = 3; i < n + 1; i++) { dp[i] = dp[i - 2] + dp[i - 1]; } return dp[n]; } }
package com.saartak.el.adapter; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.signature.MediaStoreSignature; import com.saartak.el.R; import com.saartak.el.database.entity.DocumentUploadTableNew; import com.saartak.el.keystore.JealousSky; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; import static com.saartak.el.constants.AppConstant.IMAGE_ENC_PSWD; import static com.saartak.el.constants.AppConstant.IMAGE_ENC_SALT; public class ImageCaptureAdapterJLG extends RecyclerView.Adapter<ImageCaptureAdapterJLG.ImageCaptureViewHolder> { List<DocumentUploadTableNew> documentUploadTableNewList; Context context; ImageCaptureInterface imageCaptureInterface; public ImageCaptureAdapterJLG(List<DocumentUploadTableNew> documentUploadTableNewList, Context context, ImageCaptureInterface imageCaptureInterface) { this.documentUploadTableNewList = documentUploadTableNewList; this.context = context; this.imageCaptureInterface = imageCaptureInterface; } @NonNull @Override public ImageCaptureViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view= LayoutInflater.from(context).inflate(R.layout.view_capture_image,parent,false); return new ImageCaptureViewHolder(view); } @Override public void onBindViewHolder(@NonNull ImageCaptureViewHolder holder, int position) { try{ final DocumentUploadTableNew documentUploadTableNew = documentUploadTableNewList.get(position); if (documentUploadTableNew != null) { int count=position+1; String imagePosition="Front"; if(count % 2==0){ imagePosition="Back"; } holder.tvImageTitle.setText(documentUploadTableNew.getDocument_name() + " " + imagePosition); if (!TextUtils.isEmpty(documentUploadTableNew.getFile_path())) { holder.ivDefaultImage.setVisibility(View.GONE); if (documentUploadTableNew.isDocument_status()) { holder.ivImageStatus.setVisibility(View.VISIBLE); } else { holder.ivImageStatus.setVisibility(View.GONE); } holder.ivCaptureImage.setVisibility(View.VISIBLE); holder.ivCaptureImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (documentUploadTableNew.isEditable()) { imageCaptureInterface. openImageCallBack(documentUploadTableNew, position); } } }); holder.ivRemoveImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (documentUploadTableNew.isEditable()) { imageCaptureInterface.removeImageCallBack(documentUploadTableNew, position); } } }); RequestOptions requestOptions = new RequestOptions() .diskCacheStrategy(DiskCacheStrategy.DATA) .sizeMultiplier(0.5f) .signature(new MediaStoreSignature("JPEG", System.currentTimeMillis(), 0)) .dontAnimate(); JealousSky jealousSky = JealousSky.getInstance(); jealousSky.initialize( IMAGE_ENC_PSWD, IMAGE_ENC_SALT); InputStream inputStream=new FileInputStream(documentUploadTableNew.getFile_path()); byte[] decryptedByteArrayImage=jealousSky.decrypt(inputStream); if(decryptedByteArrayImage !=null && decryptedByteArrayImage.length>0){ Glide.with(context) .asBitmap() .load(decryptedByteArrayImage) .apply(requestOptions) .thumbnail( Glide.with(context).asBitmap() .load(decryptedByteArrayImage) // TODO: Load Decrypted Image .apply(requestOptions)) .into(holder.ivCaptureImage); }else{ Glide.with(context) .asBitmap() .load(documentUploadTableNew.getFile_path()) .apply(requestOptions) .thumbnail( Glide.with(context).asBitmap() .load(documentUploadTableNew.getFile_path()) // TODO: Load File Path .apply(requestOptions)) .into(holder.ivCaptureImage); } } else { holder.ivCaptureImage.setImageBitmap(null); holder.ivDefaultImage.setVisibility(View.VISIBLE); holder.ivImageStatus.setVisibility(View.GONE); holder.ivDefaultImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (documentUploadTableNew.isEditable()) { imageCaptureInterface. openCameraImageCallBack(documentUploadTableNew, position); } } }); } } }catch (Exception ex){ ex.printStackTrace(); } } @Override public int getItemCount() { return documentUploadTableNewList.size(); } public class ImageCaptureViewHolder extends RecyclerView.ViewHolder{ ImageView ivCaptureImage; ImageView ivDefaultImage; ImageView ivRemoveImage; ImageView ivImageStatus; TextView tvImageTitle; public ImageCaptureViewHolder(@NonNull View itemView) { super(itemView); ivCaptureImage=(ImageView) itemView.findViewById(R.id.iv_capture_image); ivDefaultImage = (ImageView) itemView.findViewById(R.id.iv_default_image); tvImageTitle = (TextView) itemView.findViewById(R.id.tv_image_title); ivRemoveImage = (ImageView) itemView.findViewById(R.id.iv_remove_image); ivImageStatus = (ImageView) itemView.findViewById(R.id.iv_image_status); } } public interface ImageCaptureInterface{ void removeImageCallBack(DocumentUploadTableNew documentUploadTableNew, int position); void openImageCallBack(DocumentUploadTableNew documentUploadTableNew, int position); void openCameraImageCallBack(DocumentUploadTableNew documentUploadTableNew, int position); } }
#pragma once /** @defgroup solverRK12 Solver.RK12 * Module for RK12 integration methods * @{ */ #include "FactoryExport.h" #include <Core/Solver/SolverDefaultImplementation.h> class IRK12Settings; /*****************************************************************************/ /** RK12 method for the solution of a non-stiff initial value problem of a system of ordinary differantial equations of the form z' = f(t,z). Dense output may be used. Zero crossing are detected by bisection or linear interpolation. \date 01.09.2008 \author */ /***************************************************************************** Copyright (c) 2008, OSMC *****************************************************************************/ class RK12 : public ISolver, public SolverDefaultImplementation { public: RK12(IMixedSystem* system, ISolverSettings* settings); virtual ~RK12(); /// Set start time for numerical solution virtual void setStartTime(const double& t); /// Set end time for numerical solution virtual void setEndTime(const double& t); /// Set the initial step size (needed for reinitialization after external zero search) virtual void setInitStepSize(const double& h); /// (Re-) initialize the solver virtual void initialize(); /// Approximation of the numerical solution in a given time interval virtual void solve(const SOLVERCALL command = UNDEF_CALL); /// Provides the status of the solver after returning ISolver::SOLVERSTATUS getSolverStatus(); /// Write out statistical information (statistical information of last simulation, e.g. time, number of steps, etc.) virtual void writeSimulationInfo(); virtual void setTimeOut(unsigned int time_out); virtual void stop(); /// Indicates whether a solver error occurred during integration, returns type of error and provides error message virtual int reportErrorMessage(ostream& messageStream); virtual bool stateSelection(); private: /* embedded RK12, i.e. explicit euler as predictor and heuns method as corrector */ void doRK12(); void doRK12_stepControl(); void outputStepSize(bool *_activeStates, double time ,double hLatent, double hActive); void RK12Integration(bool *activeStates, double time, double *z0, double *z1, double h, double *error, double relTol, double absTol, int *numErrors); void RK12InterpolateStates(bool *activeStates, double *leftIntervalStates,double *rightIntervalStates,double leftTime,double rightTime, double *interpolStates, double interpolTime); /// Encapsulation of determination of right hand side void calcFunction(const double& t, const double* z, double* zDot); /// Output routine called after every sucessfull solver step (calls setZeroState() and writeToFile() in SolverDefaultImpl.) void solverOutput(const int& stp, const double& t, double* z, const double& h); // Hilfsfunktionen //------------------------------------------ // Interpolation der Lösung für RK12-Verfahren void interp1(double time, double* value); double toleranceOK(double z1, double z2, double relTol, double absTol); double relError(double z1, double z2); /// Kapselung der Nullstellensuche void doMyZeroSearch(); void doZeroSearch(); // gibt den Wert der Nullstellenfunktion für die Zeit t und den Zustand y wieder void giveZeroVal(const double &t,const double *y,double *zeroValue); // gibt die Indizes der Nullstellenfunktion mit Vorzeichenwechsel zurück void giveZeroIdx(double *vL,double *vR,int *zeroIdx, int &zeroExist); /// Berechnung der Jacobimatrix void calcJac(double* yHelp, double* _fHelp, const double* _f, double* jac, const bool& flag); // Member variables //--------------------------------------------------------------- IRK12Settings *_RK12Settings; ///< Settings for the solver long int _dimSys, ///< Temp - (total) Dimension of systems (=number of ODE) _idid, ///< Input, Output - Status Flag _dimParts; /// - number of partitions int _latentSteps, _activeSteps, _outputStp, _outputStps; ///< Output - Number of output steps double *_z, // State vector in latent step *_z0, // (Old) state vector at left border of latent interval *_z1, // (New) state vector at right border of latent interval *_z_a, // State vector in active step *_z_a_0, // (Old) state vector at left border of active interval *_z_a_1, // (New) state vector at right border of active interval *_zPred, // Predictor state after first step in RK12 *_zInit, // Temp - Initial state vector *_zWrite, // Temp - write to res *_f0, *_f1, *_zDot0, // state derivative for state *_zDotPred; // state derivative for predictor state double _hOut, // Ouput step size for dense output _hZero, // Downscale of step size to approach the zero crossing _hUpLim, // Maximal step size _h00, _h01, _h10, _h11, _h_a; // step size for the active step double _tOut, ///< Output - Time for dense output _tLastZero, ///< Temp - Stores the time of the last zero (not last zero crossing!) _tRealInitZero, ///< Temp - Time of the very first zero in all zero functions _doubleZeroDistance, ///< Temp - In case of two zeros in one intervall (doubleZero): distance between zeros _tZero, ///< Temp - Nullstelle _tLastWrite, ///< Temp - Letzter Ausgabezeitpunkt _zeroTol; int *_zeroSignIter; ///< Temp - Temporary zeroSign Vector bool *_activePartitions, // boolean vector which partition has to be activated *_activeStates; // boolean vector which state has to be calculated in an active step ISystemProperties* _properties; IContinuous* _continuous_system; IEvent* _event_system; IMixedSystem* _mixed_system; ITime* _time_system; }; /** @} */ // end of solverRK12
import { useState } from "react"; import { DepartmentUpdateReq, deleteDepartment, getDepartments, insertDepartment, updateDepartment } from "../../api"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Container, Loader, Message, Table } from "semantic-ui-react"; import styles from "../Styles.module.scss"; import { InsertDepartmentModal } from "./InsertDepartmentModal"; import { DeleteDepartmentModal } from "./DeleteDepartmentModal"; import { UpdateDepartmentModal } from "./UpdateDepartmentModal"; import { AxiosError } from "axios"; import { Department } from "../../UI/Department"; export function DepartmentTable() { const { data, isLoading, isError, error, refetch } = useQuery({ queryKey: ["departmentData"], queryFn: getDepartments, }); const [errorMessage, setErrorMessage] = useState<string>(); const departmentDelete = useMutation({ mutationFn: deleteDepartment, onSuccess: () => { refetch(); setErrorMessage(undefined); }, onError: () => setErrorMessage("Could not delete department") }); const departmentInsert = useMutation({ mutationFn: insertDepartment, onSuccess: () => { refetch(); setErrorMessage(undefined); }, onError: (_error, variables, _context) => setErrorMessage(` Could not insert ${variables.departmentName}, ${variables.departmentLocation}`), }); const departmentUpdate = useMutation({ mutationFn: updateDepartment, onSuccess: () => { refetch(); setErrorMessage(undefined) }, onError: () => setErrorMessage("Could not update department") }) if (isLoading) return <Loader />; if (isError) return ( <Message negative={true}> Error: {(error as AxiosError).message} </Message> ); return ( <Container className={styles.tableContainer}> {errorMessage && <Message error={true}>{errorMessage}</Message>} <Table celled striped> <Table.Header> <Table.Row> <Table.HeaderCell>Department Name</Table.HeaderCell> <Table.HeaderCell>Department Location</Table.HeaderCell> <Table.HeaderCell> <InsertDepartmentModal onConfirm={departmentInsert.mutate} /> </Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {data.map((entry: Department, i: number) => ( <Table.Row key={i}> <Table.Cell>{entry.departmentName}</Table.Cell> <Table.Cell>{entry.departmentLocation}</Table.Cell> <Table.Cell className="department-cell"> <DeleteDepartmentModal onConfirm={() => departmentDelete.mutate({ departmentName: entry.departmentName, departmentLocation: entry.departmentLocation, }) } /> <UpdateDepartmentModal onConfirm={(departmentUpdateData: DepartmentUpdateReq ) => departmentUpdate.mutate( departmentUpdateData ) } department={entry} /> </Table.Cell> </Table.Row> ))} </Table.Body> </Table> </Container> ); }
=title Marpa for building parsers - a first look =timestamp 2017-10-13T13:41:01 =indexes Marpa, parser =status show =books marpa =author grandfather =comments_disqus_enable 1 =abstract start Parsers seem to be esoteric, hard and to lack much day to day application. Marpa lowers the bar to entry by hiding a lot of the mysterious stuff, adding some fun and making parsers easy enough to use for solving some common problems. =abstract end <h2>The back story</h2> Long ago when Computer Science was still about compilers and data structures I took a couple of first year CS papers. I learned about recursive decent parsers and have since used them to do real work. When I picked up Perl I took a look at <a href="https://metacpan.org/pod/Parse::RecDescent">Parse::RecDescent</a>. Parse::RecDescent was a lot more work and less fun than I expected. In fact I <a href="http://perlmonks.org/?node_id=574311">called on the Monks</a> for help and was surprised at how many moving parts are buried under the surface of the iceberg (see ikegami's later replies in particular). In contrast, playing with <a href="https://metacpan.org/pod/Marpa::R2">Marpa</a> recently to answer <a href="http://perlmonks.org/?node_id=1151415">a PerlMonks question</a> turned out to be a bundle of fun. It still took some playing around to come to grips with, but at least it had sane error messages! So lets explore Marpa for the task I struggled with using P::RD. The big picture task doesn't much matter and I can't remember it anyway. The task I presented to the Monks was to parse a bunch of assignment statements and generate a hash of name/value pairs. <h2>A first look at Marpa</h2> Marpa works with a syntax provided in a BNF (<a href="https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form">WikiPedia: Backus Naur Form</a>) style definition. A little extra markup hooks up actions to elements of the syntax and a little boiler plate handles setting up common parsing options: <code lang="perl"> lexeme default = latm => 1 declaration ::= assignment* action => doResult assignment ::= name '=' number action => doAssign name ~ [\w]+ number ~ [\d]+ :discard ~ spaces spaces ~ [\s]+ </code> The lexeme line sets the parser for longest token match. The 'spaces' lines at the end sets up a general rule for discarding white space. The interesting bit is in the middle where the syntax description lives. Ignoring the <hl>action => ...</hl> bits for the moment, the first <hl>::=</hl> line (<b>rule</b>) says that a <hl>declaration</hl> is 0 or more <hl>assignment</hl>s. The second rule says that an <hl>assignment</hl> is a <hl>name</hl> followed by the '<hl>=</hl>' character followed by a <hl>number</hl>. A <hl>name</hl> is one or more word characters and a <hl>number</hl> is one or more digits. The <hl>[\w]+</hl> match expression looks kinda weird to Perl eyes, but it's what Marpa wants so it's what Marpa gets. So far, so good. The '<hl>action => xxx</hl>' bits hook an action (subroutine call) up to a rule so that when the rule matches, something happens. The subroutine gets called with a bunch of parameters passed that depend on the rule definition and results from processing other rules. Lets see some code: <include file="examples/marpa/asHash.pl"> The output from running the code is: <code> { 1 => 1, 42 => 3, wibble => 42, x => 1, y1 => 2, z => 3 } </code> from which you can see that variable names are a rather loose concept in this parser (numbers are not usually valid variable names!). But, that aside, things work as desired. <hl>doAssign</hl> takes the <hl>name</hl> and <hl>number</hl> from the <hl>assignment</hl> rule and returns a hash ref with the <hl>name</hl> as the key. <hl>doResult</hl> takes the list of all the <hl>doAssign</hl> generated hash refs and turns them into a single hash ref containing all the variables. Note that it doesn't do anything smart like checking for <hl>name</hl> collisions! <h2>Extending the parser</h2> So now we have had a first taste. Let's add strings values as well as numbers. Most of what we have already stays the same. Here's the extra syntax to be inserted following the assignment rule: <code> | name '=' string action => doAssignStr string ::= ['] chars1 ['] action => [values] | '"' chars2 '"' action => [values] chars1 ~ [^']* chars2 ~ [^"]* </code> and the extra handler for the <hl>string</hl> assignment: <code lang="perl"> sub doAssignStr { my (@params) = @_; return {$params[1] => $params[3][1]}; } </code> The <hl>string</hl> rules don't need any code support. Instead the <hl>action</hl> creates a list of three values that are returned by the rule. The string value is the middle value in the list, with the quote characters as the other two values. <hl>doAssignStr</hl> fishes the string value out of the third parameter passed in to it - the returned value from the string rule. The complete script with new test assignments is: <include file="examples/marpa/asHashExtended.pl"> which prints: <code> { wibble => 42, wobble => "twenty three", x => 1, y => 2, z => 3 } </code> So, we haven't written a compiler yet, but there is a hint of how such a thing might be done. An interesting exercise is to write a script to perform the same task without using helper modules. The simple numeric assignment parsing is easy, especially if you use a couple of Perlish tricks. Things start getting a bit more hairy when the string parsing is added. It isn't just a matter of extending the original code a little as was the case with the Marpa code above. Note that this is very much a play thing. It doesn't provide any sort of sensible error handling or allow quoted characters in the strings or even do very much that is immediately useful. It does provide a starting point and a playground for exploring Marpa however. I've written parsers of various sorts in a variety of languages, mostly for arithmetic expression parsing. Parsers can be fun, and are almost always frustrating to debug. My (small) experience so far with Marpa is that it enhances the fun and reduces the frustration.
#include "main.h" #include <stdlib.h> /** * create_file - creates a file * @filename: name of the file to create * @text_content: a pointer to the string to write to the file * * Return: -1 on failure of the function and 1 on success */ int create_file(const char *filename, char *text_content) { int fd, j, len = 0; if (filename == NULL) return (-1); if (text_content != NULL) { for (len = 0; text_content[len];) len++; } fd = open(filename, O_CREAT | O_RDWR | O_TRUNC, 0600); j = write(fd, text_content, len); if (fd == -1 || j == -1) return (-1); close(fd); return (1); }
import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import axios from 'axios'; import './styles.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import { BiSortAlt2 } from "react-icons/bi" const UserTable = () => { const [users, setUsers] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [rowsPerPage, setRowsPerPage] = useState(5); const [sortField, setSortField] = useState(null); const navigate = useNavigate(); useEffect(() => { const fetchData = async () => { const response = await axios.get('https://jsonplaceholder.typicode.com/users'); setUsers(response.data); }; fetchData(); }, []); const deleteUser = (userId) => { setUsers(users.filter((user) => user.id !== userId)); }; const openUserDetails = (userId) => { // Navigate to the user details view using React Router // Pass the relevant user details to the new view navigate(`/user-details/${userId}`); }; const handleSort = (field) => { if (sortField === field) { setUsers([...users].reverse()); } else { setSortField(field); setUsers([...users].sort((a, b) => a[field].localeCompare(b[field]))); } }; const indexOfLastRow = currentPage * rowsPerPage; const indexOfFirstRow = indexOfLastRow - rowsPerPage; const currentRows = users.slice(indexOfFirstRow, indexOfLastRow); const renderTableRows = currentRows.map((user) => ( <tr key={user.id}> <td>{user.name}</td> <td>{user.username}</td> <td>{user.email}</td> <td>{user.address.city}</td> <td>{user.phone}</td> <td>{user.website}</td> <td>{user.company.name}</td> <td> <button onClick={() => openUserDetails(user.id)}>Open</button> <button onClick={() => deleteUser(user.id)}>Delete</button> </td> </tr> )); const renderTableHeaders = ( //using table headers for sorting based on respective field <tr> <th className='sortingFields' onClick={() => handleSort('name')}>Name <BiSortAlt2 /></th> <th>Username</th> <th className='sortingFields' onClick={() => handleSort('email')}>Email <BiSortAlt2 /> </th> <th>Address</th> <th>Phone</th> <th>Website</th> <th>Company</th> <th>Actions</th> </tr> ); const renderPagination = ( <div className='pagination'> <button onClick={() => setCurrentPage(currentPage > 1 ? currentPage - 1 : 1)} disabled={currentPage === 1} > Prev </button> <button onClick={() => setCurrentPage( currentPage < Math.ceil(users.length / rowsPerPage) ? currentPage + 1 : currentPage ) } disabled={currentPage === Math.ceil(users.length / rowsPerPage)} > Next </button> </div> ); const handleRowsPerPageChange = (event) => { const value = parseInt(event.target.value); setCurrentPage(1); setRowsPerPage(value); }; return ( <div className='container'> <div class="pagination"> <label htmlFor="rowsPerPage" className='form-label'>Rows per page: </label> <select id="rowsPerPage" className='form-select rowsSelect' value={rowsPerPage} onChange={handleRowsPerPageChange}> <option value={5}>5</option> <option value={10}>10</option> <option value={20} disabled>20</option> </select> </div> <div class="well"> <table className='table'> <thead>{renderTableHeaders}</thead> <tbody>{renderTableRows}</tbody> </table> {renderPagination} </div> </div> ); }; export default UserTable;
########################### ## XMAS-ICETUBE FIRMWARE ## ########################### The xmas-icetube firmware is a complete reimplementation of the Adafruit Ice Tube Clock firmware and runs on *both* the Adafruit Ice Tube Clock v1.1 and the xmas-icetube hardware revision. Since most users will be using the xmas-icetube firmware on the Adafruit Ice Tube Clock v1.1, the default firmware configuration is set for the Adafruit clock. The xmas-icetube firmware is discussed in the following Adafruit thread, which is a good place to post questions and comments: http://forums.adafruit.com/viewtopic.php?f=41&t=34924 ############## ## FEATURES ## ############## Many of the features in the xmas-icetube firmware were first implemented in other firmware projects; see the CREDITS file for details. This firmware boasts the following improvements over the official Adafruit firmware: - animated display transitions - multiple time and date formats - optionally pulse display during alarm and snooze - three alarm times for selectable days of the week - functional alarm during power outage - adjustable alarm volume (from 0 to 10) - progressive alarm option (gradually increasing volume) - selectable alarm sound (high frequency beeps, low frequency beeps, high frequency three beep pulse, low frequency three beep pulse, Merry Christmas, Big Ben, Reveille, or For He's a Jolly Good Fellow) - adjustable snooze duration - DST support (USA, EU, or manual) - fully automatic correction for time drift - time-from-GPS support* - temperature compensated timekeeping* - no beeping or time loss after external power failure - 4-fold or 25-fold* increase in backup battery life - low battery warning before battery failure - larger range for user-configured display brightness - per-digit brightness adjustment for uneven displays - automatic brightness control by ambient light* - optionally disable display during specified time periods - optionally disable display at night (when dark)* - IV-18 VFD tube driven to specifications* * For the Adafruit Ice Tube Clock v1.1, these hacks require hardware modification and support must be enabled by uncommenting macros in config.h. See the HACKS AND MODS section of this file as well as the comments in config.h for more information. For clock hackers, this firmware has (1) compatibility with the ATmega328p, (2) a pseudo object-oriented design, (3) good source code documentation, and (4) display/menus by finite state machine. ################## ## INSTALLATION ## ################## Installation requires GNU Make, avr-libc, avr-gcc, and avrdude; the instructions below presume proficiency with these tools. This firmware requires the ATmega328p, not the ATmega168v included with the Adafruit kit. Due to the many features, xmas-icetube currently requires around 30 kB of program memory, but the ATmega168v only has 16 kB. The ATmega328p also supports Atmel picoPower features that are used to extend battery life by 4-fold (and 25-fold with a minor hardware modification). The ATmega168v does not support picoPower. Note that if your ATmega328p has an Arduino bootloader installed, it will not work without reconfiguration. See the TROUBLESHOOTING section for reconfiguration instructions. To program the chip, any avrdude-compatible ISP programmer should work, but programming has been tested with the Adafruit USBtinyISP, the Atmel AVR Dragon, and an Arduino programed with the ArduinoISP sketch. Compilation and installation has been tested under (a) Ubuntu Linux 12.04 with the avr-gcc and avrdude packages, (b) MacOS 10.14.5 with CrossPack for AVR Development, and (c) Windows 10 with WinAVR and Cygwin's perl and bash packages. To compile and install this firmware, first configure compile-time options by editing the Makefile and config.h. Then build and install the project using the included Makefile: (1) Edit the Configuration Variables First, review the macro definitions in config.h, changing definitions as needed to enable support for various hardware hacks. The default values in config.h are suitable for the Adafruit Ice Tube Clock v1.1 and includes support for the autodimmer and GPS mods. For the xmas-icetube hardware revision, it may be more convenient to copy the config.h file from the hardware directory and edit that as desired: % cp ../hardware/config.h config.h Next, review the Makefile to ensure that configuration variables are reasonable given your hardware. In particular, AVRISP and AVRDUDEOPT seem most likely to require attention. (2) Compile the Firmware Build icetube_fuse.hex, icetube_flash.hex, icetube_eeprom.hex, and icetube_lock.hex which contain the fuse bits, program memory (flash), EEPROM data, and lock bits: % make (3) Connect the Programmer Ensure the clock has an ATmega328p installed and not an ATmega168v. Unplug and disassemble the clock. Remove the side PCB with VFD tube. Make sure that the AVR programmer will not provide power to the clock. (For the Adafruit USBtinyISP, this means ensuring that the power jumper is not installed.) Connect the AVR programmer to the clock's ISP header, ensuring that pin one on the cable and the marked pin on the clock's ISP header match. Finally, power the clock board with the external power adaptor. (4) Install the Firmware Install this firmware to an ATmega328p by setting the fuse bits, writing the flash program, writing the EEPROM data, and setting the lock bits: % make install-all Alternatively, this firmware may be installed or upgraded in separate steps. If you wish not to set lockbits or not to overwrite the EEPROM (clock settings), simply skip those commands below. % make install-fuse % make install-flash % make install-eeprom % make install-lock (5) Verify Successful Programming (Optional, but Recommended) To ensure that the chip has been successfully programmed, one may check the chip data against what should have been installed in the previous step: % make verify-all One may also verify the individual sections of programmed memory. The following commands are equivalent to "make verify-all": % make verify-fuse % make verify-flash % make verify-eeprom % make verify-lock ##################### ## USING THE CLOCK ## ##################### The USAGE file contains an overview of how to use the clock. #################### ## HACKS AND MODS ## #################### Development of the various hacks and mods supported by this firmware have been discussed extensively on the Adafruit discussion board. Options requiring hardware changes can be enabled by uncommenting macros in the config.h file. Comments in the config.h describe each optional feature in detail. :: Automatic Display Dimming :: http://forums.adafruit.com/viewtopic.php?f=41&t=12932 http://forums.adafruit.com/viewtopic.php?p=219736#p219736 :: Temperature Compensated Timekeeping :: http://forums.adafruit.com/viewtopic.php?f=41&t=14941 http://forums.adafruit.com/viewtopic.php?f=41&t=43998 :: GPS Timekeeping :: http://forums.adafruit.com/viewtopic.php?f=41&t=36873 http://learn.adafruit.com/ice-tube-clock-kit/mods http://forums.adafruit.com/viewtopic.php?f=41&t=32660 :: Extended Battery Life :: http://forums.adafruit.com/viewtopic.php?f=41&t=36697 :: IV-18 To-Spec Hack :: http://forums.adafruit.com/viewtopic.php?f=41&t=41811 :: Reliably Sleeping During Power Failure :: http://forums.adafruit.com/viewtopic.php?f=41&t=22515 :: Automatic Drift Correction :: http://forums.adafruit.com/viewtopic.php?f=41&t=12720 :: Per-Digit Brightness Adjustment :: http://forums.adafruit.com/viewtopic.php?f=41&t=23586 ##################### ## TROUBLESHOOTING ## ##################### :: General Troubleshooting :: For many hardware issues, the Adafruit FAQs are quite helpful: http://forums.adafruit.com/viewtopic.php?f=41&t=27032 http://learn.adafruit.com/ice-tube-clock-kit/faq The Adafruit Clocks forums is an excellent place to ask for help: http://forums.adafruit.com/viewforum.php?f=41 :: Reset and Diagnostic Messages :: After a reset, the microcontroller will examine MCUSR (microcontroller unit status register) to determine the reason for the reset, and the display will alternate between the restored time and a message showing the cause of the reset. Reset messages can be dismissed by setting the time, as the time is usually wrong after a reset. "bod rset" (brown out detection reset): The clock was reset due to insufficient voltage. This usually happens when power is lost and the backup battery is nearly dead. "pin rset" (external reset): The clock was reset by an external signal to the microcontroller reset pin (pin 1). Programming the clock through the ISP header will trigger an external reset. Accidently shorting the reset pin to ground will do the same. This message used to read "ext rset", but the "x" looked more like an "H". "pwr rset" (power reset): The clock started up after a complete power loss. This usually happens if the clock loses external with without a backup battery or with a completely dead backup battery. "wdt rset" (watchdog timer reset): During normal operation the clock will periodically reset the watchdog timer. If this timer expires, the clock is behaving abnormally and will reset itself in an attempt to fix the problem. Usually watchdog timer resets are caused by problems with the crystal oscillator; see the troubleshooting entry on crystal oscillator problems. "oth rset" (other reset): If no flags were set in MCUSR to indicate the cause of the reset, the display will flash "oth rest". In theory, this should never happen. The clock might also flash one of the following status messages: "bad batt" (low battery warning): The microcontroller checks the system voltage whenever the clock sleeps for more than ten minutes. When the battery is low, the display will flash "bad batt" after the clock wakes, and the message can be dismissed by pressing any button. "gps lost" (GPS signal lost; only applies if GPS_TIMEKEEPING was defined in config.h): The clock is receiving data from the GPS, but the GPS has been unable to acquire a signal for at least three minutes. "temp err" (temperature sensor error; only applies if TEMPERATURE_SENSOR was defined in config.h): If the microcontroller is unable to communicate with the temperature sensor, the display will flash "temp err". :: Programming Fails with an Arduino Chip :: The Arduino Uno chip is an ATmega328p, but will not work in an Ice Tube Clock without reconfiguration. Arduino chips have their fuse settings configured to use an external 16 MHz oscillator for the system clock. The Ice Tube Clock does not provide a suitable external oscillator, and without an external oscillator, an Arduino chip will not function--not even to be reconfigured. To provide an external oscillator for reconfiguration, insert the Arduino chip into an Arduino board. Next, connect a programmer to the ISP on the Arduino board and reprogram the fuses with the xmas-icetube Makefile: "make install-fuse". The ATmega328p's fuse settings are now configured to use the 8 MHz internal oscillator and can be installed and programmed as described in the INSTALLATION section. This method is also described in the following thread: http://forums.adafruit.com/viewtopic.php?p=184722#p184722 :: Other Programming Failures :: First, ensure that the hardware is connected properly, as described in the installation instructions above. Second, double check the Makefile configuration section, paying particular attention to the AVRISP and AVRDUDEOPT macros. Third, try programming the chip at a lower bit rate by changing the "-B 2" option to "-B 25" in the AVRDUDEOPT macro: AVRDUDEOPT ?= -B 25 -P usb -c $(AVRISP) -p $(AVRMCU) Fourth, if the chip cannot be programmed in the clock, try programming it in a development board such as the Arduino Uno. Finally, it's possible that the chip is somehow damaged or bricked; usually, the simplest solution is to simply replace the ATmega328p with a new chip and try again. :: Dim Digits :: The per-digit brightness control in the xmas-icetube firmware provides one way to increase the brightness of dim digits. With Adafruit clocks, a dim initial or final digit is almost invariably due to insufficient filament current. In those cases, increasing filament current usually produces better results, but increasing current may also introduce a brightness gradient across the display when the menu-configured brightness level is low. To find the optimal current for a given clock, a good approach is to gradually increase current across the filament until all digits have consistent brightness at the highest menu-configured brightness setting: First, upgrade Q3 to a FET capable of supplying more current. One such FET is the ZVP2110A available from Digi-Key or Mouser.** If the digit remains dim after upgrading Q3, replace R3 with an 11 ohm resistor to further increase current. And if the digit is still dim, replace R3 with a jumper. Note that Q3 provides power to both the filament and VFD driver chip. Replacing R3 with a jumper or smaller resistor without first upgrading Q3 will increase filament current, but might also result in an insufficient logic supply voltage to the VFD driver chip. That, in turn, could cause faulty display operation. **UPDATE: For anyone who purchased an official Adafruit kit, Adafruit will now provide a free ZVP2110A to resolve the issue: http://forums.adafruit.com/viewtopic.php?p=340772#p340772 :: Flaky Segments :: On some Adafruit clocks, display segments are flaky. The exact symptoms vary depending on the particular clock, but most commonly, the clock will start normally and segments will quickly stop working until few or no segments are active. Also common is a display that only shows one or two blinking segments. But occasionally the symptoms are more bizarre such as a display with all digits and segments continuously lit or a single digit going blank at a certain time. The following threads describe the flaky segment problem and several solutions in more detail: http://forums.adafruit.com/viewtopic.php?f=41&t=47733 http://forums.adafruit.com/viewtopic.php?f=41&t=49619 http://forums.adafruit.com/viewtopic.php?f=41&t=50823 http://forums.adafruit.com/viewtopic.php?f=41&t=51207 The flaky segment problem can be solved by replacing Q3. Although Adafruit will provide a free replacement for Q3, I recommend replacing Q3 with a better FET, such as the ZVP2110A available from Digi-Key or Mouser.** By providing additional current across the VFD filament, the ZVP2110A will also eliminate the dim digit problem described in the previous entry as well as extending tube life by slowing cathode poisoning. **UPDATE: For anyone who purchased an official Adafruit kit, Adafruit will now provide a free ZVP2110A to resolve the issue: http://forums.adafruit.com/viewtopic.php?p=340772#p340772 :: Nonfunctional Drift Correction :: Initially the clock will not perform drift correction. Use the clock normally and the automatic drift correction will eventually enable itself. Accuracy will improve over time. The clock estimates time drift when users change the time by more than 15 seconds. The fastest way to enable drift correction is to (1) set the correct time, (2) wait for the clock to drift by more than 15 seconds, and (3) set the correct time. Occasionally setting an incorrect time will not have much effect on drift correction, and changing time for different timezones or daylight saving is similarly unproblematic. The automatic drift correction method is quite robust: http://forums.adafruit.com/viewtopic.php?p=178611#p178611 :: Crystal Oscillator Problems ("wdt rset") :: The ATmega328p is more prone to oscillator issues than the ATmega168v, and users occasionally encounter oscillator problems after upgrading. Oscillator problems usually result in inconsistent timekeeping; the clock may keep accurate time one day, but not on another. When oscillator problems are severe, the microcontroller's watchdog circuit will detect that time is not advancing and reset the clock in an attempt to fix the problem. After such a reset, the clock will beep and display "wdt rset" to indicate possible time loss due to a watchdog reset. Fixing oscillator issues requires some trial and error, but following the procedure below will likely fix the problem. First, excess flux or burnt flux can cause oscillator problems. Sometimes cleaning the board thoroughly with flux cleaner--or simply alcohol and a toothbrush--will solve the problem. Second, the 20 pF oscillator capacitors included in the Adafruit kit are a bit large. Replacing C8 and C9 with with 10 pF caps will sometimes fix the oscillator. Even if the clock is functioning normally, installing 10 pF caps will increase timekeeping accuracy. Finally, replacing the crystal will sometimes resolve the issue. The replacement should be another 32.768 kHz crystal with a 12.5 pF load capacitance and equivalent series resistance of 30 kOhm or less. The AB38T-32.768KHZ is a good choice and is available from Digi-Key or Mouser. When installing and soldering the crystal, gently push the crystal through the circuit board until there is 2-3 mm of space between the bottom of the crystal and the circuit board. Leaving this space prevents undue stress on the leads which could damage the crystal; it also ensures solder will not make unwanted electrical contact with the metallic crystal housing. The following threads provide more information on oscillator issues after upgrading to the ATmega328p: http://forums.adafruit.com/viewtopic.php?p=189366#p189366 http://forums.adafruit.com/viewtopic.php?f=41&t=51960 ############# ## LICENSE ## ############# The xmas-icetube firmware may be used as described in the LICENSE file.
// Define a function to check if a given year is a leap year function isLeapYear(year: number): boolean { // Leap year is divisible by 4, but not by 100 unless it is also divisible by 400 return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } // Test cases let year = 2020; console.log(year, "is a leap year?", isLeapYear(year)); // Output: true year = 2021; console.log(year, "is a leap year?", isLeapYear(year)); // Output: false year = 1900; console.log(year, "is a leap year?", isLeapYear(year)); // Output: false year = 2000; console.log(year, "is a leap year?", isLeapYear(year)); // Output: true
package com.example.demo.service; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import com.example.demo.entity.Orders; import com.example.demo.model.MailInfo; import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeMessage; @Service public class EmailService { @Autowired JavaMailSender sender; @Autowired private TemplateEngine templateEngine; public void send(MailInfo mail) throws MessagingException { // Tạo message MimeMessage message = sender.createMimeMessage(); // Sử dụng Helper để thiết lập các thông tin cần thiết cho message MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8"); helper.setFrom(mail.getFrom()); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); Map<String, Object> map = new HashMap<>(); map.put("name", mail.getBody().getUser().getFullname()); map.put("ord", mail.getBody().getOrder_details()); map.put("id", mail.getBody().getId()); Context context = new Context(); context.setVariables(map); String htmlBody = templateEngine.process("/util/OrderTemplateEmail", context); helper.setText(htmlBody, true); // Gửi message đến SMTP server sender.send(message); } public void send(String to, String subject, Orders body) throws MessagingException { this.send(new MailInfo(to, subject, body)); } }
document.addEventListener('alpine:init', () => { Alpine.data('usersData',()=>({ mainUsers : [], users: [], pageUsers: [], isLoading: false, showAddModal: false, pageCount: 1, itemsCount: 4, currentPage: 1, newUserInfo: { name:"", username:"", email: "", }, userIdToEdit: null, getUsers(){ this.isLoading = true axios.get("https://jsonplaceholder.typicode.com/users").then((res)=>{ this.mainUsers = res.data this.users = res.data this.pagination() }).finally(()=>{ this.isLoading = false }) }, pagination(){ this.pageCount = Math.ceil(this.users.length / this.itemsCount) // 10 / 4 = 3 let start = (this.currentPage * this.itemsCount) - this.itemsCount let end = this.currentPage * this.currentPage * this.itemsCount this.pageUsers = this.users.slice(start, end) console.log(this.pageUsers) // this.users.slice(0,3) }, nextPage(){ this.currentPage++ if (this.currentPage > this.pageCount){ this.currentPage = this.pageCount } this.pagination() }, prevPage(){ this.currentPage-- if (this.currentPage < 1) this.currentPage = 1 this.pagination() }, handleChangeItemCount(e){ this.itemsCount = e.value if(this.itemsCount < 1) this.itemsCount = 1 if(this.itemsCount > this.users.length) this.itemsCount = this.users.length this.pagination() }, handleSearch(e){ setTimeout(()=>{ this.users = this.mainUsers.filter(user=>(user.name.includes(e.value) || user.username.includes(e.value) || user.email.includes(e.value))) this.currentPage = 1 this.pagination() }, 100) }, handleSubmitAddUserForm(){ this.isLoading = true axios.post("https://jsonplaceholder.typicode.com/users", this.newUserInfo).then((res)=>{ if (res.status == 201){ this.mainUsers.push(res.data) this.showAddModal = false this.handleResetForm() this.pagination() M.toast({html: 'User created successfully ... ', classes: 'rounded green'}) } }).finally(()=>{ this.isLoading = false }) }, handleResetForm(){ this.newUserInfo = { name: "", username: "", email: "", } }, handleDeleteUser(userId){ var toastHTML = '<span>Are you sure?('+userId+')</span><button class="btn-flat toast-action"x-on:click="handleConfirmDeleteUser('+userId+')">Delete</button>'; M.toast({html: toastHTML}); }, handleConfirmDeleteUser(userId){ this.isLoading = true axios.delete("https://jsonplaceholder.typicode.com/users/"+userId).then((res)=>{ if (res.status == 200) { this.mainUsers = this.mainUsers.filter(user=>user.id != userId) this.users = this.users.filter(user=>user.id != userId) this.pagination() M.toast({html: 'User deleted successfully...', classes: 'green'}) } }).finally(()=>{ this.isLoading = false }) }, handleUpdateUser(user){ axios.get("https://jsonplaceholder.typicode.com/users/"+user.id).then(res=>{ if (res.status == 200){ this.newUserInfo={ name:res.data.name, username:res.data.username, email:res.data.email, }, this.userIdToEdit = res.data.id } }) this.showAddModal = true }, handleConfirmEditUser(){ this.isLoading = true axios.put("https://jsonplaceholder.typicode.com/users/"+this.userIdToEdit, this.newUserInfo).then((res)=>{ if (res.status === 200) { const userIndex = this.mainUsers.findIndex(user=>user.id == this.userIdToEdit) this.mainUsers[userIndex] = res.data this.showAddModal= false this.handleResetForm() this.userIdToEdit = null this.pagination() M.toast({html: 'User updated successfully...', classes: 'green'}) } }).finally(()=>{ this.isLoading = false }) } })) })
import cors from 'cors'; import express, { Application, NextFunction, Request, Response } from 'express'; import httpStatus from 'http-status'; import globalErrorHandler from './app/middlewares/globalErrorHandler'; import routes from './app/routes/index'; const app: Application = express(); app.use(cors()); // parser app.use(express.json()); app.use(express.urlencoded({ extended: true })); // routes app.use('/api/v1/', routes); // testing app.get('/', async (req: Request, res: Response) => { res.send('Server is running'); }); // global error handler middleware app.use(globalErrorHandler); // handle not found route app.use((req: Request, res: Response, next: NextFunction) => { res.status(httpStatus.NOT_FOUND).json({ success: false, message: 'Not Found', errorMessages: [ { path: req.originalUrl, message: 'Api Not Found', }, ], }); next(); }); export default app;
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify from flask_mysql_connector import MySQL from config import DB_USERNAME, DB_PASSWORD, DB_NAME, DB_HOST, SECRET_KEY, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, MAIL_USE_TLS, MAIL_USE_SSL, cloud_name, api_key, api_secret from flask_wtf.csrf import CSRFProtect from flask_login import LoginManager, login_user, current_user from flask_mail import Mail from flask_socketio import SocketIO import cloudinary import cloudinary.uploader import cloudinary.api mysql = MySQL() login_manager = LoginManager() mail = Mail() csrf = CSRFProtect() socketio = SocketIO() def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = SECRET_KEY app.config['MYSQL_HOST'] = DB_HOST app.config['MYSQL_USER'] = DB_USERNAME app.config['MYSQL_PASSWORD'] = DB_PASSWORD app.config['MYSQL_DATABASE'] = DB_NAME app.config['MAIL_SERVER']= MAIL_SERVER app.config['MAIL_PORT'] = MAIL_PORT app.config['MAIL_USERNAME'] = MAIL_USERNAME app.config['MAIL_PASSWORD'] = MAIL_PASSWORD app.config['MAIL_USE_TLS'] = MAIL_USE_TLS app.config['MAIL_USE_SSL'] = MAIL_USE_SSL cloudinary.config ( cloud_name=cloud_name, api_key=api_key, api_secret=api_secret, secure = True ) mysql.init_app(app) csrf.init_app(app) mail.init_app(app) socketio.init_app(app) login_manager = LoginManager(app) @login_manager.user_loader def load_user(user_id): return User.get(user_id) @app.route("/", methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = User.authenticate(username, password) if user: login_user(user) User.record_login(user.role.upper(), current_user.username) if user.role == 'admin': return redirect(url_for('admin.dashboard')) elif user.role == 'doctor': return redirect(url_for('doctor.dashboard')) elif user.role == 'medtech': return redirect(url_for('medtech.dashboard')) elif user.role == 'receptionist': return redirect(url_for('receptionist.dashboard')) else: flash("The username or password you've entered is incorrect", 'error') return render_template("login.html") @socketio.on('connect') def handle_connect(): print('Client connected') @socketio.on('disconnect') def handle_disconnect(): print('Client disconnected') from app.routes.admin_bp import admin_bp from app.routes.doctor_bp import doctor_bp from app.routes.medtech_bp import medtech_bp from app.routes.receptionist_bp import receptionist_bp from app.models.login_m import User app.register_blueprint(admin_bp, url_prefix='/admin/') app.register_blueprint(doctor_bp, url_prefix='/doctor/') app.register_blueprint(medtech_bp, url_prefix='/medtech/') app.register_blueprint(receptionist_bp, url_prefix='/receptionist/') return app
* { margin: 0; padding: 0; body { width: 100%; .nav-container { width: 100%; display: flex; flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 10px; .icon-container { margin: 10px; font-size: 28px; line-height: 30px; } .manu-container { ul { display: flex; li { display: inline; margin: 3px; a { text-decoration: none; color: black; margin-right: 15px; font-size: 25px; } a:hover { font-size: 30px; font-weight: bold; transition: all .4s ease-in; color: rgba(255, 141, 34, 0.884); } } } } } main { // banner section .banner-container { display: flex; gap: 5px; margin: 20px; margin-top: 40px; justify-content: space-between; align-items: center; // border: 2px solid green; .banner-description { text-align: start; h2 { margin-bottom: 8px; } } .banner-img-div { width: 100%; // border: 2px solid black; position: relative; .banner-img { width: 100%; img { width: 100%; } &:hover{ box-shadow: 5px 5px 10px black; } } .Chef-div { background: #000; color: white; padding: 10px; width: fit-content; position: absolute; top: 290px; right: 30px; } } } .picake-container { display: flex; gap: 5px; flex-direction: row-reverse; margin: 20px; margin-top: 100px; justify-content: space-between; align-items: center; // border: 2px solid red; .picake-description { width: 50%; text-align: end; h2 { margin-bottom: 8px; } // border: 2px solid yellow; } .picake-img-div { flex: 1; width: 50%; position: relative; // border: 2px solid green; .picake-img { width: 100%; // border: 2px solid gray; img { width: 100%; } &:hover{ box-shadow: 5px 5px 10px black; } } .Chef2-div { background: #000; color: white; padding: 10px; width: fit-content; position: absolute; bottom: -30px; left: 30px; } } } } footer { background-color: rgb(5, 5, 5); text-align: center; .footer-elements { margin-top: 50px; display: flex; flex-direction: row; justify-content: space-around; background: rgb(48, 48, 48); padding: 20px; align-items: center; color: white; .useful-links { text-align: center; ul { margin-top: 8px; li { display: block; a { text-decoration: none; color: white; &:hover{ font-size: 20px; color: coral; } } } } } .comment-area { text-align: center; h4 { padding-bottom: 10px; } textarea{ border-radius: 5px; padding: 10px; &:hover{ box-shadow: 4px 4px 10px white; } } input { margin-top: 10px; padding: 10px 12px; color: white; border: none; border-radius: 5px; background-color: tomato; &:hover { cursor: pointer; font-weight: bold; padding: 14px 16px; box-shadow: 3px 3px 8px white; } } } .contact-div { text-align: center; ul { margin-top: 8px; li { display: inline; a { text-decoration: none; color: white; margin: 5px; &:hover{ color: rgb(175, 0, 0); font-size: 25px; transition: all .3s ease-out; } } } } } } small{ color: white; width: 100%; width: 100%; } } } } // responsive @media screen and (max-width:576px) { body { .nav-container { display: flex; flex-direction: column; gap: 10px; .manu-container { ul { display: flex; flex-direction: column; text-align: center; } } } main { // banner .banner-container { flex-direction: column; .banner-img-div { // .banner-img{ // } .Chef-div { top: 120px; right: 10px; // h6{ // font-size: 10px; // margin-bottom: 5px; // } // p{ // font-size: 8px; // } // h4{ // font-size: 15px; // } } } } .picake-container { flex-direction: column; .picake-description { width: 100%; } .picake-img-div { width: 100%; } } } footer{ .footer-elements{ flex-direction: column; gap: 20px; h4{ color: lightblue; } } } } }
+++ title = 'Crafting Robustness: Achieving 100% Test Coverage in Lexer Development' date = 2023-09-07T03:20:23+02:00 draft = false author = 'Denis Chevalier' description = 'Journey into testing a lexer.' tags = ['compiler','project','status','lexical analyzer', 'lexer', 'testing'] categories = ['status', 'blog'] series = ['Project Advencement'] +++ ## Introduction In the arcane world of compilers, lexers are the unsung heroes. Acting as the initial phase of any compilation process, a lexer breaks down an input stream into constituent tokens, setting the stage for parsing and eventual execution. For those embarking on the grand adventure of crafting a compiler for a minimalist lambda calculus language, the lexer is the first proving ground. In this exposé, we will delineate the pathway we took: the testing strategies we employed, the roadblocks we encountered, and the indescribable satisfaction of hitting a 100% test coverage rate. ## The Importance of Testing Why spend countless hours writing test cases? The answer lies in the very nature of lexing itself—a process susceptible to a plethora of edge cases. Lexers are the gatekeepers, responsible for handling everything from keywords and identifiers to string literals and white spaces. Each token must be correctly identified and tagged for the subsequent phases to function accurately. Inadequate or lackadaisical testing could lead to hidden bugs, which might surface later, often at the least opportune moments. **Example**: Consider a string containing both double quotes and escape sequences. If not tested properly, the lexer could misinterpret this string, leading to a cascade of errors downstream. ## Testing Strategy: Structured Yet Flexible A strategic approach was essential. Our testing modus operandi consisted of three distinct but interrelated steps: 1. **Unit Testing**: We initiated the process with the elemental. By using a Test-Driven Development (TDD) methodology, we first wrote tests for individual tokens like `IDENT`, `STRING`, and special characters. **Example**: To test the `IDENT` token, we fed an arbitrary identifier string into the lexer and compared the output token type with the expected `IDENT` type. 2. **Integration Testing**: Unit tests are indispensable, but they only paint a partial picture. To address this limitation, integration tests were conducted to ascertain the lexer's aptitude in forming syntactically accurate token streams. **Example**: A sample code snippet containing assignments and operations was processed by the lexer, and the resultant token stream was checked for correct sequence and type. 3. **Special Cases**: The devil is in the details, and in lexing, the details often reside in edge cases, special characters, and escape sequences. **Example**: To adequately test escape sequences, we ran multiple test cases that included all potential combinations of backslashes and subsequent characters, examining if the lexer handled them as anticipated. ## Challenges Encountered 1. **Token Generation**: A perplexing issue was the inexplicable emergence of an `ILLEGAL` token. This conundrum entailed exhaustive debugging. **Example**: Despite meticulously setting the `EOF`, an `ILLEGAL` token with position `0 - 0` surfaced, necessitating a deep-dive into the recursive lexing logic. 2. **Escape Sequences**: Strings with escape sequences were exceptionally demanding, as they necessitated an intricate handling logic. **Example**: A string like `\"Hello World\"` had to be lexed correctly to `STRING` while preserving the escape sequences intact. 3. **Monad Utilization**: Employing a monad pattern, specifically `Either[Token]`, offered robust error-handling mechanisms but introduced an additional layer of complexity. **Example**: Any failure in tokenization would result in a `Left[Error]` monadic expression, which had to be efficiently propagated and handled. ## Lessons from Challenges The quest was replete with teachable moments. The aforementioned `ILLEGAL` token mystery led us down a rabbit hole of the lexer's `EOF` handling mechanisms, token initialization, and error propagation strategies. We were able to rectify it by modifying how the lexer handled end states. ## Satisfaction of Completion For an engineer, few accomplishments are as sweet as hitting that 100% test coverage mark. In lexer development, this metric is more than a badge of honor; it is a testament to the lexer's resilience, robustness, and readiness for real-world applications. ## Conclusion Achieving a lexically sound lexer was a journey rife with intellectual challenges and equally enriching rewards. It involved not just coding prowess but also strategic acumen, resilience, and above all, an uncompromising focus on quality. The end result—a lexer with 100% test coverage—is both a personal and professional milestone, and serves as an exemplar for those aspiring to similar feats in the complex world of compiler construction.
<template> <div class="app-container"> <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="105px" :class="[formShow?'searchform':'searchform1']" > <i class="el-icon-d-arrow-right icon" @click="formShow = !formShow"></i> <el-form-item label="客户名/电话" prop="customerName"> <el-select v-model="queryParams.id" filterable remote clearable reserve-keyword placeholder="请输入客户名/手机号码" style="width:200px" :remote-method="remoteMethod" :loading="loading" @change="handleChangeName" @clear="handleClear" > <el-option v-for="item in customerOptions" :key="item.id" :label="item.customerName + ' ' + item.customerPhone" :value="item.id" > </el-option> </el-select> </el-form-item> <el-form-item label="客户来源" prop="customerSource"> <el-input v-model="queryParams.customerSource" placeholder="请输入客户来源" clearable style="width: 200px" @keyup.enter.native="handleQuery" /> </el-form-item> <el-form-item label="客户所在省" prop="prov"> <el-input v-model="queryParams.prov" placeholder="请输入省" clearable style="width: 200px" @keyup.enter.native="handleQuery" /> </el-form-item> <el-form-item label="客户所在市" prop="city"> <el-input v-model="queryParams.city" placeholder="请输入市" clearable style="width: 200px" @keyup.enter.native="handleQuery" /> </el-form-item> <!--<el-form-item label="代理商" prop="receiveId"> <el-select v-model="queryParams.receiveId" placeholder="请选择状态" clearable style="width: 200px"> <el-option v-for="(item,index) in rzCompanyList" :key="'key'+index" :label="item.companyName" :value="item.id" /> </el-select> </el-form-item> --> <el-form-item label="合作商" prop="receiveId"> <el-select v-model="queryParams.receiveId" filterable remote clearable reserve-keyword placeholder="请输入合作商" style="width:200px" :remote-method="remoteMethodt" :loading="loading" @change="handleChangereceiveId" @clear="handleClear1" > <el-option v-for="item in companyOptions" :key="item.id" :label="item.companyName" :value="item.id" > </el-option> </el-select> </el-form-item> <el-form-item label="客户QQ" prop="customerQQ"> <el-input v-model="queryParams.customerQQ" placeholder="请输入客户QQ" clearable style="width: 200px" @keyup.enter.native="handleQuery" /> </el-form-item> <el-form-item label="客户微信" prop="customerWeixin"> <el-input v-model="queryParams.customerWeixin" placeholder="请输入客户微信" clearable style="width: 200px" @keyup.enter.native="handleQuery" /> </el-form-item> <el-form-item label="接收信息时间" prop="receiveTime"> <el-date-picker clearable style="width: 200px" v-model="queryParams.receiveTime" type="date" value-format="yyyy-MM-dd" placeholder="选择合作商接收信息时间" > </el-date-picker> </el-form-item> <el-form-item label="下次跟进时间" prop="followTime"> <el-date-picker clearable style="width: 200px" v-model="queryParams.followTime" type="date" value-format="yyyy-MM-dd" placeholder="选择跟进时间" > </el-date-picker> </el-form-item> <el-form-item label="当天跟进时间" prop="createTime"> <el-date-picker clearable style="width: 200px" v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd" placeholder="选择最近跟进时间" > </el-date-picker> </el-form-item> <el-form-item label="申诉状态" prop="returnState"> <el-select v-model="queryParams.returnState" placeholder="请选择回访专员确认的申诉状态" clearable style="width: 200px" > <el-option v-for="dict in returnStateOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" /> </el-select> </el-form-item> <el-form-item label="成交状态" prop="dealState"> <el-select v-model="queryParams.dealState" placeholder="请选择" clearable style="width: 200px" > <el-option v-for="dict in dealStateOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" /> </el-select> </el-form-item> <el-form-item> <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery" >搜索</el-button > <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" >重置</el-button > </el-form-item> </el-form> <el-row :gutter="10" class="mb8"> <div class="top-right-btn"> <el-tooltip class="item" effect="dark" content="刷新" placement="top"> <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" /> </el-tooltip> <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top" > <el-button size="mini" circle icon="el-icon-search" @click="showSearch = !showSearch" /> </el-tooltip> </div> </el-row> <el-table v-loading="loading" :data="sourceList" @selection-change="handleSelectionChange" @row-click="dialogVisibles" height='720' > <el-table-column type="selection" width="55" align="center" /> <el-table-column label="资源id" align="center" prop="id"/> <el-table-column label="客户名称" align="center" prop="customerName" min-width="120" /> <el-table-column label="业务描述" align="center" prop="categoryText" min-width="400" /> <el-table-column label="客户来源" align="center" prop="customerSource"/> <el-table-column label="省" align="center" prop="prov"/> <el-table-column label="市" align="center" prop="city"/> <el-table-column label="接收用户" align="center" prop="userId" min-width="200" > <template slot-scope="scope"> <span>{{ scope.row.nickName ? scope.row.nickName : scope.row.userName }}</span> </template> </el-table-column> <el-table-column label="合作商" align="center" prop="companyName" min-width="120" /> <el-table-column label="合作商接收信息时间" align="center" prop="receiveTime" min-width="180" > <template slot-scope="scope"> <span>{{ parseTime(scope.row.receiveTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span> </template> </el-table-column> <el-table-column label="跟进时间" align="center" prop="followTime" width="180" > <template slot-scope="scope"> <span>{{ parseTime(scope.row.followTime, "{y}-{m}-{d}") }}</span> </template> </el-table-column> <el-table-column label="合作商确认" align="center" prop="agentState" :formatter="agentStateFormat" min-width="120" /> <el-table-column label="回访专员确认" align="center" prop="returnState" :formatter="returnStateFormat" min-width="120" /> <el-table-column label="商机类型" align="center" min-width="120"> <template slot-scope="scope"> <span>{{ scope.row.categoryCity + scope.row.categoryType }}</span> </template> </el-table-column> <el-table-column label="商机级别" align="center" prop="sourceTypeLv" :formatter="sourceTypeLvFormat" /> <el-table-column label="是否成交" align="center" prop="dealState" :formatter="dealStateFormat" /> <el-table-column label="备注" align="center" prop="remark" min-width="320" /> <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" min-width="220" > <template slot-scope="scope"> <el-button size="mini" type="text" icon="el-icon-view" @click="handleShowFollowList(scope.row)" >跟进记录</el-button > </template> </el-table-column> </el-table> <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" /> <!-- 用户展示框 --> <el-dialog :title="title" :visible.sync="dialogVisible" width="700px" style="margin-top:22vh;" append-to-body :destroy-on-close="true" :close-on-click-modal="false" > <el-form ref="form" :model="VisiblesList" label-width="100px" :status-icon="true" > <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="客户名称" prop="customerName"> <el-input v-model="VisiblesList.customerName" /> </el-form-item> </el-col> <!-- <el-col :span="12"> <el-form-item label="客户电话"> <el-input v-model="VisiblesList.customerPhone" maxLength="12" :show-word-limit="true" /> </el-form-item> </el-col>--> </el-row> <!-- <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="客户QQ" prop="customerQQ"> <el-input v-model="VisiblesList.customerQQ" maxLength="15" /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="客户微信" prop="customerWeixin"> <el-input v-model="VisiblesList.customerWeixin" maxLength="30" :show-word-limit="true" /> </el-form-item> </el-col> </el-row>--> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="所属区域" prop="customerQQ"> <el-input v-model="VisiblesList.prov" maxLength="15" /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="客户来源" prop="customerWeixin"> <el-input v-model="VisiblesList.customerSource" maxLength="30" :show-word-limit="true" /> </el-form-item> </el-col> </el-row> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="合作商" prop="customerQQ" > <el-input v-model="VisiblesList.companyName" maxLength="15" /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="接收时间" prop="customerWeixin"> <el-input v-model="VisiblesList.receiveTime" maxLength="30" :show-word-limit="true" /> </el-form-item> </el-col> </el-row> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="接收业务员" prop="customerQQ"> <el-input v-model="VisiblesList.nickName" maxLength="15" /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="下次跟进时间" prop="customerWeixin"> <el-input v-model="VisiblesList.followTime" maxLength="30" :show-word-limit="true" /> </el-form-item> </el-col> </el-row> <el-form-item label="业务描述" prop="categoryText"> <el-input type="textarea" :rows="2" class="resizeNone" v-model="VisiblesList.categoryText" /> </el-form-item> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="合作商确认" prop="customerQQ" :formatter="agentStateFormat"> <el-input v-model="VisiblesList.agentStateName" maxLength="15" /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="服务顾问确认" prop="customerWeixin" > <el-input v-model="VisiblesList.returnStateName" maxLength="30" :show-word-limit="true" /> </el-form-item> </el-col> </el-row> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="商机类型" prop="customerQQ"> <el-input v-model="VisiblesList.categoryType" maxLength="15" /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="成交状态" prop="customerWeixin"> <el-input v-model="VisiblesList.dealStateName" maxLength="30" :show-word-limit="true" /> </el-form-item> </el-col> </el-row> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="cancel">关闭</el-button> </div> </el-dialog> <!-- 跟进记录 --> <el-dialog title="跟进记录" :visible.sync="followsOpen" width="700px" style="margin-top:15vh;" append-to-body > <el-form ref="form" :model="form" :rules="followRules" label-width="120px" > <!-- <el-form-item label="跟进内容:" prop="content"> <el-input type="textarea" :rows="2" class="resizeNone" v-model="form.content" placeholder="请输入跟进内容" style="width:90%;" /> </el-form-item>--> </el-form> <div class="follow-div"> <div class="follow-item " v-for="(item, index) in followlistAll" :key="index" > <div> <div> <span>{{ item.nick_name }}</span> <span>({{ item.role_name }})</span> </div> <span>{{ item.phonenumber }}</span> </div> <div> <div> <span>{{ item.content }}</span> </div> <span style=" float: left;margin-left:0;">下次跟进时间:{{item.bcfollow_time, "yyyy-MM-dd " | format}} <span style="margin-left:340px">{{ item.create_time, "yyyy-MM-dd hh:mm:ss" | format }}</span> </span> </div> </div> </div> <div slot="footer" class="dialog-footer"> <el-button type="primary" @click="followSubmitForm">提 交</el-button> <el-button @click="cancel">取 消</el-button> </div> </el-dialog> </div> </template> <script> import { listSource, rzCompanyType, getSource, delSource, addSource, updateSource, exportSource, getSourceAgent, getUserlist, listSourceType, getCustomerList, getCompanyList } from "@/api/share/source"; import { listFollow, getFollow, getFollowlist, delFollow, addFollow, updateFollow, exportFollow } from "@/api/share/follow"; import { throttle } from "@/utils/ruoyi"; /*获取省市区信息*/ import { // provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from "element-china-area-data"; export default { name: "Source", data() { return { dialogVisible: false, VisiblesList: {}, remark: null, // 遮罩层 loading: true, // 选中数组 ids: [], // 非单个禁用 single: true, // 非多个禁用 multiple: true, // 显示搜索条件 showSearch: true, // 总条数 total: 0, // 资源分配表格数据 sourceList: [], // 弹出层标题 title: "", //代理商信息列表 rzCompanyList: [], // 是否显示弹出层 open: false, // 代理商接收状态 10 已接收 20未接收 字典 followStateOptions: [], // 代理商确认信息的有效状态 10有效 20无效字典 agentStateOptions: [], // 回访专员确认信息有效状态 10有效 20无效 0待审核字典 returnStateOptions: [], // 商机级别ABCD字典 sourceTypeLvOptions: [], // 是否成交10 成交 0 未成交字典 dealStateOptions: [], followlistAll: [], // 查询参数 queryParams: { pageNum: 1, pageSize: 10, id: null, customerName: null, customerPhone: null, categoryText: null, customerSource: null, prov: null, city: null, county: null, receiveId: null, receiveTime: null, followTime: null, agentState: null, returnState: null, sourceTypeLv: null, sourceTypeId: null, dealState: null, categoryCity: null, categoryType: null, customerQQ: null, customerWeixin: null, createTime: null }, querComParams: { createDate: null }, customerOptions: [], companyOptions: [], // 表单参数 form: {}, isResouceShow: 1, // 表单校验 rules: { customerName: [ { required: true, message: "客户名称不能为空", trigger: "blur" } ], customerPhone: [{ message: "客户电话不能为空", trigger: "blur" }], customerSource: [ { required: true, message: "客户来源不能为空", trigger: "blur" } ], prov: [{ required: true, message: "省不能为空", trigger: "blur" }], county: [{ required: true, message: "区不能为空", trigger: "blur" }], receiveId: [ { required: true, message: "请选择合作商", trigger: "blur" } ], returnState: [ { required: true, message: "回访确认信息状态不能为空", trigger: "blur" } ], selectedOptions: [ { required: true, message: "省市区信息不能为空", trigger: "blur" } ], sourceTypeArr: [ { required: true, message: "请选择商业类型", trigger: "blur" } ] // userId:[{ required: true, message: '请选择业务员', trigger: 'blur' }] }, followRules: { content: [ { required: true, message: "跟进内容不能为空", trigger: "blur" } ], followTime: [ { required: true, message: "下次跟进时间不能为空", trigger: "blur" } ] }, options: regionData, typeOption: [], followsOpen: false, followData: {}, agentOptions: [], userOptions: [], agentFrom: [], formShow:true }; }, created() { this.getList(); // this.getType() this.getSourceType(); this.getDicts("refer_state").then(response => { this.agentStateOptions = response.data; this.returnStateOptions = response.data; this.followStateOptions = response.data; }); this.getDicts("source_type_lv").then(response => { this.sourceTypeLvOptions = response.data; }); this.getDicts("deal_state").then(response => { // console.info(response) if (response.code) { this.dealStateOptions = response.data; } }); this.getDicts("agent_from").then(response => { this.agentFrom = response.data; }); }, // 手机号码过滤 filters: { phoneFiler(val) { if (val) { let start = val.slice(0, 3); let end = val.slice(-4); return `${start}****${end}`; } else { return ``; } } }, methods: { dialogVisibles(row, column, event) { if(column.property){ let id = row.id; this.dialogVisible = true; getSource(id).then(response => { let data = response.data data.agentStateName = this.selectDictLabel(this.agentStateOptions,data.agentState) data.returnStateName = this.selectDictLabel(this.returnStateOptions,data.returnState) data.dealStateName = this.selectDictLabel( this.dealStateOptions,data.dealState) this.VisiblesList = data; }); } }, /** 查询资源分配列表 */ getList() { this.loading = true; listSource(this.queryParams).then(response => { // console.log(response) this.sourceList = response.rows; this.total = response.total; this.loading = false; }); }, // 远程搜索客户名称电话 remoteMethod(query) { let that = this; if (query !== "") { this.loading = true; setTimeout(() => { this.loading = false; // this.companyOptions = this.list.filter(item => { // return item.label.toLowerCase() // .indexOf(query.toLowerCase()) > -1; // }); getCustomerList({ customerName: query }) .then(res => { console.log(res); if (res.code == 200) { this.customerOptions = res.rows || []; } console.info(res); }) .catch(err => {}); }, 200); } else { this.customerOptions = []; } }, // 选择客户姓名的同时把手机也传给后台进行搜索 handleChangeName(val){ // console.log(this.customerOptions) // console.log(val) this.customerOptions.map(item=>{ if(item.id == val){ this.queryParams.customerName = item.customerName this.queryParams.customerPhone = item.customerPhone } return item }) this.getList() }, // 清除选择的客户名称和电话 内容 handleClear(){ this.queryParams.customerName = null this.queryParams.customerPhone = null this.getList() }, //远程搜索代理商 remoteMethodt(query) { // console.log(query) let that = this; if (query !== "") { this.loading = true; setTimeout(() => { this.loading = false; // this.companyOptions = this.list.filter(item => { // return item.label.toLowerCase() // .indexOf(query.toLowerCase()) > -1; // }); getCompanyList({ companyName: query }) .then(res => { console.log(res); if (res.code == 200) { this.companyOptions = res.rows || []; } console.info(res); }) .catch(err => {}); }, 200); } else { this.companyOptions = []; } }, // 选择代理商同时进行搜索 handleChangereceiveId(val){ // console.log(this.customerOptions) console.log(val) this.queryParams.receiveId = val; this.getList() }, // 清除代理商 内容 handleClear1(){ this.queryParams.receiveId = null this.getList() }, // 根据省市区选择商机类型 getSourceType() { var data = { prov: this.form.prov || "", city: this.form.city || "", county: this.form.county || "" }; if (data.prov && data.city && data.county) { getSourceAgent(data).then(res => { if (res.code == 200) { console.log(res); let data = res.sourceType || []; let tempList = [], temp = []; data.map((item, index, array) => { let city = item.categoryCity; if (temp.includes(city)) { } else { temp.push(city); let ch = array.filter((x, y, a) => { x.label = x.categoryType + " (" + x.content + ")"; return x.categoryCity == city; }); tempList.push({ label: city, id: index, children: ch || [] }); } }); this.typeOption = tempList || []; } else { this.typeOption = []; } }); } }, //根据省市区 + 商机 获取代理商 getAgentList() { var data = { prov: this.form.prov || "", city: this.form.city || "", county: this.form.county || "", sourceTypeId: this.form.sourceTypeId || "" }; if (data.prov && data.city && data.county && data.sourceTypeId) { getSourceAgent(data).then(response => { // console.info(response) if (response.code == 200) { this.form.receiveId = null; this.form.userId = null; this.agentOptions = response.customerSources || []; } else { this.agentOptions = []; } }); } }, //根据代理商 获取 业务员 getSalesman() { var data = { companyId: this.form.companyId || "" }; if (data.companyId) { getUserlist(data).then(response => { // console.info(response) if (response.code == 200) { this.remark = response.companyAndUser.companyRemark; console.log(response.companyAndUser.companyRemark); this.userOptions = response.companyAndUser.sharUser || []; } else { this.userOptions = []; } }); } }, /* 省市选择 */ handleChange(value) { // console.log(value) (this.remark = null), (this.form.sourceTypeArr = null); (this.form.receiveId = null), (this.form.userId = null), ++this.isResouceShow; this.form.selectedOptions = value; this.form.prov = CodeToText[value[0]]; this.form.city = CodeToText[value[1]]; this.form.county = CodeToText[value[2]]; if (this.form.county == "市辖区") { this.$message.error("请选择具体的市辖区"); this.typeOption = []; this.userOptions = []; this.agentOptions = []; return; } else { this.getSourceType(); } }, handleChange2: function(value) { (this.remark = null), // console.log(value) (this.form.receiveId = null), (this.form.userId = null), (this.form.sourceTypeId = value[1]); this.form.sourceTypeArr = value; this.getAgentList(); }, handleUser: function(value) { console.log(value); (this.form.userId = null), (this.form.companyId = value); this.getSalesman(); }, // getCompUserlist: function() { // var data = { // companyId: this.form.companyId || '' // } // if (data.companyId) { // getUserlist(data).then(response => { // console.info(response) // console.info(response.sharUser) // if (response.code == 200) { // this.userOptions = response.sharUser || [] // } else { // this.userOptions = [] // } // }) // } // }, // 代理商接收状态 10 已接收 20未接收 字典翻译 followStateFormat(row, column) { return this.selectDictLabel(this.followStateOptions, row.followState); }, // 代理商确认信息的有效状态 10有效 20无效字典翻译 agentStateFormat(row, column) { return this.selectDictLabel(this.agentStateOptions, row.agentState); }, // 回访专员确认信息有效状态 10有效 20无效 0待审核字典翻译 returnStateFormat(row, column) { return this.selectDictLabel(this.returnStateOptions, row.returnState); }, // 商机级别ABCD字典翻译 sourceTypeLvFormat(row, column) { return this.selectDictLabel(this.sourceTypeLvOptions, row.sourceTypeLv); }, // 是否成交10 成交 0 未成交字典翻译 dealStateFormat(row, column) { return this.selectDictLabel(this.dealStateOptions, row.dealState); }, // 取消按钮 cancel() { this.dialogVisible = false; this.VisiblesList = []; this.remark = null; this.open = false; this.followsOpen = false; this.reset(); }, // bfclose:function(done){ // this.reset(); // done(); // }, // 表单重置 reset() { (this.remark = null), (this.form = { id: null, customerName: null, customerPhone: null, categoryText: null, customerSource: null, prov: null, city: null, county: null, receiveId: null, receiveTime: null, followTime: null, agentState: null, returnState: null, sourceTypeLv: null, dealState: null, createBy: null, createTime: null, updateBy: null, updateTime: null, remark: null, content: null, selectedOptions: null, sourceTypeId: null, sourceTypeArr: null, userId: null, customerQQ: null, customerWeixin: null }); this.resetForm("form"); }, /** 搜索按钮操作 */ handleQuery() { this.queryParams.pageNum = 1; this.getList(); }, // guan(){ // this.remark=null // }, /** 重置按钮操作 */ resetQuery() { this.resetForm("queryForm"); this.handleQuery(); }, // 多选框选中数据 handleSelectionChange(selection) { this.ids = selection.map(item => item.id); this.single = selection.length !== 1; this.multiple = !selection.length; }, /** 新增按钮操作 */ handleAdd() { this.reset(); this.open = true; this.title = "添加资源分配"; }, /** 修改按钮操作 */ handleUpdate(row) { this.reset(); const id = row.id || this.ids; getSource(id).then(response => { console.info(response); let data = response.data; let selectedOptions = []; selectedOptions.push(TextToCode[data.prov].code); selectedOptions.push(TextToCode[data.prov][data.city].code); selectedOptions.push( TextToCode[data.prov][data.city][data.county].code ); data.selectedOptions = selectedOptions; data.sourceTypeArr = data.sourceTypeId ? [data.sourceTypeId] : null; this.form = data; this.open = true; this.title = "修改资源分配"; }); }, /** 提交按钮 */ submitForm: throttle(function() { this.remark = null; console.info(this.form); this.$refs["form"].validate(valid => { if (valid) { if (this.form.id != null) { updateSource(this.form).then(response => { if (response.code === 200) { this.msgSuccess("修改成功"); this.open = false; this.getList(); } }); } else { addSource(this.form).then(response => { if (response.code === 200) { this.msgSuccess("新增成功"); this.open = false; this.getList(); } }); } } else { console.info(valid); } }); }, 6000), /** 删除按钮操作 */ handleDelete(row) { const ids = row.id || this.ids; this.$confirm( '是否确认删除资源分配编号为"' + ids + '"的数据项?', "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" } ) .then(function() { return delSource(ids); }) .then(() => { this.getList(); this.msgSuccess("删除成功"); }) .catch(function() {}); }, /** 导出按钮操作 */ handleExport() { const queryParams = this.queryParams; this.$confirm("是否确认导出所有资源分配数据项?", "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }) .then(function() { return exportSource(queryParams); }) .then(response => { this.download(response.msg); }) .catch(function() {}); }, /**获取该用户的所有跟进信息*/ handleShowFollowList(row) { this.loading = true; this.followData = { customerId: row.id }; getFollowlist(this.followData).then(response => { console.log(response); this.followlistAll = response.follows || []; this.loading = false; this.followsOpen = true; }); console.info(row); }, /** 跟进记录提交按钮 */ followSubmitForm() { this.$refs["form"].validate(valid => { if (valid) { var data = this.followData; data.content = this.form.content; // data.followTime = this.form.followTime console.log(data); addFollow(data).then(response => { if (response.code === 200) { this.msgSuccess("新增成功"); this.open = false; getFollowlist(data).then(response => { this.followlistAll = response.follows || []; console.log(this.followlistAll); this.loading = false; this.reset(); }); } }); } }); }, querySearch(queryString, cb) { var restaurants = this.agentFrom; var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants; // 调用 callback 返回建议列表的数据 cb(results); }, createFilter(queryString) { return restaurant => { return ( restaurant.dictLabel .toLowerCase() .indexOf(queryString.toLowerCase()) === 0 ); }; }, handleSelectAgentFrom(item) { console.log(item); } } }; </script> <style rel="stylesheet/scss" lang="scss"> .follow-div { max-height: 40vh; display: flex; flex-direction: column; padding: 15px; overflow-y: auto; } .follow-item { display: flex; flex-direction: column; padding: 12px 12px; border-radius: 8px; box-shadow: 0 0 15px 3px rgba(24, 60, 150, 0.1) !important; margin-bottom: 15px; } .follow-item > div:first-child { display: flex; flex-direction: row; justify-content: space-between; width: 100%; } .follow-item > div:nth-child(2) { display: flex; flex-direction: column; justify-content: flex-end; width: 100%; margin-top: 8px; } .follow-item > div:nth-child(2) > div { border: 1px #eee solid; border-radius: 5px; padding: 8px; } .follow-item > div:nth-child(2) > span { margin-top: 8px; margin-left: auto; } .el-dialog__footer { padding-top: 0px; } .resizeNone { .el-textarea__inner { //el_input中的隐藏属性 resize: none; //主要是这个样式 } } .searchform{ position:relative; height:58px; overflow: hidden; } .searchform1{ position:relative; height: auto; } .searchform1 .icon{ font-size: 22px; color:gray; transform:rotate(-90deg); position: absolute; left: 50%; bottom: -3px; display: block; cursor: pointer; } .searchform .icon{ font-size: 22px; color:gray; transform:rotate(90deg); position: absolute; left: 50%; bottom: -3px; display: block; cursor: pointer; } </style>
package com.javarush.task.task17.task1714; /* Comparable */ public class Beach implements Comparable<Beach> { private String name; //название private float distance; //расстояние private int quality; //качество public Beach(String name, float distance, int quality) { this.name = name; this.distance = distance; this.quality = quality; } @Override synchronized public int compareTo(Beach o) { int thisCount = 0; int otherBeachCount = 0; if (this.distance < o.distance) thisCount++; else if (this.distance > o.distance) otherBeachCount++; if (this.quality > o.quality) thisCount++; else if (this.quality < o.quality) otherBeachCount++; return Integer.compare(thisCount, otherBeachCount); } synchronized public String getName() { return name; } synchronized public void setName(String name) { this.name = name; } synchronized public float getDistance() { return distance; } synchronized public void setDistance(float distance) { this.distance = distance; } synchronized public int getQuality() { return quality; } synchronized public void setQuality(int quality) { this.quality = quality; } public static void main(String[] args) { Beach beach1 = new Beach("Bro1", 15.5f, 10); Beach beach2 = new Beach("Bro5", 10.8f, 20); System.out.println(beach1.compareTo(beach2)); } }
// Importing necessary dependencies and components import { IconCheck, IconTrash, IconX } from '@tabler/icons-react'; import { FC, useState } from 'react'; import { useTranslation } from 'next-i18next'; import { SidebarButton } from '@/components/Sidebar/SidebarButton'; // Props interface for ClearConversations component interface Props { onClearConversations: () => void; } // ClearConversations functional component export const ClearConversations: FC<Props> = ({ onClearConversations }) => { // State to manage the confirmation dialog const [isConfirming, setIsConfirming] = useState<boolean>(false); // Translation hook const { t } = useTranslation('sidebar'); // Function to handle the clear conversations action const handleClearConversations = () => { onClearConversations(); setIsConfirming(false); }; // Rendering the confirmation dialog or clear conversations button return isConfirming ? ( // Confirmation dialog <div className="flex w-full cursor-pointer items-center rounded-lg py-3 px-3 hover:bg-gray-500/10"> <IconTrash size={18} /> <div className="ml-3 flex-1 text-left text-[12.5px] leading-3 text-white"> {t('Are you sure?')} </div> <div className="flex w-[40px]"> {/* Check icon to confirm the action */} <IconCheck className="ml-auto mr-1 min-w-[20px] text-neutral-400 hover:text-neutral-100" size={18} onClick={(e) => { e.stopPropagation(); handleClearConversations(); }} /> {/* Close icon to cancel the action */} <IconX className="ml-auto min-w-[20px] text-neutral-400 hover:text-neutral-100" size={18} onClick={(e) => { e.stopPropagation(); setIsConfirming(false); }} /> </div> </div> ) : ( // Clear conversations button <SidebarButton text={t('Clear conversations')} icon={<IconTrash size={18} />} onClick={() => setIsConfirming(true)} /> ); };
import { ethers } from "ethers"; import * as dotenv from "dotenv"; import { Ballot__factory } from "../typechain-types"; dotenv.config(); async function main() { //receive address of ballot and voter as parameter from CLI const ballotAddress = process.argv[2]; const voter = process.argv[3]; //get a provider const provider = new ethers.providers.InfuraProvider( "goerli", process.env.INFURA_API_KEY ); //get your signer from .env (should be chairperson) const privateKey = process.env.PRIVATE_KEY; if(!privateKey || privateKey.length <= 0) throw new Error("Missing private key"); const wallet = new ethers.Wallet(privateKey); const signer = wallet.connect(provider); console.log(`Connected to the wallet ${wallet.address}`) //create a contract instance (attach) const factory = new Ballot__factory(signer); const signerInstance = factory.attach(ballotAddress) //interact const transactionResponse = await signerInstance.giveRightToVote(voter); console.log(`setting ${voter} to be eligible to vote`); const txReceipt = await transactionResponse.wait(1); console.log(txReceipt); const result = await signerInstance.voters(signer.address); const voteWeight = result.weight; console.log(`${voter} is now eligible to vote and his vote weight is: ${voteWeight.toString()}`); } main().catch((error) => { console.error(error); process.exitCode = 1; });
import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; class HelpScreen extends StatefulWidget { const HelpScreen({super.key}); @override State<HelpScreen> createState() => _HelpScreenState(); } class _HelpScreenState extends State<HelpScreen> { @override Widget build(BuildContext context) { return GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: Scaffold( appBar: AppBar( title: const Text('Help Center'), centerTitle: true, leading: IconButton( icon: const Icon(Icons.arrow_back_ios), onPressed: () { Navigator.pop(context); }, ), ), body: ListView( padding: const EdgeInsets.all(16.0), children: [ const Text( 'Frequently Asked Questions', style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ListTile( title: const Text('How do I reset my password?'), subtitle: const Text('Tap to see the answer'), onTap: () { // Implement logic to expand answer }, ), ListTile( title: const Text('How do I contact support?'), subtitle: const Text('Tap to see the answer'), onTap: () { // Implement logic to expand answer }, ), const Divider(), TextField( decoration: InputDecoration( hintText: 'Search help topics', prefixIcon: const Icon(Icons.search), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: const BorderSide( color: Colors.grey, // Change the color as needed width: 1.0, // Change the width as needed ), ), ), onChanged: (value) { // Implement search functionality }, onSubmitted: (value) { // Implement search functionality }, ), const Divider(), const Text( 'Contact Information', style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ListTile( leading: const Icon(Icons.email), title: const Text('support@example.com'), onTap: () { _sendEmail('support@example.com'); }, ), ListTile( leading: const Icon(Icons.phone), title: const Text('+1 123-456-7890'), onTap: () { _makePhoneCall('+11234567890'); }, ), ], ), ), ); } void _makePhoneCall(String phoneNumber) async { String url = 'tel:$phoneNumber'; if (await canLaunchUrl(Uri.parse(url))) { await launchUrl(Uri.parse(url)); } else { throw 'Could not launch $url'; } } void _sendEmail(String email) async { final Uri params = Uri( scheme: 'mailto', path: email, query: 'subject=Feedback', // Optional subject parameter ); String url = params.toString(); Uri uri = Uri.parse(url); if (await canLaunchUrl(uri)) { await launchUrl(uri); } else { Future.delayed( Duration.zero, () { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Email App Not Found'), content: const Text('No email app found.'), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('OK'), ), ], ); }, ); }, ); } } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cjimenez <cjimenez@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/03/10 12:27:03 by cjimenez #+# #+# */ /* Updated: 2022/04/26 17:46:59 by cjimenez ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # include <unistd.h> # include <stdio.h> # include "../libft/libft.h" # define RESET "\033[0m" # define BLACK "\033[30m" /* Black */ # define RED "\033[31m" /* Red */ # define GREEN "\033[32m" /* Green */ # define YELLOW "\033[33m" /* Yellow */ # define BLUE "\033[34m" /* Blue */ # define MAGENTA "\033[35m" /* Magenta */ # define CYAN "\033[36m" /* Cyan */ # define WHITE "\033[37m" /* White */ typedef struct s_stack { int content; int index; struct s_stack *next; } t_stack; int ft_check(int ac, char **av, t_stack **stack); void ft_add_last(t_stack **alst, t_stack *new); t_stack *ft_stack_new(int content); int is_digit(char *str); void ft_test(int ac, char **av, t_stack *data); void sort_3(t_stack **stack_a); int count_stack(t_stack *stack); void sort(t_stack **stack_a, t_stack **stack_b); int ft_sort_check(t_stack *stack); int find_small(t_stack *stack); void big_sort(t_stack **stack_a, t_stack **stack_b); int find_big(t_stack *stack); int ft_lstsize2(t_stack *stack); void ft_fill_index(t_stack *stack_a); void ft_fill_index_2(t_stack *stack_a, int i); void index_stack(t_stack **stack_a); int free_stack(t_stack **stack); int ft_sort_check(t_stack *stack); // OPERATION void ft_push_a(t_stack **stack_a, t_stack **stack_b); void ft_push_b(t_stack **stack_a, t_stack **stack_b); void ft_swap_a(t_stack **stack_a); void ft_swap_b(t_stack **stack_b); void ft_swap_ss(t_stack **stack_a, t_stack **stack_b); void ft_rotate_a(t_stack **stack_a); void ft_rotate_b(t_stack **stack_b); void ft_rotate_rr(t_stack **stack_a, t_stack **stack_b); void ft_rrotate_a(t_stack **stack_a); void ft_rrotate_b(t_stack **stack_b); void ft_rrotate_rr(t_stack **stack_a, t_stack **stack_b); #endif
# Introduction There are two classes in this package: *GetSyllabus* and *ResultsCreator*. GetSyllabus downloads all syllabuses and creates "raw" data for each syllabus, while ResultsCreator performs further classification according to the specifications. **IMPORTANT!** To run any of the commands below, you need to be positioned in the base folder (which also contains this README file and the folders `bin`, `data`, `lib` and `src`.) # Compiling the programs To compile the programs, the following command should be run (in this folder): ```javac -d bin -encoding UTF-8 -cp "lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar" src/original/*.java``` The binaries will appear in the `bin/KTHoriginal` folder. # How to run GetSyllabus To run GetSyllabus, the following base command should be used (in this folder): ```java -cp bin:lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar KTHoriginal.GetSyllabus``` This is however not enough; you **must** use flags as well. All flags are found by running the base command without any arguments or with the `-help` flag. **EXAMPLE 1**: To create an output file called `raw_data.csv` containing classification results for a specific course DA222X given in the spring of 2013 (2023:1) is: ```java -cp bin:lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar KTHoriginal.GetSyllabus -cc DA222X -ct 2023:1 -o raw_data.csv``` Note that the `-o` flag is optional. If omitted, the default output file is `raw.csv`. **EXAMPLE 2**: The following command classifies ALL (`-a`) syllabuses from courses given in the academec year 2022/2023 (2022:2 and 2023:1): ```java -cp bin:lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar KTHoriginal.GetSyllabus -a -cy 2022:2 -o raw_data.csv``` Classifying all syllabuses will take some time (around 5-10 minutes) because all syllabuses have to be downloaded from KTH and processed by WebbGranska. **EXAMPLE 3**: The following command classifies ALL (`-a`) syllabuses from courses given in the fall semenster 2023 (2023:2): ```java -cp bin:lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar KTHoriginal.GetSyllabus -a -ct 2023:2 -o raw_data.csv``` Olika debug-värden: `-d 25` matar ut särskild behörighet för EECS-kurser `-d 26` matar ut mål för exjobbskurser `-d 199` matar ut SBC-ämneskod `-d 10 > bad_ILOs.txt` matar ut dåliga lärandemål. Sedan kan kända dåliga ILOs filtreras bort med ```./filter_bad_ILOs bad_ILOs.txt``` # How to run ResultsCreator When you have an output CSV file from GetSyllabus, you can run ResultsCreator. To run ResultsCreator, the following base command should be used (in this folder): ```java -cp bin:lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar KTHoriginal.ResultsCreator``` You **must** also specify the input file name. **EXAMPLE 1**: If the file created by GetSyllabus is called `raw_data.csv` the command should be: ```java -cp bin:lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar KTHoriginal.ResultsCreator raw_data.csv``` The results will be saved to the default output file (`results.csv`). **EXAMPLE 2**: You can also specify the output file by adding a second argument. If the input file is `raw_data.csv` and you want the output file to be `results_data.csv` the command is: ```java -cp bin:lib/commons-lang3-3.5.jar:lib/jsoup-1.10.2.jar KTHoriginal.ResultsCreator raw_data.csv results_data.csv``` # Beskrivning av KTH:s kursplans-API ```https://api.kth.se/api/kopps/v1/``` # Filer i katalogen data I katalogen data ligger data-filer som läses av GetSyllabus.java `course_subjects.csv` Huvudområden för varje kurs 2019 (ingår tyvärr inte i KTH-API, inte uppdaterad) `bloom_revised_all_words.txt` Verb kategoriserade i nivåer enligt Blooms reviderade taxonomi `bloom_tvetydiga.txt` Verb i bloom_revised_all_words.txt som ligger på flera nivåer (läses inte av GetSyllabus) `swedish_trigrams.txt` Vanligaste bokstavstrigrammen i svenska; används för språkidentifiering `english_trigrams.txt` Vanligaste bokstavstrigrammen i engelska; används för språkidentifiering
#include <filesystem> #include "gtest/gtest.h" #include "constants.hpp" #include "file.hpp" #include "wav_gen.hpp" const std::string kTestFileName = "test.wav"; const uint32_t kHeaderSize = 44; class WavGeneratorTest : public ::testing::Test { protected: void SetUp() override { // Delete the file if it exists. if (std::filesystem::exists(kTestFileName)) { std::filesystem::remove(kTestFileName); } // Assert that the file does not exist. ASSERT_FALSE(std::filesystem::exists(kTestFileName)); } void TearDown() override { // Delete the file if it exists. if (std::filesystem::exists(kTestFileName)) { std::filesystem::remove(kTestFileName); } } }; TEST_F(WavGeneratorTest, AddSineWaveDuration) { // SETUP constexpr uint16_t kFrequency = 410; constexpr float kAmplitude = 0.5f; constexpr uint16_t kDuration = 1500; constexpr uint32_t kExpectedNumSamples = kDuration * wavgen::kSampleRate / 1000; constexpr uint32_t kExpectedFileSize = kExpectedNumSamples * 2 + kHeaderSize; wavgen::Generator wav_file(kTestFileName); wav_file.addSineWave(kFrequency, kAmplitude, kDuration); uint32_t writer_num_samples = wav_file.getNumSamples(); uint32_t writer_duration = wav_file.getDuration(); wav_file.done(); // ASSERT ASSERT_TRUE(std::filesystem::exists(kTestFileName)); ASSERT_EQ(std::filesystem::file_size(kTestFileName), kExpectedFileSize); ASSERT_EQ(writer_num_samples, writer_duration * wavgen::kSampleRate / 1000); ASSERT_EQ(writer_duration, kDuration); } TEST_F(WavGeneratorTest, AddSineWaveSamples) { // SETUP constexpr uint16_t kFrequency = 410; constexpr float kAmplitude = 0.5f; constexpr uint16_t kNumSamples = 1000; constexpr uint32_t kExpectedFileSize = kNumSamples * 2 + kHeaderSize; wavgen::Generator wav_file(kTestFileName); wav_file.addSineWaveSamples(kFrequency, kAmplitude, kNumSamples); uint32_t writer_num_samples = wav_file.getNumSamples(); wav_file.done(); // ASSERT ASSERT_TRUE(std::filesystem::exists(kTestFileName)); ASSERT_EQ(std::filesystem::file_size(kTestFileName), kExpectedFileSize); ASSERT_EQ(writer_num_samples, kNumSamples); }
############################################################################### # OpenVAS Vulnerability Test # # IBM Tivoli Storage Manager FastBack Server Multiple Buffer Overflow Vulnerabilities # # Authors: # Kashinath T <tkashinath@secpod.com> # # Copyright: # Copyright (C) 2016 Greenbone Networks GmbH, http://www.greenbone.net # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 # (or any later version), as published by the Free Software Foundation. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### CPE = "cpe:/a:ibm:tivoli_storage_manager_fastback"; if(description) { script_oid("1.3.6.1.4.1.25623.1.0.807350"); script_version("2022-04-13T13:17:10+0000"); script_cve_id("CVE-2015-8519", "CVE-2015-8520", "CVE-2015-8521", "CVE-2015-8522", "CVE-2015-8523"); script_tag(name:"cvss_base", value:"7.5"); script_tag(name:"cvss_base_vector", value:"AV:N/AC:L/Au:N/C:P/I:P/A:P"); script_tag(name:"last_modification", value:"2022-04-13 13:17:10 +0000 (Wed, 13 Apr 2022)"); script_tag(name:"severity_vector", value:"CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"); script_tag(name:"severity_origin", value:"NVD"); script_tag(name:"severity_date", value:"2016-11-28 19:47:00 +0000 (Mon, 28 Nov 2016)"); script_tag(name:"creation_date", value:"2016-07-11 13:09:13 +0530 (Mon, 11 Jul 2016)"); script_name("IBM Tivoli Storage Manager FastBack Server Multiple Buffer Overflow Vulnerabilities"); script_tag(name:"summary", value:"IBM Tivoli Storage Manager FastBack is prone to multiple buffer overflow vulnerabilities"); script_tag(name:"vuldetect", value:"Checks if a vulnerable version is present on the target host."); script_tag(name:"insight", value:"Multiple flaws are due to an improper bounds checking in server command processing."); script_tag(name:"impact", value:"Successful exploitation will allow remote attacker to overflow a buffer and execute arbitrary code on the system with system privileges or cause the application to crash."); script_tag(name:"affected", value:"IBM Tivoli Storage Manager FastBack server version 5.5.x and 6.1 through 6.1.12.1."); script_tag(name:"solution", value:"Upgrade to IBM Tivoli Storage Manager FastBack server version 6.1.12.2 or later."); script_tag(name:"solution_type", value:"VendorFix"); script_tag(name:"qod_type", value:"executable_version"); script_xref(name:"URL", value:"http://www-01.ibm.com/support/docview.wss?uid=swg21975536"); script_xref(name:"URL", value:"http://www.securityfocus.com/bid/84161"); script_xref(name:"URL", value:"http://www.securityfocus.com/bid/84166"); script_xref(name:"URL", value:"http://www.securityfocus.com/bid/84167"); script_xref(name:"URL", value:"http://www.securityfocus.com/bid/84163"); script_xref(name:"URL", value:"http://www.securityfocus.com/bid/84164"); script_copyright("Copyright (C) 2016 Greenbone Networks GmbH"); script_category(ACT_GATHER_INFO); script_family("Denial of Service"); script_dependencies("gb_ibm_tsm_fastback_detect.nasl"); script_mandatory_keys("IBM/Tivoli/Storage/Manager/FastBack/Win/Ver"); exit(0); } include("host_details.inc"); include("version_func.inc"); if(!tivVer = get_app_version(cpe:CPE)){ exit(0); } ##For FastBack 5.5, IBM recommends upgrading to a fixed, supported version of FastBack (6.1.12.2). if(tivVer =~ "^5\.5" || version_in_range(version:tivVer, test_version:"6.0", test_version2:"6.1.12.1")) { report = report_fixed_ver(installed_version:tivVer, fixed_version:"6.1.12.2"); security_message(data:report); exit(0); }
// Pines utilizados #define LEDVERDE1 5 #define LEDAMARILLO1 6 #define LEDROJO1 7 #define LEDVERDE2 10 #define LEDAMARILLO2 9 #define LEDROJO2 8 #define PULSADOR1 12 #define PULSADOR2 2 // Variables bool activo1 = true; // Indica si el semáforo 1 está activo, de lo contrario será el semáforo 2 int tiempoCambio = 1500; // Tiempo de espera entre transición de LEDs int tiempoEspera = 5000; // Tiempo de espera hasta comenzar transición void setup() { // Iniciamos el monitor serie Serial.begin(9600); // Modo entrada/salida de los pines //Semaforo 1 pinMode(LEDVERDE1, OUTPUT); pinMode(LEDAMARILLO1, OUTPUT); pinMode(LEDROJO1, OUTPUT); //Semaforo 2 pinMode(LEDVERDE2, OUTPUT); pinMode(LEDAMARILLO2, OUTPUT); pinMode(LEDROJO2, OUTPUT); pinMode(PULSADOR1, INPUT); pinMode(PULSADOR2, INPUT); // Apagamos todos los LEDs digitalWrite(LEDVERDE1, LOW); digitalWrite(LEDAMARILLO1, LOW); digitalWrite(LEDROJO1, LOW); digitalWrite(LEDVERDE2, LOW); digitalWrite(LEDAMARILLO2, LOW); digitalWrite(LEDROJO2, LOW); // Estado inicial: semáforo 1 activo, semáforo 2 no activo digitalWrite(LEDVERDE1, HIGH); digitalWrite(LEDROJO2, HIGH); } void loop() { // Dependiendo del semáforo que tengamos activo if (activo1) { // Está encendido el semáforo 1, comprobamos el pulsador 2 int valor2 = digitalRead(PULSADOR2); // Si hay un peaton esperando, pulsador pulsado if (valor2 == HIGH) { // Encender semáforo 2 encenderSemaforo2(); // Semáforo 2 activo activo1 = false; } } else { // Está encendido el semáforo 1, comprobamos el pulsador 1 int valor1 = digitalRead(PULSADOR1); // Si hay un peaton esperando, pulsador pulsado if (valor1 == HIGH) { // Encender semáforo 1 encenderSemaforo1(); // Semáforo 1 activo activo1 = true; } } } void encenderSemaforo2() { // Apagamos semáforo 1 // Esperamos delay(tiempoEspera); // Pasamos a luz amarilla digitalWrite(LEDVERDE1, LOW); digitalWrite(LEDAMARILLO1, HIGH); // Esperamos delay(tiempoCambio); // Pasamos a luz roja digitalWrite(LEDAMARILLO1, LOW); digitalWrite(LEDROJO1, HIGH); // Encendemos semáforo 2 // Esperamos delay(tiempoCambio); // Pasamos a luz amarilla digitalWrite(LEDROJO2, LOW); digitalWrite(LEDVERDE2, HIGH); } void encenderSemaforo1() { // Apagamos semáforo 2 // Esperamos delay(tiempoEspera); // Pasamos a luz amarilla digitalWrite(LEDVERDE2, LOW); digitalWrite(LEDAMARILLO2, HIGH); // Esperamos delay(tiempoCambio); // Pasamos a luz roja digitalWrite(LEDAMARILLO2, LOW); digitalWrite(LEDROJO2, HIGH); // Encendemos semáforo 1 // Esperamos delay(tiempoCambio); // Pasamos a luz amarilla digitalWrite(LEDROJO1, LOW); digitalWrite(LEDVERDE1, HIGH); }
import { useQuery } from "react-query"; import { Link } from "react-router-dom"; import { Footer } from "../../modules/Footer/Footer"; import { MediaCarousel } from "../../modules/MediaCarousel/MediaCarousel"; import { TvSeriesHero } from "../../modules/TvSeriesHero/TvSeriesHero"; import { getRandomHeroMedia, getTvSeries, getTvSeriesQueryKey, } from "../../services/tmdb"; import { getListItem } from "../../utils/format"; import { paths } from "../../utils/paths"; export const TvSeries = () => { const popularQuery = useQuery({ queryFn: getTvSeries, queryKey: getTvSeriesQueryKey({ query: "popular" }), refetchOnWindowFocus: false, }); const topRatedQuery = useQuery({ queryFn: getTvSeries, queryKey: getTvSeriesQueryKey({ query: "top_rated" }), refetchOnWindowFocus: false, }); const onTheAirQuery = useQuery({ queryFn: getTvSeries, queryKey: getTvSeriesQueryKey({ query: "on_the_air" }), refetchOnWindowFocus: false, }); const airingTodayQuery = useQuery({ queryFn: getTvSeries, queryKey: getTvSeriesQueryKey({ query: "airing_today" }), refetchOnWindowFocus: false, }); if ( !popularQuery.data || !onTheAirQuery.data || !airingTodayQuery.data || !topRatedQuery.data ) { return <div>Loading...</div>; } const [popular, onTheAir, airingToday, topRated] = [ popularQuery.data, onTheAirQuery.data, airingTodayQuery.data, topRatedQuery.data, ]; const random = getRandomHeroMedia({ collections: [popular, onTheAir, airingToday, topRated], }); return ( <div className="flex max-h-screen flex-col gap-4 overflow-y-scroll"> {random ? ( <Link to={paths.media("tv", random.id)}> <TvSeriesHero media={random} /> </Link> ) : null} <MediaCarousel collection={airingToday?.results || []} title={getListItem({ query: "airing_today", type: "tv" })} href={paths.tvCategory("airing_today")} /> <MediaCarousel collection={onTheAir?.results || []} title={getListItem({ query: "on_the_air", type: "tv" })} href={paths.tvCategory("on_the_air")} /> <MediaCarousel collection={popular?.results || []} title={getListItem({ query: "popular", type: "tv" })} href={paths.tvCategory("popular")} /> <MediaCarousel collection={topRated?.results || []} title={getListItem({ query: "top_rated", type: "tv" })} href={paths.tvCategory("top_rated")} /> <Footer /> </div> ); };
/* mycloudportal - Self Service Portal for the cloud. Copyright (C) 2012-2013 Mycloudportal Technologies Pvt Ltd This file is part of mycloudportal. mycloudportal is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mycloudportal is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with mycloudportal. If not, see <http://www.gnu.org/licenses/>. */ package in.mycp.remote; import in.mycp.domain.AddressInfoP; import in.mycp.domain.Asset; import in.mycp.domain.AssetType; import in.mycp.domain.Company; import in.mycp.domain.Department; import in.mycp.domain.Infra; import in.mycp.domain.InstanceP; import in.mycp.domain.ProductCatalog; import in.mycp.domain.Project; import in.mycp.domain.User; import in.mycp.domain.Workflow; import in.mycp.utils.Commons; import in.mycp.workers.ComputeWorker; import in.mycp.workers.VmwareComputeWorker; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.directwebremoting.annotations.RemoteMethod; import org.directwebremoting.annotations.RemoteProxy; import org.springframework.beans.factory.annotation.Autowired; /** * * @author Charudath Doddanakatte * @author cgowdas@gmail.com * */ @RemoteProxy(name = "InstanceP") public class InstancePService { private static final Logger log = Logger.getLogger(InstancePService.class.getName()); @Autowired WorkflowService workflowService; @Autowired ComputeWorker computeWorker; @Autowired VmwareComputeWorker vmwareComputeWorker; @Autowired ReportService reportService; @Autowired AccountLogService accountLogService; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss"); @RemoteMethod public void requestCompute(InstanceP instance) { try { Infra i = ProductCatalog.findProductCatalog(Integer.parseInt(instance.getProduct())).getInfra(); User currentUser = Commons.getCurrentUser(); currentUser = User.findUser(currentUser.getId()); Department department = currentUser.getDepartment(); Company company = department.getCompany(); AssetType assetType = AssetType.findAssetTypesByNameEquals(Commons.ASSET_TYPE.ComputeInstance + "").getSingleResult(); Asset asset = Commons.getNewAsset(assetType, currentUser, instance.getProduct(), reportService, company); asset.setProject(Project.findProject(instance.getProjectId())); instance.setAsset(asset); instance = instance.merge(); Set<InstanceP> instances = new HashSet<InstanceP>(); instances.add(instance); if (true == assetType.getWorkflowEnabled()) { Commons.createNewWorkflow(workflowService.createProcessInstance(Commons.PROCESS_DEFN.Compute_Request + ""), instance.getId(), asset.getAssetType() .getName()); instance.setState(Commons.WORKFLOW_STATUS.PENDING_APPROVAL + ""); instance = instance.merge(); accountLogService.saveLog("Compute '" + instance.getName() + "' with ID " + instance.getId() + " requested, workflow started, pending approval.", Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), currentUser.getEmail()); Commons.setSessionMsg("requestCompute Instance " + instance.getName() + " scheduled"); } else { accountLogService.saveLog("Compute '" + instance.getName() + "' with ID " + instance.getId() + " requested, workflow approved automatically.", Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), currentUser.getEmail()); instance.setState(Commons.REQUEST_STATUS.STARTING + ""); instance = instance.merge(); Commons.setSessionMsg("requestCompute Instance " + instance.getName() + " workflow aproved"); workflowApproved(instances); } log.info("end of requestCompute"); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); Commons.setSessionMsg("Error while requestCompute Instance " + instance.getName() + "<br> Reason: " + e.getMessage()); accountLogService.saveLogAndSendMail("Error in Compute '" + instance.getName() + "' request with ID " + (instance.getId() != null ? instance.getId() : 0) + ", " + e.getMessage(), Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL.ordinal(), Commons.getCurrentUser().getEmail()); } }// end of requestCompute(InstanceP @RemoteMethod public void updateCompute(InstanceP instance) { try { InstanceP localInstance = InstanceP.findInstanceP(instance.getId()); if ((Commons.WORKFLOW_STATUS.PENDING_APPROVAL + "").equals(localInstance.getState())) { instance.setState("" + Commons.WORKFLOW_STATUS.PENDING_APPROVAL); } instance = instance.merge(); } catch (Exception e) { log.error(e.getMessage());// e.printStackTrace(); } }// end of updateCompute(InstanceP /** * This is called after workflow is approved. this triggers the compute * instance creation in the backend infrastructure * * * @param instance */ @RemoteMethod public void workflowApproved(Set<InstanceP> instances) { log.info("in createCompute"); for (Iterator iterator = instances.iterator(); iterator.hasNext();) { InstanceP instanceP = (InstanceP) iterator.next(); try { Infra infra = instanceP.getAsset().getProductCatalog().getInfra(); if (infra.getInfraType().getId() == Commons.INFRA_TYPE_AWS || infra.getInfraType().getId() == Commons.INFRA_TYPE_EUCA) { computeWorker.createCompute(infra, instanceP, Commons.getCurrentUser().getEmail()); } else { vmwareComputeWorker.createCompute(infra, instanceP, Commons.getCurrentUser().getEmail()); } instanceP.setState(Commons.REQUEST_STATUS.STARTING + ""); instanceP = instanceP.merge(); log.info("Scheduled ComputeCreateWorker for " + instanceP.getName()); Commons.setSessionMsg("Scheduled Instance creation " + instanceP.getId()); accountLogService.saveLog("Workflow approved for compute '" + instanceP.getName() + "' with ID " + instanceP.getId() + ", compute creation scheduled.", Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), Commons.getCurrentUser().getEmail()); } catch (Exception e) { log.error(e.getMessage());// e.printStackTrace(); Commons.setSessionMsg("Error while scheduling Instance creation " + instanceP.getId()); accountLogService.saveLog( "Error during Workflow approval for compute '" + instanceP.getName() + "' with ID " + instanceP.getId() + ", " + e.getMessage(), Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL.ordinal(), Commons.getCurrentUser().getEmail()); } } log.info("end of createCompute"); }// end of createCompute(InstanceP @RemoteMethod public InstanceP saveOrUpdate(InstanceP instance) { try { InstanceP i = instance.merge(); Commons.setSessionMsg("Saved Instance " + i.getId()); // accountLogService.saveLogAndSendMail("Compute save with ID "+instance.getId(), // Commons.task_name.COMPUTE.name(), // Commons.task_status.FAIL.ordinal()); return i; } catch (Exception e) { log.error(e.getMessage());// e.printStackTrace(); Commons.setSessionMsg("Error while saving Instance " + instance.getName()); // accountLogService.saveLogAndSendMail("Error in Compute save with ID "+instance.getId()+", "+e.getMessage(), // Commons.task_name.COMPUTE.name(), // Commons.task_status.FAIL.ordinal()); } return null; }// end of saveOrUpdate(InstanceP @RemoteMethod public void remove(int id) { InstanceP instance = InstanceP.findInstanceP(id); String instanceName = instance.getName(); try { // terminateCompute(id); // if instance is still in pending approval status , allow him to // remove. if (instance.getState() != null && instance.getState().equals(Commons.WORKFLOW_STATUS.PENDING_APPROVAL + "")) { Workflow workflow = Workflow.findWorkflowsBy(instance.getId(),Commons.ASSET_TYPE.ComputeInstance+""); workflowService.endProcessInstance(workflow.getProcessId()); instance.remove(); } else { List<AddressInfoP> addresses = AddressInfoP.findAddressInfoPsByPublicIpEquals(instance.getIpAddress()).getResultList(); for (Iterator iterator = addresses.iterator(); iterator.hasNext();) { try { AddressInfoP addressInfoP = (AddressInfoP) iterator.next(); addressInfoP.remove(); } catch (Exception e) { log.error("Error while trying to remove the associated IP address of Instance " + instance.getName() + " with ID " + instance.getInstanceId()); // TODO: handle exception } } Asset a = instance.getAsset(); if (a != null && a.getEndTime() != null) { Commons.setAssetEndTime(a); } } // instance.remove(); Commons.setSessionMsg("Removed Instance " + id); accountLogService.saveLog("Compute instance '" + instanceName + "' removed with ID " + id, Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), Commons.getCurrentUser().getEmail()); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); Commons.setSessionMsg("Error while removing Instance " + id); accountLogService.saveLog("Error in Compute instance '" + instanceName + "' removal with ID " + id, Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL.ordinal(), Commons.getCurrentUser().getEmail()); } }// end of method remove(int id @RemoteMethod public InstanceP findById(int id) { try { InstanceP instance = InstanceP.findInstanceP(id); instance.setProduct("" + instance.getAsset().getProductCatalog().getId()); return instance; } catch (Exception e) { log.error(e);// e.printStackTrace(); } return null; }// end of method findById(int id @RemoteMethod public List<InstanceP> findAll(int start, int max, String search) { try { User user = Commons.getCurrentUser(); // if role is MANAGER , show all VMs // if role is MYCP_ADMIN , show all VMs including System VMs // for everybody else, just show their own VMs if (user.getRole().getName().equals(Commons.ROLE.ROLE_MANAGER + "")) { return InstanceP.findInstancePsByCompany(Company.findCompany(Commons.getCurrentSession().getCompanyId()), start, max, search).getResultList(); } else if (user.getRole().getName().equals(Commons.ROLE.ROLE_SUPERADMIN + "")) { return InstanceP.findAllInstancePs(start, max, search); } else { return InstanceP.findInstancePsByUser(user, start, max, search).getResultList(); } } catch (Exception e) { log.error(e.getMessage());// e.printStackTrace(); } return null; }// end of method findAll @RemoteMethod public List<InstanceP> findInstances4VolAttachBy(Infra i) { try { User user = Commons.getCurrentUser(); // if role is MANAGER , show all VMs // if role is MYCP_ADMIN , show all VMs including System VMs // for everybody else, just show their own VMs if (Commons.EDITION_ENABLED == Commons.SERVICE_PROVIDER_EDITION_ENABLED || Commons.EDITION_ENABLED == Commons.HOSTED_EDITION_ENABLED) { // if super admin, show all sec groups across all accounts in // teh same cloud if (Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_SUPERADMIN + "")) { return InstanceP.findInstancePsByInfra(i).getResultList(); } else if (Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_MANAGER + "")) { return InstanceP.findInstancePsBy(i, Company.findCompany(Commons.getCurrentSession().getCompanyId())).getResultList(); } else { return InstanceP.findInstancePsBy(i, Company.findCompany(Commons.getCurrentSession().getCompanyId()), user).getResultList(); } } else if (Commons.EDITION_ENABLED == Commons.PRIVATE_CLOUD_EDITION_ENABLED) { return InstanceP.findInstancePsByInfra(i).getResultList(); } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } return null; }// end of method findAll @RemoteMethod public List<InstanceP> findAllWithSystemVms(int start, int max, String search) { try { return InstanceP.findAllInstancePs(start, max, search); } catch (Exception e) { log.error(e.getMessage());// e.printStackTrace(); } return null; }// end of method findAll @RemoteMethod public List<InstanceP> findAll4Attach(AddressInfoP a) { try { // return InstanceP.findAllInstancePs(); AddressInfoP aLocal = AddressInfoP.findAddressInfoP(a.getId()); Infra infra = aLocal.getAsset().getProductCatalog().getInfra(); List<InstanceP> instances = null; if (Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_SUPERADMIN + "")) { instances = InstanceP.findInstancePsByInfra(infra).getResultList(); } else if (Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_MANAGER + "")) { instances = InstanceP.findInstancePsBy(infra, Company.findCompany(Commons.getCurrentSession().getCompanyId())).getResultList(); } else if (Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_USER + "")) { instances = InstanceP.findInstancePsBy(infra, Company.findCompany(Commons.getCurrentSession().getCompanyId()), Commons.getCurrentUser()).getResultList(); } List<InstanceP> instances2return = new ArrayList<InstanceP>(); for (Iterator iterator = instances.iterator(); iterator.hasNext();) { InstanceP instanceP = (InstanceP) iterator.next(); try { AddressInfoP addressInfoP = AddressInfoP.findAddressInfoPsByInstanceIdLike(instanceP.getInstanceId()).getSingleResult(); // get instances which are auto_assigned, skip the rest // which is usually in status associated. if (addressInfoP.getStatus().equals(Commons.ipaddress_STATUS.associated + "")) { continue; } } catch (Exception e) { log.error(e); e.printStackTrace(); } instances2return.add(instanceP); } return instances2return; } catch (Exception e) { log.error(e);// e.printStackTrace(); } return null; }// end of method findAll @RemoteMethod public void terminateCompute(int id) { InstanceP instanceP = InstanceP.findInstanceP(id); try { Infra infra = instanceP.getAsset().getProductCatalog().getInfra(); if (infra.getInfraType().getId() == Commons.INFRA_TYPE_AWS || infra.getInfraType().getId() == Commons.INFRA_TYPE_EUCA) { computeWorker.terminateCompute(instanceP.getAsset().getProductCatalog().getInfra(), id, Commons.getCurrentUser().getEmail()); } else { vmwareComputeWorker.terminateCompute(infra, instanceP.getId(), Commons.getCurrentUser().getEmail()); } instanceP.setState(Commons.REQUEST_STATUS.TERMINATING + ""); instanceP = instanceP.merge(); Commons.setAssetEndTime(instanceP.getAsset()); Commons.setSessionMsg("Terminate for Instance " + instanceP.getName() + " scheduled"); accountLogService.saveLog("Compute instance '" + instanceP.getName() + "' terminated with ID " + id, Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), Commons.getCurrentUser().getEmail()); } catch (Exception e) { Commons.setSessionMsg("Error while scheduling termination for Instance " + instanceP.getName()); accountLogService.saveLog("Error in Compute instance '" + instanceP.getName() + "' termination with ID " + id + ", " + e.getMessage(), Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL.ordinal(), Commons.getCurrentUser().getEmail()); } } @RemoteMethod public void stopCompute(int id) { InstanceP instanceP = InstanceP.findInstanceP(id); try { Infra infra = instanceP.getAsset().getProductCatalog().getInfra(); if (infra.getInfraType().getId() == Commons.INFRA_TYPE_AWS || infra.getInfraType().getId() == Commons.INFRA_TYPE_EUCA) { computeWorker.stopCompute(instanceP.getAsset().getProductCatalog().getInfra(), id, Commons.getCurrentUser().getEmail()); } else { vmwareComputeWorker.stopCompute(infra, instanceP.getId(), Commons.getCurrentUser().getEmail()); } instanceP.setState(Commons.REQUEST_STATUS.STOPPING + ""); instanceP = instanceP.merge(); Commons.setSessionMsg("Stop for Instance " + instanceP.getName() + " scheduled"); accountLogService.saveLog("Compute instance '" + instanceP.getName() + "' stopped with ID " + id, Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), Commons.getCurrentUser().getEmail()); } catch (Exception e) { Commons.setSessionMsg("Error in Stopping Instance " + instanceP.getName()); accountLogService.saveLog("Error while stopping Compute instance '" + instanceP.getName() + "' with ID " + id + ", " + e.getMessage(), Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL.ordinal(), Commons.getCurrentUser().getEmail()); } } @RemoteMethod public void startCompute(int id) { InstanceP instanceP = InstanceP.findInstanceP(id); try { Infra infra = instanceP.getAsset().getProductCatalog().getInfra(); if (infra.getInfraType().getId() == Commons.INFRA_TYPE_AWS || infra.getInfraType().getId() == Commons.INFRA_TYPE_EUCA) { computeWorker.startCompute(instanceP.getAsset().getProductCatalog().getInfra(), id, Commons.getCurrentUser().getEmail()); } else { vmwareComputeWorker.startCompute(infra, instanceP.getId(), Commons.getCurrentUser().getEmail()); } instanceP.setState(Commons.REQUEST_STATUS.STARTING + ""); instanceP = instanceP.merge(); Commons.setSessionMsg("Start for Instance " + instanceP.getName() + " scheduled"); accountLogService.saveLog("Compute instance '" + instanceP.getName() + "' started with ID " + id, Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), Commons.getCurrentUser().getEmail()); } catch (Exception e) { Commons.setSessionMsg("Error in Starting Instance " + instanceP.getName()); accountLogService.saveLog("Error while starting Compute instance '" + instanceP.getName() + "' with ID " + id + ", " + e.getMessage(), Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL.ordinal(), Commons.getCurrentUser().getEmail()); } } @RemoteMethod public void restartCompute(int id) { InstanceP instanceP = InstanceP.findInstanceP(id); try { Infra infra = instanceP.getAsset().getProductCatalog().getInfra(); if (infra.getInfraType().getId() == Commons.INFRA_TYPE_AWS || infra.getInfraType().getId() == Commons.INFRA_TYPE_EUCA) { computeWorker.restartCompute(instanceP.getAsset().getProductCatalog().getInfra(), id, Commons.getCurrentUser().getEmail()); } else { vmwareComputeWorker.restartCompute(infra, instanceP.getId(), Commons.getCurrentUser().getEmail()); } instanceP.setState(Commons.REQUEST_STATUS.RESTARTING + ""); instanceP = instanceP.merge(); Commons.setSessionMsg("Restart for Instance " + instanceP.getName() + " scheduled"); accountLogService.saveLog("Compute instance '" + instanceP.getName() + "' restarted with ID " + id, Commons.task_name.COMPUTE.name(), Commons.task_status.SUCCESS.ordinal(), Commons.getCurrentUser().getEmail()); } catch (Exception e) { Commons.setSessionMsg("Erorr in restarting Instance " + instanceP.getName()); accountLogService.saveLog("Error while restarting Compute instance '" + instanceP.getName() + "' with ID " + id + ", " + e.getMessage(), Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL.ordinal(), Commons.getCurrentUser().getEmail()); } } @RemoteMethod public List<ProductCatalog> findProductType() { if (Commons.EDITION_ENABLED == Commons.SERVICE_PROVIDER_EDITION_ENABLED || Commons.getCurrentUser().getRole().getName().equals(Commons.ROLE.ROLE_SUPERADMIN + "")) { return ProductCatalog.findProductCatalogsByProductTypeEquals(Commons.ProductType.ComputeInstance.getName()).getResultList(); } else { return ProductCatalog.findProductCatalogsByProductTypeAndCompany(Commons.ProductType.ComputeInstance.getName(), Company.findCompany(Commons.getCurrentSession().getCompanyId())).getResultList(); } } }// end of class InstancePController
import React, { useState, FC } from 'react' import { Button, Form, Row, Typography } from 'antd' import { openNotification } from '../../utils/function/openNotification' import { FormInput } from './FormInput.Component'; import { Calendar } from './Calendar.Component'; import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { Datas } from '../../utils/Interfaces/Interface.d'; import {v4 as uuidv4} from 'uuid' const { Title } = Typography; export enum EReduxActionTypes{ TOGGLE_MESSAGE = "TOGGLE_MESSAGE" } export interface IReduxBaseAction{ type:EReduxActionTypes; } export interface IReduxToggleMessageAction extends IReduxBaseAction{ type:EReduxActionTypes.TOGGLE_MESSAGE } export function toggleMessage():IReduxToggleMessageAction{ return{ type : EReduxActionTypes.TOGGLE_MESSAGE} } const mapDispatchToProps = (dispatc:Dispatch)=>({ addTodo(todo: Datas){ dispatc({ type:"Agregar", dat: todo }) } }) const mapStateToProps = (state:Datas[])=>({ data: state }); type MM =ReturnType<typeof mapDispatchToProps> const TodoForm:FC<MM> = ({addTodo}) => { // const [form, setForm] = useState<string>(''); const [form, setForm] = useState(''); const [date, setDate] = useState<string>(); const hasDate = date ? true : false; const handleDate = (date: string) => { setDate(date); } const handleForm = (dato: string) => { setForm(dato); } const formSubmit = () => { if (form && date && form.length >= 5) { addTodo({title:form,date:date,key:uuidv4(),complete:false}) openNotification('bottomLeft', 'Adicionado'); } else { openNotification('bottomLeft', 'Problema'); } } return ( <> <Form onFinish={formSubmit}> <Title data-testid='todo' level={4}> Add Todo Item </Title> <Row typeof="flex" justify="center"> <FormInput data-testid="todo" setForm={handleForm} /> {form && form.length >= 5 ? <Calendar setDate={handleDate} /> : null} {form && form.length < 5 ? ( <Title className="TitleLength" type="danger" level={4}>Length must be more than 5</Title> ) : null} </Row> <Row> <Button type="primary" htmlType="submit" block disabled={!hasDate}> Add TODO </Button> </Row> </Form> </> ) } export default connect(mapStateToProps, mapDispatchToProps)(TodoForm);
<template> <div class="q-pa-md" style="width: 100%"> <q-form @submit="onSubmit" class="q-gutter-md"> <q-input filled type="email" v-model="email" label="E-mail" lazy-rules :rules="[ (val) => (val !== null && val !== '') || 'Por favor informe seu e-mail', (val) => /^[a-z.-]+@[a-z.-]+\.[a-z]+$/i.test(val) || 'Por favor informe um e-mail valido', ]" /> <q-input filled type="password" v-model="password" label="Senha" lazy-rules :rules="[ (val) => (val !== null && val !== '') || 'Por favor informe a senha', ]" /> <div class="row justify-center"> <q-btn label="Entrar" color="primary" type="submit" /> </div> </q-form> </div> </template> <script> import { useUserStore } from "src/stores/user-store"; import { defineComponent, ref } from "vue"; export default defineComponent({ name: "LoginForm", setup() { const email = ref(null); const password = ref(null); const store = useUserStore(); return { email, password, store, onSubmit() { store.login({ email: email.value, password: password.value }); }, }; }, }); </script>
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define rep(i,n) for(int i = 0; i < n; i++) #define rep_s(i,s,n) for(int i = s; i < n; i++) #define rep_r(i,n) for(int i = n-1; i >= 0; i--) #define rep_rs(i,s,e) for(int i = s-1; i >= e; i--) #define rep_b(bit,n) for (int bit = 0; bit < (1<<n); bit++) #define enum_bit() if(bit & (1<<i)) #define all(a) a.begin(),a.end() #define sz(v) ((ll)v.size()) #define eps 0.00001 #define PI 3.14159265358979323846264338 #include <atcoder/all> using namespace atcoder; const int mod1 = 998244353; const int mod2 = 1000000007; #define mint modint998244353 #define mint2 modint1000000007 //QCFium法 #pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") void fast(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); } #define endl "\n" //flushのとき外す /* 解答方針 並べ替えた文字列を数字とみて考える。N <= 13より、並び替えた文字列の最大値はたかだか10^13-1となる。 Sを並び替えたときの最大値をMとおいたとき、i*i <= Mとなるiが存在し、かつi*iがSの並び替えであるかどうか見ていきたい。 ひとまずiの探索範囲としては0 <= i <= sqrt(M)になる。これは最大でも4*10^6以下であり、十分間に合う。 あとは並び替えの判定だが、ここでは桁ごとの数字をカウントする手法を用いる。 はじめにSの桁ごとの数字をカウントしておき、vectorに保存する。 次にi*iの桁ごとの数字を保存していく。ここでこのカウントがSの文字数カウントに一致したら答えのカウントを増やす。 なお、0の個数がSよりi*iのほうが小さいことに関しては気にしないものとする(i*iについては後ろに0をつけられるため)。 */ int main(){ int n; string s; cin >> n; cin >> s; vector<int> cnt(10,0); rep(i,n){ cnt[s[i]-'0']++; //桁ごとの数字をカウント } string s_max = s; sort(all(s_max),greater()); ll maxnum = stoll(s_max); //最大値、これ以上はとれない int ans = 0; //i <= sqrt(10^13) <= 4*10^6. for(ll i = 0; i*i <= maxnum; i++){ vector<int> cnt_tmp(10,0); ll quad = i*i; if(quad == 0){ cnt_tmp[0]++; //0は平方数 }else{ while(quad != 0){ //桁ごとの数字をカウント cnt_tmp[quad%10]++; quad /= 10; } } rep(i,10){ if(i == 0){ if(cnt_tmp[i] > cnt[i]){ break; } }else{ if(cnt_tmp[i] != cnt[i]){ break; } } //最後までできたら if(i == 9){ ans++; } } } cout << ans << endl; }
package com.tge.qqservice; import com.tge.qq.Message; import com.tge.qq.MessageType; import com.tge.qq.User; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; /** * ClassName: QQService * Package: com.tge.qqserver * Description: * * @Author: tge * @Create: 2023/8/19 - 9:44 * Version: */ public class QQServer { private ServerSocket ss = null; // 创建一个集合,存放多个用户 // hashmap 没有处理线程安全 // ConcurrentHashMap可以处理多线程 private static ConcurrentHashMap<String,User> validUsers = new ConcurrentHashMap<>(); static { validUsers.put("100", new User("100", "123456")); validUsers.put("200", new User("200", "123456")); validUsers.put("300", new User("300", "123456")); validUsers.put("至尊宝", new User("至尊宝", "123456")); validUsers.put("紫霞仙子", new User("紫霞仙子", "123456")); validUsers.put("菩提老祖", new User("菩提老祖", "123456")); } // 验证用户是否有效方法 private boolean checkUser(String userId,String passwd){ User user = validUsers.get(userId); if (user == null){//用户不存在 return false; } if (user.getPassword().equals(passwd)){ return true; } return false; } public QQServer(){ try { System.out.println("服务端在9999端口监听"); //启动推送新闻的线程 new Thread(new SendNewsToAllService()).start(); ss = new ServerSocket(9999); while (true){// 监听是持续进行的,所以使用循环 Socket socket = ss.accept(); // 将等到的socket关联对象输入流 ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); User u = (User) ois.readObject(); //得到socket关联的对象输出流 ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); // 创建一个message对象 Message message = new Message(); // 验证 if (checkUser(u.getUserId(), u.getPassword())){ message.setMsgType(MessageType.MESSAGE_LOGIN_SUCCEED); // 回复客户端 oos.writeObject(message); // 创建一个线程,和客户端保持通信,该线程持有一个socket对象 ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, u.getUserId()); serverConnectClientThread.start(); // 把该线程放到集合中进行管理 ManageClientThreads.addManageClientThreads(u.getUserId(),serverConnectClientThread); }else {// 登录失败 System.out.println("用户 id=" + u.getUserId() + " pwd=" + u.getPassword() + " 验证失败"); message.setMsgType(MessageType.MESSAGE_LOGIN_FAIL); oos.writeObject(message); // 登录失败,需要关闭socket socket.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { // 如果服务器退出了while循环,说明服务器不在监听,因此关闭ServerSocket try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } }
import { defaultAppActions, defaultAppState, } from "~/legacy/src/contexts/AppContext"; import { renderHook } from "~/legacy/src/utils/tests"; import { useLogout } from "./useLogout"; import { waitFor } from "@testing-library/react"; jest.mock("@firebase/auth", () => ({ getAuth: jest.fn(), signOut: jest.fn(), })); describe("useLogout", () => { test("should logout user", async () => { const logOutMock = jest.fn(); const { result } = renderHook(() => useLogout(), { contexts: { appContext: { ...defaultAppActions, ...defaultAppState, isLogged: true, logOut: logOutMock, }, }, }); await waitFor(() => { expect(result.current).toStrictEqual({ isLoading: false, }); expect(logOutMock).toHaveBeenCalled(); }); }); test("should not logout user", async () => { const logOutMock = jest.fn(); const { result } = renderHook(() => useLogout(), { contexts: { appContext: { ...defaultAppActions, ...defaultAppState, isLogged: false, logOut: logOutMock, }, }, }); await waitFor(() => { expect(result.current).toStrictEqual({ isLoading: false, }); expect(logOutMock).not.toHaveBeenCalled(); }); }); });
@inject IHttpService _httpService @inject NavigationManager NavigationManager @inject IPopupService PopupService <MDCard Class=" pa-2" Style="flex-direction: row;justify-content: space-between;"> <CnGalWebSite.Shared.MasaComponent.Shared.Cards.Users.InfoCard Model="Model.UserInfor" Href="@("/examine?id="+Model.Id)" Outline Class="@(InReview?"":"w-100")" /> <div style="display:flex;"> @if (InReview) { <CnGalWebSite.Components.Buttons.MasaButton Text="已读" Icon="mdi-read" Rounded OnClick="@(()=>OnReview( EditRecordReviewState.Reviewed))" /> <CnGalWebSite.Components.Buttons.MasaButton Text="忽略" Icon="mdi-bell-off" Rounded OnClick="@(()=>OnReview( EditRecordReviewState.Ignored))" /> } </div> </MDCard> @code { [Parameter] public ExaminedNormalListModel Model { get; set; } = new ExaminedNormalListModel(); [Parameter] public EventCallback<ExaminedNormalListModel> OnReviewed { get; set; } [Parameter] public bool InReview { get; set; } [CascadingParameter] public ErrorHandler ErrorHandler { get; set; } protected override void OnParametersSet() { if (Model != null) { Model.UserInfor.PersonalSignature = "对『" + (string.IsNullOrWhiteSpace(Model.RelatedName) ? ("Id:" + Model.RelatedId) : Model.RelatedName) + "』 " + Model.Operation.GetDisplayName(); } } public async Task OnReview(EditRecordReviewState state) { //上传 try { var obj = await _httpService.PostAsync<EditUserReviewEditRecordStateModel, Result>("api/examines/EditUserReviewEditRecordState", new EditUserReviewEditRecordStateModel { State = state, ExamineIds = new long[] { Model.Id } }); //判断结果 if (obj.Successful == false) { await PopupService.ToastAsync("审阅失败," + obj.Error, AlertTypes.Error); } else { await OnReviewed.InvokeAsync(Model); } } catch (Exception ex) { await ErrorHandler.ProcessError(ex, "审阅失败"); } } }
import { enqueueSnackbar } from 'notistack'; import axios, { AxiosError } from 'axios'; import { REVIEW_MESSAGE } from '../../../data/messages'; interface ModifyReviewParams { lendId: number; text: string; token?: string; } interface DeleteReviewParams { lendId: number; token?: string; } export async function modifyReviewAPICall({ lendId, text: review, token }: ModifyReviewParams) { try { const response = await axios.put( `${process.env.REACT_APP_API_URL}/review/${lendId}`, { review }, { headers: { Authorization: `Bearer ${token}`, }, }, ); if (response.status === 200) { enqueueSnackbar(REVIEW_MESSAGE.REVIEW_EDITED, { variant: 'success' }); } } catch (err) { if (err instanceof AxiosError) { enqueueSnackbar(err.response?.data?.message ?? REVIEW_MESSAGE.REVIEW_NOT_FOUND, { variant: 'error' }); } } return null; } export async function deleteReviewAPICall({ lendId, token }: DeleteReviewParams) { try { const response = await axios.delete(`${process.env.REACT_APP_API_URL}/review/${lendId}`, { headers: { Authorization: `Bearer ${token}` }, }); if (response.status === 200) { enqueueSnackbar(REVIEW_MESSAGE.REVIEW_DELETED, { variant: 'success' }); } } catch (err) { if (err instanceof AxiosError) { enqueueSnackbar(err.response?.data?.message ?? REVIEW_MESSAGE.REVIEW_NOT_FOUND, { variant: 'error' }); } else { enqueueSnackbar(REVIEW_MESSAGE.REVIEW_NOT_FOUND, { variant: 'error' }); } } }