text
stringlengths
184
4.48M
import java.util.HashSet; import java.util.Set; // Component abstract class Component { public abstract void operation(); } // Composite class Composite extends Component { private Set<Component> children = new HashSet<>(); @Override public void operation() { System.out.println("Composite Operation."); for (Component child : children) { child.operation(); } } public void add(Component component) { children.add(component); } public void remove(Component component) { children.remove(component); } } // Leaf class Leaf extends Component { @Override public void operation() { System.out.println("Leaf Operation."); } } // Client code public class CompositePattern { public static void main(String[] args) { Composite composite = new Composite(); composite.add(new Leaf()); Composite composite2 = new Composite(); composite2.add(new Leaf()); composite.add(composite2); composite.operation(); } } /* Composite Operation. Composite Operation. Leaf Operation. Leaf Operation. */
import React from 'react'; import Grid from '@material-ui/core/Grid'; import DashboardPage from '../utils/DashboardPage'; import Section from '../utils/Section'; import { PowerSummary } from './summary'; import { TimeDomain } from '../vendor/jx/domains'; import { COMBOS, PLATFORMS, TESTS } from './config'; import { first, selectFrom } from '../vendor/vectors'; export default class Power extends React.Component { render() { const timeDomain = new TimeDomain({ past: '2month', interval: 'day' }); const suites = selectFrom(COMBOS) .groupBy('suiteLabel') .map(first) .toArray(); const cpuTest = selectFrom(TESTS).where({ id: 'cpu' }).first(); return ( <DashboardPage title="Power Usage" > {suites.map(({ suite, suiteLabel }) => ( <Section key={`section_${suite}`} title={`${suiteLabel} - ${cpuTest.label}`} > <Grid container spacing={2}> {PLATFORMS.map(({ id, label: platformLabel }) => ( <Grid key={`power_${id}_${suite}`} item xs={6}> <PowerSummary key={`power_${id}_${suite}`} platform={id} suite={suite} timeDomain={timeDomain} title={platformLabel} testId={cpuTest.id} /> </Grid> ))} </Grid> </Section> ))} </DashboardPage> ); } }
// Copyright 2015 The Crashpad Authors. All rights reserved. // // 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. #ifndef CRASHPAD_SNAPSHOT_WIN_PROCESS_READER_WIN_H_ #define CRASHPAD_SNAPSHOT_WIN_PROCESS_READER_WIN_H_ #include <windows.h> #include "util/misc/initialization_state_dcheck.h" #include "util/win/process_info.h" namespace crashpad { //! \brief Accesses information about another process, identified by a HANDLE. class ProcessReaderWin { public: ProcessReaderWin(); ~ProcessReaderWin(); //! \brief Initializes this object. This method must be called before any //! other. //! //! \param[in] process Process handle, must have PROCESS_QUERY_INFORMATION, //! PROCESS_VM_READ, and PROCESS_DUP_HANDLE access. //! //! \return `true` on success, indicating that this object will respond //! validly to further method calls. `false` on failure. On failure, no //! further method calls should be made. bool Initialize(HANDLE process); //! \return `true` if the target task is a 64-bit process. bool Is64Bit() const { return process_info_.Is64Bit(); } private: ProcessInfo process_info_; InitializationStateDcheck initialized_; DISALLOW_COPY_AND_ASSIGN(ProcessReaderWin); }; } // namespace crashpad #endif // CRASHPAD_SNAPSHOT_WIN_PROCESS_READER_WIN_H_
#!perl -w use strict; use warnings; BEGIN { use lib 't/lib'; use Handel::Test; eval 'use Catalyst 5.7001'; plan(skip_all => 'Catalyst 5.7001 not installed') if $@; eval 'use Catalyst::Devel 1.0'; plan(skip_all => 'Catalyst::Devel 1.0 not installed') if $@; eval 'use Test::MockObject 1.07'; if (!$@) { plan tests => 13; } else { plan skip_all => 'Test::MockObject 1.07 not installed'; }; my @models = ( bless({}, 'Catalyst::Model::Handel::Cart'), bless({cart_class => 'MyCart'}, 'Catalyst::Model::Handel::Cart'), bless({cart_class => 'BogusCart'}, 'Catalyst::Model::Handel::Cart'), bless({cart_class => 'Handel::Subclassing::Cart', mysetting => 'foo'}, 'Catalyst::Model::Handel::Cart'), ); Test::MockObject->fake_module('Catalyst::Model' => ( new => sub { return shift @models; } )); my $cartstorage = Test::MockObject->new; $cartstorage->set_always('clone', $cartstorage); $cartstorage->mock('mysetting' => sub { my $self = shift; if (@_) { $self->{'mysetting'} = shift; }; return $self->{'mysetting'}; }); Test::MockObject->fake_module('Handel::Subclassing::Cart' => ( storage => sub {$cartstorage}, forwardmethod => sub {return $_[1];}, new => sub {return $_[1];} )); my $mycartstorage = Test::MockObject->new; $mycartstorage->set_always('clone', $mycartstorage); Test::MockObject->fake_module('MyCart' => ( storage => sub {$mycartstorage} )); use_ok('Catalyst::Model::Handel::Cart'); use_ok('Handel::Exception', ':try'); }; ## test model with the default class { my $model = Catalyst::Model::Handel::Cart->COMPONENT; isa_ok($model, 'Catalyst::Model::Handel::Cart'); isa_ok($model->cart_manager, 'Handel::Cart', 'set default cart manager'); }; ## test model with other class { my $model = Catalyst::Model::Handel::Cart->COMPONENT; isa_ok($model, 'Catalyst::Model::Handel::Cart'); isa_ok($model->cart_manager, 'MyCart', 'set custom cart manager'); }; ## throw exception when bogus cart_class is given { eval { local $ENV{'LANGUAGE'} = 'en'; my $model = Catalyst::Model::Handel::Cart->COMPONENT; fail('no exception thrown'); }; like($@, qr/could not load cart class/i, 'could not load class in message'); }; ## test model with other unloaded class { my $model = Catalyst::Model::Handel::Cart->COMPONENT; isa_ok($model, 'Catalyst::Model::Handel::Cart'); isa_ok($model->cart_manager, 'Handel::Subclassing::Cart', 'set custom cart manager'); ok($model->cart_manager->storage->called('mysetting'), 'pass mysetting to storage config'); is($model->cart_manager->storage->mysetting, 'foo', 'mysetting was set'); is($model->forwardmethod('foo'), 'foo', 'methods forwarded to manager instance'); is($model->new('foonew'), 'foonew', 'new forwarded to manager instance'); };
/// <reference types="cypress" /> describe('new password page testing', () => { beforeEach(() => { cy.visit( '/new-password?hash=4788369dee152009edea24e2d2e4f4ea64be5e49069cd090603fa913ab4e3c7bd79f2dac17a6a16b0c7309ce8106847c' ); }); it('user can not update password if enter data is invalid', () => { cy.get('[id="new_password"]').type('12345'); cy.get('[id="repeat_password"]').type('12345'); cy.intercept('POST', Cypress.env('api_server') + '/password/recover', { statusCode: 422, }).as('sent'); cy.get('[id="save_new_password_btn"]').click(); cy.wait('@sent'); cy.contains('invalid data provided.'); }); it('user can change password if all data is valid', () => { cy.intercept('POST', Cypress.env('api_server') + '/password/recover', { statusCode: 200, }); cy.get('[id="new_password"]').type('123456'); cy.get('[id="repeat_password"]').type('123456'); cy.get('[id="save_new_password_btn"]').click(); cy.contains('Your password has been updated successfully'); }); it('check password did not match error', () => { cy.get('[id="new_password"]').type('1238'); cy.get('[id="repeat_password"]').type('1234'); cy.get('[id="save_new_password_btn"]').click(); cy.contains('password did not match'); }); });
import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:work_time_check/auth/firebase_auth/auth_util.dart'; import 'package:work_time_check/flutter_flow/flutter_flow_icon_button.dart'; import 'package:work_time_check/flutter_flow/flutter_flow_theme.dart'; import 'package:work_time_check/flutter_flow/upload_data.dart'; import 'package:work_time_check/solo/solo_function.dart'; List<CameraDescription> _cameras = []; class CustomCameraPage extends StatefulWidget { const CustomCameraPage({Key? key}) : super(key: key); @override State<CustomCameraPage> createState() => _CustomCameraPageState(); } class _CustomCameraPageState extends State<CustomCameraPage> { late CameraController controller; bool isReady = false; @override void initState() { super.initState(); // On page load action. SchedulerBinding.instance.addPostFrameCallback((_) async { _cameras = await availableCameras(); controller = CameraController(_cameras[1], ResolutionPreset.max); controller.initialize().then((_) { if (!mounted) { return; } setState(() { isReady = true; }); }).catchError((Object e) { if (e is CameraException) { switch (e.code) { case 'CameraAccessDenied': // Handle access errors here. break; default: // Handle other errors here. break; } } }); }); } @override void dispose() { controller.dispose(); super.dispose(); } Future<dynamic> onTakePictureButtonPressed() async { var file = await takePicture(); final mediaBytes = await compressFile(await file!.readAsBytes()); final path = getStoragePath(null, file!.name, false); final selectedMedia = [ SelectedFile( storagePath: path, filePath: file!.path, bytes: mediaBytes!, dimensions: null, ) ]; Navigator.pop(context, selectedMedia); } Future<XFile?> takePicture() async { final CameraController? cameraController = controller; if (cameraController == null || !cameraController.value.isInitialized) { return null; } if (cameraController.value.isTakingPicture) { // A capture is already pending, do nothing. return null; } try { XFile file = await cameraController.takePicture(); return file; } on CameraException catch (e) { return null; } } @override Widget build(BuildContext context) { if (!isReady) { return Container(); } return Scaffold( appBar: AppBar( backgroundColor: FlutterFlowTheme.of(context).primary, automaticallyImplyLeading: false, leading: FlutterFlowIconButton( borderColor: Colors.transparent, borderRadius: 30.0, borderWidth: 1.0, buttonSize: 60.0, icon: Icon( Icons.chevron_left_rounded, color: Colors.white, size: 30.0, ), onPressed: () async { Navigator.pop(context); }, ), title: Text( 'ถ่ายรูปพนักงาน', style: FlutterFlowTheme.of(context).headlineMedium.override( fontFamily: 'Kanit', color: Colors.white, fontSize: 22.0, ), ), actions: [], centerTitle: false, elevation: 2.0, ), body: SafeArea( child: Stack( children: [ Container( width: MediaQuery.of(context).size.width, child: CameraPreview(controller), ), Align( alignment: Alignment.bottomCenter, child: Container( height: 80, color: FlutterFlowTheme.of(context).primary, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( width: 60, height: 60, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(30), ), child: IconButton( icon: const Icon(Icons.camera_alt), color: Colors.blue, onPressed: controller != null && controller.value.isInitialized && !controller.value.isRecordingVideo ? onTakePictureButtonPressed : null, ), ), ], ), ), ), ], ), ), ); } }
/* Copyright (C) 2017 Alexandru-Valentin Musat (contact@nexuralsoftware.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "params_parser.h" #include "helper.h" namespace nexural { namespace parser { int ParseInt(std::map<std::string, std::string> &map, std::string key) { if (map.find(key) == map.end()) throw std::runtime_error("The key " + key + " was not found!"); if (map[key].empty()) { throw std::runtime_error("Empty key value!"); } int value = -1; try { value = std::stoi(map[key]); } catch (...) { throw std::runtime_error("Error while parsing!"); } return value; } int ParseLong(std::map<std::string, std::string> &map, std::string key) { if (map.find(key) == map.end()) throw std::runtime_error("The key " + key + " was not found!"); if (map[key].empty()) { throw std::runtime_error("Empty key value!"); } int value = -1; try { value = std::stol(map[key]); } catch (...) { throw std::runtime_error("Error while parsing!"); } return value; } float_n ParseFloat(std::map<std::string, std::string> &map, std::string key) { if (map.find(key) == map.end()) throw std::runtime_error("The key " + key + " was not found!"); if (map[key].empty()) { throw std::runtime_error("Empty key value!"); } float_n value = -1; try { value = std::stof(map[key]); } catch (...) { throw std::runtime_error("Error while parsing!"); } return value; } bool ParseBool(std::map<std::string, std::string> &map, std::string key) { if (map.find(key) == map.end()) throw std::runtime_error("The key " + key + " was not found!"); if (map[key].empty()) { throw std::runtime_error("Empty key value!"); } return map[key] == "1" || map[key] == "true"; } std::string ParseString(std::map<std::string, std::string> &map, std::string key) { if (map.find(key) == map.end()) throw std::runtime_error("The key " + key + " was not found!"); if (map[key].empty()) { throw std::runtime_error("Empty key value!"); } std::string value = map[key]; return value; } std::vector<std::string> ParseStrVector(std::map<std::string, std::string> &map, std::string key) { if (map.find(key) == map.end()) throw std::runtime_error("The key " + key + " was not found!"); if (map[key].empty()) { throw std::runtime_error("Empty key value!"); } std::vector<std::string> tokens = helper::TokenizeString(map[key], ","); return tokens; } std::vector<float_n> ParseFltVector(std::map<std::string, std::string> &map, std::string key) { if (map.find(key) == map.end()) throw std::runtime_error("The key " + key + " was not found!"); if (map[key].empty()) { throw std::runtime_error("Empty key value!"); } std::vector<std::string> tokens = helper::TokenizeString(map[key], ","); size_t tokens_cnt = (size_t)tokens.size(); std::vector<float_n> result(tokens_cnt); bool safely_parsed = true; for (size_t token_id = 0; token_id < tokens_cnt; ++token_id) { float_n value = 0; try { value = std::stof(tokens[token_id]); } catch (...) { safely_parsed = false; break; } result[token_id] = value; } if (!safely_parsed) { throw std::runtime_error("Error while parsing!"); } return result; } } }
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users = User.all end def new @new_user = true @user = User.new end def edit if current_user.id != @user.id raise AccessDenied end end def create @user = User.new(user_params) respond_to do |format| if @user.save format.html { redirect_to users_path, notice: 'User was successfully created.' } else format.html { render :new } end end end def update respond_to do |format| if @user.update(user_params) format.html { redirect_to users_path, notice: 'User was successfully updated.' } else format.html { render :edit } end end end def destroy @user.destroy respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params if admin_check params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :admin) else params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :admin) end end end
import React, {useCallback, useContext, useEffect, useState} from 'react' import { View, Text, SafeAreaView, StyleSheet, TouchableOpacity, ScrollView, TouchableWithoutFeedback, Alert, Animated } from "react-native"; import ScreenWrapper from "../../components/ScreenWrapper"; import colors from "../../config/colors"; import AntDesign from '@expo/vector-icons/AntDesign'; import useDB from "../../../db/useDB"; import {useFocusEffect} from "@react-navigation/native"; import {Feather} from '@expo/vector-icons'; import {Ionicons} from '@expo/vector-icons'; import constants from 'expo-constants'; import NoteCard from "../../components/NoteCard"; import {plusButtonStyle} from "../../styles/styles"; import useSelect from "../../hooks/useSelect"; import HeaderButtons from "../../components/HeaderButtons"; const NoteHomeScreen = ({navigation}) => { const {fetchNotes, deleteNotesByIds, createNoteTable} = useDB(); const {isSelecting, setIsSelecting, isSelectedAll, setIsSelectedAll} = useSelect(); const [selectedNotes, setSelectedNotes] = useState([]); const [notes, setNotes] = useState([]); const getAllNotes = async () => { try { let res = await fetchNotes(); setNotes(res); } catch (error) { console.log('error', error); alert(error); } } useEffect(() => { if (notes.length && notes.length === selectedNotes.length) { setIsSelectedAll(true); } }, [selectedNotes]); useEffect(() => { const migrate = async () => { try { let res = await createNoteTable(); // console.log('Response', res); } catch (e) { // console.log(e); } } migrate(); }, []); useFocusEffect( useCallback(() => { let isActive = true; const fetchData = async () => { if (isActive) { await getAllNotes(); } } fetchData(); return () => { isActive = false; } }, []) ); const handleLongPress = (note) => { if (isSelecting) return; setIsSelecting(true); setSelectedNotes(pre => [...pre, note.id]); } const handlePress = (note) => { if (!isSelecting) { navigation.navigate('NoteFormScreen', { ...note, content: note.content?.startsWith('"') ? JSON.parse(note.content) : note.content }); return; } ; if (selectedNotes.includes(note.id)) { setSelectedNotes(pre => { let selectedItems = pre.filter(item => item !== note.id); selectedItems.length === 0 && setIsSelecting(false); return selectedItems; }); setIsSelectedAll(false); } else { setSelectedNotes(pre => [...pre, note.id]); } } const handleCancelSelect = () => { setIsSelecting(false); setSelectedNotes([]); setIsSelectedAll(false); } const handleSelectAll = () => { if (isSelectedAll) { setSelectedNotes([]); setIsSelecting(true); setIsSelectedAll(false); } else { let noteIds = []; notes.forEach(note => { noteIds.push(note.id); }); setSelectedNotes(noteIds); setIsSelecting(true); } } const handleDelete = async () => { try { deleteNotesByIds(selectedNotes); setIsSelecting(false); setSelectedNotes([]); getAllNotes(); } catch (error) { console.log(error); } } return ( <SafeAreaView style={styles.container}> <TouchableOpacity onPress={() => navigation.navigate('NoteFormScreen')} style={plusButtonStyle}> <AntDesign name="plus" size={28} color="white"/> </TouchableOpacity> <HeaderButtons handleCancelSelect={handleCancelSelect} handleDelete={handleDelete} handleSelectAll={handleSelectAll} isSelectedAll={isSelectedAll} isSelecting={isSelecting}/> <ScreenWrapper> <ScrollView showsVerticalScrollIndicator={false}> { isSelecting ? <Text style={{ fontSize: 20, color: colors.white, padding: 10, fontWeight: '600', opacity: isSelecting ? 1 : 0 }}>{selectedNotes.length} item selected.</Text> : <Text style={styles.title}>Note</Text> } { notes.length === 0 ? <View style={{justifyContent: 'center', alignItems: 'center'}}> <Text style={{color: colors.gray, marginTop: 100, fontSize: 20}}>No notes</Text> </View> : <> { notes.map((item) => ( <NoteCard key={item.id} selectedNotes={selectedNotes} handleLongPress={handleLongPress} handlePress={handlePress} isSelecting={isSelecting} item={item}/> )) } </> } </ScrollView> </ScreenWrapper> </SafeAreaView> ) } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: colors.black, paddingTop: constants.statusBarHeight, }, title: { fontSize: 25, fontWeight: '700', marginBottom: 15, color: colors.white, }, }); export default NoteHomeScreen;
import React from 'react' import { Helmet } from 'react-helmet-async' const MetaHelmet = ({ title, description, image }) => { return ( <Helmet> <title>{title}</title> <meta name='description' content={description} /> <meta property="og:title" content={title} /> <meta property="og:description" content={description} /> <meta property="og:image" content={image} /> <meta property="og:image:width" content="1200" /> <meta property="og:image:height" content="630" /> <meta name="twitter:title" content={title} /> <meta name="twitter:description" content={description} /> <meta name="twitter:image" content={image} /> </Helmet> ) } export default MetaHelmet
import React, { ReactChild } from "react"; import { FormattedMessage } from 'react-intl' import { FavouritesContainer } from "../../components/favourites"; import { ErrorContainer } from '../../components/error' import { StyledFlexColumnWrapper } from "../../components/styled/flexColumnWrapper"; import { StyledFlexWrapper } from "../../components/styled/flexWrapper"; import { StyledLayoutFooter, StyledErrorWrapper } from "./style"; interface IProps { children: ReactChild; } function MainLayout({ children }: IProps) { return ( <StyledFlexColumnWrapper> <header> <h1><FormattedMessage id="pokesarch" /></h1> </header> <div> <main>{children}</main> </div> <StyledLayoutFooter> <footer> <StyledErrorWrapper> <ErrorContainer /> </StyledErrorWrapper> <StyledFlexWrapper> <FavouritesContainer /> </StyledFlexWrapper> </footer> </StyledLayoutFooter> </StyledFlexColumnWrapper> ); } export default MainLayout;
import { users } from "db/schema/user"; import { eq } from "drizzle-orm"; import { db } from "~/services/db.server"; import { hashPassword } from "~/utils/password"; export type User = typeof users.$inferSelect; export type NewUser = typeof users.$inferInsert; export async function createUser( email: string, password: string, ): Promise<User> { const hashedPassword = await hashPassword(password); const returnedUsers: User[] = await db .insert(users) .values({ email, password: hashedPassword, }) .returning(); return returnedUsers[0]; } export async function getUserById(id: number): Promise<User> { const returnedUsers = await db.select().from(users).where(eq(users.id, id)); return returnedUsers[0]; } export async function getUserByEmail(email: string): Promise<User> { const returnedUsers = await db .select() .from(users) .where(eq(users.email, email)); return returnedUsers[0]; } export async function changePassword(user_id: number, password: string) { const hashedPassword = await hashPassword(password); await db .update(users) .set({ password: hashedPassword }) .where(eq(users.id, user_id)); } export async function updateUserById(user_id: number, update: Partial<User>) { await db.update(users).set(update).where(eq(users.id, user_id)); } export async function getUserByCustomerId(customerId: string) { const returnedUsers = await db .select() .from(users) .where(eq(users.subscription_customer, customerId)); return returnedUsers[0]; }
import 'package:country_flags/country_flags.dart'; import 'package:flutter/cupertino.dart'; import 'package:watchlistfy/pages/main/discover/movie_discover_list_page.dart'; import 'package:watchlistfy/pages/main/discover/tv_discover_list_page.dart'; import 'package:watchlistfy/static/constants.dart'; class PreviewCountryList extends StatelessWidget { final bool isMovie; const PreviewCountryList({required this.isMovie, super.key}); @override Widget build(BuildContext context) { return SizedBox( height: 75, child: ListView.builder( itemCount: (isMovie ? Constants.MoviePopularCountries : Constants.TVPopularCountries).length, scrollDirection: Axis.horizontal, itemBuilder: (context, index) { final country = (isMovie ? Constants.MoviePopularCountries : Constants.TVPopularCountries)[index]; return Padding( padding: index == 0 ? const EdgeInsets.only(left: 8, right: 4) : const EdgeInsets.symmetric(horizontal: 4), child: GestureDetector( onTap: () { Navigator.of(context, rootNavigator: true).push( CupertinoPageRoute(builder: (_) { if (isMovie) { return MovieDiscoverListPage(country: country.request); } else { return TVDiscoverListPage(country: country.request); } }) ); }, child: ClipRRect( borderRadius: BorderRadius.circular(8), child: SizedBox( width: 96, height: 75, child: Stack( children: [ CountryFlag.fromCountryCode( country.request, width: 96, height: 75, ), SizedBox( width: 96, child: Align( alignment: Alignment.bottomCenter, child: ColoredBox( color: CupertinoColors.black.withOpacity(0.6), child: SizedBox( width: double.infinity, child: Padding( padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 6), child: Text( country.name, textAlign: TextAlign.center, style: const TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: CupertinoColors.white ), ), ), ), ), ), ), ], ), ), ), ), ); } ), ); } }
import torch from flask import Flask, render_template, request, jsonify from transformers import AutoModelForSequenceClassification, AutoTokenizer from torch.nn.functional import softmax from flask import Flask, render_template, request, redirect, url_for from flask import Flask, session from flask_mysqldb import MySQL import mysql.connector import secrets app = Flask(__name__) app.secret_key = secrets.token_hex(16) # Configure MySQL app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' # Change this if your MySQL username is different app.config['MYSQL_PASSWORD'] = '' # Enter your MySQL password here app.config['MYSQL_DB'] = 'journal' mysql = MySQL(app) # Initialize sentiment analysis model and tokenizer model_name = "j-hartmann/emotion-english-distilroberta-base" model = AutoModelForSequenceClassification.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) def analyze_sentiment(text): inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512) outputs = model(**inputs) predictions = softmax(outputs.logits, dim=-1) emotion_scores = {model.config.id2label[i]: score.item() for i, score in enumerate(predictions[0])} return emotion_scores @app.route("/") def index(): return redirect(url_for('login')) # Redirect to the login page @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": email = request.form["email"] password = request.form["password"] confirm_password = request.form["confirmPassword"] # Check if email already exists cur = mysql.connection.cursor() cur.execute("SELECT * FROM users WHERE email = %s", (email,)) user = cur.fetchone() cur.close() if user: return render_template("signup.html", error="Email already exists") if password != confirm_password: return render_template("signup.html", error="Passwords do not match") cur = mysql.connection.cursor() cur.execute("INSERT INTO users (email, password) VALUES (%s, %s)", (email, password)) mysql.connection.commit() cur.close() return redirect(url_for('login')) return render_template("signup.html", error="") @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": email = request.form["email"] password = request.form["password"] cur = mysql.connection.cursor() cur.execute("SELECT * FROM users WHERE email = %s", (email,)) user = cur.fetchone() cur.close() if user: if password == user[2]: session['logged_in'] = True session['email'] = email return redirect(url_for('home')) else: return render_template("login.html", error="Invalid email/password combination") return render_template("login.html", error="Invalid email/password combination") return render_template("login.html") @app.route("/home") def home(): if 'logged_in' in session: return render_template("home.html") else: return redirect(url_for('login')) @app.route("/analysis") def analysis(): return render_template("analysis.html") @app.route("/logout") def logout(): session.pop('logged_in', None) session.pop('email', None) return redirect(url_for('login')) @app.route("/analyze", methods=["POST"]) def analyze(): if request.method == 'POST': journal_text = request.form['journal'] sentiments = analyze_sentiment(journal_text) if mysql.connection is None: return "Error: Database connection not established" cur=mysql.connection.cursor() cur.execute("INSERT INTO journalentry (journal_text, sentiments) VALUES (%s, %s)", (journal_text, str(sentiments))) mysql.connection.commit() cur.close() return jsonify({'sentiments': sentiments}) @app.route('/weekly_analysis', methods=['GET']) def weekly_analysis(): # Fetch entries from the database cur=mysql.connection.cursor() cur.execute("SELECT * FROM journalentry ORDER BY id DESC") entries = cur.fetchall() cur.close() combined_analysis = [] # Process entries in batches of 7 for i in range(0, len(entries), 7): batch_entries = entries[i:i+7] batch_texts = [entry[1] for entry in batch_entries] # Assuming the text is in the second column batch_emotions = [analyze_sentiment(text) for text in batch_texts] combined_analysis.append(batch_emotions) return jsonify(combined_analysis) @app.route("/previous") def previous(): if mysql.connection is None: return "Error: Database connection not established" # Fetch journal entries from the database cur = mysql.connection.cursor() cur.execute("SELECT * FROM journalentry ORDER BY id DESC") # Assuming 'id' is the primary key entries = cur.fetchall() cur.close() # Render the template with the fetched entries return render_template('previous.html', entries=entries) if __name__ == '__main__': app.run(debug=True)
import { SimpleNumMap, nil } from "../../shared/util/simpleTypes.js"; const nameCache = new Map<number, string>(); /** * Mixin for the `methods` object on Vue components. Gives the component access * to a global list of EVE ID -> name mappings. * * In order to avoid data duplication, some server endpoints return a single * map of ID -> name at the end of the response instead of sprinkling in `name` * fields throughout. * * Whenever a component receives a network request that contains an id -> name * map, it should call addNames(). This allows any child components to * access the map without it being passed to them explicitly. */ export const NameCacheMixin = { methods: { addNames(names: SimpleNumMap<string>) { for (const id in names) { nameCache.set(parseInt(id), names[id]); } }, name(id: number) { return nameCache.get(id) ?? "[Unknown entity]"; }, nameOrUnknown(id: number | nil) { if (id == null) { return "[Unknown entity]"; } else { return nameCache.get(id) ?? "[Unknown entity]"; } }, }, };
import { useDispatch } from "react-redux"; import { useSelector } from "react-redux"; import { register } from "../../redux/auth/auth-operations"; import { getAuth } from "../../redux/auth/auth-selectors"; import RegisterForm from "../../components/RegisterForm/RegisterForm"; import Loader from "../../components/Loader/Loader"; import styles from "./registerPage.module.css"; const RegisterPage = () => { const dispatch = useDispatch(); const { loading } = useSelector(getAuth); if (loading) { return <Loader />; } const onRegister = (data) => dispatch(register(data)); return ( <div className={styles.wrapper}> <h1 className={styles.title}> Please fill in the forms so we can start! </h1> <RegisterForm onSubmit={onRegister} /> </div> ); }; export default RegisterPage;
import pygame import random ############################################################## # 초기화 (반드시 필요) pygame.init() # 화면 크기 설정 screen_width = 480 # 가로크기 screen_height = 640 # 세로크기 screen = pygame.display.set_mode((screen_width, screen_height)) # 화면 타이틀 설정 pygame.display.set_caption("Woong Game") # FPS clock = pygame.time.Clock() ############################################################## # 1. 사용자 게임 초기화 (배경화면, 게임 이미지, 좌표, 속도, 폰트 등) # 배경 이미지 불러오기 background = pygame.image.load( "/Users/woong/Desktop/Python_Game/background.png") # 캐릭터(스프라이트) 블러오기 character = pygame.image.load( "/Users/woong/Desktop/Python_Game/character.png") character_size = character.get_rect().size # 이미지의 크기를 구해옴 character_width = character_size[0] # 캐릭터의 가로 크기 character_height = character_size[1] # 캐릭터의 세로 크기 character_x_pos = (screen_width / 2) - (character_width / 2) # 화면 가로의 절반 크기에 해당하는 곳에 위치 (가로) # 화면 세로 크기 가장 아래에 해당하는 곳에 위치 (세로) character_y_pos = screen_height - character_height # 이동할 좌표 to_x = 0 to_y = 0 # 이동 속도 character_speed = 0.6 # 적 enemy 캐릭터 enemy = pygame.image.load("/Users/woong/Desktop/Python_Game/enemy.png") enemy_size = enemy.get_rect().size # 이미지의 크기를 구해옴 enemy_width = enemy_size[0] # 캐릭터의 가로 크기 enemy_height = enemy_size[1] # 캐릭터의 세로 크기 enemy_x_pos = random.randint(enemy_width, 480) - enemy_width # 화면 가로의 절반 크기에 해당하는 곳에 위치 (가로) enemy_y_pos = 0 # 화면 세로 크기 중간에 해당하는 곳에 위치 (세로) running = True while running: dt = clock.tick(30) # 게임화면의 초당 프레임 수를 설정 enemy_y_pos += 5 # 2. 이벤트 처리 (키보드, 마우스 등) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 3. 게임 캐릭터 위치 정의 if event.type == pygame.KEYDOWN: # 키가 눌러졌는지 확인 if event.key == pygame.K_LEFT: # 캐릭터를 왼쪽으로 to_x -= character_speed elif event.key == pygame.K_RIGHT: # 캐릭터를 오른쪽으로 to_x += character_speed if event.type == pygame.KEYUP: # 방향키를 때면 멈춤 if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: to_x = 0 character_x_pos += to_x * dt # 가로 경계값 처리 if character_x_pos < 0: character_x_pos = 0 elif character_x_pos > screen_width - character_width: character_x_pos = screen_width - character_width # 세로 경계값 처리 (enemy) if enemy_y_pos > screen_height: enemy_y_pos = 0 enemy_x_pos = random.randint(enemy_width, 480) - enemy_width # 4. 충돌 처리 character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos enemy_rect = enemy.get_rect() enemy_rect.left = enemy_x_pos enemy_rect.top = enemy_y_pos # 충돌 체크 if character_rect.colliderect(enemy_rect): print("충돌했어요") running = False # 5. 화면에 그리기 screen.blit(background, (0, 0)) # 배경 그리기 screen.blit(character, (character_x_pos, character_y_pos)) # 캐릭터 그리기 screen.blit(enemy, (enemy_x_pos, enemy_y_pos)) # 적 그리기 pygame.display.update() # 게임화면을 다시 그리기! pygame.quit()
import React from 'react' import { View } from 'react-native' import { useSelector } from 'react-redux' import PropTypes from 'prop-types' import _noop from '@lodash/noop' import _prependZero from '@lodash/prependZero' import { NEW_GAME } from '@resources/stringLiterals' import Button from '@ui/molecules/Button' import Text, { TEXT_VARIATIONS } from '@ui/atoms/Text' import { useStyles } from '@utils/customHooks/useStyles' import { GameState } from '../utils/classes/gameState' import { getGameState } from '../store/selectors/gameState.selectors' import { GAME_OVER_CARD_TEST_ID } from './gameResultCard.constants' import { getStyles } from './gameResultCard.styles' const getTimeView = (time, styles) => { const { hours = 0, minutes = 0, seconds = 0 } = time || {} return ( <View style={styles.timeStatContainer}> {hours ? <Text style={styles.textColor}>{hours}</Text> : null} <Text style={styles.textColor}>{`${_prependZero(minutes)}:`}</Text> <Text style={styles.textColor}>{_prependZero(seconds)}</Text> </View> ) } const GameResultCard = ({ stats, openNextGameMenu }) => { const { mistakes, difficultyLevel, time, hintsUsed, } = stats const styles = useStyles(getStyles) const gameState = useSelector(getGameState) const getGameSolvedView = () => { if (!new GameState(gameState).isGameSolved()) return null return ( <> {/* this trophy icon works well only for debug builds. for release build app crashes. my guess is that it's because of wrong formats. like "m"(web) and "M"(App) for drawings */} {/* <TrophyIcon width={TROPHY_ICON_DIMENSION} height={TROPHY_ICON_DIMENSION} /> */} <Text style={[styles.congratsText, styles.textColor]} type={TEXT_VARIATIONS.HEADING_SMALL}> Congratulations! </Text> <View style={styles.statsContainer}> <View style={styles.statContainer}> <Text style={styles.textColor}>Difficulty</Text> <Text style={styles.textColor}>{difficultyLevel}</Text> </View> <View style={styles.statContainer}> <Text style={styles.textColor}>Time</Text> {getTimeView(time, styles)} </View> <View style={styles.statContainer}> <Text style={styles.textColor}>Mistakes</Text> <Text style={styles.textColor}>{mistakes}</Text> </View> {/* <View style={styles.statContainer}> <Text style={styles.textColor}>Hints Used</Text> <Text style={styles.textColor}>{hintsUsed}</Text> </View> */} </View> </> ) } const getGameUnsolvedView = () => { if (!new GameState(gameState).isGameUnsolved()) return null return ( <Text style={[styles.gameUnsolvedMsg, styles.textColor]}> You have reached the maximum mistakes limit. Better Luck Next Time </Text> ) } const renderNewGameButton = () => ( <Button label={NEW_GAME} onPress={openNextGameMenu} containerStyle={styles.newGameButtonContainer} /> ) return ( <View onStartShouldSetResponder={() => true} style={styles.container} testID={GAME_OVER_CARD_TEST_ID} > {getGameSolvedView()} {getGameUnsolvedView()} {renderNewGameButton()} </View> ) } export default React.memo(GameResultCard) GameResultCard.propTypes = { stats: PropTypes.object, openNextGameMenu: PropTypes.func, } GameResultCard.defaultProps = { stats: {}, openNextGameMenu: _noop, }
package folders import ( "database/sql" "net/http" "net/http/httptest" "regexp" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/stretchr/testify/assert" ) func (ts *TransactionSuite) TestList() { defer ts.conn.Close() tcs := []struct { Desc string ExpectedStatusCode int WithMockErr bool }{ { Desc: "Should returns status OK", ExpectedStatusCode: http.StatusOK, WithMockErr: false, }, { Desc: "Should returns status 500", ExpectedStatusCode: http.StatusInternalServerError, WithMockErr: true, }, } for _, tc := range tcs { recorder := httptest.NewRecorder() request := httptest.NewRequest(http.MethodGet, "/", nil) setMockGetSubFolder(ts.mock) setMockListRootFiles(ts.mock, tc.WithMockErr) h := handler{ ts.conn, } h.List(recorder, request) assert.Equal(ts.T(), tc.ExpectedStatusCode, recorder.Result().StatusCode) } } func (ts *TransactionSuite) TestRootSubFolder() { defer ts.conn.Close() setMockGetSubFolder(ts.mock) folders, err := getRootSubFolder(ts.conn) assert.NoError(ts.T(), err) assert.Equal(ts.T(), len(folders), 1) } func setMockGetSubFolder(mock sqlmock.Sqlmock) { columns := []string{ "id", "name", "parent_id", "created_at", "modified_at", "deleted", } rows := sqlmock.NewRows(columns). AddRow( 1, "any folder name", 0, time.Now(), time.Now(), false, ) expectedSQL := regexp.QuoteMeta(` SELECT id, name, parent_id, created_at, modified_at, deleted FROM "folders" WHERE "parent_id" IS NULL "deleted"=false`) mock.ExpectQuery(expectedSQL). WillReturnRows(rows) } func setMockListRootFiles(mock sqlmock.Sqlmock, withMockErr bool) { expectedSQL := regexp.QuoteMeta(`SELECT id, name, folder_id, owner_id, type, path, created_at, modified_at, deleted FROM files WHERE folder_id IS NULL AND deleted = false`) rows := sqlmock.NewRows([]string{ "id", "name", "folder_id", "owner_id", "type", "path", "created_at", "modified_at", "deleted_at", }).AddRow( 1, "any_name", 1, 1, "file", "/any/path", time.Now(), time.Now(), false, ) expected := mock.ExpectQuery(expectedSQL) if !withMockErr { expected.WillReturnRows(rows) } else { expected.WillReturnError(sql.ErrNoRows) } }
(function(window) { 'use strict'; var App = window.App || {}; var $ = window.jQuery; function CheckList(selector) { if(!selector) { throw new Error('No selector provided'); } this.$element = $(selector); if(this.$element.length === 0) { throw new Error('Could not find element with selector: ' + selector); } } CheckList.prototype.addRow = function (coffeeOrder) { this.removeRow(coffeeOrder.emailAddress); //Create a new instance of a row, using the coffeee order info var rowElement = new Row(coffeeOrder); //Add the new row instance to the DOM CheckList this.$element.append(rowElement.$element); }; CheckList.prototype.removeRow = function (email) { this.$element .find('[value="' + email + '"]') .closest('[data-coffee-order="checkbox"]') .remove(); }; CheckList.prototype.addClickHandler = function (fn) { this.$element.on('click','input',function(event){ var email = event.target.value; fn(email) .then(function() { this.removeRow(email); }.bind(this)); }.bind(this)); }; function Row(coffeeOrder) { // Constructor code will go here for Row var $div = $('<div></div>', { 'data-coffee-order': 'checkbox', 'class': 'checkbox' }); var $label = $('<label></label>'); var $checkbox = $('<input></input>', { type: 'checkbox', value: coffeeOrder.emailAddress }); var description = coffeeOrder.size + ' '; if(coffeeOrder.flavor) { description += coffeeOrder.flavor + ' '; } description += coffeeOrder.coffee + ', '; description += ' (' + coffeeOrder.emailAddress + ')'; description += ' [' + coffeeOrder.strength + 'x]'; $label.append($checkbox); $label.append(description); $div.append($label); this.$element = $div; } App.CheckList = CheckList; window.App = App; })(window)
using System.Net; using MediatR; using Tesodev.Case.Customer.Application.Commands; using Tesodev.Case.Customer.Application.Dtos; using Tesodev.Case.Customer.Application.Queries; using Tesodev.Case.Customer.Application.Utilities.Results; namespace Tesodev.Case.Customer.API.Controllers.V1; [ApiVersion("1.0")] [ApiController] [Route("api/v{version:apiVersion}/customers")] public class CustomerController : Controller { private readonly IMediator _mediator; public CustomerController(IMediator mediator) { _mediator = mediator; } /// <summary> /// Get customers /// </summary> /// <returns><see cref="Task{IActionResult}"/></returns> [HttpGet] [Produces("application/json", "text/plain")] [Consumes("application/json", "text/plain")] [ProducesResponseType(typeof(SuccessDataResult<List<GetCustomerDto>>), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> GetCustomers() { var commandResult = await _mediator.Send(new GetCustomersQuery()); return Ok(commandResult); } /// <summary> /// Get customer by id /// </summary> /// <returns><see cref="Task{IActionResult}"/></returns> [HttpGet("{id}")] [Produces("application/json", "text/plain")] [Consumes("application/json", "text/plain")] [ProducesResponseType(typeof(SuccessDataResult<GetCustomerDto>), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> GetCustomerById([FromRoute] string id) { var commandResult = await _mediator.Send(new GetCustomerByIdQuery(id)); return Ok(commandResult); } /// <summary> /// Add customer /// </summary> /// <param name="addCustomerCommand">Add item command</param> /// <returns><see cref="Task{IActionResult}"/></returns> [HttpPost] [Produces("application/json", "text/plain")] [Consumes("application/json", "text/plain")] [ProducesResponseType(typeof(SuccessDataResult<GetCustomerDto>), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> AddCustomer([FromBody] AddCustomerCommand addCustomerCommand) { var commandResult = await _mediator.Send(addCustomerCommand); return CreatedAtAction(nameof(GetCustomers), commandResult); } /// <summary> /// Delete customer /// </summary> /// <returns><see cref="Task{IActionResult}"/></returns> [HttpDelete("{id}")] [Produces("application/json", "text/plain")] [Consumes("application/json", "text/plain")] [ProducesResponseType(typeof(SuccessResult), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> DeleteCustomer([FromRoute] string id) { var commandResult = await _mediator.Send(new DeleteCustomerCommand(id)); return Ok(commandResult); } /// <summary> /// Update customer /// </summary> /// <returns><see cref="Task{IActionResult}"/></returns> [HttpPut("{id}")] [Produces("application/json", "text/plain")] [Consumes("application/json", "text/plain")] [ProducesResponseType(typeof(SuccessDataResult<GetCustomerDto>), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> UpdateCustomer([FromRoute] string id, [FromBody] UpdateCustomerCommand updateCustomerCommand) { updateCustomerCommand.CustomerId = id; var commandResult = await _mediator.Send(updateCustomerCommand); return Ok(commandResult); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Phaser</title> </head> <body> <script src="node_modules/phaser/dist/phaser.min.js"></script> <script> var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { game.load.image('sky', 'assets/sky.png'); game.load.image('ground', 'assets/platform.png'); game.load.image('star', 'assets/star.png'); game.load.spritesheet('dude', 'assets/dude.png', 32, 48); } var platforms; function create() { // We're going to be using physics, so enable the Arcade Physics system game.physics.startSystem(Phaser.Physics.ARCADE); // Background sky game.add.sprite(0, 0, 'sky'); platforms = game.add.group(); platforms.enableBody = true; // Ground var ground = platforms.create(0, game.world.height - 64, 'ground'); ground.scale.setTo(2, 2); ground.body.immovable = true; // Platforms var ledge = platforms.create(400, 400, 'ground'); ledge.body.immovable = true; ledge = platforms.create(-150, 250, 'ground'); ledge.body.immovable = true; game.add.sprite(50, 110, 'star'); player = game.add.sprite(32, game.world.height - 600, 'dude'); player.animations.add('left', [0, 1, 2, 3], 20, true); player.animations.add('right', [5, 6, 7, 8], 20, true); game.physics.arcade.enable(player); player.body.bounce.y = 0.2; player.body.gravity.y = 6000; player.body.collideWorldBounds = true; // Controls cursors = game.input.keyboard.createCursorKeys(); } function update() { game.physics.arcade.collide(player, platforms); player.body.velocity.x = 0; if (cursors.left.isDown) { // Move to the left player.body.velocity.x = -650; player.animations.play('left'); } else if (cursors.right.isDown) { // Move to the right player.body.velocity.x = 650; player.animations.play('right'); } else { // Stand still player.animations.stop(); player.frame = 4; } if (cursors.up.isDown && player.body.touching.down) { player.body.velocity.y = -6500; } } </script> </body> </html>
import React, { FC, useCallback, useEffect, useState } from 'react'; import styles from './ShoppingList.module.scss'; import { IPurchase } from '../../ts/models/shopping.model'; import { testShopping } from '../../data/testShoppingData'; import ShoppingItem from './ShoppingItem/ShoppingItem'; import purchasesApi from '../../api/purchases'; import SortedList from './SortedList/SortedList'; import SearchedList from './SearchedList/SearchedList'; interface IShoppingList { isUpdate: boolean; setIsUpdate: SetState<boolean>; } const ShoppingList: FC<IShoppingList> = ({ isUpdate, setIsUpdate }) => { const [shoppingList, setShoppingList] = useState<IPurchase[]>(testShopping); const [data, setData] = useState<IPurchase[]>([]); const getData = useCallback(async () => { setIsUpdate(false); // const res = await purchasesApi.fetchAllList(); // if (!res) return; // setShoppingList(res.data); // setData(data); }, []); useEffect(() => { getData(); }, []); useEffect(() => { isUpdate && getData(); }, [isUpdate]); return ( <section className={styles.container}> <SearchedList setShoppingList={setShoppingList} data={data} /> <SortedList shoppingList={shoppingList} setShoppingList={setShoppingList} /> <ul className={styles.wrapper}> {shoppingList.length ? shoppingList.map((purchase) => ( <ShoppingItem key={purchase.purchase_id} purchase={purchase} setIsUpdate={setIsUpdate} /> )) : null} </ul> </section> ); }; export default ShoppingList;
/* Laura Mills Nelson Interactive Web I December 17, 2019 CSS Style page for "About Me" website This style sheet uses a colored leaf theme. The three new CSS techniques that were not covered in class that I researched and applied were as follows: 1. Text transparency 2. The Hamburger menu icon/drop down menu for mobile screens 3. The z-index property */ body { background-color: #2B292A; color: #000000; font-family: 'Nunito Sans', sans-serif; font-size: 1.2em; } /* Uses colorful leaves as background image */ header { background-image: url("images/colorful_leaves_desktop.jpg"); background-repeat: no-repeat; background-size: cover; line-height: 378px; } h1 { color: #FFFFFF; color: hsla(0, 0%, 100%, .85); line-height: 378px; text-align: center; font-size: 350%; font-family: 'Fira Code', monospace; } /* Aligns the navigational bar links in the center of the page*/ nav { font-family: 'Nunito Sans', sans-serif; font-size: 110%; margin-top: -50px; text-align: center; font-weight: bold; width: 100%; } nav li { display: inline-block; width: 5.25em; font-size: 120%; text-align: center; border-style: solid; border-color: #3F3F3F; border-width: 5px; padding: 1% 1%; margin-top: 5px; margin-left: -40px; } /* unvisited link */ a:link { color: #FFFFFF; text-decoration: none; } /* visited link */ a:visited { color: #000000; text-decoration: none; } /* mouse over link */ a:hover { color: #D8D8D8; text-decoration: none; } main { margin-left: 60px; margin-right: 60px; } p { line-height: 120%; } /* Indents the numbered list of countries slightly more than default*/ ol { text-indent: 1em; } img { float: right; border-color: #FFFFFF; border-width: 10px; border-style: solid; box-shadow: 5px 5px 5px #828282; margin: 10px 1% 20px 60px; max-width: 40%; height: auto; } h2 { color: #3F3F3F; font-family: 'Nunito Sans', sans-serif; font-size: 200%; } h3 { color: #3F3F3F; font-family: 'Nunito Sans', sans-serif; font-size: 140%; } /* Uses a wrapper ID to center each page*/ #wrapper { width: 80%; margin-left: auto; margin-right: auto; background-color: #D4CDBD; } /* Uses a class selector to make the hyperlinks on the Cooking page bold */ .hyperlink { font-weight: bold; } /* unvisited paragraph link */ p a:link { color: #FFFFFF; text-decoration: none; } /* visited paragraph link */ p a:visited { color: #000000; text-decoration: none; } /* mouse over paragraph link */ p a:hover { color: #3F3F3F; text-decoration: none; } footer { text-align: center; } /* Uses an ID selector to italicize the copyright on each page */ #copyright { font-style: italic; text-align: center; } /* The following classes make each navigational item a different color */ .home { background-color: #D83757; } .cooking { background-color: #F27A5E; margin-left: -10px; } .books { background-color: #EAAC46; margin-left: -10px; } .hiking { background-color: #959938; margin-left: -10px; } .travel { background-color: #687247; margin-left: -10px; } #welcome { text-align: center; font-size: 120%; } #hobbies { margin-top: -25px; } /* Hide the links inside the navigation menu */ .topnav #myLinks { display: none; } /* makes the website responsive for tablet-sized screens */ @media only screen and (max-width: 1024px) { body { margin: 0; } #wrapper { width: 95%; } header { background-image: url("images/colorful_leaves_tablet.jpg"); background-repeat: no-repeat; background-size: cover; line-height: 200px; } h1 { line-height: 200px; font-size: 300%; } nav { margin-top: -44px; } nav li { display: inline-block; width: 4.85em; font-size: 120%; text-align: center; border-width: 5px; padding: 1% 1%; margin-top: 5px; margin-left: -40px; } /* Hide the links inside the navigation menu */ .topnav /*#myLinks*/ { display: none; } } /* makes the website responsive for mobile-sized screens */ @media only screen and (max-width: 768px) { #wrapper { width: auto; } /* Style the navigation menu */ .topnav { background-color: #2B292A; position: relative; height: 55px; margin: -10px -5px; z-index: 3; } /* Hide the links inside the navigation menu */ .topnav #myLinks { display: none; } /* Style navigation menu links */ .topnav a { color: #FFFFFF; padding: 14px 16px; text-decoration: none; text-align: center; font-family: 'Nunito Sans', sans-serif; font-weight: bold; font-size: 17px; display: block; margin-left: 5px; width: 80px; border-style: solid; border-color: #2B292A; border-width: 2px; } /* Style the hamburger menu */ .topnav a.icon { background-color: #000000; border-style: none; display: block; width: 15px; position: relative; left: 0; top: 2px; z-index: 3; } /* Add the beige background color on mouse-over */ .topnav a:hover { background-color: #D4CDBD; color: #000000; } /* formats header image */ header { position: absolute; top: 45px; left: 0px; height: 5%; width: 100%; background-image: url("images/colorful_leaves_mobile.jpg"); background-repeat: no-repeat; background-size: cover; border-style: solid; border-color: #2B292A; border-width: 3px 5px; z-index: 2; } h1 { font-size: 0; } main { margin: 110px 5% 0px 5%; width: auto; } body { margin: 1%; } nav { display: none; } nav li { display: none; } /* centers image when page reaches mobile size */ img { border-width: 4px; margin-left: 50%; margin-right: 30% } } /* creates compatibility between different browsers */ header, main, nav, footer, figure, figcaption { display: block; }
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:teacher/domain/models/teacher_exam_model.dart'; import '../../../resources/strings_manager.dart'; import '../../../widgets/error_screen.dart'; import '../../../widgets/loading_screen.dart'; import '../../../widgets/top_bar.dart'; import '../controller/exams_controller.dart'; import '../widgets/exam_list.dart'; class ExamsAndBanksScreen extends StatelessWidget { final TeacherCourse course; const ExamsAndBanksScreen({super.key, required this.course}); @override Widget build(BuildContext context) { return Scaffold( body: ListView( shrinkWrap: true, physics: const ClampingScrollPhysics(), children: [ const TopBar(title: AppStrings.examsAndBanks), GetX<ExamsController>( init: Get.find<ExamsController>(), builder: (ExamsController controller) { if (controller.status.isLoading) { return const LoadingScreen(); } else if (controller.status.isError) { return ErrorScreen(error: controller.status.errorMessage ?? ''); } else { TeacherExam? exam = controller.getCourseExams(course.id ?? -1); TeacherBank? banks = controller.getCourseBanks(course.id ?? -1); return ExamList(exams: exam, banks: banks,); } }, ), ], ), ); } }
.-----------------------------------------------------------------. | PLAYSTATION PATCH FILE VERSION 3.0 FILE-STRUCTURE FOR DEVELOPERS| '-----------------------------------------------------------------' 1. The PPF 3.0 Header: @START_PPF30HEADER .----------+--------+----------------------------------------------. | POSITION | SIZE | E X P L A N A T I O N | +----------|--------|----------------------------------------------+ | 00-04 | 05 | PPF-Magic: "PPF30" | +----------|--------|----------------------------------------------+ | 05 | 01 | Encoding Method: | | | | - 0x00 = is a PPF 1.0 Patch | | | | - 0x01 = is a PPF 2.0 Patch | | | | - 0x02 = is a PPF 3.0 Patch | +----------|--------|----------------------------------------------+ | 06-55 | 50 | Patch Description | +----------|--------|----------------------------------------------+ | 56 | 01 | Imagetype: | | | | - 0x00 = BIN (any) | | | | - 0x01 = GI (PrimoDVD) | +----------|--------|----------------------------------------------+ | 57 | 01 | Blockcheck/Patchvalidation: | | | | - 0x00 = Disabled | | | | - 0x01 = Enabled | | | | If disabled applyppf won't validate the patch| | | | also the 1024 byte block won't be available. | +----------|--------|----------------------------------------------+ | 58 | 01 | Undo data: | | | | - 0x00 = Not available | | | | - 0x01 = Available | | | | If available applyppf will be able to | | | | restore a previous patched bin to back to its| | | | original state. Patchsize increases of course| +----------|--------|----------------------------------------------+ | 59 | 01 | Dummy: | | | | Not used. | +----------|--------|----------------------------------------------+ | 60-1083 | 1024 | Binary block: | | | | It is used for patchvalidation. | | | | If Imagetype = 0x00 then its data starting | | | | from 0x9320. | | | | If Imagetype = 0x01 then its data starting | | | | from 0x80A0. | | | | If Blockcheck = 0x00 then this block won't be| | | | available. | +----------|--------|----------------------------------------------+ | 1084-X | XX | The Patch itself.. see below for structure! | '----------+--------+----------------------------------------------' @END_PPF30HEADER - TOTAL HEADER-SIZE = 1084 BYTE with validation and 60 BYTE without validation. 2. The PPF 3.0 Patch Itself (Encoding Method #2) @START_PPF30PATCH FORMAT : yyyyyyyyyyyyyyyy , zz , dd/uu[..] yyyyyyyyyyyyyyyy = Offset in file. [64 bit integer] zz = Number of bytes that will be changed. [u_char] dd/uu = Patch data following undo data (if present) [char array] EXAMPLES: Starting from file offset 0x15F9D0 replace 3 byte with 01,02,03: D0 F9 15 00 00 00 00 00 - 03 - 01 02 03 Starting from file offset 0x15F9D0 undo 3 byte to 0A,0A,0A which were formerly patched to 01,02,03: D0 F9 15 00 00 00 00 00 - 03 - 01 02 03 0A 0A 0A PPF3.0 is able to patch binfiles up to: 9,223,372,036,854,775,807 byte. Be careful! Endian format is Intel! @END_PPF30PATCH 3. The PPF 3.0 Fileid area @START_FILEID The fileid area is used to store additional patch information of the PPF 3.0 file. I implemented this following the AMIGA standard of adding a fileid to e.g. .txt files. You dont have to add a FILE_ID to the PPF 3.0 patch. It for your pleasure only! For developers: A file_id area begins with @BEGIN_FILE_ID.DIZ and ends with @END_FILE_ID.DIZ (Amiga BBS standard). Between @BEGIN_FILE_ID.DIZ and @END_FILE_ID.DIZ you will find the File_Id and followed after @END_FILE_ID.DIZ you will find an unsigned short (2 byte) with the length of the FILE_ID.DIZ! A File_ID.diz file cannot exceed 3072 byte. If you want to do a PPF3.0 Applier be sure to check for an existing FILE_ID area, because it is located after the PATCH DATA! @END_FILEID
require "test_helper" class Track::Trophies::ReadFiftyCommunitySolutionsTrophyTest < ActiveSupport::TestCase test "award?" do user = create :user other_user = create :user track = create :track other_track = create :track, slug: 'kotlin' trophy = create :read_fifty_community_solutions_trophy exercise = create(:practice_exercise, :random_slug, track:) other_exercise = create(:practice_exercise, :random_slug, track: other_track) create(:user_track, user:, track:) create(:user_track, user:, track: other_track) # Don't award trophy if no community solutions have been read refute trophy.award?(user, track) # Don't award trophy if less than fifty community solutions in the track have been read create_list(:practice_solution, 30, exercise:) do |solution| create(:user_track_viewed_community_solution, user:, track:, solution:) end refute trophy.award?(user, track) # Don't award trophy if other user has read fifty community solutions in the track create_list(:practice_solution, 50, exercise:) do |solution| create(:user_track_viewed_community_solution, user: other_user, track:, solution:) end refute trophy.award?(user, track) # Don't count viewed community solutions for other track create_list(:practice_solution, 60, exercise: other_exercise) do |solution| create(:user_track_viewed_community_solution, user:, track: other_track, solution:) end refute trophy.award?(user, track) # Award trophy when fifty community solutions in the track have been read create_list(:practice_solution, 20, exercise:) do |solution| create(:user_track_viewed_community_solution, user:, track:, solution:) end assert trophy.award?(user, track) end end
import React, { Component } from "react"; import withStyles from "@material-ui/styles/withStyles"; import { Link } from "react-router-dom"; import ColorBox from "./ColorBox"; import Navbar from "./Navbar"; import PaletteFooter from "./PaletteFooter"; import SingleColorPaletteStyles from "./styles/SingleColorPaletteStyles"; class SingleColorPalette extends Component { constructor(props) { super(props); this._shades = this.gatherShades(this.props.palette, this.props.colorId); this.state = { format: "hex" }; this.changeFormat = this.changeFormat.bind(this); } changeFormat(format) { this.setState({ format }); } // return all shades of given color gatherShades(palette, colorToFilterBy) { let shades = []; let allColors = palette.colors; for (let key in allColors) { shades = shades.concat( allColors[key].filter((color) => color.id === colorToFilterBy) ); } // The first entry is always white. We don't need it, so remove it. return shades.slice(1); } render() { const { format } = this.state; const { classes } = this.props; const { id, paletteName, emoji } = this.props.palette; const colorBoxes = this._shades.map((color) => ( <ColorBox key={color.name} name={color.name} background={color[format]} showingFullPalette={false} /> )); return ( <div className={classes.Palette}> <Navbar handleChange={this.changeFormat} showSlider={false} /> <div className={classes.colors}> {colorBoxes} <div className={classes.goBack}> <Link to={`/palette/${id}`}>Go Back</Link> </div> </div> <PaletteFooter paletteName={paletteName} emoji={emoji} /> </div> ); } } export default withStyles(SingleColorPaletteStyles)(SingleColorPalette);
""" Base.py Defines the Base class for all the ORM models to inherit from, so that SQLAlchemy can relate them together. """ from sqlalchemy.orm import DeclarativeBase, Session, load_only from sqlalchemy import select, Select class Base(DeclarativeBase): """ The declarative base class used by all AutoUmpire's ORM models On top of the standard DeclarativeBase class I define a `session` property that fetches the object's session. This is in order to make au_core self-contained; otherwise we would have to import the sqlalchemy.orm.Session class. """ @property def session(self) -> Session: """ :return: The sqlalchemy.orm.Session to which this object is attached. """ return Session.object_session(self) @classmethod def select(self, *columns_to_load) -> Select: """ :param *columns_to_load: positional arguments are passed to a load_only option on the select, i.e. which attributes of the class should be selected. :return: A select clause on this object """ return select(self).options(*(load_only(attr) for attr in columns_to_load)) # nice printed representation of ORM model instances def __repr__(self) -> str: return f"{type(self).__name__}({','.join([f'{c.key}={self.__getattribute__(c.key)}' for c in self.__table__.columns if self.__getattribute__(c.key) is not None])})"
<?php /** * The public-facing functionality of the plugin. * * @link http://slushman.com * @since 1.0.0 * * @package Como_Pipeline * @subpackage Como_Pipeline/public */ /** * The public-facing functionality of the plugin. * * Defines the plugin name, version, and two examples hooks for how to * enqueue the dashboard-specific stylesheet and JavaScript. * * @package Como_Pipeline * @subpackage Como_Pipeline/public * @author Slushman <chris@slushman.com> */ class Como_Pipeline_Public { /** * The plugin options. * * @since 1.0.0 * @access private * @var string $options The plugin options. */ private $options; /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $Como_Pipeline The name of the plugin. * @param string $version The version of this plugin. */ public function __construct( $plugin_name, $version ) { $this->plugin_name = $plugin_name; $this->version = $version; $this->set_options(); } /** * Register the stylesheets for the public-facing side of the site. * * @since 1.0.0 */ public function enqueue_styles() { wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/como-pipeline-public.min.css', array(), $this->version, 'all' ); } /** * Register the stylesheets for the public-facing side of the site. * * @since 1.0.0 */ public function enqueue_scripts() { wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/como-pipeline-public.min.js', array( 'jquery' ), $this->version, true ); } /** * Processes shortcode comopipeline * * @param array $atts The attributes from the shortcode * * @uses get_option * @uses get_layout * * @return mixed $output Output of the buffer */ public function display_pipeline_chart( $atts = array() ) { if (!is_admin()) { ob_start(); $defaults['loop-template'] = $this->plugin_name . '-loop'; $defaults['order'] = 'menu_order'; $defaults['quantity'] = 100; $defaults['type'] = null; $defaults['id'] = null; $defaults['class'] = null; $defaults['footnote'] = null; $args = shortcode_atts( $defaults, $atts, 'como-pipeline' ); //echo '<p>PASSED FROM SHORTCODE: '; //print_r($args); //echo '<p>'; $instID = (isset($atts['id']) ? $atts['id'] : ''); $shared = new Como_Pipeline_Shared( $this->plugin_name, $this->version ); $items = $shared->get_candidates( $args, $instID ); if ( is_array( $items ) || is_object( $items ) ) { include como_pipeline_get_template($args['loop-template']); } else { echo $items; } $output = ob_get_contents(); ob_end_clean(); return $output; } } // display_pipeline_chart() /** * Registers all shortcodes at once * * @return [type] [description] */ public function register_shortcodes() { add_shortcode( 'pipeline-chart', array( $this, 'display_pipeline_chart' ) ); } // register_shortcodes() /** * Adds a default single view template for a candidate opening * * @param string $template The name of the template * @return mixed The single template */ public function single_cpt_template( $template ) { global $post; $return = $template; if ( $post->post_type == 'candidate' ) { $return = como_pipeline_get_template( 'single-candidate' ); } return $return; } // single_cpt_template() /** * Sets the class variable $options */ private function set_options() { $this->options = get_option( $this->plugin_name . '-options' ); } // set_options() } // class
import { DosCommandInterface } from "../js-dos-ci"; export interface GamepadConfig { buttons: string[]; keymap: {[button: string]: number}; mapArrows: boolean; stickThreshold: number; } export interface GamepadOptions { gamepads: GamepadConfig[]; scanEvery: number; scanOnTick: boolean; } export default function Gamepad( ci: DosCommandInterface, options: GamepadOptions) { const xBox360Buttons: string[] = [ "a", "b", "x", "y", // 0, 1, 2, 3 "lb", "rb", "lt", "rt", // 4, 5, 6, 7 "back", "start", "N/A", "N/A", // 8, 9, 10, 11 "up", "down", "left", "right", // 12, 13, 14, 15 ]; const arrows: {[button: string]: number} = { left: 37, right: 39, up: 38, down: 40, lsleft: 37, lsright: 39, lsup: 38, lsdown: 40, rsleft: 37, rsright: 39, rsup: 38, rsdown: 40, }; const consumer = ci.getKeyEventConsumer(); const detected: number[] = []; const lastStates: {[index: number]: number[]} = {}; function pushPressed( button: string, config: GamepadConfig, pressed: number[]) { const keymap = config.keymap || {}; let key = config.keymap[button]; if (!key && config.mapArrows) { key = arrows[button]; } if (key && (pressed.indexOf(key) === -1)) { pressed.push(key); } } function getPressed(gp: any, config: GamepadConfig) { const buttons = config.buttons || xBox360Buttons; const pressed: number[] = []; for (let i = 0; i < buttons.length; i++) { if (gp.buttons[i] && gp.buttons[i].pressed) { pushPressed(buttons[i], config, pressed); } } mapStickToKeys( gp.axes[0], gp.axes[1], "ls", config, pressed); mapStickToKeys( gp.axes[2], gp.axes[3], "rs", config, pressed); return pressed; } function mapStickToKeys( x: number, y: number, stick: string, config: GamepadConfig, pressed: number[]) { const threshold = config.stickThreshold; if (!threshold) { return; } if (x > threshold) { pushPressed(stick + "right", config, pressed); } if (x < -threshold) { pushPressed(stick + "left", config, pressed); } if (y > threshold) { pushPressed(stick + "down", config, pressed); } if (y < -threshold) { pushPressed(stick + "up", config, pressed); } } function getActions(newState: number[], lastState: number[]) { const release: number[] = []; const press: number[] = []; lastState = lastState || []; // tslint:disable-next-line for (let i = 0; i < lastState.length; i++) { if (newState.indexOf(lastState[i]) === -1) { release.push(lastState[i]); } } // tslint:disable-next-line for (let i = 0; i < newState.length; i++) { if (lastState.indexOf(newState[i]) === -1) { press.push(newState[i]); } } return { press, release, }; } function getGamepadConfiguration(gpi: number) { let mapIndex = detected.indexOf(gpi); if (mapIndex === -1) { mapIndex = detected.length; detected.push(gpi); } mapIndex = Math.min(mapIndex, options.gamepads.length - 1); return options.gamepads[mapIndex]; } function scan() { const gps = navigator.getGamepads(); for (let i = 0; i < gps.length; i++) { const gp = gps[i]; if (gp && gp.connected) { const config = getGamepadConfiguration(i); const pressed = getPressed(gp, config); const actions = getActions(pressed, lastStates[i]); // tslint:disable-next-line for (let j = 0; j < actions.press.length; j++) { consumer.onPress(actions.press[j]); } // tslint:disable-next-line for (let j = 0; j < actions.release.length; j++) { consumer.onRelease(actions.release[j]); } lastStates[i] = pressed; } } } if (options.scanEvery) { // when game is paused tick listener // does not fire, so we need a workaround // so we can resume! setInterval(scan, options.scanEvery); } if (options.scanOnTick) { const dos = ci.dos; dos.registerTickListener(scan); } }
package chaos import ( "fmt" "math/big" "testing" "github.com/ethereum/go-ethereum/common" "github.com/onsi/gomega" "github.com/smartcontractkit/seth" "github.com/stretchr/testify/require" ctfClient "github.com/smartcontractkit/chainlink-testing-framework/client" ctf_config "github.com/smartcontractkit/chainlink-testing-framework/config" "github.com/smartcontractkit/chainlink-testing-framework/k8s/chaos" "github.com/smartcontractkit/chainlink-testing-framework/k8s/environment" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/chainlink" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/ethereum" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/mockserver" mockservercfg "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/mockserver-cfg" "github.com/smartcontractkit/chainlink-testing-framework/logging" "github.com/smartcontractkit/chainlink-testing-framework/networks" "github.com/smartcontractkit/chainlink-testing-framework/utils/ptr" "github.com/smartcontractkit/chainlink-testing-framework/utils/testcontext" actions_seth "github.com/smartcontractkit/chainlink/integration-tests/actions/seth" "github.com/smartcontractkit/chainlink/integration-tests/contracts" "github.com/smartcontractkit/chainlink/integration-tests/utils" "github.com/smartcontractkit/chainlink/integration-tests/actions" "github.com/smartcontractkit/chainlink/integration-tests/client" tc "github.com/smartcontractkit/chainlink/integration-tests/testconfig" ) var ( defaultOCRSettings = map[string]interface{}{ "replicas": 6, "db": map[string]interface{}{ "stateful": true, "capacity": "1Gi", "resources": map[string]interface{}{ "requests": map[string]interface{}{ "cpu": "250m", "memory": "256Mi", }, "limits": map[string]interface{}{ "cpu": "250m", "memory": "256Mi", }, }, }, } chaosStartRound int64 = 1 chaosEndRound int64 = 4 ) func getDefaultOcrSettings(config *tc.TestConfig) map[string]interface{} { defaultOCRSettings["toml"] = networks.AddNetworksConfig(baseTOML, config.Pyroscope, networks.MustGetSelectedNetworkConfig(config.Network)[0]) return defaultAutomationSettings } func TestOCRChaos(t *testing.T) { t.Parallel() l := logging.GetTestLogger(t) config, err := tc.GetConfig("Chaos", tc.OCR) require.NoError(t, err, "Error getting config") var overrideFn = func(_ interface{}, target interface{}) { ctf_config.MustConfigOverrideChainlinkVersion(config.GetChainlinkImageConfig(), target) ctf_config.MightConfigOverridePyroscopeKey(config.GetPyroscopeConfig(), target) } chainlinkCfg := chainlink.NewWithOverride(0, getDefaultOcrSettings(&config), config.ChainlinkImage, overrideFn) testCases := map[string]struct { networkChart environment.ConnectedChart clChart environment.ConnectedChart chaosFunc chaos.ManifestFunc chaosProps *chaos.Props }{ // network-* and pods-* are split intentionally into 2 parallel groups // we can't use chaos.NewNetworkPartition and chaos.NewFailPods in parallel // because of jsii runtime bug, see Makefile and please use those targets to run tests // // We are using two chaos experiments to simulate pods/network faults, // check chaos.NewFailPods method (https://chaos-mesh.org/docs/simulate-pod-chaos-on-kubernetes/) // and chaos.NewNetworkPartition method (https://chaos-mesh.org/docs/simulate-network-chaos-on-kubernetes/) // in order to regenerate Go bindings if k8s version will be updated // you can pull new CRD spec from your current cluster and check README here // https://github.com/smartcontractkit/chainlink-testing-framework/k8s/blob/master/README.md NetworkChaosFailMajorityNetwork: { ethereum.New(nil), chainlinkCfg, chaos.NewNetworkPartition, &chaos.Props{ FromLabels: &map[string]*string{ChaosGroupMajority: ptr.Ptr("1")}, ToLabels: &map[string]*string{ChaosGroupMinority: ptr.Ptr("1")}, DurationStr: "1m", }, }, NetworkChaosFailBlockchainNode: { ethereum.New(nil), chainlinkCfg, chaos.NewNetworkPartition, &chaos.Props{ FromLabels: &map[string]*string{"app": ptr.Ptr("geth")}, ToLabels: &map[string]*string{ChaosGroupMajorityPlus: ptr.Ptr("1")}, DurationStr: "1m", }, }, PodChaosFailMinorityNodes: { ethereum.New(nil), chainlinkCfg, chaos.NewFailPods, &chaos.Props{ LabelsSelector: &map[string]*string{ChaosGroupMinority: ptr.Ptr("1")}, DurationStr: "1m", }, }, PodChaosFailMajorityNodes: { ethereum.New(nil), chainlinkCfg, chaos.NewFailPods, &chaos.Props{ LabelsSelector: &map[string]*string{ChaosGroupMajority: ptr.Ptr("1")}, DurationStr: "1m", }, }, PodChaosFailMajorityDB: { ethereum.New(nil), chainlinkCfg, chaos.NewFailPods, &chaos.Props{ LabelsSelector: &map[string]*string{ChaosGroupMajority: ptr.Ptr("1")}, DurationStr: "1m", ContainerNames: &[]*string{ptr.Ptr("chainlink-db")}, }, }, } for n, tst := range testCases { name := n testCase := tst t.Run(fmt.Sprintf("OCR_%s", name), func(t *testing.T) { t.Parallel() testEnvironment := environment.New(&environment.Config{ NamespacePrefix: fmt.Sprintf("chaos-ocr-%s", name), Test: t, }). AddHelm(mockservercfg.New(nil)). AddHelm(mockserver.New(nil)). AddHelm(testCase.networkChart). AddHelm(testCase.clChart) err := testEnvironment.Run() require.NoError(t, err) if testEnvironment.WillUseRemoteRunner() { return } err = testEnvironment.Client.LabelChaosGroup(testEnvironment.Cfg.Namespace, "instance=node-", 1, 2, ChaosGroupMinority) require.NoError(t, err) err = testEnvironment.Client.LabelChaosGroup(testEnvironment.Cfg.Namespace, "instance=node-", 3, 5, ChaosGroupMajority) require.NoError(t, err) err = testEnvironment.Client.LabelChaosGroup(testEnvironment.Cfg.Namespace, "instance=node-", 2, 5, ChaosGroupMajorityPlus) require.NoError(t, err) cfg := config.MustCopy().(tc.TestConfig) readSethCfg := cfg.GetSethConfig() require.NotNil(t, readSethCfg, "Seth config shouldn't be nil") network := networks.MustGetSelectedNetworkConfig(cfg.GetNetworkConfig())[0] network = utils.MustReplaceSimulatedNetworkUrlWithK8(l, network, *testEnvironment) sethCfg, err := utils.MergeSethAndEvmNetworkConfigs(network, *readSethCfg) require.NoError(t, err, "Error merging seth and evm network configs") err = utils.ValidateSethNetworkConfig(sethCfg.Network) require.NoError(t, err, "Error validating seth network config") seth, err := seth.NewClientWithConfig(&sethCfg) require.NoError(t, err, "Error creating seth client") chainlinkNodes, err := client.ConnectChainlinkNodes(testEnvironment) require.NoError(t, err, "Connecting to chainlink nodes shouldn't fail") bootstrapNode, workerNodes := chainlinkNodes[0], chainlinkNodes[1:] t.Cleanup(func() { err := actions_seth.TeardownRemoteSuite(t, seth, testEnvironment.Cfg.Namespace, chainlinkNodes, nil, &cfg) require.NoError(t, err, "Error tearing down environment") }) ms, err := ctfClient.ConnectMockServer(testEnvironment) require.NoError(t, err, "Creating mockserver clients shouldn't fail") linkContract, err := contracts.DeployLinkTokenContract(l, seth) require.NoError(t, err, "Error deploying link token contract") err = actions_seth.FundChainlinkNodesFromRootAddress(l, seth, contracts.ChainlinkK8sClientToChainlinkNodeWithKeysAndAddress(chainlinkNodes), big.NewFloat(10)) require.NoError(t, err) ocrInstances, err := actions_seth.DeployOCRv1Contracts(l, seth, 1, common.HexToAddress(linkContract.Address()), contracts.ChainlinkK8sClientToChainlinkNodeWithKeysAndAddress(workerNodes)) require.NoError(t, err) err = actions.CreateOCRJobs(ocrInstances, bootstrapNode, workerNodes, 5, ms, fmt.Sprint(seth.ChainID)) require.NoError(t, err) chaosApplied := false gom := gomega.NewGomegaWithT(t) gom.Eventually(func(g gomega.Gomega) { for _, ocr := range ocrInstances { err := ocr.RequestNewRound() require.NoError(t, err, "Error requesting new round") } round, err := ocrInstances[0].GetLatestRound(testcontext.Get(t)) g.Expect(err).ShouldNot(gomega.HaveOccurred()) l.Info().Int64("RoundID", round.RoundId.Int64()).Msg("Latest OCR Round") if round.RoundId.Int64() == chaosStartRound && !chaosApplied { chaosApplied = true _, err = testEnvironment.Chaos.Run(testCase.chaosFunc(testEnvironment.Cfg.Namespace, testCase.chaosProps)) require.NoError(t, err) } g.Expect(round.RoundId.Int64()).Should(gomega.BeNumerically(">=", chaosEndRound)) }, "6m", "3s").Should(gomega.Succeed()) }) } }
package com.doyatama.university.service; import com.doyatama.university.exception.BadRequestException; import com.doyatama.university.exception.ResourceNotFoundException; import com.doyatama.university.model.*; import com.doyatama.university.model.Exam; import com.doyatama.university.payload.DefaultResponse; import com.doyatama.university.payload.ExamRequest; import com.doyatama.university.payload.PagedResponse; import com.doyatama.university.repository.*; import com.doyatama.university.util.AppConstants; import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; @Service public class ExamService { private ExamRepository examRepository = new ExamRepository(); private QuestionRepository questionRepository = new QuestionRepository(); private RPSRepository rpsRepository = new RPSRepository(); private static final Logger logger = LoggerFactory.getLogger(ExamService.class); public PagedResponse<Exam> getAllExam(int page, int size, String studyProgramId) throws IOException { validatePageNumberAndSize(page, size); // Retrieve Polls List<Exam> examResponse = new ArrayList<>(); if(studyProgramId.equalsIgnoreCase("*")) examResponse = examRepository.findAll(size); if(!studyProgramId.equalsIgnoreCase("*")) examResponse = examRepository.findAllByProdi(studyProgramId, size); return new PagedResponse<>(examResponse, examResponse.size(), "Successfully get data", 200); } public Exam createExam(ExamRequest examRequest) throws IOException { Exam exam = new Exam(); List<Question> questionList = questionRepository.findAllById(examRequest.getQuestions()); RPS rpsResponse = rpsRepository.findById(examRequest.getRps_id()); ZoneId zoneId = ZoneId.of("Asia/Jakarta"); ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId); Instant instant = zonedDateTime.toInstant(); if (questionList.size() != 0 && rpsResponse.getName() != null) { exam.setName(examRequest.getName()); exam.setDescription(examRequest.getDescription()); exam.setMin_grade(examRequest.getMin_grade()); exam.setDuration(examRequest.getDuration()); exam.setDate_start(examRequest.getDate_start()); exam.setDate_end(examRequest.getDate_end()); exam.setQuestions(questionList); exam.setRps(rpsResponse); exam.setCreated_at(instant); return examRepository.save(exam); } else { return null; } } public DefaultResponse<Exam> getExamById(String examId) throws IOException { // Retrieve Exam Exam examResponse = examRepository.findById(examId); return new DefaultResponse<>(examResponse.isValid() ? examResponse : null, examResponse.isValid() ? 1 : 0, "Successfully get data"); } public Exam updateExam(String examId, ExamRequest examRequest) throws IOException { Exam exam = new Exam(); List<Question> questionList = questionRepository.findAllById(examRequest.getQuestions()); RPS rpsResponse = rpsRepository.findById(examRequest.getRps_id()); if (questionList.size() != 0 && rpsResponse.getName() != null) { exam.setName(examRequest.getName()); exam.setDescription(examRequest.getDescription()); exam.setMin_grade(examRequest.getMin_grade()); exam.setDuration(examRequest.getDuration()); exam.setDate_start(examRequest.getDate_start()); exam.setDate_end(examRequest.getDate_end()); exam.setQuestions(questionList); exam.setRps(rpsResponse); return examRepository.update(examId, exam); } else { return null; } } public void deleteExamById(String examId) throws IOException { Exam examResponse = examRepository.findById(examId); if(examResponse.isValid()){ examRepository.deleteById(examId); }else{ throw new ResourceNotFoundException("Exam", "id", examId); } } private void validatePageNumberAndSize(int page, int size) { if(page < 0) { throw new BadRequestException("Page number cannot be less than zero."); } if(size > AppConstants.MAX_PAGE_SIZE) { throw new BadRequestException("Page size must not be greater than " + AppConstants.MAX_PAGE_SIZE); } } }
package com.example.lms.course.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.time.LocalDate; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.CollectionUtils; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; import com.example.lms.admin.service.CategoryService; import com.example.lms.course.dto.CourseDto; import com.example.lms.course.model.CourseInput; import com.example.lms.course.model.CourseParam; import com.example.lms.course.service.CourseService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor @Controller public class AdminCourseController extends BaseController { private final CourseService courseService; private final CategoryService categoryService; @GetMapping("/admin/course/list.do") public String list(Model model, CourseParam courseParam) { courseParam.init(); List<CourseDto> courseList = courseService.list(courseParam); long totalCount = 0; if (!CollectionUtils.isEmpty(courseList)) { totalCount = courseList.get(0).getTotalCount(); } String queryString = courseParam.getQueryString(); String pageHtml = getPaperHtml(totalCount, courseParam.getPageSize(), courseParam.getPageIndex(), queryString); model.addAttribute("list", courseList); model.addAttribute("totalCount", totalCount); model.addAttribute("pager", pageHtml); return "admin/course/list"; } @GetMapping(value = {"/admin/course/add.do", "/admin/course/edit.do"}) public String add(Model model, HttpServletRequest request, CourseInput courseInput) { model.addAttribute("category", categoryService.list()); boolean editMode = request.getRequestURI().contains("/edit.do"); CourseDto detail = new CourseDto(); if (editMode) { long id = courseInput.getId(); CourseDto existCourse = courseService.getById(id); if (existCourse == null) { model.addAttribute("message", "강좌 정보가 존재하지 않습니다."); return "common/error"; } detail = existCourse; } model.addAttribute("editMode", editMode); model.addAttribute("detail", detail); return "admin/course/add"; } private String[] getNewSaveFile(String baseLocalPath, String baseUrlPath, String originalFilename) { LocalDate now = LocalDate.now(); String[] dirs = { String.format("%s/%d/", baseLocalPath, now.getYear()), String.format("%s/%d/%02d/", baseLocalPath, now.getYear(), now.getMonthValue()), String.format("%s/%d/%02d/%02d/", baseLocalPath, now.getYear(), now.getMonthValue(), now.getDayOfMonth())}; String urlDir = String.format("%s/%d/%02d/%02d/", baseUrlPath, now.getYear(), now.getMonthValue(), now.getDayOfMonth()); for(String dir : dirs) { File file = new File(dir); if (!file.isDirectory()) { file.mkdir(); } } String fileExtension = ""; if (originalFilename != null) { int dotPos = originalFilename.lastIndexOf("."); if (dotPos > -1) { fileExtension = originalFilename.substring(dotPos + 1); } } String uuid = UUID.randomUUID().toString().replace("-", ""); String newFilename = String.format("%s%s", dirs[2], uuid); String newUrlFilename = String.format("%s%s", urlDir, uuid); if (fileExtension.length() > 0) { newFilename += "." + fileExtension; newUrlFilename += "." + fileExtension; } String[] returnFilename = {newFilename, newUrlFilename}; return returnFilename; } @PostMapping(value = {"/admin/course/add.do", "/admin/course/edit.do"}) public String addSubmit(Model model, HttpServletRequest request, MultipartFile file, CourseInput courseInput) { String saveFilename = ""; String urlFilename = ""; if (file != null) { String originalFilename = file.getOriginalFilename(); String baseLocalPath = "C:/dev/LMS_Project/lms/files"; String baseUrlPath = "/files"; String urlPath = "/files/2022/07/16/8f85120b80c34460934a6d7b58407615.png"; String[] arrFilename = getNewSaveFile(baseLocalPath, baseUrlPath, originalFilename); saveFilename = arrFilename[0]; urlFilename = arrFilename[1]; try { File newFile = new File(saveFilename); FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(newFile)); } catch (IOException e) { e.printStackTrace(); } } courseInput.setFilename(saveFilename); courseInput.setUrlFilename(urlFilename); boolean editMode = request.getRequestURI().contains("/edit.do"); CourseDto detail = new CourseDto(); if (editMode) { long id = courseInput.getId(); CourseDto existCourse = courseService.getById(id); if (existCourse == null) { model.addAttribute("message", "강좌 정보가 존재하지 않습니다."); return "common/error"; } boolean result = courseService.set(courseInput); } else { boolean result = courseService.add(courseInput); } return "redirect:/admin/course/list.do"; } @PostMapping("/admin/course/delete.do") public String del(Model model, HttpServletRequest request, CourseInput courseInput) { boolean result = courseService.del(courseInput.getIdList()); return "redirect:/admin/course/list.do"; } }
// Created by Frederic Jacobs on 16/11/14. // Copyright (c) 2014 Open Whisper Systems. All rights reserved. #import <Mantle/MTLModel+NSCoding.h> @class YapDatabaseConnection; @class YapDatabaseReadTransaction; @class YapDatabaseReadWriteTransaction; @interface TSYapDatabaseObject : MTLModel /** * Initializes a new database object with a unique identifier * * @param uniqueId Key used for the key-value store * * @return Initialized object */ - (instancetype)initWithUniqueId:(NSString *)uniqueId NS_DESIGNATED_INITIALIZER; /** * Returns the collection to which the object belongs. * * @return Key (string) identifying the collection */ + (NSString *)collection; /** * Get the number of keys in the models collection. Be aware that if there * are multiple object types in this collection that the count will include * the count of other objects in the same collection. * * @return The number of keys in the classes collection. */ + (NSUInteger)numberOfKeysInCollection; /** * Removes all objects in the classes collection. */ + (void)removeAllObjectsInCollection; /** * A memory intesive method to get all objects in the collection. You should prefer using enumeration over this method * whenever feasible. See `enumerateObjectsInCollectionUsingBlock` * * @return All objects in the classes collection. */ + (NSArray *)allObjectsInCollection; /** * Enumerates all objects in collection. */ + (void)enumerateCollectionObjectsUsingBlock:(void (^)(id obj, BOOL *stop))block; + (void)enumerateCollectionObjectsWithTransaction:(YapDatabaseReadTransaction *)transaction usingBlock:(void (^)(id object, BOOL *stop))block; /** * @return A shared database connection. */ - (YapDatabaseConnection *)dbConnection; + (YapDatabaseConnection *)dbConnection; /** * Fetches the object with the provided identifier * * @param uniqueID Unique identifier of the entry in a collection * @param transaction Transaction used for fetching the object * * @return Instance of the object or nil if non-existent */ + (instancetype)fetchObjectWithUniqueID:(NSString *)uniqueID transaction:(YapDatabaseReadTransaction *)transaction; + (instancetype)fetchObjectWithUniqueID:(NSString *)uniqueID; /** * Saves the object with a new YapDatabaseConnection */ - (void)save; /** * Saves the object with the provided transaction * * @param transaction Database transaction */ - (void)saveWithTransaction:(YapDatabaseReadWriteTransaction *)transaction; /** * The unique identifier of the stored object */ @property (nonatomic) NSString *uniqueId; - (void)removeWithTransaction:(YapDatabaseReadWriteTransaction *)transaction; - (void)remove; @end
import React from 'react'; import PropTypes from 'prop-types'; import { Form } from 'react-bootstrap'; function Input({ type, name, testID, onChange, labelText, value }) { return ( <div> <Form.Label className="label" htmlFor={ name }>{ labelText }</Form.Label> <Form.Control type={ type } name={ name } data-testid={ testID } onChange={ onChange } id={ name } value={ value } /> </div> ); } const { string, func } = PropTypes; Input.propTypes = { type: string, name: string, testID: string, onChange: func, labelText: func, value: string, }.isRequired; export default Input;
package com.hotel.reservationSystem.controllers; import com.hotel.reservationSystem.models.Category; import com.hotel.reservationSystem.services.CategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/categories") public class CategoryController { CategoryService categoryService; @Autowired public CategoryController(CategoryService categoryService) { this.categoryService = categoryService; } @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public List<Category> getCategories(){ return categoryService.findAll(); } @GetMapping(value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE) public Category getCategory(@PathVariable int id){ return categoryService.find(id); } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity createCategory(@RequestBody Category category){ categoryService.save(category); return ResponseEntity.status(201).body(category); } @GetMapping(value = "{name}", produces = MediaType.APPLICATION_JSON_VALUE) public Category getCategoryByName(@PathVariable String name){ return categoryService.findByName(name); } }
import 'package:dartz/dartz.dart'; import '../../../../core/errors/failure.dart'; import '../../../../core/params/usecase.dart'; import '../../data/models/flight_offer/flight_offer.dart'; import '../repositories/amadeus_repository.dart'; /// Flight search: users can search for flights by specifying criteria such as /// destination, departure and arrival dates, number of passengers, etc. class GetFlightOffersSearch implements UseCase<FlightOffer, AvailableFlightParams> { final AmadeusRepository repository; GetFlightOffersSearch(this.repository); @override Future<Either<Failure, FlightOffer>> call( AvailableFlightParams params) async { return await repository.getFlightOffersSearch( params.departure, params.arrival, params.departureDate, params.numberOfPassengers, ); } }
using KsqlDb.Domain; using ksqlDB.RestApi.Client.KSql.Linq; using ksqlDB.RestApi.Client.KSql.Query.Options; using ksqlDB.RestApi.Client.KSql.RestApi; using Xunit.Abstractions; using FluentAssertions; using KsqlDb.Configuration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using KsqlDb.DbContext; using KsqlDb.Domain.Models; using IHttpClientFactory = ksqlDB.RestApi.Client.KSql.RestApi.Http.IHttpClientFactory; namespace KsqlDbTests; //https://github.com/tomasfabian/ksqlDB.RestApi.Client-DotNet public class TestOfKafkaksqlDbUsage { private readonly ITestOutputHelper output; private readonly IHost host; private readonly IServiceProvider serviceProvider; public TestOfKafkaksqlDbUsage(ITestOutputHelper output) { this.output = output; var configurationBuilder = new ConfigurationBuilder();// configurationBuilder.AddJsonFile("appsettings.IntegrationTests.json"); IConfigurationRoot configuration = configurationBuilder.Build(); IHostBuilder builder = new HostBuilder(); builder.ConfigureServices((services) => { services.AddKafka(configuration); services.AddKsqlDb(configuration); }) .ConfigureLogging((_, logging) => { logging.AddConsole(); logging.AddDebug(); }); host = builder.Build(); serviceProvider = host.Services; } [Fact] public void VerifySetup() { var ksqlDbOptions = serviceProvider.GetRequiredService<IOptions<KsqlDbConfiguration>>().Value; ksqlDbOptions.EndPoint.Should().Be("http://localhost:8088"); ksqlDbOptions.KafkaTopic.Should().Be("tweets"); } [Fact] public void VerifyConfiguration() { serviceProvider.GetService<IOptions<KsqlDbConfiguration>>().Should().NotBeNull(); serviceProvider.GetService<IApplicationKSqlDbContext>().Should().NotBeNull(); serviceProvider.GetService<IKSqlDbContextFactory>().Should().NotBeNull(); serviceProvider.GetService<KsqlDbTweetProcessor>().Should().NotBeNull(); serviceProvider.GetService<IHttpClientFactory>().Should().NotBeNull(); serviceProvider.GetService<ILoggerFactory>().Should().NotBeNull(); serviceProvider.GetService<IKSqlDbRestApiClient>().Should().NotBeNull(); } [Fact(Skip="Must create User stream before usage")] public async Task TestOfUserStreamSubscription() { var factory = serviceProvider.GetRequiredService<IKSqlDbContextFactory>(); await using var context = factory.Create((options => options.ShouldPluralizeFromItemName = true)); using var subscription = context.CreateQueryStream<User>() .WithOffsetResetPolicy(AutoOffsetReset.Latest) .Where(p => p.Gender != "Hello world") .Select(l => new { l.UserId, l.Id, l.Gender, l.RegionId }) .Take(2) .Subscribe(message => { output.WriteLine($"{nameof(User)}: {message.Id} - {message.UserId} - {message.Gender} - {message.RegionId}"); }, error => { output.WriteLine($"Exception: {error.Message}"); }, () => output.WriteLine("Completed")); await Task.Delay(10000); output.WriteLine("done"); } }
const { readFile, writeFile } = require('fs'); // THIS IS ASYNCHRONOUS APPROACH which is good because // files are read in asynchronous manner, which means that the script execution // is NOT BLOCKED for the duration needed for reading the files and NodeJS can do some other tasks. // So the order of console.logs is this: // "start" => "continue main script execution" => "done with file task" // which IS DIFFERENT from synchronous approach and very useful. console.log('start'); // some callback hell here... readFile('./content/first.txt', 'utf8', (err, result) => { if (err) { return; } const first = result; readFile('./content/second.txt', 'utf8', (err1, result1) => { if (err1) { return; } const second = result1; writeFile( './content/result-async.txt', `Here is the result: ${first}, ${second}`, (err2) => { if (err2) { return; } console.log('done with file task'); }, ); }); }); console.log('continue main script execution');
# install.packages("devtools") # devtools::install_github("phamdinhkhanh/VNDS", force = TRUE) # library(VNDS) library(tidyverse) library(httr) library(rvest) #' @param v vector can convert #' @export ############################### chung cho cac ham ############################ removeBlankCol <- function(df){ df[,which(unlist(lapply(df, function(x) sum(nchar(as.vector(x)))>0)))] } ############################### getBusinessReport ######################################## #Loai bo dau ',' giua cac chu so va convert ve dang numeric convertNumber <- function(v) { str_replace_all(v,",","") %>% as.numeric() } ############################# getPrice VNDIRECT ######################################## myexport <- function(...) { arg.list <- list(...) names <- all.names(match.call())[-1] for (i in seq_along(names)) assign(names[i],arg.list[[i]],.GlobalEnv) } dateChar <- function(dateTime){ dateTime %<>% as.Date() %>% format(.,format = "%d/%m/%Y") return(dateTime) } ############################## getPrice CP 68 ######################################## #ham convertDate convertDate <- function(dt){ paste0(str_sub(dt,7,10),"-",str_sub(dt,4,5),"-",str_sub(dt,1,2)) } #ham thay the dau comma subComma <- function(v) { str_replace_all(v,",","") } #chuyen percent dang text sang numeric convertPercent <- function(v){ str_replace_all(v,"%","") %>% as.numeric()*0.01 } tq_get_cafef <- function (symbol, from, to, ...) { url <- paste0("http://s.cafef.vn/Lich-su-giao-dich-", symbol, "-1.chn") cname1 <- c("date", "adjusted", "close", "change.percent", "match.volume", "match.value", "reconcile.volume", "reconcile.value", "open", "high", "low", "volume.round1", "volume.round2", "volume.round3") cname2 <- c("date", "adjusted", "close", "average", "change.percent", "match.volume", "match.value", "reconcile.volume", "reconcile.value", "reference", "open", "high", "low") symbolData <- matrix(nrow = 0, ncol = 14, byrow = TRUE, dimnames = list(c(), cname1)) body <- list(`ctl00$ContentPlaceHolder1$scriptmanager` = "ctl00$ContentPlaceHolder1$ctl03$panelAjax|ctl00$ContentPlaceHolder1$ctl03$pager2", `ctl00$ContentPlaceHolder1$ctl03$txtKeyword` = symbol, `ctl00$ContentPlaceHolder1$ctl03$dpkTradeDate1$txtDatePicker` = dateChar(from), `ctl00$ContentPlaceHolder1$ctl03$dpkTradeDate2$txtDatePicker` = dateChar(to), `__EVENTTARGET` = "ctl00$ContentPlaceHolder1$ctl03$pager2", `__EVENTARGUMENT` = 1, `__ASYNCPOST` = "true") resp <- POST(url, user_agent("Mozilla"), body = body, endcode = "form") tmp <- resp %>% read_html() %>% html_nodes(xpath = "//*[@id=\"GirdTable2\"]") %>% html_table(fill = TRUE) %>% as.data.frame() if (nrow(tmp) != 0) { table_id <- "GirdTable2" } else { table_id <- "GirdTable" } for (i in 1:10000) { body <- list(`ctl00$ContentPlaceHolder1$scriptmanager` = "ctl00$ContentPlaceHolder1$ctl03$panelAjax|ctl00$ContentPlaceHolder1$ctl03$pager2", `ctl00$ContentPlaceHolder1$ctl03$txtKeyword` = symbol, `ctl00$ContentPlaceHolder1$ctl03$dpkTradeDate1$txtDatePicker` = dateChar(from), `ctl00$ContentPlaceHolder1$ctl03$dpkTradeDate2$txtDatePicker` = dateChar(to), `__EVENTTARGET` = "ctl00$ContentPlaceHolder1$ctl03$pager2", `__EVENTARGUMENT` = i, `__ASYNCPOST` = "true") resp <- POST(url, user_agent("Mozilla"), body = body, endcode = "form") tmp <- resp %>% read_html() %>% html_nodes(xpath = glue::glue("//*[@id=\"{table_id}\"]")) %>% html_table(fill = TRUE) %>% as.data.frame() if (nrow(tmp) == 2) { break } if (table_id == "GirdTable2") { if (ncol(tmp) == 14) tmp <- data.frame(X1 = tmp[-c(1:2), c(1)], reference = NA, tmp[-c(1:2), -c(1, 4)]) if (ncol(tmp) == 15) tmp <- tmp[-c(1:2), c(-5)] } else { if (ncol(tmp) == 13) { tmp <- data.frame(tmp[-c(1:2), c(1:3)], average = NA, tmp[-c(1:2), c(4:13)]) } else { tmp <- tmp[-c(1:2), ] } } if (!exists("convertDate", mode = "function")) { source("R/utils.R") } tmp[, 1] <- as.Date(convertDate(tmp[, 1]), format = "%Y-%m-%d") if (min(tmp[, 1]) > to) { next } if (max(tmp[, 1]) < from) { break } if (!exists("subComma", mode = "function")) { source("R/utils.R") } symbolData <- rbind(symbolData, tmp) } if (table_id == "GirdTable2") { colnames(symbolData) <- cname1 symbolData <- data.frame(symbolData, row.names = symbolData[, 1]) symbolData <- symbolData[, c(1, 4, 9:11, 3, 2, 5, 7, 6, 8, 12:14)] symbolData[, 3:14] <- lapply(symbolData[, 3:14], subComma) symbolData[, 3:14] <- lapply(symbolData[, 3:14], as.numeric) } else { symbolData <- symbolData[, -6] colnames(symbolData) <- cname2 symbolData <- data.frame(symbolData, row.names = symbolData[, 1]) symbolData[, c(6:9)] <- lapply(symbolData[, c(6:9)], subComma) symbolData[, c(2:4, 6:13)] <- lapply(symbolData[, c(2:4, 6:13)], as.numeric) symbolData <- symbolData[, c(1, 5, 11:13, 3:4, 2, 10, 6, 8, 7, 9)] } symbolData <- subset(symbolData, date >= from & date <= to) symbolData <- tibble::as_tibble(symbolData) cat(paste0("#", symbol, " from ", from, " to ", to, " already cloned \n")) invisible(symbolData) } get_data <- function (Symbol) { tq_get_cafef( symbol = Symbol, src = "CAFEF", from = '2015-01-01', to = '2023-05-19' ) |> write.csv(paste0(Symbol, '.csv'), row.names = F) } # Bluechip: VNM, VIC, VCB, FPT, MWG get_data("VIC") get_data("VCB") get_data("FPT") get_data("MWG") # Rr: HVN, UDC, MCG, NVL get_data("HVN") get_data("UDC") get_data("MCG") get_data("NVL") # Midcap: LDG, FCN, PVD, LCG, TPB get_data("LDG") get_data("FCN") get_data("PVD") get_data("LCG") get_data("TPB")
import { BaseState } from "./BaseState"; import { GumballMachine } from "./GumballMachine"; export class NoQuarterState extends BaseState { constructor(gumballMachine: GumballMachine) { super(gumballMachine); } public override insertQuarter(): void { console.log("You inserted a quarter"); this.gumballMachine.setState(this.gumballMachine.hasQuarterState); } }
(* Semantic checking for the LILY compiler *) open Libparser open Ast let preprocess (program_block: program) :program = let get_default_return (t:typ): expr = match t with Int -> LitInt(0) | Bool -> LitBool(false) | Char -> LitChar('a') | Float -> LitFloat(0.0) | List(_) -> Null | _ -> LitInt(0) in let rec check_block (block: block): block = let bind_to_typ (bind: bind): typ = match bind with (t, _) -> t in let bind_to_name (bind: bind): string = match bind with (_, n) -> n in let bind_list_to_typ_list (bl: bind list): typ list = List.map bind_to_typ bl in let bind_list_to_names (bl: bind list): string list = List.map bind_to_name bl in let form_bind (t: typ) (n: string) = (t, n) in let form_binds (tl: typ list) (nl: string list) = List.map2 form_bind tl nl in let has_any (args: typ list) = List.mem (List(Any)) args in let replace_any_with_typ (arg_list: typ list) (new_t: typ): typ list = List.map (fun x -> (if x = List(Any) then (List(new_t)) else x)) arg_list in let check_func (t, name, binds, b): stmt list = let ret_stmt = Return(get_default_return t ) in let ret_block = match b with Block(sl) -> Block(sl @ [ret_stmt]) in let args = bind_list_to_typ_list binds in let bind_names = bind_list_to_names binds in let make_fdecl_for_t (lt: typ): stmt = let new_types = replace_any_with_typ args lt in let new_binds = form_binds new_types bind_names in let ret_typ = (if t = List(Any) then List(lt) else t) in Fdecl(ret_typ, name, new_binds, ret_block) in if has_any args then List.map make_fdecl_for_t [Int; Bool; Char; Float] else [Fdecl(t, name ,binds, ret_block)] in let check_stmt (s: stmt): stmt list = match s with If (e, b1, b2) -> [If(e, (check_block b1), check_block b2)] | While(e, b) -> [While(e, (check_block b))] | For(e, a, b) -> [For(e, a, (check_block b))] | ForIn(id, e, b) -> [ForIn(id, e, b)] | ExprStmt(e) -> [ExprStmt(e)] | Return(e) -> [Return(e)] | Decl(typ, id) -> [Decl(typ, id)] | DeclAssign(et, id, e) -> [DeclAssign(et, id, e)] | Fdecl(t, name, binds, b) -> (check_func (t, name, binds, b)) in let reform_block (sll: stmt list list) : stmt list = let rec get_sl (sll: stmt list list) = match sll with [] -> [] | h ::t -> h @ (get_sl t) in get_sl sll in match block with Block(sl) -> let sll = List.map check_stmt (sl) in Block(reform_block sll) in check_block program_block
<?php namespace App\Notifications; use Filament\Facades\Filament; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; class LoginRequest extends Notification { use Queueable; /** * Create a new notification instance. */ public function __construct(protected string $temporaryPassword) { // } /** * Get the notification's delivery channels. * * @return array<int, string> */ public function via(object $notifiable): array { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->subject('Hello'.' '.$notifiable->name) ->line('Welcome to our application! Here is your temporary password for initial login:') ->line('Temporary Password: '.$this->temporaryPassword) ->action('Login Now', url(Filament::getLoginUrl())) ->line('Please use this temporary password to log in and change your password immediately. This temporary password will expire shortly.') ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @return array<string, mixed> */ public function toArray(object $notifiable): array { return [ // ]; } }
import unidecode import string import random import re import time import math import torch import matplotlib.pyplot as plt from torch.autograd import Variable CHUNK_LEN = 200 TRAIN_PATH = './data/dickens_train.txt' def load_dataset(path): all_characters = string.printable file = unidecode.unidecode(open(path, 'r').read()) return file def random_chunk(): ''' Splits big string of data into chunks. ''' file = load_dataset(TRAIN_PATH) start_index = random.randint(0, len(file) - CHUNK_LEN - 1) end_index = start_index + CHUNK_LEN + 1 return file[start_index:end_index] def char_tensor(strings): ''' Each chunk of the training data needs to be turned into a sequence of numbers (of the lookups), specifically a LongTensor (used for integer values). This is done by looping through the characters of the string and looking up the index of each character. ''' all_characters = string.printable tensor = torch.zeros(len(strings)).long() for c in range(len(strings)): # why are characters indeced like this? e.g. 10, 11, 12, 13, etc. tensor[c] = all_characters.index(strings[c]) return Variable(tensor) def random_training_set(): ''' Assembles a pair of input and target tensors for training from a random chunk. The inputs will be all characters up to the last, and the targets will be all characters from the first. So if our chunk is "test" the inputs will correspond to “tes” while the targets are “est”. ''' chunk = random_chunk() inp = char_tensor(chunk[:-1]) target = char_tensor(chunk[1:]) return inp, target def time_since(since): """ A helper to print the amount of time passed. """ s = time.time() - since m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s) def plot_experiment_results(experiment_results, max_experiments_per_plot=10): """ Plot experiment results from a dictionary. Args: experiment_results (dict): Dictionary where each key corresponds to a list of values. max_experiments_per_plot (int): Maximum number of experiments to include in each plot. Returns: None """ # Set up the plot plt.figure(figsize=(10, 6)) plt.xlabel('Epoch') plt.ylabel('Loss') plt.title('Experiment Results') # Plot each experiment for i, (experiment_name, results) in enumerate(experiment_results.items()): print(i, experiment_name, results) if i % max_experiments_per_plot == 0 and i > 0: # Start a new plot for every max_experiments_per_plot experiments plt.legend() plt.show() plt.figure(figsize=(10, 6)) plt.xlabel('Epoch') plt.ylabel('Loss') plt.title('Loss vs. Epoch for Different Experiments') plt.plot(range(1, len(results) + 1), results, label=experiment_name) # Add legend and show the final plot plt.legend(loc='upper left') plt.savefig('./results/output.jpg') plt.show()
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:project22/utils/app_colors/colors.dart'; import 'package:project22/utils/app_images/app_images.dart'; import 'package:project22/utils/my_size/mysize.dart'; class CustomCheckbox extends StatelessWidget { final bool value; final ValueChanged<bool?>? onChanged; const CustomCheckbox({ required this.value, required this.onChanged, }); @override Widget build(BuildContext context) { MySize().init(context); return GestureDetector( onTap: () { bool? newValue = !value; onChanged?.call(newValue); }, child: Container( padding: EdgeInsets.all(MySize.size5), width: MySize.size25, height: MySize.size25, decoration: BoxDecoration( border: Border.all( color: value ? AppColors.secondary : AppColors.grey.withOpacity(0.3), width: 1.0, ), borderRadius: BorderRadius.circular(5.0), color: AppColors.whiteColor), child: value ? Image.asset( AppImages.feedBacktickpng, ) : null, ), ); } }
import { DbSaveArticle } from '@/data/usecases' import { SaveArticlesRepositorySpy } from './mock-article' import { mockArticle } from '@/tests/domain/mocks' type Sut = { saveArticlesRepositorySpy: SaveArticlesRepositorySpy sut: DbSaveArticle } const makeSut = (): Sut => { const saveArticlesRepositorySpy = new SaveArticlesRepositorySpy() const sut = new DbSaveArticle(saveArticlesRepositorySpy) return { sut, saveArticlesRepositorySpy } } describe('DbSaveArticles UseCase', () => { it('Should call SaveArticlesRepository whit correct params', async () => { const { sut, saveArticlesRepositorySpy } = makeSut() const article = mockArticle() await sut.save(article) expect(saveArticlesRepositorySpy.params[0]).toEqual(article) }) it('Should throw if SaveArticlesRepository throws', () => { const { sut, saveArticlesRepositorySpy } = makeSut() jest.spyOn(saveArticlesRepositorySpy, 'save').mockRejectedValueOnce(new Error()) const promise = sut.save(mockArticle()) expect(promise).rejects.toThrow() }) })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="../../images/logo.svg" type="image/x-icon" /> <link rel="stylesheet" href="../../css/navbar.css"> <link rel="stylesheet" href="../../css/sidebar.css"> <link rel="stylesheet" href="../../css/colors.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/atom-one-dark.min.css" /> <link rel="stylesheet" href="style.css"> <title>PaperUI | Colors</title> <script src="../../script.js" defer></script> </head> <body> <nav class="navbar"> <div class="nav-title"> <span class = "brand"> <h2><a href="../../">PaperUI</a></h2> <span>v1.0</span> </span> <span class="material-icons ml-auto" id = "menu">menu</span> </div> <ul class="nav-links"> <li class = "navbar-items"><a href = "../../documentation.html">Docs</a> <span class = "material-icons" id = "close-btn">close</span> </li> <li class = "navbar-items"><a href = "#">Examples</a></li> <li class = "navbar-items"><a href = "#">Resources</a></li> </ul> </nav> <div class="grid-container"> <ul class="side-navbar"> <h3 class="list-heading">Getting Started</h3> <li class="nav-items"><a class="reset-a" href="#">Introduction</a></li> <li class="nav-items"><a class="reset-a active" href="#">Color</a></li> <li class="nav-items"><a class="reset-a" href="../typography/">Typography</a></li> <li class="nav-items"><a class="reset-a" href="../conclusion/">Conclusion</a></li> <h3 class="list-heading">Components</h3> <li class="nav-items"><a class="reset-a" href="../../components/alert/">Alert</a></li> <li class="nav-items"><a class="reset-a" href="../../components/avatar">Avatar</a></li> <li class="nav-items"><a class="reset-a" href="../../components/badge">Badge</a></li> <li class="nav-items"><a class="reset-a" href="../../components/button">Button</a></li> <li class="nav-items"><a class="reset-a" href="../../components/card">Card</a></li> <li class="nav-items"><a class="reset-a" href="../../components/image/">Image</a></li> <li class="nav-items"><a class="reset-a" href="../../components/input/">Input</a></li> <li class="nav-items"><a class="reset-a" href="../../components/lists/">Lists</a></li> <li class="nav-items"><a class="reset-a" href="../../components/navigation/">Navigation</a></li> <li class="nav-items"><a class="reset-a" href="../../components/text-utilities/">Text Utilities</a></li> <li class="nav-items"><a class="reset-a" href="../../components/toast/">Toast</a></li> <li class="nav-items"><a class="reset-a" href="../../components/ratings/">Ratings</a></li> <li class="nav-items"><a class="reset-a" href="../../components/modals/">Modals</a></li> <li class="nav-items"><a class="reset-a" href="../../components/grid/">Grids</a></li> <li class="nav-items"><a class="reset-a" href="../../components/slider/">Slider</a></li> </ul> <main class="main-content"> <h1>Colors</h1> <p class="main-content">PaperUI uses 2 type of colors: Document and Components.</p> <hr /> <h1>Document Colors</h1> <p class="main-content">These are the colors used by paperUI itself.</p> <div class = "colors-div"> <div class="colors"> <p>#FF6619</p> <p>Primary</p> </div> <div class="colors"> <p>#1e1e1e</p> <p>Secondary</p> </div> <div class="colors"> <p>#fefefe</p> <p>font</p> </div> <div class="colors"> <p>#009FFD</p> <p>active</p> </div> </div> <h1>Component Colors</h1> <p class="main-content">These are the colors used by the components.</p> <div class = "colors-div"> <div class="colors comp"> <p>#3454D1</p> <p>Primary</p> </div> <div class="colors comp"> <p>#71717a</p> <p>Secondary</p> </div> <div class="colors comp"> <p>#32cd32</p> <p>success</p> </div> <div class="colors comp"> <p>#dc2626</p> <p>danger</p> </div> <div class="colors comp"> <p>#f59e0b</p> <p>warning</p> </div> <div class="colors comp"> <p>#1e1e1e</p> <p>dark</p> </div> <div class="colors comp"> <p>#ffffff</p> <p>white</p> </div> </div> <hr /> <footer class="nav-footer"> <i class="material-icons">chevron_left</i><a class="footer-a far-left" href="../../documentation.html">Docs</a> <a class="footer-a" href="../typography/">Typography</a><i class="material-icons">chevron_right</i> </footer> </main> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/highlight.min.js"></script> <script>hljs.highlightAll();</script> </body> </html>
<?php namespace App\Form; use App\Entity\User; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Length; class UserFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('email', EmailType::class) ->add('firstname', TextType::class) ->add('lastname', TextType::class) ->add('society', TextType::class, ['required' => false]) ->add('address', TextType::class, ['required' => false]) ->add('postal_code', TextType::class, ['required' => false]) ->add('city', TextType::class, ['required' => false]) ->add('country', TextType::class, ['required' => false]) ->add('plainPassword', PasswordType::class, [ 'mapped' => false, 'required' => false, ]) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => User::class, ]); } }
import numpy as np from scipy.stats import linregress import analysis.data_gathering import pandas as pd from sklearn.preprocessing import MinMaxScaler cities = ["Atlanta city, Georgia", "Baltimore city, Maryland", "Boston city, Massachusetts", "Charlotte city, North Carolina", "Chicago city, Illinois", "Cleveland city, Ohio", "Denver city, Colorado", "Detroit city, Michigan", "Houston city, Texas", "Indianapolis city (balance), Indiana", "Las Vegas city, Nevada", "Los Angeles city, California", "Miami city, Florida", "Nashville-Davidson metropolitan government (balance), Tennessee", "New Orleans city, Louisiana", "New York city, New York", "Philadelphia city, Pennsylvania", "San Francisco city, California", "Seattle city, Washington", "Washington city, District of Columbia"] index = ['Atlanta, GA', 'Baltimore, MD', 'Boston, MA', 'Charlotte, NC', 'Chicago, IL', 'Cleveland, OH', 'Denver, CO', 'Detroit, MI', 'Houston, TX', 'Indianapolis, IN', 'Las Vegas, NV', 'Los Angeles, CA', 'Miami, FL', 'Nashville, TN', 'New Orleans, LA', 'New York, NY', 'Philadelphia, PA', 'San Francisco, CA', 'Seattle, WA', 'Washington, DC'] matching_dict = dict(zip(index, cities)) # Auxiliary function to normalize a dataset def normalize(data): scaler = MinMaxScaler() normalized_data = scaler.fit_transform(data) return normalized_data # Create dataset containing all SES def get_SES(): median_income = analysis.data_gathering.get_median_household_income() education = analysis.data_gathering.get_education_attainment() occupation = analysis.data_gathering.get_occupation() health_coverage = analysis.data_gathering.get_health_coverage() merge1 = pd.merge(median_income, education, on=['GEO_ID', 'NAME'], how='outer') merge2 = pd.merge(merge1, occupation, on=['GEO_ID', 'NAME'], how='outer') SES = pd.merge(merge2, health_coverage[['GEO_ID', 'NAME', 'PERCENTAGE_INSURED']], on=['GEO_ID', 'NAME'], how='outer') return SES # Create dataset containing all SES def get_demographics(): population_age_sex_race = analysis.data_gathering.get_population_age_sex_race() return population_age_sex_race # Create dataset the VADER scores averaged per city def get_mean_VADER(): sentiment_compressed = [] sentiment_compressed.extend(analysis.data_gathering.get_sentiment_data()) sentiment = pd.DataFrame(columns=['NAME', 'VADER_SCORE']) for i in range(0, len(cities)): city = sentiment_compressed[i] sentiment.loc[i] = [cities[i], city['mean'].mean()] return sentiment # Create dataset containing number of COVID-19 cases averaged per city def get_mean_COVID_cases(): covid_data = analysis.data_gathering.get_covid_data() covid_data['value'] = covid_data['value'].astype(float) covid_data_grouped = covid_data.groupby('city')['value'].mean().reset_index() covid_data_grouped['city'] = covid_data_grouped['city'].map(matching_dict) covid_data_grouped = covid_data_grouped.rename(columns={'city': 'NAME', 'value': 'CASES'}) return covid_data_grouped def percent_to_float(percent_string): return float(percent_string.strip('%')) / 100 # NSES index: percentage of population below poverty level # https://data.census.gov/table?q=percent+below+poverty&g=160XX00US0644000,0667000,0820000,1150000,1245000,1304000,1714000,1836003,2255000,2404000,2507000,2622000,3240000,3651000,3712000,3916000,4260000,4752006,4835000,5363000&y=2020 def get_below_poverty(): below_poverty = pd.read_csv('C:\\Users\\lucac\\Desktop\\Thesis\\data\\SES\\below_poverty.csv') below_poverty = below_poverty.iloc[[0]] below_poverty = below_poverty.T.reset_index() below_poverty.columns = ['NAME', 'PERCENTAGE_BELOW_POVERTY'] below_poverty = below_poverty.drop(index=0).reset_index(drop=True) below_poverty['NAME'] = below_poverty['NAME'].loc[ below_poverty['NAME'].str.contains('Estimate') & below_poverty['NAME'].str.contains('Percent below poverty level')] below_poverty = below_poverty.dropna() below_poverty['NAME'] = below_poverty['NAME'].str.split('!', n=1).str[0] below_poverty['PERCENTAGE_BELOW_POVERTY'] = below_poverty['PERCENTAGE_BELOW_POVERTY'].apply(percent_to_float) return below_poverty # NSES index: percentage of female-headed households # https://data.census.gov/table?q=DP02&g=160XX00US0644000,0667000,0820000,1150000,1245000,1304000,1714000,1836003,2255000,2404000,2507000,2622000,3240000,3651000,3712000,3916000,4260000,4752006,4835000,5363000&y=2020&tid=ACSDP5Y2020.DP02&moe=false def get_female_household(): female_household = pd.read_csv('C:\\Users\\lucac\\Desktop\\Thesis\\data\\SES\\female_household.csv') female_household = female_household.T.reset_index() female_household = female_household.iloc[:, [0, 11, 13]] female_household = female_household.drop(index=0).reset_index(drop=True) female_household.columns = ['NAME', 'TOTAL', 'SINGLE'] female_household['NAME'] = female_household['NAME'].loc[female_household['NAME'].str.contains('Percent')] female_household = female_household.dropna() female_household['NAME'] = female_household['NAME'].str.split('!', n=1).str[0] female_household['PERCENTAGE_FEMALE_HOUSEHOLD'] = female_household['TOTAL'].apply(percent_to_float)-female_household['SINGLE'].apply(percent_to_float) female_household['PERCENTAGE_FEMALE_HOUSEHOLD'] = female_household['PERCENTAGE_FEMALE_HOUSEHOLD'] return female_household[['NAME','PERCENTAGE_FEMALE_HOUSEHOLD']].reset_index(drop=True) # NSES index: unemployment rate def get_unemployment_rate(): occupation = analysis.data_gathering.get_occupation() return occupation[['NAME','UNEMPLOYMENT_RATE']] # NSES index: median household income def get_median_household_income(): income = analysis.data_gathering.get_median_household_income() return income # NSES index: percentage of graduates def get_number_graduate(): education = analysis.data_gathering.get_education_attainment() return education[['NAME','HIGH_SCHOOL_GRADUATE']] # NSES index: percentage of degree holders def get_number_degree(): education = analysis.data_gathering.get_education_attainment() return education[['NAME','DEGREE_HOLDERS']] # NSES index: final calculation # NSES = log(median household income) + (-1.129 * (log(percent of female-headed households))) + (-1.104 * # (log(unemployment rate))) + (-1.974 * (log(percent below poverty))) + .451*((high school grads)+(2*(bachelor's degree # holders))) def get_NSES(): merge1 = pd.merge(get_median_household_income(), get_female_household(), on='NAME') merge2 = pd.merge(merge1,get_unemployment_rate(),on='NAME') merge3 = pd.merge(merge2, get_below_poverty(), on='NAME') merge4 = pd.merge(merge3, get_number_graduate(), on='NAME') nses = pd.merge(merge4, get_number_degree(), on='NAME') nses['NSES'] = np.log(nses['MEDIAN_HOUSEHOLD_INCOME']) + (-1.129 * (np.log(nses['PERCENTAGE_FEMALE_HOUSEHOLD']))) + (-1.104 * (np.log(nses['UNEMPLOYMENT_RATE']))) + (-1.974 * (np.log(nses['PERCENTAGE_BELOW_POVERTY']))) + .451*((nses['HIGH_SCHOOL_GRADUATE']) +(2*(nses['DEGREE_HOLDERS']))) return nses[['NAME','NSES']] # Trend: function to compute regression line's slope def compute_regression_slope(group): slope, intercept, r_value, p_value, std_err = linregress(group['AVERAGE_CASES'], group['WEIGHTED_AVERAGE_VADER']) return slope # Trend: final trend measure between weekly time series def get_trend_weekly(): covid = analysis.data_gathering.get_covid_data() covid = covid.loc[:, ['FIPS', 'city', 'time_value', 'value']].dropna() covid_cities = dict(tuple(covid.groupby('city'))) dfs = [] for city in index: city_covid = covid_cities[city] sentiment_data = next(data for data in analysis.data_gathering.get_sentiment_data()) merged_data = pd.merge(sentiment_data[['index', 'mean', 'counts']], city_covid, left_on='index', right_on='time_value', how='inner') dfs.append(merged_data) result = pd.concat(dfs) result = result.reset_index(drop=True) result['city'] = result['city'].map(matching_dict) result = result.rename(columns={'mean': 'vader', 'value': 'cases'}) result = result.drop('time_value', axis=1) result['index'] = pd.to_datetime(result['index']) result[['vader', 'counts', 'cases']] = result[['vader', 'counts', 'cases']].astype(float) weighted_avg_vader_city = result.groupby([pd.Grouper(key='index', freq='W'), 'city']).apply( lambda x: (x['vader'] * x['counts']).sum() / x['counts'].sum()) avg_cases_city = result.groupby([pd.Grouper(key='index', freq='W'), 'city'])['cases'].mean() weekly_averages_city = pd.DataFrame( {'WEIGHTED_AVERAGE_VADER': weighted_avg_vader_city, 'AVERAGE_CASES': avg_cases_city}).reset_index() weekly_averages_city[['WEIGHTED_AVERAGE_VADER', 'AVERAGE_CASES']] = normalize( weekly_averages_city[['WEIGHTED_AVERAGE_VADER', 'AVERAGE_CASES']]) grouped = weekly_averages_city.groupby('city') trends = pd.DataFrame({'trend': grouped.apply(compute_regression_slope)}) trends.reset_index(inplace=True) trends = trends.rename(columns={'city': 'NAME', 'trend': 'TREND'}) return trends # Creates final full dataset using separate SES def get_full_data(): merge = pd.merge(get_SES(), get_mean_VADER(), on='NAME', how='outer') merge1 = pd.merge(merge, get_trend_weekly(), on='NAME', how='outer') merge2 = pd.merge(merge1, get_demographics(), on=['GEO_ID', 'NAME'], how='outer') data = pd.merge(merge2, get_mean_COVID_cases(), on='NAME', how='outer') data['RATIO_BLACK_TO_WHITE'] = data['AFRICAN_AMERICAN'] / data['WHITE'] return data # Creates final full dataset using NSES def get_full_data_NSES(): merge = pd.merge(get_NSES(), get_mean_VADER(), on='NAME', how='outer') merge1 = pd.merge(merge, get_trend_weekly(), on='NAME', how='outer') merge2 = pd.merge(merge1, get_demographics(), on='NAME', how='outer') data = pd.merge(merge2, get_mean_COVID_cases(), on='NAME', how='outer') data['RATIO_BLACK_TO_WHITE'] = data['AFRICAN_AMERICAN'] / data['WHITE'] return data
import React from "react"; import { ComponentMeta, ComponentStory } from "@storybook/react"; import { RadioButton } from "./RadioButton"; export default { title: "RadioButton", component: RadioButton, argTypes: { variant: { control: "select", options: ["Primary", "Secondary", "Success", "Warning", "Critical"], }, size: { control: "select", options: ["Inherit", "50", "100", "200", "300", "400", "500", "600"], }, }, } as ComponentMeta<typeof RadioButton>; const Template: ComponentStory<typeof RadioButton> = (args) => <RadioButton {...args} />; export const Secondary = Template.bind({}); Secondary.args = { defaultChecked: false, };
package com.pinyougou.cart.service.impl; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.transaction.annotation.Transactional; import com.alibaba.dubbo.config.annotation.Service; import com.pinyougou.cart.service.CartService; import com.pinyougou.mapper.TbItemMapper; import com.pinyougou.pojo.TbItem; import com.pinyougou.pojo.TbOrderItem; import com.pinyougou.pojogroup.Cart; /** * 购物车服务实现类 * @author Administrator * */ @Service @Transactional public class CartServiceImpl implements CartService { @Autowired private TbItemMapper itemMapper; @Autowired private RedisTemplate redisTemplate; /** * 将商品添加到购物车里 */ @Override public List<Cart> addGoodsToCartList(List<Cart> cartList, Long itemId, Integer num) { //1.根据商品SKU ID查询SKU商品信息 TbItem item = itemMapper.selectByPrimaryKey(itemId); if (item==null) { throw new RuntimeException("该商品不存在"); } if (!item.getStatus().equals("1")) { throw new RuntimeException("该商品未审核"); } //2.获取商家ID String sellerId = item.getSellerId(); //3.根据商家ID判断购物车列表中是否存在该商家的购物车 Cart cart = searchCartBySellerId(cartList,sellerId); if(cart==null) {//4.如果购物车列表中不存在该商家的购物车 //4.1 新建购物车对象 cart= new Cart(); //4.2将购物车对象添加到购物车列表 cart.setSellerId(sellerId); cart.setSellerName(item.getSeller());//item表中有商家姓名属性 List orderItemList = new ArrayList<>(); //这里封装了一个创建orderItem类的方法 TbOrderItem orderItem=createOrderItem(item,num); orderItemList.add(orderItem); cart.setOrderItemList(orderItemList); cartList.add(cart); }else {//5.如果购物车列表中存在该商家的购物车 // 判断购物车明细列表中是否存在该商品 TbOrderItem orderItem = searchOrderItemByItemId(cart.getOrderItemList(),itemId); if (orderItem==null) {//5.1. 如果没有,新增购物车明细 orderItem = createOrderItem(item,num); cart.getOrderItemList().add(orderItem); }else {//5.2. 如果有,在原购物车明细上添加数量,更改金额 orderItem.setNum(orderItem.getNum()+num);//num可能是整数,也可能是负数 orderItem.setTotalFee(new BigDecimal(orderItem.getPrice().doubleValue()*orderItem.getNum())); if(orderItem.getNum()<=0) {//当前商品的数量是0或者0以下,移除该商品 cart.getOrderItemList().remove(orderItem);//移除购物车明细 } if (cart.getOrderItemList().size()==0) {//购物车内的商品列表内容是空 cartList.remove(cart);//移除该商家的购物车列表 } } } return cartList; } /** * 根据商品ID判断购物明细列表中是否存在该商品 * @param orderItemList //购物车列表 * @param itemId //购物车的商品ID * @return */ private TbOrderItem searchOrderItemByItemId(List<TbOrderItem> orderItemList,Long itemId) { for(TbOrderItem orderItem:orderItemList) { //判断是否是同一个商家 if(orderItem.getItemId().longValue()==itemId.longValue()) { return orderItem; } } //当循环走完,还没有匹配返回,说明不存在同一商品 return null; } /** * 根据商家ID判断购物车列表中是否存在该商家的购物车 * @param cartList //购物车列表 * @param sellerId //商家ID * @return */ private Cart searchCartBySellerId(List<Cart> cartList,String sellerId) { for(Cart cart:cartList) { //判断是否是同一个商家 if(cart.getSellerId().equals(sellerId)) { return cart; } } //当循环走完,还没有匹配返回,说明不存在同一商家购物车 return null; } /** * 根据数量和商品创建订单(加入购物车一次只有一个SKU) * @param item * @param num * @return */ private TbOrderItem createOrderItem(TbItem item,Integer num) { if (num<=0) { throw new RuntimeException("数量非法"); } TbOrderItem orderItem = new TbOrderItem(); orderItem.setItemId(item.getId());//商品ID orderItem.setGoodsId(item.getGoodsId());//SPU的ID orderItem.setNum(num);//商品购买数量 orderItem.setPicPath(item.getImage());//商品图片地址 orderItem.setPrice(item.getPrice());//商品单价 orderItem.setSellerId(item.getSellerId());//商家ID orderItem.setTitle(item.getTitle());//商品标题 orderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue()*num));//商品总金额 return orderItem; } /** * redis中提取购物车数据 */ @Override public List<Cart> findCartListFromRedis(String username) { System.out.println("从redis中提取购物车数据....."+username); List<Cart> cartList = (List<Cart>) redisTemplate.boundHashOps("cartList").get(username); //System.out.println(cartList); if (cartList == null) { cartList = new ArrayList<>(); } //System.out.println(cartList); return cartList; } /** * 向redis存入购物车数据 */ @Override public void saveCartListToRedis(String username, List<Cart> cartList) { System.out.println("向redis存入购物车数据....."+username); redisTemplate.boundHashOps("cartList").put(username,cartList); } /** * 合并购物车 */ @Override public List<Cart> mergeCartList(List<Cart> cartList1, List<Cart> cartList2) { System.out.println("合并购物车"); for(Cart cart: cartList2){ for(TbOrderItem orderItem:cart.getOrderItemList()){ cartList1= addGoodsToCartList(cartList1,orderItem.getItemId(),orderItem.getNum()); } } return cartList1; } }
from server.src.command import Command from server.src.world import World class State(Command): def __init__(self): super().__init__('state') def execute(self, request): if self.valid_request(request): world = World.get_instance() robot = world.get_robot(request["robot"]) if robot is not None: position = robot.get_position() state = { "position": [position.x_coordinate, position.y_coordinate], "direction": robot.get_direction(), "shields": robot.get_shields(), "shots": robot.get_shots(), "status": robot.get_status() } return state else: return self._invalid_robot_error() else: return self._invalid_request_error() def valid_request(self, request): """ Checks that the received request is valid""" if "robot" not in request or request["robot"] is None: return False elif "command" not in request or request["command"] is None: return False elif "arguments" not in request or request["arguments"] is None: return False elif type(request["arguments"]) is not list or len(request["arguments"]) != 0: return False else: return True def _invalid_request_error(self): """Returns an error response when the request is invalid""" return { "result": "ERROR", "data": { "message": "Your request is not configured properly" } } def _invalid_robot_error(self): """Returns an error response when the request contains a robot name that does not exist""" return { "result": "ERROR", "data": { "message": "Robot does not exist" } }
/************************************* * Filename: Receiver.java *************************************/ import java.util.Random; import java.util.HashMap; public class Receiver extends NetworkHost { /* * Predefined Constants (static member variables): * * int MAXDATASIZE : the maximum size of the Message data and * Packet payload * * * Predefined Member Methods: * * void startTimer(double increment): * Starts a timer, which will expire in * "increment" time units, causing the interrupt handler to be * called. You should only call this in the Sender class. * void stopTimer(): * Stops the timer. You should only call this in the Sender class. * void udtSend(Packet p) * Puts the packet "p" into the network to arrive at other host * void deliverData(String dataSent) * Passes "dataSent" up to app layer. You should only call this in the * Receiver class. * double getTime() * Returns the current time in the simulator. Might be useful for * debugging. * void printEventList() * Prints the current event list to stdout. Might be useful for * debugging, but probably not. * * * Predefined Classes: * * Message: Used to encapsulate a message coming from app layer * Constructor: * Message(String inputData): * creates a new Message containing "inputData" * Methods: * boolean setData(String inputData): * sets an existing Message's data to "inputData" * returns true on success, false otherwise * String getData(): * returns the data contained in the message * Packet: Used to encapsulate a packet * Constructors: * Packet (Packet p): * creates a new Packet, which is a copy of "p" * Packet (int seq, int ack, int check, String newPayload) * creates a new Packet with a sequence field of "seq", an * ack field of "ack", a checksum field of "check", and a * payload of "newPayload" * Packet (int seq, int ack, int check) * chreate a new Packet with a sequence field of "seq", an * ack field of "ack", a checksum field of "check", and * an empty payload * Methods: * boolean setSeqnum(int n) * sets the Packet's sequence field to "n" * returns true on success, false otherwise * boolean setAcknum(int n) * sets the Packet's ack field to "n" * returns true on success, false otherwise * boolean setChecksum(int n) * sets the Packet's checksum to "n" * returns true on success, false otherwise * boolean setPayload(String newPayload) * sets the Packet's payload to "newPayload" * returns true on success, false otherwise * int getSeqnum() * returns the contents of the Packet's sequence field * int getAcknum() * returns the contents of the Packet's ack field * int getChecksum() * returns the checksum of the Packet * String getPayload() * returns the Packet's payload * */ // Add any necessary class variables here. They can hold // state information for the receiver. int rcvBase; int NAK; HashMap<Integer, Packet> pktBuf; // SeqNum:Packet // Also add any necessary methods (e.g. for checksumming) private int checkSum(Packet pkt) { int sum = 0; byte[] bytes_arr = pkt.getPayload().getBytes(); for (byte bt : bytes_arr) { // assume each character is a 8-bit integer int num = bt & 0xff; sum += num; } // add ack and sequence number sum += (pkt.getAcknum() + pkt.getSeqnum()); return sum; } // This is the constructor. Don't touch!!! public Receiver(int entityName, EventList events, double pLoss, double pCorrupt, int trace, Random random) { super(entityName, events, pLoss, pCorrupt, trace, random); } // This routine will be called whenever a packet sent from the sender // (i.e. as a result of a udtSend() being done by a Sender procedure) // arrives at the receiver. "packet" is the (possibly corrupted) packet // sent from the sender. protected void Input(Packet packet) { int seqNum = packet.getSeqnum(); String dataSent = packet.getPayload(); // correctly received packet if (seqNum == rcvBase && packet.getChecksum() == checkSum(packet)) { deliverData(dataSent); rcvBase++; while (!pktBuf.isEmpty() && pktBuf.containsKey(rcvBase)) { deliverData(pktBuf.get(rcvBase).getPayload()); rcvBase++; } Packet pkt = new Packet(seqNum, rcvBase, seqNum + rcvBase); udtSend(pkt); } // detect dulplicate or buffer coming packets else if (packet.getChecksum() == checkSum(packet)) { // ignore the packet and send ack // ack of this packet is the rcv base Packet pkt = new Packet(seqNum, rcvBase, seqNum + rcvBase); udtSend(pkt); if (seqNum > rcvBase) { // buffer the packet pktBuf.put(seqNum, packet); } } // fail the checksum else { // ignore } } // This routine will be called once, before any of your other receiver-side // routines are called. It can be used to do any required // initialization (e.g. of member variables you add to control the state // of the receiver). protected void Init() { rcvBase = 0; NAK = -1; pktBuf = new HashMap<>(); } }
import { getAccessRequestListParamsAtom } from '../states'; import { useEffect } from 'react'; import useApi from 'src/modules/share/hooks/useApi'; import { AccessRequest, GetAccessRequestListParams } from '../types'; import { useRecoilValue, useResetRecoilState } from 'recoil'; type GetAccessRequestListResponse = { data: { totalItems: number; itemPerPage: number; items: AccessRequest[]; }; }; type GetAccessRequestListError = unknown; const useGetAccessRequestList = () => { const params = useRecoilValue(getAccessRequestListParamsAtom); const resetParams = useResetRecoilState(getAccessRequestListParamsAtom); const { fetchApi, data, isLoading } = useApi< GetAccessRequestListParams, GetAccessRequestListResponse, GetAccessRequestListError >('getAccessRequestList', ({ page, limit, alumniId, name }) => ({ method: 'GET', url: '/api/access_requests', params: { page, limit, alumniId, name, }, })); useEffect(() => resetParams, []); useEffect(() => { fetchApi(params); }, [params]); const reload = () => { fetchApi(params); }; return { data, isLoading, getAccessRequestListList: fetchApi, reload, }; }; export default useGetAccessRequestList;
use actix_web::{web, HttpResponse, ResponseError}; use anyhow::Context; use reqwest::StatusCode; use sqlx::PgPool; use uuid::Uuid; #[derive(serde::Deserialize)] pub struct Parameters { subscription_token: String, } #[tracing::instrument(name = "Confirm a pending subscriber", skip(pool, parameters))] pub async fn confirm( parameters: web::Query<Parameters>, pool: web::Data<PgPool>, ) -> Result<HttpResponse, ConfirmError> { let id = get_subscriber_id_from_token(&pool, &parameters.subscription_token) .await .context("Failed to query for a subscriber id.")?; match id { None => Err(ConfirmError::UnauthorizedError( "Provided subscription token could not be found.".into(), )), Some(subscriber_id) => { confirm_subscriber(&pool, subscriber_id) .await .context("Failed to mark a subscriber as confirmed.")?; Ok(HttpResponse::Ok().finish()) } } } pub async fn get_subscriber_id_from_token( pool: &PgPool, token: &str, ) -> Result<Option<Uuid>, sqlx::Error> { let result = sqlx::query!( r#" SELECT subscriber_id FROM subscription_tokens WHERE subscription_token = $1 "#, token, ) .fetch_optional(pool) .await?; Ok(result.map(|r| r.subscriber_id)) } pub async fn confirm_subscriber(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> { sqlx::query!( r#" UPDATE subscriptions SET status = $1 WHERE id = $2 "#, "confirmed", id, ) .execute(pool) .await?; Ok(()) } #[derive(thiserror::Error, Debug)] pub enum ConfirmError { #[error("{0}")] UnauthorizedError(String), #[error(transparent)] UnexpectedError(#[from] anyhow::Error), } impl ResponseError for ConfirmError { fn status_code(&self) -> StatusCode { match self { ConfirmError::UnauthorizedError(_) => StatusCode::UNAUTHORIZED, ConfirmError::UnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR, } } }
# Outils de Diagnostic Réseau 🌐 ## 1. PING 🏓 - **Définition** : PING (Packet Internet Groper) est un outil de diagnostic réseau utilisé pour tester la connectivité entre deux nœuds sur un réseau. - **Utilisation** : Envoie des paquets ICMP 'echo request' à une adresse spécifique et attend des réponses. Utilisé pour vérifier la disponibilité en ligne d'un appareil et mesurer la latence. ## 2. HOST 🔍 - **Définition** : HOST est un outil de ligne de commande pour trouver le nom de domaine ou l'adresse IP associée à un serveur ou un domaine. - **Utilisation** : Retourne les adresses IP pour un nom de domaine donné et vice versa. Utile pour le dépannage DNS et obtenir des informations de mappage IP. ## 3. NSLOOKUP 🔎 - **Définition** : NSLOOKUP (Name Server Lookup) est un outil pour interroger les serveurs DNS afin d'obtenir des informations sur les enregistrements DNS. - **Utilisation** : Trouve divers enregistrements DNS associés à un nom de domaine, tels que les enregistrements A, MX, NS, etc. Essentiel pour les administrateurs réseau pour le débogage et le test DNS. ## 4. WHOIS 📖 - **Définition** : WHOIS est un protocole utilisé pour interroger des bases de données stockant les informations d'enregistrement des ressources Internet. - **Utilisation** : Fournit des informations sur le propriétaire d'un domaine, les dates d'expiration et de création, les serveurs de noms, et les contacts. Important pour la recherche de domaine et la résolution de litiges.
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link rel="preconnect" href="https://rsms.me/"> <link rel="stylesheet" href="https://rsms.me/inter/inter.css"> <link href="{% static 'fontawesomefree/css/fontawesome.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'fontawesomefree/css/brands.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'fontawesomefree/css/solid.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/tailwind-output.css' %}"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="icon" type="image/x-icon" href="{% static '/images/logo.svg' %}"> {# <script src="https://unpkg.com/htmx.org/dist/htmx.js"></script>#} <!-- ##### remember to remove ###### --> <script src="https://cdn.tailwindcss.com"></script> <script src="https://kit.fontawesome.com/9a09bfee6b.js" crossorigin="anonymous"></script> <!-- ##### remember to remove ###### --> <script src="https://unpkg.com/hyperscript.org@0.9.11"></script> <script src="{% static 'htmx/htmx.min.js' %}" defer></script> <script src="{% static 'js/base.js' %}" defer></script> <script src="//unpkg.com/alpinejs" defer></script> </head> <body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'> <!-- Mobile view warning overlay --> <div class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center lg:hidden"> <div class="bg-white p-4 rounded shadow-lg text-center"> <p>This site is designed for desktop view. Please access it on a larger screen.</p> </div> </div> <div id="header" class="relative"> {% block header %} <nav class="bg-gray-700 h-14 sm:h-fit py-4 fixed top-0 left-0 right-0 "> <div class=" mx-auto px-4 sm:px-6 lg:px-8"> <div class="hidden sm:flex justify-between"> <div class="flex"> <a href="/" class="text-white"> <svg class="fill-current" viewBox="0 0 150 150" xmlns="http://www.w3.org/2000/svg" width="40" height="40"> <defs> <!-- Inset shadow filter definition --> <filter id="inset-shadow" x="-50%" y="-50%" width="200%" height="200%"> <feComponentTransfer in="SourceAlpha"> <feFuncA type="table" tableValues="0 0 1"></feFuncA> </feComponentTransfer> <feGaussianBlur stdDeviation="3"></feGaussianBlur> <feOffset dx="2" dy="2" result="offsetblur"></feOffset> <feFlood flood-color="black" result="color"></feFlood> <feComposite in2="offsetblur" operator="in"></feComposite> <feComposite in2="SourceAlpha" operator="in"></feComposite> <!-- Adjusted filter primitives for the deeper inner shadow --> <feMorphology operator="dilate" radius="24" in="SourceAlpha" result="expand"></feMorphology> <feComposite in="expand" in2="SourceAlpha" operator="out" result="shadow"></feComposite> <feGaussianBlur in="shadow" stdDeviation="2" result="shadowblur"></feGaussianBlur> <feOffset in="shadowblur" dx="-2" dy="-2" result="shadowoffset"></feOffset> <feFlood flood-color="black" flood-opacity="0.7" result="shadowcolor"></feFlood> <feComposite in2="shadowoffset" in="shadowcolor" operator="in"></feComposite> <feComposite in2="SourceAlpha" operator="in"></feComposite> <feMerge> <feMergeNode in="SourceGraphic"></feMergeNode> <feMergeNode></feMergeNode> </feMerge> </filter> </defs> <path d="M 0,0 L 0,50 37.5,75 0,100 0,150 56.25,112.5 56.25,87.5 75,100 93.75,87.5 93.75,112.5 150,150 150,100 112.5,75 150,50 150,0 75,50" filter="url(#inset-shadow)"/> </svg> </a> </div> <div class="flex space-x-4"> <a href="{% url 'chat' %}" class="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium">Projects</a> <a href="{% url 'projectlio0-index' %}" class="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium">Contact</a> </div> </div> </div> </nav> {% endblock %} </div> <div id="content" class=""> {% block content %} {% endblock %} </div> </body> </html>
package main_test import ( "bufio" "fmt" "github.com/CameronHonis/Mila" . "github.com/onsi/ginkgo/v2" "log" "os" "strconv" "strings" "time" ) const QUIET = true const PRINT_ROOT_MOVE_NODES = false const FOCUS_TEST_IDX = -1 const MAX_DEPTH = 4 var scanner *bufio.Scanner func perft(pos *main.Position, depth int) int { return _perft(pos, depth, true) } func _perft(pos *main.Position, depth int, isRoot bool) int { isLeaf := depth == 1 nodeCnt := 0 iter := main.NewLegalMoveIter(pos) var done bool for { var move main.Move move, done = iter.Next() if done { break } var moveNodeCnt int if isLeaf { moveNodeCnt = 1 } else { capturedPiece, lastFrozenPos := pos.MakeMove(move) moveNodeCnt = _perft(pos, depth-1, false) pos.UnmakeMove(move, lastFrozenPos, capturedPiece) } if !QUIET && PRINT_ROOT_MOVE_NODES && isRoot { fmt.Printf("%s: %d\n", move, moveNodeCnt) } nodeCnt += moveNodeCnt } return nodeCnt } func parsePerftLine(line string) (fen string, depthNodeCntPairs [][2]int) { splitTxt := strings.Split(line, ";") fen = strings.TrimSpace(splitTxt[0]) depthNodeCntPairs = make([][2]int, 0) for _, perftStr := range splitTxt[1:] { perftStrSplit := strings.Split(perftStr, " ") depthStr := perftStrSplit[0][1:] depth, parseDepthErr := strconv.Atoi(depthStr) if parseDepthErr != nil { log.Fatalf("could not parse depth from %s:\n\t%s", depthStr, parseDepthErr) } expNodeCntStr := perftStrSplit[1] expNodeCnt, parseNodeCntErr := strconv.Atoi(expNodeCntStr) if parseNodeCntErr != nil { log.Fatalf("could not parse expNodeCnt from %s:\n\t%s", expNodeCntStr, parseNodeCntErr) } depthNodeCntPairs = append(depthNodeCntPairs, [2]int{depth, expNodeCnt}) } return fen, depthNodeCntPairs } func perftFromFile() { file, err := os.Open("./perft") if err != nil { log.Fatalf("failed to open file: %s", err) } scanner = bufio.NewScanner(file) scanner.Split(bufio.ScanLines) testIdx := 0 for scanner.Scan() { currTestIdx := testIdx testIdx++ shouldSkipTest := FOCUS_TEST_IDX >= 0 && FOCUS_TEST_IDX != currTestIdx if shouldSkipTest { continue } line := scanner.Text() if !QUIET { fmt.Printf("[TEST %d] %s\n", currTestIdx, line) } fen, depthNodeCntPairs := parsePerftLine(line) pos, posErr := main.FromFEN(fen) if posErr != nil { log.Fatalf("could not build pos from FEN %s:\n\t%s", fen, posErr) } for _, depthNodeCntPair := range depthNodeCntPairs { depth := depthNodeCntPair[0] expNodeCnt := depthNodeCntPair[1] if depth > MAX_DEPTH { continue } start := time.Now() actNodeCnt := perft(pos, depth) if actNodeCnt != expNodeCnt { log.Fatalf("node count mismatch at depth %d, actual %d vs exp %d", depth, actNodeCnt, expNodeCnt) } else { elapsed := time.Since(start) if !QUIET { fmt.Printf("depth %d passed in %s\n", depth, elapsed) } } } } _ = file.Close() } var _ = It("perft", func() { //f, _ := os.Create("cpu.prof") //_ = pprof.StartCPUProfile(f) //defer pprof.StopCPUProfile() perftFromFile() })
<?php namespace Sprockets; use SplFileInfo; use Sprockets\Exception\AssetNotFoundException; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { protected $loadPaths; protected $typeExtensions = array( 'stylesheet' => '.css', 'javascript' => '.js' ); public function __construct($loadPaths) { $this->loadPaths = $loadPaths; } public function find($logicalPath, $type = null) { $searchPath = $logicalPath; if ($type && !pathinfo($logicalPath, PATHINFO_EXTENSION)) { $searchPath.= $this->typeExtensions[$type]; } $searchPath = new SplFileInfo($searchPath); $finder = $this->newFinder(); $finder->path($searchPath->getPath()); $finder->name($searchPath->getBasename() . ($searchPath->getExtension() == "" ? '.*' : '*')); $iterator = $finder->getIterator(); $iterator->rewind(); return $iterator->current(); } public function all() { $files = iterator_to_array($this->newFinder()); return array_values($files); } public function __invoke($name) { return $this->find($name); } protected function newFinder() { return SymfonyFinder::create()->ignoreDotFiles(true)->files()->in($this->loadPaths); } }
<template> <div class="app-container adv-editor-container" v-loading="loading"> <el-container> <el-header height="40px"> <el-row :gutter="10" class="btn-row"> <el-col :span="1.5"> <el-button plain type="info" icon="el-icon-back" size="mini" @click="handleGoBack">{{ $t('CMS.Adv.GoBack') }}</el-button> </el-col> <el-col :span="1.5"> <el-button plain type="success" icon="el-icon-edit" size="mini" v-hasPermi="[ $p('PageWidget:Edit:{0}', [ adSpaceId ]) ]" @click="handleSave">{{ $t("Common.Save") }}</el-button> </el-col> </el-row> </el-header> <el-form ref="form" :model="form" :rules="rules" label-width="110px"> <el-container> <el-aside style="width:500px;"> <el-card shadow="never"> <div slot="header" class="clearfix"> <span>{{ $t('CMS.Adv.Basic') }}</span> </div> <el-form-item :label="$t('CMS.Adv.AdName')" prop="name"> <el-input v-model="form.name" /> </el-form-item> <el-form-item :label="$t('CMS.Adv.Type')" prop="type"> <el-select v-model="form.type"> <el-option v-for="t in adTypes" :key="t.id" :label="t.name" :value="t.id" /> </el-select> </el-form-item> <el-form-item :label="$t('CMS.Adv.Weight')" prop="weight"> <el-input-number v-model="form.weight" :min="0"></el-input-number> </el-form-item> <el-form-item :label="$t('CMS.Adv.OnlineDate')" prop="onlineDate"> <el-date-picker v-model="form.onlineDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" /> </el-form-item> <el-form-item :label="$t('CMS.Adv.OfflineDate')" prop="offlineDate"> <el-date-picker v-model="form.offlineDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" /> </el-form-item> <el-form-item :label="$t('Common.Remark')" prop="remark"> <el-input v-model="form.remark" type="textarea" :maxlength="100" /> </el-form-item> </el-card> </el-aside> <el-main> <el-card shadow="never"> <div slot="header" class="clearfix; line-height: 32px; font-size: 16px;"> <span>{{ $t('CMS.Adv.AdMaterials') }}</span> </div> <el-form-item label="" v-if="form.type==='image'" prop="resourcePath"> <cms-logo-view v-model="form.resourcePath" :src="form.resourceSrc" :width="218" :height="150"></cms-logo-view> </el-form-item> <el-form-item :label="$t('CMS.Adv.RedirectUrl')" prop="redirectUrl"> <el-input v-model="form.redirectUrl" placeholder="http(s)://" /> </el-form-item> </el-card> </el-main> </el-container> </el-form> </el-container> </div> </template> <script> import { listAdvertisementTypes, getAdvertisement, addAdvertisement, editAdvertisement } from "@/api/advertisement/advertisement"; import CMSLogoView from '@/views/cms/components/LogoView'; export default { name: "CMSAdvertisement", components: { 'cms-logo-view': CMSLogoView }, data () { return { loading: false, advertisementId: this.$route.query.id, adSpaceId: this.$route.query.adSpaceId, adTypes: [], form: { weight: 100 }, rules: { type: [ { required: true, message: this.$t('CMS.Adv.RuleTips.Type'), trigger: "blur" } ], name: [ { required: true, message: this.$t('CMS.Adv.RuleTips.Name'), trigger: "blur" } ], weight: [ { required: true, message: this.$t('CMS.Adv.RuleTips.Weight'), trigger: "blur" }, ], onlineDate: [ { required: true, message: this.$t('CMS.Adv.RuleTips.OnlineDate'), trigger: "blur" } ], offlineDate: [ { required: true, message: this.$t('CMS.Adv.RuleTips.OfflineDate'), trigger: "blur" } ] } }; }, created () { this.loadAdvertisementTypes(); if (this.advertisementId) { this.loading = true; getAdvertisement(this.advertisementId).then(response => { this.form = response.data; this.loading = false; }); } }, methods: { loadAdvertisementTypes () { listAdvertisementTypes(this.queryParams).then(response => { this.adTypes = response.data.rows; if (!this.advertisementId && this.adTypes.length > 0) { this.form.type = this.adTypes[0].id; } }); }, handleGoBack() { const obj = { path: "/cms/adspace/editor", query: { id: this.adSpaceId } }; this.$tab.closeOpenPage(obj); }, handleSave() { this.$refs["form"].validate(valid => { if (valid) { this.loading = true; if (this.form.advertisementId) { editAdvertisement(this.form).then(response => { this.$modal.msgSuccess(response.msg); this.loading = false; }); } else { this.form.adSpaceId = this.adSpaceId; addAdvertisement(this.form).then(response => { this.$modal.msgSuccess(response.msg); this.$router.push({ path: "/cms/ad/editor", query: { adSpaceId: this.adSpaceId, id: response.data } }); this.loading = false; }); } } }); } } }; </script> <style scoped> .adv-editor-container .el-input, .el-textarea, .el-select, .el-input-number { width: 300px; } .adv-editor-container .el-header { padding-left: 0; } .adv-editor-container .el-aside, .el-main { padding: 0; } .adv-editor-container .el-aside { padding-right: 10px; background-color: #fff; } .adv-editor-container .el-aside, .el-container { line-height: 24px; font-size: 16px; } .adv-editor-container .el-card { height: 460px; } </style>
// Copyright (C) 2019-2023 Aleo Systems Inc. // This file is part of the snarkVM library. // 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. use super::*; use crate::Signature; impl<N: Network> PrivateKey<N> { /// Returns a signature for the given message (as field elements) using the private key. pub fn sign<R: Rng + CryptoRng>(&self, message: &[Field<N>], rng: &mut R) -> Result<Signature<N>> { Signature::sign(self, message, rng) } /// Returns a signature for the given message (as bytes) using the private key. pub fn sign_bytes<R: Rng + CryptoRng>(&self, message: &[u8], rng: &mut R) -> Result<Signature<N>> { Signature::sign_bytes(self, message, rng) } /// Returns a signature for the given message (as bits) using the private key. pub fn sign_bits<R: Rng + CryptoRng>(&self, message: &[bool], rng: &mut R) -> Result<Signature<N>> { Signature::sign_bits(self, message, rng) } } #[cfg(test)] mod tests { use super::*; use crate::Address; use snarkvm_console_network::Testnet3; type CurrentNetwork = Testnet3; const ITERATIONS: u64 = 100; #[test] fn test_sign_and_verify() -> Result<()> { let rng = &mut TestRng::default(); for i in 0..ITERATIONS { // Sample an address and a private key. let private_key = PrivateKey::<CurrentNetwork>::new(rng)?; let address = Address::try_from(&private_key)?; // Check that the signature is valid for the message. let message: Vec<_> = (0..i).map(|_| Uniform::rand(rng)).collect(); let signature = private_key.sign(&message, rng)?; assert!(signature.verify(&address, &message)); // Check that the signature is invalid for an incorrect message. let failure_message: Vec<_> = (0..i).map(|_| Uniform::rand(rng)).collect(); if message != failure_message { assert!(!signature.verify(&address, &failure_message)); } } Ok(()) } #[test] fn test_sign_and_verify_bytes() -> Result<()> { let rng = &mut TestRng::default(); for i in 0..ITERATIONS { // Sample an address and a private key. let private_key = PrivateKey::<CurrentNetwork>::new(rng)?; let address = Address::try_from(&private_key)?; // Check that the signature is valid for the message. let message: Vec<_> = (0..i).map(|_| Uniform::rand(rng)).collect(); let signature = private_key.sign_bytes(&message, rng)?; assert!(signature.verify_bytes(&address, &message)); // Check that the signature is invalid for an incorrect message. let failure_message: Vec<_> = (0..i).map(|_| Uniform::rand(rng)).collect(); if message != failure_message { assert!(!signature.verify_bytes(&address, &failure_message)); } } Ok(()) } #[test] fn test_sign_and_verify_bits() -> Result<()> { let rng = &mut TestRng::default(); for i in 0..ITERATIONS { // Sample an address and a private key. let private_key = PrivateKey::<CurrentNetwork>::new(rng)?; let address = Address::try_from(&private_key)?; // Check that the signature is valid for the message. let message: Vec<_> = (0..i).map(|_| Uniform::rand(rng)).collect(); let signature = private_key.sign_bits(&message, rng)?; assert!(signature.verify_bits(&address, &message)); // Check that the signature is invalid for an incorrect message. let failure_message: Vec<_> = (0..i).map(|_| Uniform::rand(rng)).collect(); if message != failure_message { assert!(!signature.verify_bits(&address, &failure_message)); } } Ok(()) } }
export default class PaperDollLoader { constructor(paperDoll) { this.paperDoll = paperDoll this.scene = paperDoll.scene this.shell = paperDoll.shell this.scale = 0.7325 this.photoScale = 0.7 this.flagX = -153 this.flagY = -120 this.flagScale = 0.66 this.load = new Phaser.Loader.LoaderPlugin(this.scene) let suffix = '/client/media/clothing' this.url = this.shell.baseURL + suffix this.keyPrefix = 'paper' this.load.on('filecomplete', this.onFileComplete, this) } getUrl(slot) { switch (slot) { case 'flag': return 'icon/' default: return 'paper/' } } getKey(...args) { let key = args.join('') let prefix = this.keyPrefix || '' return `${prefix}${key}` } setColor(id) { this.paperDoll.body.tint = this.scene.world.getColor(id) } loadItems(penguin) { for (let slot of this.paperDoll.slots) { let item = penguin[slot] if (item > 0) { this.loadItem(item, slot) } } this.load.start() } loadItem(item, slot) { if (slot == 'color') { return this.setColor(item) } if (item == 0) { return this.removeItem(slot) } if (this.paperDoll.items[slot].sprite) { this.removeItem(slot) } this.paperDoll.items[slot].id = item if (this.scene.crumbs.items[item].back) { this.loadBack(item, slot) } let url = slot == 'flag' ? `${this.url}/icon` : `${this.url}/paper` let key = `${this.keyPrefix}/${slot}/${item}` if ( this.checkComplete('image', key, () => { this.onFileComplete(item, key, slot) }) ) { return } this.load.image({ key: key, url: `${url}/${item}.webp` }) } loadBack(item, parentSlot) { let key = `${this.keyPrefix}/${parentSlot}/${item}_back` if ( this.checkComplete('image', key, () => { this.onFileComplete(item, key, parentSlot, true) }) ) { return } this.load.image(key, `${this.url}/${this.keyPrefix}/${item}_back.webp`) } onFileComplete(itemId, key, slot, isBack = false) { if (!this.paperDoll.visible || !this.textureExists(key)) { return } if (itemId != this.paperDoll.items[slot].id) { return } let item = this.paperDoll.items[slot] if (isBack) { this.addBack(key, slot, item) return } if (item.sprite) { this.removeItem(slot) } if (slot == 'flag') { this.addFlag(key, slot, item) return } item.sprite = this.addPaper(key, slot, item.depth) } addBack(key, slot, parentItem) { if (parentItem.back) { this.paperDoll.destroyBack(item) } parentItem.back = this.addPaper(key, slot, parentItem.depth, 1, true) parentItem.back.setPosition(0, 6) } addFlag(key, slot, item) { item.sprite = this.addPaper(key, slot, item.depth, this.flagScale) item.sprite.setPosition(this.flagX, this.flagY) } addPaper(key, slot, depth, scale = this.scale, isBack = false) { let paper = this.scene.add.image(0, 0, key) paper.scale = scale paper.isBack = isBack // Back sprites always on bottom paper.depth = isBack ? depth : depth + 100 this.fadeIn(paper) if (slot == 'photo') { this.scene.playerCard.photo.add(paper) paper.scale = this.photoScale } else { this.paperDoll.add(paper) } if (this.paperDoll.isInputEnabled) { this.addInput(slot, paper) } this.paperDoll.sort('depth') this.updateBackSprites() return paper } fadeIn(paper) { if (!this.paperDoll.fadeIn) { return } paper.alpha = 0 this.scene.tweens.add({ targets: paper, alpha: {from: 0, to: 1}, duration: 200 }) } addInput(slot, paper) { paper.setInteractive({ cursor: 'pointer', pixelPerfect: true }) paper.on('pointerdown', () => this.onPaperClick(slot)) } onPaperClick(slot) { this.scene.airtower.sendXt('s#upr', slot) } removeItem(slot) { let item = this.paperDoll.items[slot] if (!item) { return } this.paperDoll.removeItem(item) this.updateBackSprites() } updateBackSprites() { let backs = this.getBackSprites() if (!backs.length) { return } let last = backs.pop() if (!last.visible) { last.visible = true this.fadeIn(last) } for (let back of backs) { back.visible = false } } getBackSprites() { return this.paperDoll.list.filter((item) => item.isBack) } checkComplete(type, key, callback = () => {}) { if (this.textureExists(key)) { callback() return true } this.load.once(`filecomplete-${type}-${key}`, callback) } textureExists(key) { return this.scene.textures.exists(key) } }
import streamlit as st import pandas as pd #import openai from pathlib import Path import yagmail import google.generativeai as genai # Set your OpenAI API key here #openai.api_key = 'your_openai_api_key' genai.configure(api_key="AIzaSyDVQubOFyqyRDepOELUXwVRBMnbngkHYm8") model = genai.GenerativeModel( model_name="gemini-pro", generation_config={ "temperature": 0.9, "top_p": 1, "top_k": 1, "max_output_tokens": 2048, }, safety_settings=[ { "category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE", }, { "category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE", }, { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE", }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE", }, ], ) def send_email(recipient, subject, body, attachment_path=None): # Set up your email credentials here yag = yagmail.SMTP('creativeauthoronline@gmail.com', 'dtil cwls dcai mogx') # Compose the email contents = [body] if attachment_path: contents.append(attachment_path) # Send the email yag.send(to=recipient, subject=subject, contents=contents) def main(): st.title("Email Sender with Streamlit") # Upload CSV file uploaded_file = st.file_uploader("Upload CSV file", type=["csv"]) if uploaded_file is not None: df = pd.read_csv(uploaded_file) st.write("Uploaded CSV file:") st.write(df) # Email details recipient = st.text_input("Recipient email:") subject = st.text_input("Email subject:") # Generate email body using GPT-3 prompt = st.text_area("Prompt for email body generation:", "Dear [Recipient],\n\n") generated_body = model.generate_content(prompt) body = st.text_area("Generated Email body:", value=generated_body) # Attachments attachment_type = st.radio("Select attachment type", ["None", "Image", "PDF"]) attachment_path = None if attachment_type == "Image": uploaded_image = st.file_uploader("Upload image", type=["jpg", "jpeg", "png"]) if uploaded_image: attachment_path = Path("uploaded_image." + uploaded_image.name.split(".")[-1]) with open(attachment_path, "wb") as f: f.write(uploaded_image.read()) elif attachment_type == "PDF": uploaded_pdf = st.file_uploader("Upload PDF", type=["pdf"]) if uploaded_pdf: attachment_path = Path("uploaded_pdf.pdf") with open(attachment_path, "wb") as f: f.write(uploaded_pdf.read()) # Send email button if st.button("Send Email"): if recipient and subject and body: for index, row in df.iterrows(): send_email(row['email'], subject, body, attachment_path) st.success("Emails sent successfully!") if __name__ == "__main__": main()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> <title>Signature Pad</title> <link rel="stylesheet" href="css"> <?!= HtmlService.createHtmlOutputFromFile('css').getContent() ?> </head> <body> <div class="wrapper"> <div class="title"> <p>ข้อมูลลายมือชื่อผู้บริหาร</p> <p>เพื่อใช้ในระบบสารบรรณอิเล็กทรอนิกส์</p> </div> <form class="form" id="myForm" onsubmit="submitForm()"> <div class="inputfield"> <label>คำนำหน้าชื่อ</label> <div class="custom_select"> <select id="prefix_name" name="prefix_name"> <option value="">เลือก</option> <option value="นายสัตวแพทย์">นายสัตวแพทย์</option> <option value="นาย">นาย</option> <option value="นางสาว">นางสาว</option> <option value="นาง">นาง</option> </select> </div> </div> <div class="inputfield"> <label>ชื่อ</label> <input type="text" class="input" id="first_name" name="first_name"> </div> <div class="inputfield"> <label>นามสกุล</label> <input type="text" class="input" id="last_name" name="last_name"> </div> <div class="inputfield"> <label>ชื่อภาษาอังกฤษ</label> <input type="text" class="input" id="first_name_eng" name="first_name_eng"> </div> <div class="inputfield"> <label>สกุลภาษาอังกฤษ</label> <input type="text" class="input" id="last_name_eng" name="last_name_eng"> </div> <div class="inputfield"> <label>ตำแหน่ง</label> <input type="text" class="input" id="job_itle" name="job_itle"> </div> <div class="inputfield"> <label>หน่วยงานที่สังกัด</label> <div class="custom_select"> <select id="department" name="department"> <option value="">เลือก</option> <option value="ศูนย์เทคโนโลยีสารสนเทศและการสื่อสาร">ศูนย์เทคโนโลยีสารสนเทศและการสื่อสาร</option> <option value="กองคลัง">กองคลัง</option> <option value="กองการเจ้าหน้าที่">กองการเจ้าหน้าที่</option> <option value="สำนักกฎหมาย">สำนักกฎหมาย</option> </select> </div> </div> <div class="inputfield"> <label>อีเมล</label> <input type="text" class="input" id="email" name="email"> </div> <p1> <center>โปรดลงลายมือชื่อภายในกรอบสี่เหลี่ยม</center> </p> <div> <div align="center"> <canvas id="sig2" height="100" width="260" class="signature-pad"></canvas> <div> <button type="button" class="btn" id="clearSig2">clear</button> <!-- <input type="submit" class="btn" id="send"></input> --> </div> </div> <div> <div class="inputfield"> <input type="submit" value="ลงทะเบียน" class="btn" id="send" name="image_data"> </div> </div> <script> var signaturePad; function setupSignatureBox() { var canvas = document.getElementById("sig2"); signaturePad = new SignaturePad(canvas); } function ClearSignature() { signaturePad.clear(); } function SendToDrive() { var imageData = signaturePad.toDataURL(); google.script.run.receiveSiganture(imageData); console.log(imageData); } document.getElementById("clearSig2").addEventListener("click", ClearSignature); document.getElementById("send").addEventListener("click", SendToDrive); document.addEventListener("DOMContentLoaded", setupSignatureBox); </script> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" integrity="sha384-fbbOQedDUMZZ5KreZpsbe1LCZPVmfTnH7ois6mU1QK+m14rQ1l2bGBq41eYeM/fS" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.0.0/dist/signature_pad.umd.min.js"></script> </form> </div> <script> function submitForm() { event.preventDefault() var obj = {} var formData = $('#myForm').serializeArray() formData.forEach(el => obj[el.name] = el.value) google.script.run.withSuccessHandler(() => { document.getElementById('myForm').reset() Swal.fire({ position: 'center', icon: 'success', title: 'บันทึกเรียบร้อยแล้ว', showConfirmButton: false, timer: 1500 }) }).saveData(obj) } </script> <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script> <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> </body> </html>
import express from 'express'; import { ProductStore } from '../models/product'; import { User, usersShopping } from '../models/user'; import supertest from 'supertest'; const app: express.Application = express(); const request = supertest(app); const product = new ProductStore(); const user = new usersShopping(); describe('Producct store', () => { it('Should have an index method', () => { expect(product.index).toBeDefined(); }); it('Should have an show method', () => { expect(product.show).toBeDefined(); }); it('Should have an create method', () => { expect(product.create).toBeDefined(); }); it('Get all products', async () => { const newProduct = { name: 'Product test', price: 1000, category: 'Phone', }; await product.create(newProduct); const products = await product.index(); expect(products.length).toBeGreaterThan(0); }); it('Get the product by id', async () => { const result = await product.show(1); expect(result).toEqual({ id: 1, name: 'Product test', price: 1000, category: 'Phone', }); }); it('Should be connect API success route', () => { request.get('/products').expect(200); }); it('Get all product by for API success route', () => { request.get('/products').expect(200); }); it('Get a product by for API success route', () => { request .get('/products/1') .send({ id: '1', }) .expect(200); }); it('Create a product for API success', () => { const userToken: User = { firstname: 'Duy', lastname: 'Ngo', username: 'ngoduy123', password: 'ngoduy123', }; const token: string = user.generateAccessToken(userToken); request .post('/products/create') .set('Authorization', `Bearer ${token}`) .send({ name: 'Product test', price: 1000, category: 'Phone', }) .expect(200); }); it('Get five products popular', async () => { const result = await product.getFivePopularProduct(); expect(result.length).not.toBeNaN(); }); });
import React, { useState,useEffect } from "react"; import FNHRecipoCard from "../../Components/FNHRecipoCard/index"; import { Grid } from "@mui/material"; import { Recipe } from "../../constants/index"; import styles from "./style.module.scss"; import FNHText from "../../Components/FNHText/index"; import { Box } from "@mui/system"; import AllFilltersIcon from "../../assets/icon/AllFilltersIcon"; import DateIcon from "../../assets/icon/DateIcon"; import { useDispatch,useSelector } from 'react-redux'; import { getAllRecipes, setRecipes } from '../../Redux/actions/recipeAction'; import axios from 'axios'; const Recipes = () => { const [nameFilter, setNameFilter] = useState(""); const [ingredientsFilter, setingredientsFilter] = useState(""); const [categoryFilter, setCategoryFilter] = useState(""); const dispatch = useDispatch(); const RecipeList = useSelector((state) => state.recipes.recipes); useEffect(() => { axios .get("http://localhost:9090/api/recipe") .then((response) => { const recipes = response.data; dispatch(setRecipes(recipes)); }) .catch((error) => { console.log("Error fetching recipes:", error); }); dispatch(getAllRecipes()); }, [dispatch]); console.log("RecipeList", RecipeList); return ( <Grid className={styles.SerchlistGrid}> {/* SearchBar and Filter Grid Start*/} <Box className={styles.HeaderText}> <FNHText text="Find Your Food Recipes..." color="#046380" textAlign="left" variant="h6" /> </Box> <Grid sx={{ justifyContent: "center", justifyItems: "center", alignItems: "center", }} className={styles.barGird} > <Grid className={styles.inputGrid}>{/* <FNHLiconInput /> */}</Grid> <Grid container className={styles.FilterGrid}> <Grid item> <Box sx={{ display: "flex", justifyContent: "center", justifyItems: "center", alignItems: "center", }} > <AllFilltersIcon fill="#1460BA" width="25" height="25" /> <input type="text" placeholder="Filter by name" value={nameFilter} onChange={(e) => setNameFilter(e.target.value)} style={{ padding: "8px", border: "1px solid #1460BA", borderRadius: "4px", fontSize: "16px", width: "100%", margin: "16px", }} /> </Box> </Grid> <Grid item> <Box sx={{ display: "flex", justifyContent: "center", justifyItems: "center", alignItems: "center", }} > <DateIcon fill="#1460BA" width="25" height="25" /> <input type="text" placeholder="Filter by ingredients" value={ingredientsFilter} onChange={(e) => setingredientsFilter(e.target.value)} style={{ padding: "8px", border: "1px solid #1460BA", borderRadius: "4px", fontSize: "16px", width: "100%", margin: "16px", }} /> </Box> </Grid> <Grid item> <Box sx={{ display: "flex", justifyContent: "center", justifyItems: "center", alignItems: "center", }} > <AllFilltersIcon fill="#1460BA" width="25" height="25" /> <input type="text" placeholder="Filter by category" value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)} style={{ padding: "8px", border: "1px solid #1460BA", borderRadius: "4px", fontSize: "16px", width: "100%", margin: "16px", }} /> </Box> </Grid> </Grid> </Grid> {/* SearchBar and Filter Grid End*/} <Grid className={styles.DataGrid}> <Grid sx={{ minHeight: "20rem", minWidth: "65%", display: "flex", flexDirection: "column", backgroundColor: "#EDF2F3", borderRadius: "1rem", margin: "1rem 0", }} xs={7} sm={7} md={7} lg={7} > <Box sx={{ display: "flex", justifyContent: "space-between", minHeight: "3rem", margin: "1rem 0", padding: "0 1rem", }} > <FNHText text="Food Recipes" color="#1460BA" textAlign="left" variant="h6" /> </Box> <Grid container spacing={7} sx={{ justifyContent: "center" }}> {RecipeList && RecipeList.filter((recipe) => { return ( recipe.name .toLowerCase() .includes(nameFilter.toLowerCase()) && recipe.ingredients.includes(ingredientsFilter) && recipe.category .toLowerCase() .includes(categoryFilter.toLowerCase()) ); }).map((recipe) => ( <Grid item key={recipe._id}> <FNHRecipoCard propertyId={recipe._id} name={recipe.name} ingredients={recipe.ingredients} recipeCate={recipe.category} backgroundImage={recipe.img} recipeDetails={recipe.desc} /> </Grid> ))} </Grid> </Grid> </Grid> </Grid> ); }; export default Recipes;
import { MoviesList } from 'components/MoviesList/MoviesList'; import React, { useEffect, useState } from 'react'; import { useSearchParams } from 'react-router-dom'; import { fetchSearchingMovies } from 'services/fetchAPI'; const Movies = () => { const [searchedMovies, setSearchedMovies] = useState([]); const [searchParams, setSearchParams] = useSearchParams(); const query = searchParams.get('query'); useEffect(() => { if (query) { const getSearchingMovies = async query => { try { const response = await fetchSearchingMovies(query); const searchingMovies = response.data.results; setSearchedMovies(searchingMovies); } catch (error) { console.error('Error fetching data:', error); } }; getSearchingMovies(query); } else { setSearchedMovies([]); } }, [query]); const handleSubmit = async e => { e.preventDefault(); setSearchParams({ query: e.target.elements.movie.value }); e.target.reset(); }; return ( <div> <form onSubmit={handleSubmit}> <input type="text" required name="movie" /> <button type="submit">Search</button> </form> {searchedMovies.length > 0 ? ( <MoviesList movies={searchedMovies} /> ) : null} </div> ); }; export default Movies;
// // libQuicklyView // #if os(iOS) import UIKit import libQuicklyCore protocol InputToolbarViewDelegate : AnyObject { func pressed(barItem: UIBarButtonItem) } public struct QInputToolbarActionItem : IQInputToolbarItem { public var barItem: UIBarButtonItem public var callback: () -> Void public init( text: String, callback: @escaping () -> Void ) { self.callback = callback self.barItem = UIBarButtonItem(title: text, style: .plain, target: nil, action: nil) } public init( image: QImage, callback: @escaping () -> Void ) { self.callback = callback self.barItem = UIBarButtonItem(image: image.native, style: .plain, target: nil, action: nil) } public init( systemItem: UIBarButtonItem.SystemItem, callback: @escaping () -> Void ) { self.callback = callback self.barItem = UIBarButtonItem(barButtonSystemItem: systemItem, target: nil, action: nil) } public func pressed() { self.callback() } } public struct QInputToolbarFlexibleSpaceItem : IQInputToolbarItem { public var barItem: UIBarButtonItem public init() { self.barItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) } public func pressed() { } } open class QInputToolbarView : IQInputToolbarView { public private(set) unowned var parentView: IQView? public var native: QNativeView { return self._view } public var isLoaded: Bool { return self._reuse.isLoaded } public var bounds: QRect { guard self.isLoaded == true else { return .zero } return QRect(self._view.bounds) } public var items: [IQInputToolbarItem] { didSet { guard self.isLoaded == true else { return } self._view.update(items: self.items) } } public var size: Float { didSet { guard self.isLoaded == true else { return } self._view.update(size: self.size) } } public var isTranslucent: Bool { didSet { guard self.isLoaded == true else { return } self._view.update(translucent: self.isTranslucent) } } public var barTintColor: QColor? { didSet { guard self.isLoaded == true else { return } self._view.update(barTintColor: self.barTintColor) } } public var contentTintColor: QColor { didSet { guard self.isLoaded == true else { return } self._view.update(contentTintColor: self.contentTintColor) } } public var color: QColor? { didSet { guard self.isLoaded == true else { return } self._view.update(color: self.color) } } private var _reuse: QReuseItem< InputToolbarView > private var _view: InputToolbarView { return self._reuse.content() } private var _onAppear: (() -> Void)? private var _onDisappear: (() -> Void)? public init( reuseBehaviour: QReuseItemBehaviour = .unloadWhenDisappear, reuseName: String? = nil, items: [IQInputToolbarItem], size: Float = 55, isTranslucent: Bool = false, barTintColor: QColor? = nil, contentTintColor: QColor = QColor(rgb: 0xffffff), color: QColor? = nil ) { self.items = items self.size = size self.isTranslucent = isTranslucent self.barTintColor = barTintColor self.contentTintColor = contentTintColor self.color = color self._reuse = QReuseItem(behaviour: reuseBehaviour, name: reuseName) self._reuse.configure(owner: self) } deinit { self._reuse.destroy() } public func loadIfNeeded() { self._reuse.loadIfNeeded() } public func size(available: QSize) -> QSize { return QSize(width: available.width, height: self.size) } public func appear(to view: IQView) { self.parentView = view self._onAppear?() } public func disappear() { self._reuse.disappear() self.parentView = nil self._onDisappear?() } @discardableResult public func items(_ value: [IQInputToolbarItem]) -> Self { self.items = value return self } @discardableResult public func size(available value: Float) -> Self { self.size = value return self } @discardableResult public func translucent(_ value: Bool) -> Self { self.isTranslucent = value return self } @discardableResult public func barTintColor(_ value: QColor?) -> Self { self.barTintColor = value return self } @discardableResult public func contentTintColor(_ value: QColor) -> Self { self.contentTintColor = value return self } @discardableResult public func color(_ value: QColor?) -> Self { self.color = value return self } @discardableResult public func onAppear(_ value: (() -> Void)?) -> Self { self._onAppear = value return self } @discardableResult public func onDisappear(_ value: (() -> Void)?) -> Self { self._onDisappear = value return self } } extension QInputToolbarView : InputToolbarViewDelegate { func pressed(barItem: UIBarButtonItem) { guard let item = self.items.first(where: { return $0.barItem == barItem }) else { return } item.pressed() } } #endif
import {Builder} from '@logi/base/ts/common/builder' import {Impl} from '@logi/base/ts/common/mapped_types' import {Node} from '@logi/src/lib/hierarchy/core' import {Filter} from './filter' /** * An internal product in the piping process in adviser. Simplify the * in all the information for provider to get candidates. */ export interface Trigger { /** * The text user editting which we used to find out the candidates. */ readonly text: string /** * The type to tell which providers should serves this trigger. */ readonly type: TriggerType /** * The hierachy node which adheres to the editor. * * Some providers need to know this information/ */ readonly node: Readonly<Node> readonly filters: readonly Readonly<Filter>[] readonly prefix: string readonly suffix: string readonly from: string } class TriggerImpl implements Impl<Trigger> { public text!: string public type!: TriggerType public node!: Readonly<Node> public prefix = '' public suffix = '' public from = '' public filters: readonly Readonly<Filter>[] = [] } export class TriggerBuilder extends Builder<Trigger, TriggerImpl> { public constructor(obj?: Readonly<Trigger>) { const impl = new TriggerImpl() if (obj) TriggerBuilder.shallowCopy(impl, obj) super(impl) } public text(text: string): this { this.getImpl().text = text return this } public type(type: TriggerType): this { this.getImpl().type = type return this } public node(node: Readonly<Node>): this { this.getImpl().node = node return this } public suffix(value: string): this { this.getImpl().suffix = value return this } public prefix(value: string): this { this.getImpl().prefix = value return this } public filters(value: readonly Readonly<Filter>[]): this { this.getImpl().filters = value return this } public from(value: string): this { this.getImpl().from = value return this } protected get daa(): readonly string[] { return TriggerBuilder.__DAA_PROPS__ } protected static __DAA_PROPS__: readonly string[] = [ 'text', 'type', 'node', ] } export const enum TriggerType { REFERENCE, PATH, FUNC_OR_REF, FUNCTION, DICT, SLICE, }
const taskInput = document.querySelector(".task-input input"), filters = document.querySelectorAll(".filters span"), clearAll = document.querySelector(".clear-btn"), taskBox = document.querySelector(".task-box"); let editId; let isEditedTask = false; let todos = JSON.parse(localStorage.getItem("todo-list")); filters.forEach(btn => { btn.addEventListener("click", () => { document.querySelector("span.active").classList.remove("active"); btn.classList.add("active"); showTodo(btn.id); }); }); function showTodo(filter){ let li = ""; if(todos){ todos.forEach((todo, id) =>{ let isCompleted = todo.status == "completed" ? "checked" : ""; if(filter == todo.status || filter == "all"){ li += `<li class="task flex"> <label for="${id}"> <input onclick="updateStatus(this)" type="checkbox" id="${id}" ${isCompleted}> <p class ="${isCompleted}">${todo.name}</p> </label> <div class="settings"> <i onclick="showMenu(this)" class="uil uil-ellipsis-h"></i> <ul class="task-menu"> <li onclick="editTask(${id}, '${todo.name}')"><i class="uil uil-pen">Edit</i></li> <li onclick="deleteTask(${id})"><i class="uil uil-trash-alt">Delete</i></li> </ul> </div> </li>`; } }); } taskBox.innerHTML = li || `<span>You don't have any task here</span>`; } showTodo("all"); function showMenu(selectedTask){ let taskMenu = selectedTask.parentElement.lastElementChild; taskMenu.classList.add("show"); document.addEventListener("click", e =>{ if(e.target.tagName != "I" || e.target != selectedTask){ taskMenu.classList.remove("show"); } }); } function editTask(taskId, taskName){ editId = taskId; isEditedTask = true; taskInput.value = taskName; } function deleteTask(deleteId){ todos.splice(deleteId, 1); localStorage.setItem("todo-list", JSON.stringify(todos)); showTodo("all"); } clearAll.addEventListener("click", () =>{ todos.splice(0, todos.length); localStorage.setItem("todo-list", JSON.stringify(todos)); showTodo(); }) function updateStatus(selectedTask){ let taskName = selectedTask.parentElement.lastElementChild; if(selectedTask.checked){ taskName.classList.add("checked"); todos[selectedTask.id]. status = "completed"; }else{ taskName.classList.remove("checked"); todos[selectedTask.id]. status = "pending"; } localStorage.setItem("todo-list", JSON.stringify(todos)); } taskInput.addEventListener("keyup", e =>{ let userTask = taskInput.value.trim(); if(e.key == "Enter" && userTask){ if(!isEditedTask){ if(!todos){ todos = []; } let taskInfo = {name : userTask, status: "pending"}; todos.push(taskInfo); } else{ isEditedTask = false; todos[editId].name = userTask; } //let todos = JSON.parse(localStorage.getItem("todo-list")); taskInput.value = " "; localStorage.setItem("todo-list", JSON.stringify(todos)); showTodo("all"); } });
package reversevowels func reverseVowels(s string) string { l := len(s) if l == 1 { return s } b := []byte(s) i, j := 0, l-1 for i < j { if isVowel(s[i]) && isVowel(s[j]) { b[i], b[j] = s[j], s[i] j-- i++ } if !isVowel(s[j]) { j-- continue } if !isVowel(s[i]) { i++ } } return string(b) } func isVowel(s byte) bool { return s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u' || s == 'A' || s == 'E' || s == 'I' || s == 'O' || s == 'U' } func reverseVowels_leet0ms(s string) string { arr := []rune(s) v := []int{} for i := range s { if isVowel2(arr[i]) { v = append(v, i) } } i, j := 0, len(v)-1 for i < j { i1 := v[i] i2 := v[j] arr[i1], arr[i2] = arr[i2], arr[i1] i++ j-- } return string(arr) } func isVowel2(r rune) bool { switch r { case 'a': return true case 'e': return true case 'i': return true case 'o': return true case 'u': return true case 'A': return true case 'E': return true case 'I': return true case 'O': return true case 'U': return true default: return false } return false }
<template> <v-container style="max-width: 1200px"> <h2 class="mb-4 label-title">外包廠商資料管理</h2> <v-divider class="mx-2 mt-5 mb-4" /> <v-row class="px-2 label-header"> <!-- 控制措施 --> <v-col cols="12" sm="4" md="3"> <h3 class="mb-1"> <v-icon class="mr-1 mb-1">mdi-bank</v-icon>單位 </h3> <v-select solo hide-details :items="selectdata" v-model="searchItem" /> </v-col> <v-col cols="12" sm="3" md="3" class="d-flex align-end"> <v-btn class="btn-search" dark large @click="goSearch"> <v-icon class="mr-1">mdi-magnify</v-icon>查詢 </v-btn> <v-btn dark large class="ml-2 btn-add" @click="goAdd"> <v-icon class="mr-1">mdi-plus</v-icon>新增 </v-btn> </v-col> <v-col cols="12"> <v-card> <v-data-table :headers="headers" :items="tableItems" :options.sync="pageOpt" disable-sort disable-filtering hide-default-footer class="theme-table" > <template v-slot:no-data> <span class="red--text subtitle-1">沒有資料</span> </template> <template v-slot:loading> <span class="red--text subtitle-1">資料讀取中...</span> </template> <template v-slot:item.a5="{item}"> <v-btn title="編輯" class="mr-2 btn-modify" small dark fab @click="goEdit(item.FlowID)" > <v-icon dark>mdi-pen</v-icon> </v-btn> <v-btn fab small class="btn-delete white--text" @click="goDelete(item.FlowID)"> <v-icon>mdi-delete</v-icon> </v-btn> </template> <template v-slot:footer="footer"> <Pagination :footer="footer" :pageOpt="pageOpt" @chPage="chPage" /> </template> </v-data-table> </v-card> </v-col> <!-- 編輯資料 modal --> <v-dialog v-model="Edit" max-width="900px"> <OutsourcDataEdit :flowId="detailFlow" :inType="inType" :key="componentKey" @close="close"></OutsourcDataEdit> </v-dialog> <!-- 刪除 modal --> <v-dialog v-model="Delete" persistent max-width="290"> <v-card class="theme-del-card"> <v-card-title class="white--text px-4 py-1 headline">確認是否刪除?</v-card-title> <v-card-actions> <v-spacer></v-spacer> <v-btn class="btn-close white--text" @click="close">取消</v-btn> <v-btn class="btn-add white--text" :loading="isLoading" @click="Del">刪除</v-btn> </v-card-actions> </v-card> </v-dialog> </v-row> </v-container> </template> <script> import Pagination from "@/components/Pagination.vue"; import { mapState, mapActions } from 'vuex' import { getNowFullTime,decodeObject } from '@/assets/js/commonFun' import { fetchOrganization } from '@/apis/organization' import { outsourceQueryList,outsourceDelete } from '@/apis/materialManage/outsource.js' import OutsourcDataEdit from '@/views/mmis/OutsourcDataEdit' export default { data: () => ({ Add: false, Edit: false, Delete: false, searchItem: "", pageOpt: { page: 1 }, tableItems: [], selectdata: [], headers: [ { text: "項次", value: "id", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, { text: "負責單位", value: "DepartName", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, { text: "廠商名稱", value: "VendorName", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, { text: "負責人", value: "Name", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, { text: "電話", value: "TEL", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, { text: "統一編號", value: "UniNumber", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, { text: "備註", value: "Memo", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, { text: "修改、刪除", value: "a5", align: "center", divider: true, class: "subtitle-1 white--text font-weight-bold", }, ], isLoading: false, detailFlow: "", inType: "", componentKey: 0, }), components: { Pagination, OutsourcDataEdit, }, mounted: function() { this.getOrg() this.goSearch() }, computed: { ...mapState ('user', { userData: state => state.userData, // 使用者基本資料 }), }, methods: { ...mapActions('system', [ 'chMsgbar', // messageBar 'chLoadingShow' // 切換 loading 圖顯示 ]), goSearch() { this.chLoadingShow({show:true}) outsourceQueryList({ DepartName: this.searchItem, ClientReqTime: getNowFullTime(), // client 端請求時間 OperatorID: this.userData.UserId, // 操作人id }).then(res => { if (res.data.ErrorCode == 0) { this.tableItems = decodeObject(res.data.VendorList) this.tableItems.forEach((e,i)=>{ e.id=i+1 }) } else { sessionStorage.errData = JSON.stringify({ errCode: res.data.Msg, msg: res.data.Msg }) this.$router.push({ path: '/error' }) } }).catch( err => { this.chMsgbar({ success: false, msg: '伺服器發生問題,資料讀取失敗' }) }).finally(() => { this.chLoadingShow({ show: false}) }) }, getOrg() { this.chLoadingShow({show:true}) fetchOrganization({ ClientReqTime: getNowFullTime(), // client 端請求時間 OperatorID: this.userData.UserId, // 操作人id }).then(res => { if (res.data.ErrorCode == 0) { this.selectdata = decodeObject(res.data.user_depart_list_group_1.map(item=>item.DepartName)) this.selectdata = ["" , ...this.selectdata] } else { sessionStorage.errData = JSON.stringify({ errCode: res.data.Msg, msg: res.data.Msg }) this.$router.push({ path: '/error' }) } }).catch( err => { this.chMsgbar({ success: false, msg: '伺服器發生問題,資料讀取失敗' }) }).finally(() => { this.chLoadingShow({ show: false}) }) }, goAdd() { this.componentKey += 1 this.inType = "add" this.Edit = true }, goEdit(flow) { this.componentKey += 1 this.detailFlow = flow this.inType = "edit" this.Edit = true }, goDelete(flow) { this.detailFlow = flow; this.Delete = true }, Del() { this.isLoading = true outsourceDelete({ FlowID: this.detailFlow, ClientReqTime: getNowFullTime(), // client 端請求時間 OperatorID: this.userData.UserId, // 操作人id }).then(res=>{ if (res.data.ErrorCode == 0) { this.chMsgbar({ success: true, msg: '資料刪除成功' }) } else { sessionStorage.errData = JSON.stringify({ errCode: res.data.Msg, msg: res.data.Msg }) this.$router.push({ path: '/error' }) } }).catch( err => { this.chMsgbar({ success: false, msg: '伺服器發生問題,資料刪除失敗' }) }).finally(() => { this.isLoading = false this.close() }) }, // 更換頁數 chPage(n) { this.pageOpt.page = n; }, close() { this.goSearch() this.Add = false; this.Edit = false; this.Delete = false; }, }, created() {}, }; </script>
# This script uses your bearer token to authenticate and retrieve the Usage require 'json' require 'typhoeus' # The code below sets the bearer token from your environment variables # To set environment variables on Mac OS X, run the export command below from the terminal: # export BEARER_TOKEN='YOUR-TOKEN' bearer_token = ENV["BEARER_TOKEN"] usage_tweets_url = "https://api.twitter.com/2/usage/tweets" def usage_tweets(url, bearer_token) options = { method: 'get', headers: { "User-Agent": "v2UsageTweetsRuby", "Authorization": "Bearer #{bearer_token}" } } request = Typhoeus::Request.new(url, options) response = request.run return response end response = usage_tweets(usage_tweets_url, bearer_token) puts response.code, JSON.pretty_generate(JSON.parse(response.body))
import {yupResolver} from '@hookform/resolvers/yup'; import {Popover, Spin} from 'antd'; import Form from 'antd/lib/form/Form'; import PropTypes from 'prop-types'; import React, {useEffect, useState} from 'react'; import {useForm} from 'react-hook-form'; import * as yup from 'yup'; import SelectField from '~/components/FormControl/SelectField'; import {optionCommonPropTypes} from '~/utils/proptypes'; const AvailableScheduleForm = (props) => { const { isLoading, handleGetAvailableSchedule, optionListForGetAvailableSchedule, } = props; const [showForm, setShowForm] = useState(false); const funcShowFilter = () => { showForm ? setShowForm(false) : setShowForm(true); }; const schema = yup.object().shape({ StudyTimeID: yup .array() .min(1, 'Bạn phải chọn ít nhất 1 ca học') .required('Bạn không được để trống'), RoomID: yup .array() .min(1, 'Bạn phải chọn ít nhất 1 phòng học') .required('Bạn không được để trống'), }); const defaultValuesInit = { RoomID: undefined, StudyTimeID: undefined, }; const form = useForm({ defaultValues: defaultValuesInit, resolver: yupResolver(schema), }); const checkHandleGetAvailableSchedule = (data) => { if (!handleGetAvailableSchedule) return; handleGetAvailableSchedule(data).then((res) => { if (res) { funcShowFilter(); } }); }; useEffect(() => { const {rooms, studyTimes} = optionListForGetAvailableSchedule; if (rooms.length && studyTimes.length) { const roomSelected = rooms .filter((r) => r.options.select) .map((r) => r.value); const studyTimesSelected = studyTimes .filter((r) => r.options.select) .map((r) => r.value); form.reset({ RoomID: roomSelected, StudyTimeID: studyTimesSelected, }); } }, [optionListForGetAvailableSchedule]); const content = ( <div className="available-schedule-course-form"> <Form layout="vertical" onFinish={form.handleSubmit(checkHandleGetAvailableSchedule)} > <div className="row"> <div className="col-12"> <SelectField form={form} name="RoomID" optionList={optionListForGetAvailableSchedule.rooms} mode="multiple" label="Phòng" isLoading={isLoading.type === 'FETCH_COURSE' && isLoading.status} /> </div> <div className="col-12"> <SelectField form={form} name="StudyTimeID" optionList={optionListForGetAvailableSchedule.studyTimes} mode="multiple" label="Ca học" isLoading={isLoading.type === 'FETCH_COURSE' && isLoading.status} /> </div> <div className="col-12 mt-1"> <button type="submit" className="btn btn-primary" disabled={isLoading.type == 'FETCH_SCHEDULE' && isLoading.status} > Gửi {isLoading.type == 'FETCH_SCHEDULE' && isLoading.status && ( <Spin className="loading-base" /> )} </button> </div> </div> </Form> </div> ); return ( <Popover placement="bottomRight" content={content} trigger="click" visible={showForm} onVisibleChange={funcShowFilter} overlayClassName="filter-popover" > <button className="btn btn-primary">Tải lịch học</button> </Popover> ); }; AvailableScheduleForm.propTypes = { isLoading: PropTypes.shape({ type: PropTypes.string.isRequired, status: PropTypes.bool.isRequired, }), handleGetAvailableSchedule: PropTypes.func, optionListForGetAvailableSchedule: PropTypes.shape({ rooms: optionCommonPropTypes, studyTimes: optionCommonPropTypes, }), }; AvailableScheduleForm.defaultProps = { isLoading: {type: '', status: false}, handleGetAvailableSchedule: null, optionListForGetAvailableSchedule: { rooms: [], studyTimes: [], }, }; export default AvailableScheduleForm;
import "bootstrap"; import React from "react"; import * as ReactDOM from "react-dom"; import * as BCommon from "@/bookmarks/Common"; import * as Search from "@/bookmarks/Search"; import * as Read from "@/bookmarks/Read"; import * as Write from "@/bookmarks/Write"; import * as BNative from "@/bookmarks/Native"; import { Option, None, Some, asOptional } from "@/common/Function"; import * as StateStorage from "@/storage/StateStorage"; import * as Storage from "@/storage/Storage"; import * as State from "@/state/State"; import { newIFuzzySearcher } from "@/common/Search"; import * as CommonComponent from "@/common/Component"; import * as OptionComponent from "@/optionstate/OptionComponent"; import { BaseError } from "@/common/Err"; import { ItemList } from "@/popup/Item"; import { ItemCount, SearchDuration, SearchBox } from "@/popup/Search"; import { DataModal } from "@/popup/Data"; import * as Folder from "@/bookmarks/Folder"; import "@/popup/Popup.scss"; interface IContentProps { storage: StateStorage.IOptionStateStorage; storageListener: Storage.IStorageAreaListener; searcher: Search.ISearcher; folderSearcher: Folder.ISearcher; remover: Write.IRemover; creator: Write.ICreator; scanner: Read.IScanner; newBuilder: () => State.IOptionStateBuilder; } interface IContentState { searchResult: BCommon.INodeList; error: Option<Error>; searchDuration: Option<number>; folders: BCommon.INodeList; } class Content extends React.Component<IContentProps, IContentState> { private word: string; constructor(props: IContentProps) { super(props); this.state = { searchResult: [], error: None, searchDuration: None, folders: [], }; this.word = ""; this.props.storageListener.add(() => this.executeSearch()); } private newSearchDuration(): Option<JSX.Element> { if (!this.state.searchDuration.ok) { return None; } return Some( <SearchDuration durationMilliSec={this.state.searchDuration.value} /> ); } private newQuery(word: string, state: State.IOptionState): Search.IQuery { return { word: word, queryType: state.queryType, queryTargetType: state.queryTargetType, sortType: state.sortType, sortOrderType: state.sortOrderType, filters: state.filters.map(this.fixFilter), querySourceMaxResult: asOptional(state.querySourceMaxResult), queryMaxResult: asOptional(state.queryMaxResult), }; } private fixFilter(f: Search.FilterType): Search.FilterType { if (f.kind == "before") { return { kind: f.kind, timestamp: f.timestamp + 24 * 60 * 60, // add 1 day, include end date }; } return f; } private getFolders(): void { /* * fetch all folders. * number of folders is relatively smaller than bookmarks * so leave filtering to caller */ this.props.folderSearcher .search({ word: "", }) .then((r) => this.setState({ folders: r, }) ) .catch((e) => this.handleCaughtError(e)); } private executeSearch(): void { const startTime = performance.now(); // measure elapsed time this.props.storage .read() .then((state) => this.props.searcher.search(this.newQuery(this.word, state)) ) .then((result) => { this.setState({ searchResult: result.filter((r) => r.info.url), // exclude parent searchDuration: Some(performance.now() - startTime), }); }) .catch((e) => this.handleCaughtError(e)); } private newAlert(): Option<JSX.Element> { if (!this.state.error.ok) { return None; } // reset error on state when closed const onClose = () => this.setState({ error: None, }); const e = this.state.error.value; const message = ( <div> <b>{e.name}</b> {e.message} </div> ); const c = ( <div className="col-9"> <CommonComponent.Alert id="popup-alert" message={message} onClose={() => onClose()} /> </div> ); return Some(c); } private handleCaughtError(e: unknown): void { if (!(e instanceof BaseError)) { throw e; } this.setState({ error: Some(e), }); } private genHandleItemOnClose(id: BCommon.NodeId): () => void { return () => { this.props.remover.remove(id); this.executeSearch(); }; } private handleSearchBoxChange(word: string): void { this.word = word; this.executeSearch(); this.getFolders(); } render(): JSX.Element { const opt = ( <OptionComponent.OptionTable store={this.props.storage} newBuilder={this.props.newBuilder} folders={this.state.folders} additionalClassName="table-sm" /> ); const searchResult = this.state.searchResult; const alert = this.newAlert(); const searchDuration = this.newSearchDuration(); const dataModal = ( <DataModal id="data-modal" triggerTitle="Operation" title="Batch Operation" items={this.state.searchResult} onClose={() => this.executeSearch()} remover={this.props.remover} creator={this.props.creator} folders={this.state.folders} /> ); return ( <div className="container-fluid"> <header className="popup-header sticky-top"> <div className="row"> <div className="col-8 search-wrapper"> <SearchBox onChange={(w) => this.handleSearchBoxChange(w)} /> </div> <div className="col-2 popover-wrapper"> <CommonComponent.Popover id="popover-bmctl-option" content={opt} /> </div> <div className="col-2 popover-data-modal">{dataModal}</div> </div> <div className="row result-info justify-content-between"> <div className="col"> <ItemCount count={searchResult.length} /> {searchDuration.ok && searchDuration.value} </div> </div> <div className="row result-error">{alert.ok && alert.value}</div> </header> <div className="row result"> <div className="col"> <ItemList items={searchResult} genItemOnClose={(id) => this.genHandleItemOnClose(id)} /> </div> </div> </div> ); } } chrome.tabs.query({ active: true, currentWindow: true }, (_) => { const storage = StateStorage.newIOptionStateStorage( Storage.newLocalStorageArea(), State.newIOptionStateBuilder ); const storageListener = Storage.newIStorageAreaListener(); const api = BNative.newIBookmarksAPI(); const scanner = Read.newIScanner(api); const remover = Write.newIRemover(api); const creator = Write.newICreator(api); const folders = Folder.newISearcher( scanner, newIFuzzySearcher(["info.path.str"]) ); const searcher = Search.newISearcher( scanner, newIFuzzySearcher(["info.title", "info.url"]) ); ReactDOM.render( <Content storage={storage} searcher={searcher} folderSearcher={folders} remover={remover} creator={creator} scanner={scanner} storageListener={storageListener} newBuilder={State.newIOptionStateBuilder} />, document.getElementById("popup") ); });
<div class="card-body floating-label"> @include('partials.errors') <div class="row"> <div class="col-sm-6"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> @if(isset($user) && $user->image) <img src="{{ thumbnail(200, $user) }}" data-src="{{ thumbnail(200, $user) }}" class="preview" alt="avatar" width="200" height="200"> @else <img src="{{ asset(config('paths.placeholder.avatar')) }}" data-src="{{ asset(config('paths.placeholder.avatar')) }}" class="preview" alt="avatar" width="200" height="200"> @endif </div> </div> </div> <div class="col-sm-6"> <div class="row"> <div class="col-sm-12"> <div class="form-group"> {{ Form::text('username', old('username'),['class' => 'form-control', 'required']) }} {{ Form::label('username', 'Username') }} </div> </div> <div class="col-sm-12"> <div class="form-group"> {{ Form::email('email', old('email'),['class' => 'form-control', 'required']) }} {{ Form::label('email', 'Email') }} </div> </div> </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ Form::text('first_name', old('first_name'),['class' => 'form-control']) }} {{ Form::label('first_name', 'First Name') }} </div> </div> <div class="col-sm-6"> <div class="form-group"> {{ Form::text('last_name', old('last_name'),['class' => 'form-control']) }} {{ Form::label('last_name', 'Last Name') }} </div> </div> </div> @unless(isset($user)) <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ Form::password('password', ['class' => 'form-control', 'required']) }} {{ Form::label('password', 'Password') }} </div> </div> <div class="col-sm-6"> <div class="form-group"> {{ Form::password('password_confirmation', ['class' => 'form-control', 'required']) }} {{ Form::label('password_confirmation', 'Confirm Password') }} </div> </div> </div> @endunless <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ Form::text('address', old('address'),['class' => 'form-control']) }} {{ Form::label('address', 'Address') }} </div> </div> <div class="col-sm-6"> <div class="form-group"> {{ Form::text('phone', old('phone'),['class' => 'form-control']) }} {{ Form::label('phone', 'Phone') }} </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group"> @if($roles->isEmpty()) {{ trans('messages.empty', ['entity' => 'Roles']) }} @else {{ Form::select('role', $roles, isset($user) ? $user->roles->first()->id : old('role'), ['class' => 'form-control', 'required']) }} {{ Form::label('role', 'Role') }} @endif </div> </div> <div class="col-sm-6"> <div class="form-group"> {{ Form::file('image', ['class' => 'image-input', 'accept' => 'image/*', 'data-msg' => trans('validation.mimes', ['attribute' => 'avatar', 'values' => 'png, jpeg'])]) }} {{ Form::label('image', 'Avatar') }} </div> </div> </div> </div> <div class="card-actionbar"> <div class="card-actionbar-row"> <button type="reset" class="btn btn-flat ink-reaction">Reset</button> <button type="submit" class="btn btn-flat btn-primary ink-reaction">Save</button> </div> </div>
#include <TFT_eSPI.h> // Adapted by Bodmer to work with a NodeMCU and ILI9341 or ST7735 display. // // This code currently does not "blink" the eye! // // Library used is here: // https://github.com/Bodmer/TFT_eSPI // // To do, maybe, one day: // 1. Get the eye to blink // 2. Add another screen for another eye // 3. Add varaible to set how wide open the eye is // 4. Add a reflected highlight to the cornea // 5. Add top eyelid shaddow to eye surface // 6. Add aliasing to blur mask edge // // With one lidded eye drawn the code runs at 28-33fps (at 27-40MHz SPI clock) // which is quite reasonable. Operation at an 80MHz SPI clock is possible but // the display may not be able to cope with a clock rate that high and the // performance improvement is small. Operate the ESP8266 at 160MHz for best // frame rate. Note the images are stored in SPI FLASH (PROGMEM) so performance // will be constrained by the increased memory access time. // Original header for this sketch is below. Note: the technical aspects of the // text no longer apply to this modified version of the sketch: /* //-------------------------------------------------------------------------- // Uncanny eyes for PJRC Teensy 3.1 with Adafruit 1.5" OLED (product #1431) // or 1.44" tft.Lcd LCD (#2088). This uses Teensy-3.1-specific features and // WILL NOT work on normal Arduino or other boards! Use 72 MHz (Optimized) // board speed -- OLED does not work at 96 MHz. // // Adafruit invests time and resources providing this open source code, // please support Adafruit and open-source hardware by purchasing products // from Adafruit! // // Written by Phil Burgess / Paint Your Dragon for Adafruit Industries. // MIT license. SPI FIFO insight from Paul Stoffregen's ILI9341_t3 library. // Inspired by David Boccabella's (Marcwolf) hybrid servo/OLED eye concept. //-------------------------------------------------------------------------- */ // Bodmer/ESP8266_uncannyEyes/ESP8266_uncannyEyes.ino // https://github.com/Bodmer/ESP8266_uncannyEyes/blob/master/ESP8266_uncannyEyes.ino // graphics : catEye.h,terminatorEye.h,doeEye.h,naugaEye.h,newtEye.h,owlEye.h // https://github.com/adafruit/Uncanny_Eyes/tree/master/uncannyEyes/graphics // Electronic Animated Eyes using Teensy 3.1/3.2 // https://learn.adafruit.com/animated-electronic-eyes-using-teensy-3-1?view=all // adafruit/Uncanny_Eyes : // https://github.com/adafruit/Uncanny_Eyes/tree/master/uncannyEyes #include <pgmspace.h> #include "graphics/mdefaultEye.h" // Standard human-ish hazel eye #define DISPLAY_DC 16 // Data/command pin for BOTH displays #define DISPLAY_RESET 23 // Reset pin for BOTH displays #define SELECT_L_PIN 5 // LEFT eye chip select pin //#define SELECT_R_PIN 5 // RIGHT eye chip select pin // comment out M5StickC // INPUT CONFIG (for eye motion -- enable or comment out as needed) -------- // The ESP8266 is rather constrained here as it only has one analogue port. // An I2C ADC could be used for more analogue channels #define JOYSTICK_X_PIN 26 // Analog pin for eye horiz pos (else auto) #define JOYSTICK_Y_PIN 27 // Analog pin for eye vert position (") #define JOYSTICK_X_FLIP // If set, reverse stick X axis #define JOYSTICK_Y_FLIP // If set, reverse stick Y axis #define TRACKING // If enabled, eyelid tracks pupil //#define IRIS_PIN 00 // Photocell or potentiometer (else auto iris) //#define IRIS_PIN_FLIP 37 // If set, reverse reading from dial/photocell #define IRIS_SMOOTH // If enabled, filter input from IRIS_PIN #define IRIS_MIN 140 // Clip lower analogRead() range from IRIS_PIN #define IRIS_MAX 160 //260 // Clip upper " #define WINK_L_PIN 35 // Pin for LEFT eye wink button #define BLINK_PIN 35 // Pin for blink button (BOTH eyes) //#define WINK_R_PIN 35 // Pin for RIGHT eye wink button #define AUTOBLINK // If enabled, eyes blink autonomously // Probably don't need to edit any config below this line, ----------------- // unless building a single-eye project (pendant, etc.), in which case one // of the two elements in the eye[] array further down can be commented out. // Eye blinks are a tiny 3-state machine. Per-eye allows winks + blinks. #define NOBLINK 0 // Not currently engaged in a blink #define ENBLINK 1 // Eyelid is currently closing #define DEBLINK 2 // Eyelid is currently opening typedef struct { int8_t pin; // Optional button here for indiv. wink uint8_t state; // NOBLINK/ENBLINK/DEBLINK int32_t duration; // Duration of blink state (micros) uint32_t startTime; // Time (micros) of last state change } eyeBlink; struct { uint8_t cs; // Chip select pin eyeBlink blink; // Current blink state } eye[] = { SELECT_L_PIN, { WINK_L_PIN, NOBLINK } //, // SELECT_R_PIN, { WINK_R_PIN, NOBLINK } }; TFT_eSPI tft = TFT_eSPI(135, 240); // Invoke custom library #define NUM_EYES 1 //2 uint32_t fstart = 0; // start time to improve frame rate calculation at startup const bool isSerial = true; int prevEyeX = 0; int prevEyeY = 0; // INITIALIZATION -- runs once at startup ---------------------------------- void setup(void) { tft.init(); Serial.begin(115200); //Wire.begin();if(digitalRead(39)==0){updateFromFS(SD);ESP.restart();}//SD UPdate uint8_t e = 0; //dac_output_disable(DAC_CHANNEL_1); tft.fillScreen(TFT_BLACK); tft.setRotation(3); fstart = millis() - 1; // Subtract 1 to avoid divide by zero later pinMode(35, INPUT); //pinMode(0, INPUT);pinMode(39, INPUT); } // EYE-RENDERING FUNCTION -------------------------------------------------- #define BUFFER_SIZE 256 // 64 to 512 seems optimum = 30 fps for default eye void drawEye( // Renders one eye. Inputs must be pre-clipped & valid. // Use native 32 bit variables where possible as this is 10% faster! uint8_t e, // Eye array index; 0 or 1 for left/right uint32_t iScale, // Scale factor for iris uint32_t scleraX, // First pixel X offset into sclera image uint32_t scleraY, // First pixel Y offset into sclera image uint32_t uT, // Upper eyelid threshold value uint32_t lT) { // Lower eyelid threshold value uint32_t screenX, screenY, scleraXsave; int32_t irisX, irisY; uint32_t p, a; uint32_t d; uint32_t pixels = 0; uint16_t pbuffer[BUFFER_SIZE]; // This one needs to be 16 bit // Set up raw pixel dump to entire screen. Although such writes can wrap // around automatically from end of rect back to beginning, the region is // reset on each frame here in case of an SPI glitch. // tft.setAddrWindow(x axis, y axis, Horizontal width, Vertical width); tft.setAddrWindow(tft.width() / 2 - 75, tft.height() / 2 - 75, SCREEN_WIDTH, SCREEN_HEIGHT); //if (e == 1){ tft.setAddrWindow (192,0,128,128);} // Now just issue raw 16-bit values for every pixel... scleraXsave = scleraX; // Save initial X value to reset on each line irisY = scleraY - (SCLERA_HEIGHT - IRIS_HEIGHT) / 2; for (screenY = 0; screenY < SCREEN_HEIGHT; screenY++, scleraY++, irisY++) { scleraX = scleraXsave; irisX = scleraXsave - (SCLERA_WIDTH - IRIS_WIDTH) / 2; for (screenX = 0; screenX < SCREEN_WIDTH; screenX++, scleraX++, irisX++) { if ((pgm_read_byte(lower + screenY * SCREEN_WIDTH + screenX) <= lT) || (pgm_read_byte(upper + screenY * SCREEN_WIDTH + screenX) <= uT)) { //Covered by eyelid p = 0; } else if ((irisY < 0) || (irisY >= IRIS_HEIGHT) || (irisX < 0) || (irisX >= IRIS_WIDTH)) { // In sclera p = pgm_read_word(sclera + scleraY * SCLERA_WIDTH + scleraX); } else { // Maybe iris... p = pgm_read_word(polar + irisY * IRIS_WIDTH + irisX); // Polar angle/dist d = (iScale * (p & 0x7F)) / 128; // Distance (Y) if (d < IRIS_MAP_HEIGHT) { // Within iris area a = (IRIS_MAP_WIDTH * (p >> 7)) / 512; // Angle (X) p = pgm_read_word(iris + d * IRIS_MAP_WIDTH + a); // Pixel = iris } else { // Not in iris p = pgm_read_word(sclera + scleraY * SCLERA_WIDTH + scleraX); //Pixel= clear } } *(pbuffer + pixels++) = p >> 8 | p << 8; if (pixels >= BUFFER_SIZE) { yield(); tft.pushColors((uint8_t*)pbuffer, pixels * 2); pixels = 0; } //drawEye } } if (pixels) { tft.pushColors(pbuffer, pixels); pixels = 0; } } // EYE ANIMATION ----------------------------------------------------------- const uint8_t ease[] = { // Ease in/out curve for eye movements 3*t^2-2*t^3 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, // T 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7, 8, 9, 9, 10, 10, // h 11, 12, 12, 13, 14, 15, 15, 16, 17, 18, 18, 19, 20, 21, 22, 23, // x 24, 25, 26, 27, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, // 2 40, 41, 42, 44, 45, 46, 47, 48, 50, 51, 52, 53, 54, 56, 57, 58, // A 60, 61, 62, 63, 65, 66, 67, 69, 70, 72, 73, 74, 76, 77, 78, 80, // l 81, 83, 84, 85, 87, 88, 90, 91, 93, 94, 96, 97, 98, 100, 101, 103, // e 104, 106, 107, 109, 110, 112, 113, 115, 116, 118, 119, 121, 122, 124, 125, 127, // c 128, 130, 131, 133, 134, 136, 137, 139, 140, 142, 143, 145, 146, 148, 149, 151, // J 152, 154, 155, 157, 158, 159, 161, 162, 164, 165, 167, 168, 170, 171, 172, 174, // a 175, 177, 178, 179, 181, 182, 183, 185, 186, 188, 189, 190, 192, 193, 194, 195, // c 197, 198, 199, 201, 202, 203, 204, 205, 207, 208, 209, 210, 211, 213, 214, 215, // o 216, 217, 218, 219, 220, 221, 222, 224, 225, 226, 227, 228, 228, 229, 230, 231, // b 232, 233, 234, 235, 236, 237, 237, 238, 239, 240, 240, 241, 242, 243, 243, 244, // s 245, 245, 246, 246, 247, 248, 248, 249, 249, 250, 250, 251, 251, 251, 252, 252, // o 252, 253, 253, 253, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255 }; // n #ifdef AUTOBLINK uint32_t timeOfLastBlink = 0L, timeToNextBlink = 0L; #endif void frame( // Process motion for a single frame of left or right eye uint32_t iScale) { // Iris scale (0-1023) passed in static uint32_t frames = 0; // Used in frame rate calculation static uint8_t eyeIndex = 0; // eye[] array counter int32_t eyeX, eyeY; uint32_t t = micros(); // Time at start of function // Serial.print((++frames * 1000) / (millis() - fstart)); // Serial.println("fps"); // Show frame rate if (++eyeIndex >= NUM_EYES) eyeIndex = 0; // Cycle through eyes, 1 per call // Read X/Y from joystick, constrain to circle int16_t dx, dy; int32_t d; if (isSerial) { if (Serial.available()) { eyeX = (Serial.readStringUntil(',').toFloat() * 1024) / 640; eyeY = (Serial.readStringUntil('\n').toFloat() * 1024) / 480; prevEyeX = eyeX; prevEyeY = eyeY; Serial.printf("%d, %d\n", eyeX, eyeY); } else { eyeX = prevEyeX; eyeY = prevEyeY; } #ifdef JOYSTICK_X_FLIP eyeX = 1023 - eyeX; #endif #ifdef JOYSTICK_Y_FLIP eyeY = 1023 - eyeY; #endif dx = (eyeX * 2) - 1023; // A/D exact center is at 511.5. Scale coords dy = (eyeY * 2) - 1023; // X2 so range is -1023 to +1023 w/center at 0. if ((d = (dx * dx + dy * dy)) > (1023 * 1023)) { // Outside circle d = (int32_t)sqrt((float)d); // Distance from center eyeX = ((dx * 1023 / d) + 1023) / 2; // Clip to circle edge, eyeY = ((dy * 1023 / d) + 1023) / 2; // scale back to 0-1023 } } else { // Autonomous X/Y eye motion // Periodically initiates motion to a new random point, random speed, // holds there for random period until next motion. static boolean eyeInMotion = false; static int32_t eyeOldX = 512, eyeOldY = 512, eyeNewX = 512, eyeNewY = 512; static uint32_t eyeMoveStartTime = 0L; static int32_t eyeMoveDuration = 0L; int32_t dt = t - eyeMoveStartTime; // uS elapsed since last eye event if (eyeInMotion) { // Currently moving? if (dt >= eyeMoveDuration) { // Time up? Destination reached. eyeInMotion = false; // Stop moving eyeMoveDuration = random(3000000L); // 0-3 sec stop eyeMoveStartTime = t; // Save initial time of stop eyeX = eyeOldX = eyeNewX; // Save position eyeY = eyeOldY = eyeNewY; } else { // Move time's not yet fully elapsed -- interpolate position int16_t e = ease[255 * dt / eyeMoveDuration] + 1; // Ease curve eyeX = eyeOldX + (((eyeNewX - eyeOldX) * e) / 256); // Interp X eyeY = eyeOldY + (((eyeNewY - eyeOldY) * e) / 256); // and Y } } else { // Eye stopped eyeX = eyeOldX; eyeY = eyeOldY; if (dt > eyeMoveDuration) { // Time up? Begin new move. int16_t dx, dy; uint32_t d; do { // Pick new dest in circle eyeNewX = random(1024); eyeNewY = random(1024); dx = (eyeNewX * 2) - 1023; dy = (eyeNewY * 2) - 1023; } while ((d = (dx * dx + dy * dy)) > (1023 * 1023)); // Keep trying eyeMoveDuration = random(50000, 150000); // ~1/14sec //random(72000,144000); // ~1/ 7sec eyeMoveStartTime = t; // Save initial time of move eyeInMotion = true; // Start move on next frame } } } // Blinking #ifdef AUTOBLINK // Similar to the autonomous eye movement above -- blink start times // and durations are random (within ranges). if ((t - timeOfLastBlink) >= timeToNextBlink) { // Start new blink? timeOfLastBlink = t; uint32_t blinkDuration = random(36000, 72000); // ~1/28 - ~1/14 sec // Set up durations for both eyes (if not already winking) for (uint8_t e = 0; e < NUM_EYES; e++) { if (eye[e].blink.state == NOBLINK) { eye[e].blink.state = ENBLINK; eye[e].blink.startTime = t; eye[e].blink.duration = blinkDuration; } } timeToNextBlink = blinkDuration * 3 + random(4000000); } #endif if (eye[eyeIndex].blink.state) { // Eye currently blinking? // Check if current blink state time has elapsed if ((t - eye[eyeIndex].blink.startTime) >= eye[eyeIndex].blink.duration) { // Yes -- increment blink state, unless... if ((eye[eyeIndex].blink.state == ENBLINK) && // Enblinking and... ((digitalRead(BLINK_PIN) == LOW) || // blink or wink held... digitalRead(eye[eyeIndex].blink.pin) == LOW)) { // Don't advance state yet -- eye is held closed instead } else { // No buttons, or other state... if (++eye[eyeIndex].blink.state > DEBLINK) { // Deblinking finished? eye[eyeIndex].blink.state = NOBLINK; // No longer blinking } else { // Advancing from ENBLINK to DEBLINK mode eye[eyeIndex].blink.duration *= 2; //DEBLINK is 1/2 ENBLINK speed eye[eyeIndex].blink.startTime = t; } } } } else { // Not currently blinking...check buttons! if (digitalRead(BLINK_PIN) == LOW) { // Manually-initiated blinks have random durations like auto-blink uint32_t blinkDuration = random(36000, 72000); for (uint8_t e = 0; e < NUM_EYES; e++) { if (eye[e].blink.state == NOBLINK) { eye[e].blink.state = ENBLINK; eye[e].blink.startTime = t; eye[e].blink.duration = blinkDuration; } } } else if (digitalRead(eye[eyeIndex].blink.pin) == LOW) { // Wink! eye[eyeIndex].blink.state = ENBLINK; eye[eyeIndex].blink.startTime = t; eye[eyeIndex].blink.duration = random(45000, 90000); } } // Process motion, blinking and iris scale into renderable values // Iris scaling: remap from 0-1023 input to iris map height pixel units iScale = ((IRIS_MAP_HEIGHT + 1) * 1024) / (1024 - (iScale * (IRIS_MAP_HEIGHT - 1) / IRIS_MAP_HEIGHT)); // Scale eye X/Y positions (0-1023) to pixel units used by drawEye() eyeX = map(eyeX, 0, 1023, 0, SCLERA_WIDTH - 128); eyeY = map(eyeY, 0, 1023, 0, SCLERA_HEIGHT - 128); if (eyeIndex == 1) eyeX = (SCLERA_WIDTH - 128) - eyeX; // Mirrored display // Horizontal position is offset so that eyes are very slightly crossed // to appear fixated (converged) at a conversational distance. Number // here was extracted from my posterior and not mathematically based. // I suppose one could get all clever with a range sensor, but for now... eyeX += 4; if (eyeX > (SCLERA_WIDTH - 128)) eyeX = (SCLERA_WIDTH - 128); // Eyelids are rendered using a brightness threshold image. This same // map can be used to simplify another problem: making the upper eyelid // track the pupil (eyes tend to open only as much as needed -- e.g. look // down and the upper eyelid drops). Just sample a point in the upper // lid map slightly above the pupil to determine the rendering threshold. static uint8_t uThreshold = 128; uint8_t lThreshold, n; #ifdef TRACKING int16_t sampleX = SCLERA_WIDTH / 2 - (eyeX / 2), // Reduce X influence sampleY = SCLERA_HEIGHT / 2 - (eyeY + IRIS_HEIGHT / 4); // Eyelid is slightly asymmetrical, so two readings are taken, averaged if (sampleY < 0) n = 0; else n = (pgm_read_byte(upper + sampleY * SCREEN_WIDTH + sampleX) + pgm_read_byte(upper + sampleY * SCREEN_WIDTH + (SCREEN_WIDTH - 1 - sampleX))) / 2; uThreshold = (uThreshold * 3 + n) / 4; // Filter/soften motion // Lower eyelid doesn't track the same way, but seems to be pulled upward // by tension from the upper lid. lThreshold = 254 - uThreshold; #else // No tracking -- eyelids full open unless blink modifies them uThreshold = lThreshold = 0; #endif // The upper/lower thresholds are then scaled relative to the current // blink position so that blinks work together with pupil tracking. if (eye[eyeIndex].blink.state) { // Eye currently blinking? uint32_t s = (t - eye[eyeIndex].blink.startTime); if (s >= eye[eyeIndex].blink.duration) s = 255; // At or past blink end else s = 255 * s / eye[eyeIndex].blink.duration; // Mid-blink s = (eye[eyeIndex].blink.state == DEBLINK) ? 1 + s : 256 - s; n = (uThreshold * s + 254 * (257 - s)) / 256; lThreshold = (lThreshold * s + 254 * (257 - s)) / 256; } else { n = uThreshold; } // Pass all the derived values to the eye-rendering function: drawEye(eyeIndex, iScale, eyeX, eyeY, n, lThreshold); } // AUTONOMOUS IRIS SCALING (if no photocell or dial) ----------------------- #if !defined(IRIS_PIN) || (IRIS_PIN < 0) // Autonomous iris motion uses a fractal behavior to similate both the major // reaction of the eye plus the continuous smaller adjustments that occur. uint16_t oldIris = (IRIS_MIN + IRIS_MAX) / 2, newIris; void split( // Subdivides motion path into two sub-paths w/randimization int16_t startValue, // Iris scale value (IRIS_MIN to IRIS_MAX) at start int16_t endValue, // Iris scale value at end uint32_t startTime, // micros() at start int32_t duration, // Start-to-end time, in microseconds int16_t range) { // Allowable scale value variance when subdividing if (range >= 8) { // Limit subdvision count, because recursion range /= 2; // Split range & time in half for subdivision, duration /= 2; // then pick random center point within range: int16_t midValue = (startValue + endValue - range) / 2 + random(range); uint32_t midTime = startTime + duration; split(startValue, midValue, startTime, duration, range); //First half split(midValue, endValue, midTime, duration, range); //Second half } else { // No more subdivisons, do iris motion... int32_t dt; // Time (micros) since start of motion int16_t v; // Interim value while ((dt = (micros() - startTime)) < duration) { v = startValue + (((endValue - startValue) * dt) / duration); if (v < IRIS_MIN) v = IRIS_MIN; // Clip just in case else if (v > IRIS_MAX) v = IRIS_MAX; frame(v); // Draw frame w/interim iris scale value } } } #endif // !IRIS_PIN // MAIN LOOP -- runs continuously after setup() ---------------------------- void loop() { #if defined(IRIS_PIN) && (IRIS_PIN >= 0) // Interactive iris uint16_t v = 512; //analogRead(IRIS_PIN);// Raw dial/photocell reading #ifdef IRIS_PIN_FLIP v = 1023 - v; #endif v = map(v, 0, 1023, IRIS_MIN, IRIS_MAX); // Scale to iris range #ifdef IRIS_SMOOTH // Filter input (gradual motion) static uint16_t irisValue = (IRIS_MIN + IRIS_MAX) / 2; irisValue = ((irisValue * 15) + v) / 16; frame(irisValue); #else // Unfiltered (immediate motion) frame(v); #endif // IRIS_SMOOTH #else // Autonomous iris scaling -- invoke recursive function newIris = random(IRIS_MIN, IRIS_MAX); split(oldIris, newIris, micros(), 10000000L, IRIS_MAX - IRIS_MIN); oldIris = newIris; #endif // IRIS_PIN //screenshotToConsole(); }
require 'test_helper' class FashionHatsControllerTest < ActionController::TestCase setup do @fashion_hat = fashion_hats(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:fashion_hats) end test "should get new" do get :new assert_response :success end test "should create fashion_hat" do assert_difference('FashionHat.count') do post :create, fashion_hat: { brand: @fashion_hat.brand, description: @fashion_hat.description, hat_type: @fashion_hat.hat_type, made_by_country: @fashion_hat.made_by_country, made_with: @fashion_hat.made_with, price: @fashion_hat.price, quantity: @fashion_hat.quantity, title: @fashion_hat.title } end assert_redirected_to fashion_hat_path(assigns(:fashion_hat)) end test "should show fashion_hat" do get :show, id: @fashion_hat assert_response :success end test "should get edit" do get :edit, id: @fashion_hat assert_response :success end test "should update fashion_hat" do patch :update, id: @fashion_hat, fashion_hat: { brand: @fashion_hat.brand, description: @fashion_hat.description, hat_type: @fashion_hat.hat_type, made_by_country: @fashion_hat.made_by_country, made_with: @fashion_hat.made_with, price: @fashion_hat.price, quantity: @fashion_hat.quantity, title: @fashion_hat.title } assert_redirected_to fashion_hat_path(assigns(:fashion_hat)) end test "should destroy fashion_hat" do assert_difference('FashionHat.count', -1) do delete :destroy, id: @fashion_hat end assert_redirected_to fashion_hats_path end end
<mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter"> </mat-form-field> <mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8"> <!-- Name Column --> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell> </ng-container> <!-- Author Column --> <ng-container matColumnDef="author"> <mat-header-cell *matHeaderCellDef mat-sort-header> Author </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.author}} </mat-cell> </ng-container> <!-- Genre Column --> <ng-container matColumnDef="genre"> <mat-header-cell *matHeaderCellDef mat-sort-header> Genre </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.genre}} </mat-cell> </ng-container> <!-- Format Column --> <ng-container matColumnDef="format"> <mat-header-cell *matHeaderCellDef mat-sort-header> Format </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.format}} </mat-cell> </ng-container> <!-- Condition Column --> <ng-container matColumnDef="condition"> <mat-header-cell *matHeaderCellDef mat-sort-header> Condition </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.condition}} </mat-cell> </ng-container> <!-- Price Column --> <ng-container matColumnDef="price"> <mat-header-cell *matHeaderCellDef mat-sort-header> Price </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.price | currency}} </mat-cell> </ng-container> <!-- Location Column --> <ng-container matColumnDef="location"> <mat-header-cell *matHeaderCellDef mat-sort-header> Location </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.location}} </mat-cell> </ng-container> <!-- Actions Column --> <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef mat-sort-header> Actions </mat-header-cell> <mat-cell *matCellDef="let element"> <button mat-icon-button mat-raised-button color="primary" (click)="onEdit(element)" [disabled]="isEditing" matTooltip="Edit book" [matTooltipPosition]="'below'"> <mat-icon>edit</mat-icon> </button> &nbsp; <button mat-icon-button mat-raised-button color="warn" (click)="onDelete(element.key)" [disabled]="isDeleting" matTooltip="Delete book" [matTooltipPosition]="'below'"> <mat-icon>delete</mat-icon> </button> <mat-spinner color="warn" [diameter]="30" *ngIf="isDeleting"></mat-spinner> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table>
package com.zerozero.AndroidAppAutoTestCases; import static org.junit.Assert.*; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.android.AndroidDriver; import com.zerozero.common.MyUtil; import com.zerozero.page_object.AlbumPage; import com.zerozero.page_object.HomePage; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestAlbum { private AndroidDriver<WebElement> driver; @Before public void Setup(){ DesiredCapabilities capabilities = new DesiredCapabilities(); MyUtil.setCapabilityForNonFirstInstall(capabilities); try { driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testNavToAlbumAndSwipe(){ HomePage homePage = new HomePage(); try { homePage.navToAlbumViewPage(driver); int widht = driver.manage().window().getSize().width; int height = driver.manage().window().getSize().height; driver.swipe(widht*6/7, height/2, widht*1/7, height/2, 500); Thread.sleep(2000); driver.swipe(widht*1/7, height/2, widht*6/7, height/2, 500); driver.navigate().back(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } @Test public void testOpenImg(){ AlbumPage albumPage = new AlbumPage(); List<WebElement> imgList = driver.findElements(By.id(albumPage.imgThumb_Id)); imgList.get(0).click(); driver.findElement(By.id(albumPage.imgViewBackBtn)); driver.navigate().back(); } @After public void tearDown(){ driver.quit(); } }
package fr.galaxyoyo.spigot.nbtapi; import com.google.common.collect.Maps; import org.apache.commons.lang3.Validate; import org.bukkit.entity.Entity; import java.util.Arrays; import java.util.Map; import static fr.galaxyoyo.spigot.nbtapi.ReflectionUtils.*; public class EntityUtils { /** * Get the transformed TagCompound from the entity, with auto-updating */ public static TagCompound getTagCompound(Entity e) { return getTagCompound(e, true); } /** * Get the transformed TagCompound from the entity. If the parameter update equals true, every modification will be automatically updated. Don't use this if * you want to do multiple modifications in one use, because it can generate some lags */ public static TagCompound getTagCompound(Entity e, boolean update) { Object nmsEntity = invokeBukkitMethod("getHandle", e); Object nbt = newNMS("NBTTagCompound"); invokeNMSMethod("b", nmsEntity, new Class<?>[]{getNMSClass("NBTTagCompound")}, nbt); return TagCompound.fromNMS(nbt, update ? e : null); } /** * Update the NBTTagCompound of the targetted entity */ public static void setTagCompound(Entity e, TagCompound tag) { Object nmsEntity = invokeBukkitMethod("getHandle", e); Object nbt = tag.convertToNMS(); invokeNMSMethod("a", nmsEntity, new Class<?>[]{getNMSClass("NBTTagCompound")}, nbt); } /** * Get all base attributes of target entity. Don't take about modifiers. * @param e The entity to get attributes * @return Entity's attributes */ public static Map<EntityAttributes, Double> getAllAttributes(Entity e) { Map<EntityAttributes, Double> map = Maps.newHashMap(); TagCompound tag = getTagCompound(e, false); TagList attributesTag = tag.getList("Attributes"); if (attributesTag == null) attributesTag = new TagList(); for (Object o : attributesTag) { TagCompound attributeTag = (TagCompound) o; EntityAttributes attributes = EntityAttributes.getByName(attributeTag.getString("Name")); double value = attributeTag.getDouble("Base"); map.put(attributes, value); } return map; } /** * Get the specified attribute of targetted entity */ public static double getAttribute(Entity e, EntityAttributes attributes) { return getAllAttributes(e).getOrDefault(attributes, attributes.getDefaultValue()); } /** * Set all attributes for one entity */ public static void setAllAttributes(Entity e, Map<EntityAttributes, Double> allAttributes) { TagCompound tag = getTagCompound(e); TagList attributesTag = new TagList(); for (Map.Entry<EntityAttributes, Double> entry : allAttributes.entrySet()) { Validate.inclusiveBetween(entry.getKey().getMinimum(), entry.getKey().getMaximum(), entry.getValue(), entry.getKey().getAttributeName() + " attribute must be inclusive between " + entry.getKey().getMinimum() + " and " + entry.getKey().getMaximum()); TagCompound attributeTag = new TagCompound(); attributeTag.setString("Name", entry.getKey().getAttributeName()); attributeTag.setDouble("Base", entry.getValue()); attributesTag.add(attributeTag); } tag.setList("Attributes", attributesTag); } /** * Set one attribute for one targetted entity */ public static void setAttribute(Entity e, EntityAttributes attributes, double value) { Map<EntityAttributes, Double> map = getAllAttributes(e); map.put(attributes, value); setAllAttributes(e, map); } /** * All entity attributes (update: 1.11) */ public enum EntityAttributes { /** * The maximum health of this mob (in half-hearts); determines the highest health they may be healed to. */ MAX_HEALTH("generic.maxHealth", 20.0D, 0.0D, Double.MAX_VALUE), /** * The range in blocks within which a mob with this attribute will target players or other mobs to track. Exiting this range will cause the mob to cease following the player/mob. Actual value used by most mobs is 16; for zombies it is 40. */ FOLLOW_RANGE("generic.followRange", 32.0D, 0.0D, 2048.0D), /** * The chance to resist knockback from attacks, explosions, and projectiles. 1.0 is 100% chance for resistance. */ KNOCKBACK_RESISTANCE("generic.knockbackResistance", 0.0D, 0.0D, 1.0D), /** * Speed of movement in some unknown metric. The mob's maximum speed in blocks/second is a bit over 43 times this value, but can be affected by various conditions. */ MOVEMENT_SPEED("generic.movementSpeed", 0.699999988079071D, 0.0D, Double.MAX_VALUE), /** * Damage dealt by attacks, in half-hearts. */ ATTACK_DAMAGE("generic.attackDamage", 2.0D, 0.0D, Double.MAX_VALUE), /** * Armor defense points.<br> * 1.9+ only. */ ARMOR("generic.armor", 0.0D, 0.0D, 30.0D), /** * Armor toughness.<br> * 1.9+ only. */ ARMOR_TOUGHNESS("generic.armorToughness", 0.0D, 0.0D, 20.0D), /** * Determines speed at which attack strength recharges. Value is the number of full-strength attacks per second.<br> * for players only.<br> * 1.9+ only. */ ATTACK_SPEED("generic.attackSpeed", 4.0D, 0.0D, 1024.0D), /** * Affects the results of loot tables using the <strong>quality</strong> or <strong>bonus_rolls</strong> tag (e.g. when opening chests or chest minecarts, fishing, and killing mobs).<br> * for players only.<br> * 1.9+ only. */ LUCK("generic.luck", 0.0D, -1024.0D, 1024.0D), /** * Horse jump strength in some unknown metric.<br> * for horses only. */ JUMP_STRENGTH("horse.jumpStrength", 0.69999999999999996D, 0.0D, 2.0D), /** * Chance that a zombie will spawn another zombie when attacked.<br> * for zombies only. */ SPAWN_REINFORCEMENTS("zombie.spawnReinforcements", 0.0D, 0.0D, 1.0D); private static final Map<String, EntityAttributes> BY_NAME = Maps.newHashMap(); private final String name; private final double defaultValue; private final double minimum; private final double maximum; EntityAttributes(String name, double defaultValue, double minimum, double maximum) { this.name = name; this.defaultValue = defaultValue; this.minimum = minimum; this.maximum = maximum; } public static EntityAttributes getByName(String name) { if (BY_NAME.isEmpty()) Arrays.stream(values()).forEach(attributes -> BY_NAME.put(attributes.getAttributeName(), attributes)); return BY_NAME.get(name); } public String getAttributeName() { return name; } public double getDefaultValue() { return defaultValue; } public double getMinimum() { return minimum; } public double getMaximum() { return maximum; } } }
import React, { Component } from "react"; import { Recorder } from 'react-voice-recorder' import './css/recorder.css' import axios from 'axios'; import { getToken } from "../Authenticator"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import Navbar from "../components/Navbar"; var spaceCheck; /** * Page to take audio records in the application. */ export default class Record extends Component { /** * Constructor that stores the data. * @param props */ constructor(props) { super(props); this.goBack = this.goBack.bind(this); this.state = { audioDetails: { url: null, blob: null, chunks: null, duration: { h: 0, m: 0, s: 0 } }, message: "" }; } /** * Ends the audio recording and adjust the data to the state * @param data Recorded audio data */ handleAudioStop(data) { this.setState({ audioDetails: data }); } /** * A audio record is created from the application and send it to the server after storage space check is true. * The name of the file consists of year - month - day @ hour - minute - second. * @param data Recorded audio data */ handleAudioUpload(data) { var today = new Date(); var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(); var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds(); var dateTime = date + "@" + time; try { const formData = new FormData(); formData.append("files", data, dateTime + ".webm"); const fileSize = { fileSize: data.size }; axios.post("http://localhost:80/uploadCheck", { fileSize }).then((res => { spaceCheck = res.data if (spaceCheck) { axios.post("http://localhost:80/upload", formData); this.setState({ message: "Uploaded audio" }); } else { this.setState({ message: "Not enough space" }); } })).catch(error => { console.error(error.stack); this.setState({ message: "Error while uploading audio" }); }); } catch (error) { console.error(error.stack); this.setState({ message: "Reacord audio before uploading" }); } } /** * Resets the audo data from the state */ handleReset() { const reset = { url: null, blob: null, chunks: null, duration: { h: 0, m: 0, s: 0 } }; this.setState({ audioDetails: reset }); } /** * Redirects the user to the "upload" page. */ goBack() { this.props.history.push("/upload"); } /** * Display the page that takes the input from the user. * @returns If no token is present an "Access Denied" page is displayed , otherwise the regular "record" page. */ render() { if (getToken() === "") { return ( <> <div className="container-center"> no Permission </div> </> ); } return ( <> <React.Suspense fallback={<FontAwesomeIcon icon='spinner' pulse />}> <Navbar /> </React.Suspense> <div id='main'> <div className="container-center" > <button className="logoutLblPos" onClick={this.goBack}>Back</button> <Recorder record={true} title={"New recording"} audioURL={this.state.audioDetails.url} showUIAudio handleAudioStop={data => this.handleAudioStop(data)} handleAudioUpload={data => this.handleAudioUpload(data)} handleReset={() => this.handleReset()} mimeTypeToUseWhenRecording={`audio/webm`} /> <h1>{this.state.message}</h1> </div> </div> </> ); } }
import React from "react"; import Header from "../components/header.jsx"; import { useState } from "react"; import axios from "axios"; import styles from "../styles/weather.module.css"; export default function Weather() { const [zipCode, setZipCode] = useState(""); const [weatherData, setWeatherData] = useState(null); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios.post( "http://localhost:3001/getWeather", { zipCode }, ); //print response to console for error checking console.log(response.data); // Extract specific weather information const temp = response.data.data.temp; const humidity = response.data.data.humidity; const pressure = response.data.data.pressure; const description = response.data.data.description; // Set the weather data to be displayed setWeatherData({ temp, humidity, description, pressure, }); } catch (error) { console.error("Error submitting form:", error); // error handling } }; return ( <div> <Header /> <form onSubmit={handleSubmit}> <label> Zip Code: <input type="text" value={zipCode} onChange={(e) => setZipCode(e.target.value)} /> </label> <button type="submit">Get Weather</button> </form> <br /> <br /> {weatherData && ( <div className={styles.weatherContainer}> <div className={styles.dataBox}> <h2>Temperature</h2> <p>{weatherData.temp} F</p> </div> <div className={styles.dataBox}> <h2>Humidity</h2> <p>{weatherData.humidity} %</p> </div> <div className={styles.dataBox}> <h2>Description</h2> <p>{weatherData.description}</p> </div> <div className={styles.dataBox}> <h2>Pressure</h2> <p>{weatherData.pressure} hPa</p> </div> </div> )} </div> ); }
#include <stdio.h> #include <stdlib.h> #include "main.h" /** * set_bit - Sets the value of a bit to 1 at a given index * @n: The number containing the bit * @index: The index of the bit to set * * Return: 1 if it worked, or -1 if an error occurred */ int set_bit(unsigned long int *n, unsigned int index) { /* Check if index is within range */ if (index > (sizeof(unsigned long int) * 8 - 1)) return (-1); /* Set the bit at the given index */ *n |= (1UL << index); return (1); }
import config from "../config"; import { generateUTCToLimaDate } from "../helpers/generators"; import { OPERATION_TYPE } from "../models/DocumentType"; import { Setting, Module, Role, SystemUser, Category, Product, Gender, DocumentTypeDB, User, Reception, } from "../models/Entities"; import { CATEGORIES, DOCUMENT_TYPE_DNI, EMAIL_PABLO_SYS, EMAIL_PABLO_USER, EMAIL_POL_SYS, EMAIL_POL_USER, GENDER_MAN, GENERIC_PASSWORD, MODULES, ROLES, } from "./constants"; export const settingsData: Setting[] = [ { opening_time: "06:00:00", closing_time: "20:00:00", system_manual: "", tax: 0.18, ruc: "", business_name: "Restobar admin S.A.C.", address: "Jirón Las Magnolias 500, Lima", user_double_opt_in: config.DOUBLE_OPT_IN_USER as 1 | 0, system_user_double_opt_in: config.DOUBLE_OPT_IN_SYS as 1 | 0, created_date: generateUTCToLimaDate(), status: 1, user_creator: null, last_publication_date: generateUTCToLimaDate(), last_user_publisher: null, }, ]; export const modulesData: Module[] = [ { name: MODULES.RECEPTIONS, status: 1 }, { name: MODULES.ROLES, status: 1 }, { name: MODULES.SYSTEM_USERS, status: 1, }, { name: MODULES.USERS, status: 1 }, { name: MODULES.PRODUCTS, status: 1, }, { name: MODULES.ORDERS, status: 1, }, { name: MODULES.SALES, status: 1, }, ]; export const rolesData: Role[] = [ { name: ROLES.CHEF, alias: "Cocinero(a)", permissions: [], status: 1, updated_date: generateUTCToLimaDate(), created_date: generateUTCToLimaDate(), }, { name: ROLES.WAITER, alias: "Mesero(a)", permissions: [], status: 1, updated_date: generateUTCToLimaDate(), created_date: generateUTCToLimaDate(), }, { name: ROLES.ADMIN, alias: "Administrador(a)", permissions: [], status: 1, updated_date: generateUTCToLimaDate(), created_date: generateUTCToLimaDate(), }, { name: ROLES.GLOBAL_ADMIN, alias: "Super Administrador(a)", permissions: [], status: 1, updated_date: generateUTCToLimaDate(), created_date: generateUTCToLimaDate(), }, ]; export const gendersData: Gender[] = [ { name: GENDER_MAN, status: 1, }, { name: "Mujer", status: 1, }, { name: "Otro", status: 1, }, { name: "Prefiero no decirlo", status: 1, }, ]; export const categoriesData: Category[] = [ { name: CATEGORIES.BEBIDAS, description: "Categoría que enfoca a todo lo que son bebidas como refrescos, vinos, cocteles, etc.", status: 1, }, { name: CATEGORIES.ENTRADAS, description: "Categoría enfocada a los platos de entrada.", status: 1, }, { name: CATEGORIES.A_LA_CARTA, description: "Categoría enfocada a los platos principales a la carta.", status: 1, }, { name: CATEGORIES.MENU, description: "Categoría enfocada a los platos que son el menú del día a día.", status: 1, }, { name: CATEGORIES.COMBOS, description: "Categoría enfocada a los platos que incluyen bebidas, plato fuerte, y postre (la selección de platos puede variar).", status: 1, }, { name: CATEGORIES.POSTRES, description: "Categoría enfocada a los postres.", status: 1, }, ]; export const documentTypesData: DocumentTypeDB[] = [ { name: DOCUMENT_TYPE_DNI, operation: OPERATION_TYPE.IDENTITY, status: 1, code: "DNI", sequential: 0, length: 0, regex: "^(0-9){8}$", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "RUC", operation: OPERATION_TYPE.IDENTITY, status: 1, code: "RUC", sequential: 0, length: 0, regex: "^(10|20)[0-9]{9}$", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "Carnet de Diplomacia", operation: OPERATION_TYPE.IDENTITY, status: 1, code: "CDI", sequential: 0, length: 0, regex: "^([a-zA-Z0-9-]{9,15})$", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "Carnet de Extranjería", operation: OPERATION_TYPE.IDENTITY, status: 1, code: "CEX", sequential: 0, length: 0, regex: "^([a-zA-Z0-9-]{9,15})$", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "Orden", operation: OPERATION_TYPE.TRANSACTION, status: 1, code: "O001", sequential: 0, length: 8, created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "Venta", operation: OPERATION_TYPE.TRANSACTION, status: 1, code: "V001", sequential: 0, length: 8, created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, ]; export const receptionData: Reception[] = [ { code: "R000000", available: 1, status: 1, number_table: "000", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { code: "R000001", available: 1, status: 1, number_table: "001", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { code: "R000002", available: 1, status: 1, number_table: "002", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { code: "R000003", available: 1, status: 1, number_table: "003", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { code: "R000004", available: 1, status: 1, number_table: "004", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, ]; export const systemUsersData: SystemUser[] = [ { email: EMAIL_PABLO_SYS, password: GENERIC_PASSWORD, first_name: "Pablo", last_name: "Urbano", photo: "", status: 1, verified: 1, // role: undefined, // user_creator: null, // account_suspension_day: undefined, access_token: "", refresh_token: "", validation_token: "", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { email: EMAIL_POL_SYS, password: GENERIC_PASSWORD, first_name: "Pol Reyes", last_name: "Reyes", photo: "", status: 1, verified: 1, // role: undefined, // user_creator: null, // account_suspension_day: undefined, access_token: "", refresh_token: "", validation_token: "", created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, ]; export const usersData: User[] = [ { first_name: "Pablo Jamiro", last_name: "Urbano", second_last_name: "", // document_type: undefined, document_number: "", cellphone_number: "", address: "", // gender: undefined, email: EMAIL_PABLO_USER, password: GENERIC_PASSWORD, verified: 1, photo: "", token: "", status: 1, tokens: [], created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { first_name: "Pol Wilmer", last_name: "Reyes", second_last_name: "Mamani", // document_type: undefined, document_number: "", cellphone_number: "", address: "", // gender: undefined, email: EMAIL_POL_USER, password: GENERIC_PASSWORD, verified: 1, photo: "", token: "", status: 1, tokens: [], created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, ]; export const productsMenuData: Product[] = [ { name: "Salchipapa", available: 1, description: "", // category: undefined, price: 30.0, status: 1, created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "Alitas BBQ", available: 1, description: "", // category: undefined, price: 20.0, status: 1, created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, ]; export const productsBeveragesData: Product[] = [ { name: "Pisco Sour", available: 1, description: "", // category: undefined, price: 20.0, status: 1, created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "Machu Picchu", available: 1, description: "", // category: undefined, price: 20.0, status: 1, created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, { name: "Cerveza", available: 1, description: "", // category: undefined, price: 10.0, status: 1, created_date: generateUTCToLimaDate(), updated_date: generateUTCToLimaDate(), }, ];
<template> <!-- 添加用户界面 --> <view> <view class="info-box"> <!-- 个人信息项 --> <view class="info-item" v-if="userType==='教师'"> <text class="text">入职年份:</text> <view class="inp-item"> <picker :range="yearList" :value="yi" @change="changeYear">{{yearList[yi]}} <!-- V 图标 --> <uni-icons class="icon-bottom" color="#20517f" type="bottom" size="22"></uni-icons> </picker> </view> </view> <view class="info-item"> <text class="text">姓名:</text> <input class="inp-item" v-model="name" /> </view> <view class="info-item"> <text :class="['text', userType==='教师'?'move-left':'']">班级:</text> <view class="class-box" v-if="userType==='教师'"> <view class="class-item" v-for="(item,index) in classList" :key="index">{{item}}<!-- X 图标 --> <uni-icons class="icon-del" color="#6f6f6f" type="clear" size="24" @click="delCla(item)"></uni-icons> </view> <picker :range="classes" :value="i" @change="changeCla"> <!-- + 图标 --> <uni-icons class="icon-add" color="#20517f" type="plusempty" size="22"></uni-icons> </picker> </view> <view class="uninput" v-else>{{className}}</view> </view> <view class="info-item"> <text class="text">密码:</text> <input class="inp-item" v-model="pwd" /> </view> <view class="info-item" v-if="userType==='学生'"> <text class="text">专业:</text> <view class="uninput">{{professional}}</view> </view> <view class="info-item"> <text class="text">学院:</text> <view class="uninput">{{college}}</view> </view> </view> <button class="btn-add" @click="addUser">添加</button> </view> </template> <script> // 导入自己封装的 mixin 模块 import intopageMix from '@/mixins/before-into-teadpage.js'; export default { // 只有教师和管理员可进入该页面 mixins: [intopageMix], onLoad(option) { this.college = option.college; this.userType = option.userType; if (this.userType === '教师') { // 获取某学院所有班级信息 this.getClasses(); } else { this.className = option.className; this.professional = option.professional; } }, data() { return { // 添加用户类型 userType: '', // 学院 college: '', // 班级 i: 0, classes: [], classList: [], // 添加学生时的班级 className: '', // 添加学生时的专业 professional: '', // 默认密码 pwd: '1212', // 姓名 name: '', // 入职年份\ yi: 0, }; }, computed: { yearList() { let y = uni.$getDate().slice(0, 4); let list = []; for (let i = 0; i <= 10; i++) { list.push((parseInt(y) - i).toString()); } return list; } }, methods: { // 获取某学院所有班级信息 async getClasses() { const res = await uni.$http.get('/api/classes', { college: this.college }) // 请求失败 if (res.statusCode !== 200) return uni.$showMsg('获取信息失败!') if (res.data.status === 0) { this.classes = res.data.classes // console.log(this.classes, '------classes') } else { return uni.$showMsg(res.data.message) } }, // 改变班级选择器 changeCla(e) { this.i = e.detail.value; this.classList.push(this.classes[this.i]) this.classList = [...new Set(this.classList)] }, // 改变入职年份选择器 changeYear(e) { this.yi = e.detail.value; }, // 删除添加的班级 delCla(name) { // 是最后一个 if (name === this.classList[this.classList.length - 1]) this.classList.pop() // 不是最后一个 else { for (let i = 1; i < this.classList.length; i++) { if (this.classList[i - 1] === name) { this.classList[i - 1] = this.classList[i] } } this.classList.pop() } }, // 添加用户 async addUser() { if (!this.name || !this.pwd) return uni.$showMsg('姓名和密码不可为空'); // 请求路径 let url = '/addteacher'; // 请求携带的参数 let data = { college: this.college, name: this.name, userType: this.userType, classes: this.classList.toString(), pwd: this.pwd, year: this.yearList[this.yi] } if (this.userType === '学生') { data = { college: this.college, professional: this.professional, name: this.name, userType: this.userType, className: this.className, pwd: this.pwd } url = '/addstudent' } const res = await uni.$http.post(url, data) // 请求失败 if (res.statusCode !== 200) return uni.$showMsg('获取信息失败!') if (res.data.status === 0) { uni.navigateBack({ complete() { uni.$showMsg("添加成功!") } }) } else { // 编辑失败原因为身份认证失败 if (res.data.message === '身份认证失败!') { // 3秒后跳转登录 uni.$showTips() } else { // 其他原因导致失败 return uni.$showMsg(res.data.message) } } } } } </script> <style lang="scss" scoped> // 个人信息 .info-box { width: 93%; box-sizing: border-box; padding: 10px; margin: 20px auto; border-radius: 14px; border: 1px solid #20517f; box-shadow: 5px -4px 0 #20517f; // 个人信息项 .info-item { display: flex; align-items: center; padding: 10px 0; font-size: 18px; color: #20517f; // 文字 .text { width: 37%; text-align: right; } .move-left { position: relative; right: 10px; } // 班级 .class-box { width: 60%; // 管理班级 .class-item { position: relative; padding: 5px; margin: 5px; color: white; display: inline-block; border-radius: 18px; background-color: #20517f; // X 图标 .icon-del { position: absolute; right: -7px; top: -9px; } } // + 图标 .icon-add { padding-left: 40px; } } // 非输入框,有固定值的 .uninput { width: 66%; height: 24px; font-size: 16px; padding: 5px 10px; border-radius: 18px; color: white; background-color: #20517f; } // 输入框 .inp-item { width: 66%; height: 24px; font-size: 16px; padding: 5px 10px; border-radius: 18px; border: 2px solid #20517f; background-color: white; // V图标 .icon-bottom { float: right; } } } } // 添加按钮 .btn-add { width: 90%; color: white; margin-top: 20px; border-radius: 20px; background-color: #20517f; } </style>
import React, { FC, useCallback, useEffect, useState } from "react"; import { Button, View, Text, FlatList, StyleSheet, Image, TextInput, } from "react-native"; export interface IUser { id: number; email: string; first_name: string; last_name: string; avatar: string; } export const AccountScreen: FC = ({ navigation }: any) => { const [users, setUsers] = useState<IUser[]>([]); const [newFirstName, setNewFirstName] = useState<string>(""); const [newLastName, setNewLastName] = useState<string>(""); const [newEmail, setNewEmail] = useState<string>(""); useEffect(() => { fetch("https://reqres.in/api/users") .then((res) => res.json()) .then((data) => setUsers(data.data)); }, []); const handleAddUser = () => { const newUserId = users.length > 0 ? Math.max(...users.map((user) => user.id)) + 1 : 1; const newUser: IUser = { id: newUserId, email: newEmail, first_name: newFirstName, last_name: newLastName, avatar: "https://reqres.in/img/faces/6-image.jpg", }; setUsers([...users, newUser]); setNewFirstName(""); setNewLastName(""); setNewEmail(""); }; const handleDeleteUser = (userId: number) => { setUsers(users.filter((user) => user.id !== userId)); }; const handleViewUser = useCallback((userId: number) => { console.log(userId); navigation.navigate("Post", { userId }); }, []); return ( <View style={styles.container}> <View style={styles.form}> <Text>Add New User</Text> <TextInput placeholder="First Name" value={newFirstName} onChangeText={setNewFirstName} style={styles.input} /> <TextInput placeholder="Last Name" value={newLastName} onChangeText={setNewLastName} style={styles.input} /> <TextInput placeholder="Email" value={newEmail} onChangeText={setNewEmail} style={styles.input} /> <Button title="Add User" onPress={handleAddUser} /> </View> <FlatList data={users} renderItem={({ item }) => ( <UserCard {...item} onViewUser={handleViewUser} onDeleteUser={handleDeleteUser} /> )} keyExtractor={(item) => item.id.toString()} /> </View> ); }; interface IUserCardProps extends IUser { onViewUser: (userId: number) => void; onDeleteUser: (userId: number) => void; } const UserCard: FC<IUserCardProps> = ({ first_name, avatar, id, onViewUser, onDeleteUser, }) => { return ( <View style={styles.userCard}> <Image source={{ uri: avatar }} style={styles.avatar} /> <View> <Text style={styles.userName}>{first_name}</Text> <Button title="View" onPress={() => onViewUser(id)} /> <Button title="Delete" onPress={() => onDeleteUser(id)} color="red" /> </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 10, }, form: { marginBottom: 20, }, input: { borderWidth: 1, borderColor: "#ccc", padding: 8, marginBottom: 8, }, userCard: { flexDirection: "row", alignItems: "center", padding: 10, borderBottomWidth: 1, borderBottomColor: "#ccc", }, avatar: { width: 50, height: 50, borderRadius: 25, marginRight: 10, }, userName: { fontSize: 16, }, });
package com.gmail.bukkitSmerf.killPoints; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class Db { private static String url; private static String driver; private static Statement st; private static Connection con = null; private static boolean useMySQl = false; private Db(String host, String db, String username, String password) { url = "jdbc:mysql://" + host + "/" + db + "?user=" + username + "&password=" + password; driver = ("com.mysql.jdbc.Driver"); } private Db(String filePath) { url = "jdbc:sqlite:" + new File(filePath).getAbsolutePath(); driver = ("org.sqlite.JDBC"); } private Connection open(int type) throws SQLException, ClassNotFoundException { Class.forName(driver); con = DriverManager.getConnection(url); return con; } public static void clear() { update("DROP TABLE bukkitsmerf;"); Bukkit.shutdown(); } private static void update(String sql) { try { if (st.isClosed()) st = con.createStatement(); st.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } } private static ResultSet query(String sql) throws SQLException { if (st.isClosed()) st = con.createStatement(); return st.executeQuery(sql); } public static boolean connectToDatabase() { try { if (Cfg.isUseMySQL()) { con = new Db(Cfg.getMySQLHost(), Cfg.getMySQLDb(), Cfg.getMySQLUser(), Cfg.getMySQLPass()).open(0); st = con.createStatement(); update("CREATE TABLE IF NOT EXISTS bukkitsmerf (player VARCHAR(20), kills INT(7), deaths INT(7), kd DOUBLE, points BIGINT);"); useMySQl = true; Utils.log("&a Connected to MySQL!"); } else { con = new Db(KillPoints.getPluginDataFolder() + File.separator + "SQLite.db").open(0); st = con.createStatement(); update("CREATE TABLE IF NOT EXISTS bukkitsmerf (player, kills, deaths, kd, points);"); Utils.log("&a Connected to SQLite!"); } return true; } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); Utils.warn("&4 Error when try connect to DataBase. &c(is MySQL: " + useMySQl + ")"); return false; } } public static void createPlayer(String player) { update("INSERT INTO bukkitsmerf (player, kills, deaths, kd, points) VALUES ('" + player + "', 0, 0, 0, " + Cfg.getStartingPoints() + ");"); } public static LocalPlayer loadPlayer(String playerName) { try { ResultSet playerResult = query("SELECT * FROM bukkitsmerf WHERE player LIKE '" + playerName + "'"); if (playerResult.next()) { return new LocalPlayer(playerName, playerResult.getInt("kills"), playerResult.getInt("deaths"), playerResult.getLong("points")); } else return null; } catch (SQLException e) { e.printStackTrace(); Utils.warn("Error when try load: " + playerName + " from dataBase"); } return null; } public static void savePlayers() { for (Player p : Bukkit.getOnlinePlayers()) savePlayer(PlayersHandler.getPlayer(p.getName())); } public static void savePlayer(LocalPlayer player) { update("UPDATE bukkitsmerf SET kills=" + player.kills + ", deaths=" + player.deaths + ", kd=" + player.getKD() + ", points=" + player.points + " WHERE player LIKE '" + player.playerName + "'"); } public static boolean isPlayer(String playerName) { try { ResultSet result = query("SELECT player FROM bukkitsmerf WHERE player LIKE '" + playerName + "'"); if (result.next()) return true; } catch (SQLException e) { e.printStackTrace(); Utils.warn("Error when try check if: " + playerName + " is in dataBase"); } return false; } public static List<LocalPlayer> getTopKills(int from) { return getTop("kills", from); } public static List<LocalPlayer> getTopDeaths(int from) { return getTop("deaths", from); } public static List<LocalPlayer> getTopPoints(int from) { return getTop("points", from); } public static List<LocalPlayer> getTopKD(int from) { return getTop("kd", from); } private static List<LocalPlayer> getTop(String col, int from) { try { ArrayList<LocalPlayer> top = new ArrayList<LocalPlayer>(); ResultSet result = query("SELECT player FROM bukkitsmerf ORDER BY " + col + " " + "DESC LIMIT " + (from - 1) + ",10"); ArrayList<String> players = new ArrayList<String>(); while (result.next()) players.add(result.getString("player")); for (String p : players) { LocalPlayer player = PlayersHandler.tryGetPlayer(p); if (player == null) player = PlayersHandler.tempLoadPlayer(p); top.add(player); } return top; } catch (SQLException e) { e.printStackTrace(); Utils.warn("Error when try get TopList from database"); return new ArrayList<LocalPlayer>(); } } }
package data import ( "context" "log" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var client *mongo.Client func New(mongo *mongo.Client) Models { client = mongo return Models{ Image: Image{}, } } type Models struct { Image Image } type Image struct { ID string `bson:"_id,omitempty" json:"id,omitempty"` PostId uint `bson:"postId,omitempty" json:"postId,omitempty"` ImageBody string `bson:"imageBody,omitempty" json:"imageBody,omitempty"` CreatedAt time.Time `bson:"created_at,omitempty" json:"created_at,omitempty"` UpdatedAt time.Time `bson:"updated_at,omitempty" json:"updated_at,omitempty"` } func (l *Image) Insert(entry Image) error { collection := client.Database("images").Collection("images") _, err := collection.InsertOne(context.TODO(), Image{ PostId: entry.PostId, ImageBody: entry.ImageBody, CreatedAt: time.Now(), UpdatedAt: time.Now(), }) if err != nil { log.Println("error inserting image", err) return err } return nil } // []*LogEntry - slice of pointer to LogEntry func (l *Image) All() ([]*Image, error) { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() collection := client.Database("images").Collection("images") opts := options.Find() opts.SetSort(bson.D{{"created_at", -1}}) cursor, err := collection.Find(context.TODO(), bson.D{}, opts) if err != nil { log.Println("Failed to find all images", err) return nil, err } defer cursor.Close(ctx) // slice of pointer to LogEntry var logs []*Image for cursor.Next(ctx) { var item Image err := cursor.Decode(&item) if err != nil { log.Println("Failed to decode log into slice", err) return nil, err } logs = append(logs, &item) } return logs, nil } func (l *Image) GetOne(id string) (*Image, error) { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() collection := client.Database("images").Collection("images") docID, err := primitive.ObjectIDFromHex(id) if err != nil { return nil, err } var entry Image err = collection.FindOne(ctx, bson.M{"_id": docID}).Decode(&entry) if err != nil { return nil, err } return &entry, nil } func (l *Image) FindByPostId(postId uint) ([]*Image, error) { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() collection := client.Database("images").Collection("images") opts := options.Find() opts.SetSort(bson.D{{"created_at", -1}}) filter := bson.D{{"postId", postId}} cursor, err := collection.Find(context.TODO(), filter, opts) if err != nil { log.Println("Failed to find all images", err) return nil, err } defer cursor.Close(ctx) // slice of pointer to LogEntry var logs []*Image for cursor.Next(ctx) { var item Image err := cursor.Decode(&item) if err != nil { log.Println("Failed to decode log into slice", err) return nil, err } logs = append(logs, &item) } return logs, nil } func (l *Image) DropCollection() error { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() collection := client.Database("images").Collection("images") if err := collection.Drop(ctx); err != nil { return err } return nil } func (l *Image) Update() (*mongo.UpdateResult, error) { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() collection := client.Database("images").Collection("images") docID, err := primitive.ObjectIDFromHex(l.ID) if err != nil { return nil, err } result, err := collection.UpdateOne( ctx, bson.M{"_id": docID}, bson.D{ {"$set", bson.D{ {"postId", l.PostId}, {"imageBody", l.ImageBody}, {"updated_at", time.Now()}, }}, }, ) if err != nil { return nil, err } return result, nil }
import { Client } from "@pepperi-addons/debug-server/dist"; import { AddonData, CodeJob, PapiClient } from "@pepperi-addons/papi-sdk"; import { CommonMethods } from "./CommonMethods"; import { PNSSubscribeHelper } from "./PNSSubscribeHelper" export class DataIndexActions{ client: Client; papiClient: PapiClient; dataIndexType: string; tsaRefToApiResource: any; private adalTableName = "data_index"; constructor(inClient: Client,inDataIndexType: string) { this.client = inClient; this.papiClient = CommonMethods.getPapiClient(this.client); this.dataIndexType = inDataIndexType; } public async rebuild(): Promise<any> { var resultObject: {[k: string]: any} = {}; resultObject.success=true; resultObject.resultObject={}; var fieldsToExport : string[]; var pnsHelper = new PNSSubscribeHelper(this.client,this.dataIndexType); var adalRecord = await CommonMethods.getDataIndexTypeAdalRecord(this.papiClient,this.client,this.dataIndexType); try { var UIAdalRecord = await CommonMethods.getDataIndexUIAdalRecord(this.papiClient,this.client); fieldsToExport = UIAdalRecord[`${this.dataIndexType}_fields`]? UIAdalRecord[`${this.dataIndexType}_fields`] : []; console.log(`Start ${this.dataIndexType} rebuild function`); //Add defaultFields to fieldToExport fieldsToExport = CommonMethods.addDefaultFieldsByType(fieldsToExport,this.dataIndexType); fieldsToExport = fieldsToExport.filter(CommonMethods.distinct) //Unsubscribe old subscription and subscribe to new fields changes await pnsHelper.handleUnsubscribeAndSubscribeToPNS(adalRecord, fieldsToExport); //Run papi_rebuild var rebuildObject = await this.papiClient.post(`/bulk/data_index/rebuild/${this.dataIndexType}`,{FieldsToExport:fieldsToExport}); //Save the rebuild object that is returns from the above run in data_index DADL adalRecord["RebuildData"] = rebuildObject; //Create a code Job that calles the polling function that run every 5 minutes var codeJob = await this.createRebuildPollingCodeJob(adalRecord); adalRecord["PollingCodeJobUUID"] = codeJob["UUID"]; //save the ADAL record with the RebuildData and PollingCodeJobUUID await CommonMethods.saveDataIndexTypeAdalRecord(this.papiClient,this.client,adalRecord); resultObject.resultObject = rebuildObject; } catch(e) { resultObject.success = false; resultObject.erroeMessage = e.message; adalRecord["RebuildData"]["Status"] = 'Failure'; adalRecord["RebuildData"]["Message"] = e.message; await CommonMethods.saveDataIndexTypeAdalRecord(this.papiClient,this.client,adalRecord); } return resultObject } async handleRebuildStatus(adalRecord:any) { var status = adalRecord["RebuildData"]["Status"]; if(status != "InProgress") { await this.unscheduledPollingCodeJob(adalRecord); } console.log(`Data Index ${this.dataIndexType} rebuild ended with status ${status}`) } async getPollingResults(rebuildData:any) : Promise<any> { return rebuildData; } public async polling(): Promise<any> { var resultObject: {[k: string]: any} = {}; resultObject = {}; try { //Run papi_rebuild_Poling var rebuildData = await this.papiClient.post(`/bulk/data_index/rebuild/polling/${this.dataIndexType}`); //update the rebuildDataObject in the data_index ADAL record var adalRecord = await this.saveTheRebuildDataObjectInADAL(rebuildData); //Check the status await this.handleRebuildStatus(adalRecord); resultObject = await this.getPollingResults(adalRecord["RebuildData"]); } catch(e) { resultObject.erroeMessage = e.message; } return resultObject } protected async unscheduledPollingCodeJob(adalRecord: AddonData) { var codeJobUUID = this.client["CodeJobUUID"] ? this.client["CodeJobUUID"] : adalRecord["PollingCodeJobUUID"]; if (codeJobUUID) { //unscheduld the codeJob var codeJob = await this.papiClient.codeJobs.upsert({ UUID: codeJobUUID, IsScheduled: false, CodeJobName: `${this.dataIndexType} rebuild polling code job` }); console.log(`Setting code job ${codeJobUUID} with IsScheduled: false results: ${JSON.stringify(codeJob)}`) } } public async retry(): Promise<any> { var resultObject: {[k: string]: any} = {}; resultObject.success=true; resultObject.resultObject={}; try { var adalRecord = await CommonMethods.getDataIndexTypeAdalRecord(this.papiClient,this.client,this.dataIndexType); //Run papi_rebuild_retry var rebuildObject = await this.papiClient.post(`/bulk/data_index/rebuild/retry/${this.dataIndexType}`); var codeJobUUID = adalRecord["PollingCodeJobUUID"]; if(codeJobUUID) {//scheduld the codeJob await this.papiClient.codeJobs.upsert({UUID:codeJobUUID ,IsScheduled:true, CodeJobName:`${this.dataIndexType} rebuild polling code job`}); } resultObject.resultObject = rebuildObject; } catch(e) { resultObject.success = false; resultObject.erroeMessage = e.message; } return resultObject } async saveTheRebuildDataObjectInADAL(rebuildObject: Promise<any>, adalRecord? :AddonData) { if(!adalRecord){ adalRecord = await CommonMethods.getDataIndexTypeAdalRecord(this.papiClient,this.client,this.dataIndexType); } if(!adalRecord["RebuildData"] || // if no rebuild data or the rebuild data is not up to date - update it (new Date(adalRecord["RebuildData"]["ModificationDateTime"]) < new Date(rebuildObject["ModificationDateTime"]))) { adalRecord["RebuildData"] = rebuildObject; adalRecord = await CommonMethods.saveDataIndexTypeAdalRecord(this.papiClient,this.client,adalRecord); } return adalRecord; } private async createRebuildPollingCodeJob(adalRecord:any) { var codeJobUUID = adalRecord["PollingCodeJobUUID"]; var codeJobName = `${this.dataIndexType} rebuild polling code job`; var codeJob; if (codeJobUUID) { // get existing codeJob codeJob = await this.papiClient.codeJobs.uuid(codeJobUUID).find(); } var functionName = this.getPollingFunctionName(); if (codeJob && codeJob["UUID"]) {//reschedule existing code job codeJob = await this.papiClient.codeJobs.upsert({UUID:codeJobUUID,FunctionName:functionName ,IsScheduled:true, CodeJobName:codeJobName}); console.log(`Reschedule ${codeJobName} with function '${functionName}' result: ${JSON.stringify(codeJob)}`) } else { //create new polling code job codeJob = { Type: "AddonJob", CodeJobName: codeJobName, IsScheduled: true, CronExpression: "*/5 * * * *", AddonPath: "data_index.js", AddonUUID: this.client.AddonUUID, FunctionName: functionName }; codeJob = await this.papiClient.codeJobs.upsert(codeJob); console.log(`Create new code job ${codeJobName} with function '${functionName}' result: ${JSON.stringify(codeJob)}`) } return codeJob; } getPollingFunctionName() { return `${this.dataIndexType}_polling`; } }
import { useWindowSize } from '@react-hook/window-size'; import React, { MutableRefObject } from 'react'; import TinderCard from 'react-tinder-card'; import { Translation } from '../../graphql/translation/types'; import { Direction } from '../Flashcards'; import './Flashcard.css'; interface FlashcardProps { translation: Translation; childRef: MutableRefObject<any>; handleSwipe: (dir: Direction) => void; } const Flashcard: React.FC<FlashcardProps> = ({ translation, childRef, handleSwipe, }) => { const [showTranslation, setShowTranslation] = React.useState(true); const [width, height] = useWindowSize(); const requirementFulfilled = React.useRef(true); const swipeThreshold = (width * height) / 3000; const flipCard = () => { showTranslation === false ? setShowTranslation(true) : setShowTranslation(false); }; const handleFulfilled = (dir: Direction) => { if (dir === 'left' || dir === 'right') { requirementFulfilled.current = true; } else { requirementFulfilled.current = false; } }; const prepareSwipe = (dir: Direction) => { if (requirementFulfilled.current) { handleSwipe(dir); } }; return ( <TinderCard ref={childRef} className="swipe" key={translation.id} onSwipe={prepareSwipe} preventSwipe={['up', 'down']} swipeRequirementType="position" onSwipeRequirementFulfilled={(dir: Direction) => handleFulfilled(dir)} swipeThreshold={swipeThreshold} > <div className="card" onClick={flipCard}> <div className="details"> {showTranslation ? ( <div> <h2>{translation.wordTo.name}</h2> <h5>{translation.sentences[0].textTo}</h5> </div> ) : ( <div> <h2>{translation.wordFrom.name}</h2> <h5>{translation.sentences[0].textFrom}</h5> </div> )} </div> </div> </TinderCard> ); }; export default Flashcard;
/* This file is part of darktable, Copyright (C) 2009-2022 darktable developers. darktable 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. darktable 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 darktable. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <inttypes.h> struct dt_dev_pixelpipe_t; struct dt_iop_buffer_dsc_t; struct dt_iop_roi_t; /** * implements a simple pixel cache suitable for caching float images * corresponding to history items and zoom/pan settings in the develop module. * correctness is secured via the hash so make sure everything is included here. * No caching if cl_mem, instead copied cache buffers are used. */ typedef struct dt_dev_pixelpipe_cache_t { int32_t entries; size_t allmem; size_t memlimit; void **data; size_t *size; struct dt_iop_buffer_dsc_t *dsc; dt_hash_t *hash; int32_t *used; int32_t *ioporder; uint64_t calls; int32_t lastline; // profiling & stats: uint64_t tests; uint64_t hits; uint32_t lused; uint32_t linvalid; uint32_t limportant; } dt_dev_pixelpipe_cache_t; typedef enum dt_dev_pixelpipe_cache_test_t { DT_CACHETEST_PLAIN = 0, DT_CACHETEST_USED = 1, DT_CACHETEST_FREE = 2, DT_CACHETEST_INVALID = 3, } dt_dev_pixelpipe_cache_test_t; /** constructs a new cache with given cache line count (entries) and float buffer entry size in bytes. \param[out] returns 0 if fail to allocate mem cache. */ gboolean dt_dev_pixelpipe_cache_init(struct dt_dev_pixelpipe_t *pipe, const int entries, const size_t size, const size_t limit); void dt_dev_pixelpipe_cache_cleanup(struct dt_dev_pixelpipe_t *pipe); /** creates a hopefully unique hash from the complete module stack up to the module-th, including current viewport. */ dt_hash_t dt_dev_pixelpipe_cache_hash(const dt_imgid_t imgid, const struct dt_iop_roi_t *roi, struct dt_dev_pixelpipe_t *pipe, const int position); /** returns a float data buffer in 'data' for the given hash from the cache, dsc is updated too. If the hash does not match any cache line, use an old buffer or allocate a fresh one. The size of the buffer in 'data' will be at least of size bytes. Returned flag is TRUE for a new buffer */ gboolean dt_dev_pixelpipe_cache_get(struct dt_dev_pixelpipe_t *pipe, const dt_hash_t hash, const size_t size, void **data, struct dt_iop_buffer_dsc_t **dsc, struct dt_iop_module_t *module, const gboolean important); /** test availability of a cache line without destroying another, if it is not found. */ gboolean dt_dev_pixelpipe_cache_available(struct dt_dev_pixelpipe_t *pipe, const dt_hash_t hash, const size_t size); /** invalidates all cachelines. */ void dt_dev_pixelpipe_cache_flush(const struct dt_dev_pixelpipe_t *pipe); /** invalidates all cachelines for modules with at least the same iop_order */ void dt_dev_pixelpipe_cache_invalidate_later(const struct dt_dev_pixelpipe_t *pipe, const int32_t order); /** makes this buffer very important after it has been pulled from the cache. */ void dt_dev_pixelpipe_important_cacheline(const struct dt_dev_pixelpipe_t *pipe, const void *data, const size_t size); /** mark the given cache line as invalid or to be ignored */ void dt_dev_pixelpipe_invalidate_cacheline(const struct dt_dev_pixelpipe_t *pipe, const void *data); /** print out cache lines/hashes and do a cache cleanup */ void dt_dev_pixelpipe_cache_report(struct dt_dev_pixelpipe_t *pipe); void dt_dev_pixelpipe_cache_checkmem(struct dt_dev_pixelpipe_t *pipe); // clang-format off // modelines: These editor modelines have been set for all relevant files by tools/update_modelines.py // vim: shiftwidth=2 expandtab tabstop=2 cindent // kate: tab-indents: off; indent-width 2; replace-tabs on; indent-mode cstyle; remove-trailing-spaces modified; // clang-format on
import axios from 'axios' import { useEffect, useState } from 'react' import { getEmployee, updateEmployee } from '../api/employee' import TextField from './TextField' type UpdateFormCardPropsType = { refreshData?: () => void id?: number } const UpdateFormCard = ({ refreshData, id: employeeId, }: UpdateFormCardPropsType) => { const [id, setId] = useState(employeeId || 1) const [form, setForm] = useState({ id: '', name: '', rules: '' }) const [show, setShow] = useState(false) const setEmployeeData = async () => { if (id && id > 0) { const { data: { data: { employee }, }, } = await axios(getEmployee(id.toString(), {})) if (employee) { setForm({ id: employee.id, name: employee.name, rules: employee.rules }) console.log(employee) console.log(form) } } else setForm({ id: '', name: '', rules: '' }) } const handleIdSubmit = async (e: any) => { e.preventDefault() setEmployeeData() } const handleNameSubmit = async (e: any) => { e.preventDefault() await axios(updateEmployee(id.toString(), { data: form })) console.log(form) refreshData?.() } useEffect(() => { if (employeeId) setEmployeeData() }, [employeeId]) return ( <ul className="week-list"> <li className="week-list-item"> <h1>Oppdater ansatt</h1> {show && ( <> {!employeeId && ( <form className="form" onSubmit={handleIdSubmit}> <TextField name="id" placeholder="1" value={id} onChange={(e: any) => setId(e.target.value)} /> <button type="submit">Get Employee Name</button> </form> )} <form className="form" onSubmit={handleNameSubmit}> <TextField prefix="Oppdater" name="navn" placeholder="Lars" value={form.name} onChange={(e: any) => setForm({ ...form, name: e.target.value }) } /> <button type="submit">Send inn</button> </form> </> )} <button type="button" onClick={() => setShow(!show)}> Oppdater en ansatt </button> </li> </ul> ) } export default UpdateFormCard
interface RowData { fullName: string warName: string registration: string birthDate: string rg: string cpf: string placeOfBirth: string ufNatural: string civilState: string cep: string address: string number: string neighborhood: string city: string complement: string uf: string email: string cellphone: string phone: string gender: string motherName: string fatherName: string scolarity: string religion: string bloodType: string actualWorkSituation: string admissionDate: string jobRole: string bodyOfLaw: string lotation: string workPost: string } export function normalizeAndCreateObject(row: RowData) { return { fullName: row.fullName, warName: row.warName || "Atualizar Campo", registration: row.registration, birthDate: new Date(row.birthDate).getTime() || new Date().getTime(), rg: row.rg, cpf: row.cpf, placeOfBirth: row.placeOfBirth || "Atualizar Campo", ufNatural: row.ufNatural || "Atualizar Campo", civilState: row.civilState || "Atualizar Campo", cep: row.cep || "Atualizar Campo", address: row.address || "Atualizar Campo", number: row.number || "Atualizar Campo", neighborhood: row.neighborhood || "Atualizar Campo", city: row.city || "Atualizar Campo", complement: row.complement || "Atualizar Campo", uf: row.uf || "Atualizar Campo", email: row.email, cellphone: row.cellphone || "Atualizar Campo", phone: row.phone || "Atualizar Campo", gender: row.gender || "Atualizar Campo", motherName: row.motherName || "Atualizar Campo", fatherName: row.fatherName || "Atualizar Campo", scolarity: row.scolarity || "Atualizar Campo", religion: row.religion || "Atualizar Campo", bloodType: row.bloodType || "Atualizar Campo", actualWorkSituation: row.actualWorkSituation || "Atualizar Campo", admissionDate: new Date(row.admissionDate).getTime() || new Date().getTime(), jobRole: row.jobRole || "Atualizar Campo", bodyOfLaw: row.bodyOfLaw || "Atualizar Campo", lotation: row.lotation || "Atualizar Campo", workPost: row.workPost || "Atualizar Campo", systemRole: "Sindicalizado", password: "1234", dependents: [] }; } interface RowData { fullName: string warName: string registration: string birthDate: string rg: string cpf: string placeOfBirth: string ufNatural: string civilState: string cep: string address: string number: string neighborhood: string city: string complement: string uf: string email: string cellphone: string phone: string gender: string motherName: string fatherName: string scolarity: string religion: string bloodType: string actualWorkSituation: string admissionDate: string jobRole: string bodyOfLaw: string lotation: string workPost: string } export function errosData(row: RowData) { const errorFields: string[] = []; for (const key in row) { if (Object.prototype.hasOwnProperty.call(row, key)) { if (key === "cpf" || key === "fullName" || key === "email" || key === "registration") { const value = row[key as keyof RowData]; const isValid = validateField(key, value); if (!isValid) { errorFields.push(key); } } } } return errorFields; } export function validateField(key: string, value: any) { switch (key) { case "admissionDate": return validateDate(value) case "birthDate": return validateDate(value) case "cpf": return validateCpf(value) case "rg": return validateRg(value) case "cep": return validateCep(value) case "number": return validateNumber(value) case "email": return validateEmail(value) case "phone": return validatePhone(value) case "cellphone": return validatePhone(value) default: return validateString(value) } } export function validateString(value: string) { if (value === "") { return false } return true } export function validateDate(value: string) { const regexData = /^\d{4}-\d{2}-\d{2}$/ if (!regexData.test(value)) { return false } const data = new Date(value) if (isNaN(data.getTime())) { return false } const hoje = new Date() if (data > hoje) { return false } return true } export function validateCpf(value: string) { const cpfLimpo = value.replace(/[^\d]/g, "") if (cpfLimpo.length !== 11) { return false } if (/^(\d)\1+$/.test(cpfLimpo)) { return false } let soma = 0 for (let i = 0; i < 9; i++) { soma += parseInt(cpfLimpo.charAt(i)) * (10 - i) } let resto = soma % 11 let digitoVerificador1 = resto < 2 ? 0 : 11 - resto soma = 0 for (let i = 0; i < 10; i++) { soma += parseInt(cpfLimpo.charAt(i)) * (11 - i) } resto = soma % 11 let digitoVerificador2 = resto < 2 ? 0 : 11 - resto if ( parseInt(cpfLimpo.charAt(9)) !== digitoVerificador1 || parseInt(cpfLimpo.charAt(10)) !== digitoVerificador2 ) { return false } return true } export function validateRg(value: string) { const rgLimpo = value.replace(/[^\d]/g, "") if (rgLimpo.length !== 9) { return false } const multiplicadores = [2, 3, 4, 5, 6, 7, 8, 9] let soma = 0 for (let i = 0; i < 8; i++) { soma += parseInt(rgLimpo.charAt(i)) * multiplicadores[i] } const resto = soma % 11 const digitoVerificador = 11 - resto const ultimoDigito = parseInt(rgLimpo.charAt(8)) if ( (digitoVerificador === 10 && ultimoDigito !== 0) || (digitoVerificador !== 10 && digitoVerificador !== ultimoDigito) ) { return false } return true } export function validateCep(value: String) { const cepLimpo = value.replace(/[^\d]/g, "") const regexCEP = /^\d{8}$/ return regexCEP.test(cepLimpo) } export function validateNumber(value: String) { return !isNaN(Number(value)) } export function validateEmail(value: string) { const regexEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ return regexEmail.test(value) } export function validatePhone(value: string) { const telefoneLimpo = value.replace(/[^\d]/g, "") const regexTelefone = /^(?:\d{10}|\d{11})$/ return regexTelefone.test(telefoneLimpo) }
package et.com.sample.Security.Filters; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import org.springframework.http.MediaType; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static et.com.sample.Security.Constants.TOKEN_SIGNATURE; import static java.util.Arrays.stream; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import static org.springframework.http.HttpStatus.FORBIDDEN; public class CustomAuthorizationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //If the user is trying to login there is no need to check for //tokens. if (request.getServletPath().equals("/auth/login") || request.getServletPath().equals("auth/refreshtoken")) { filterChain.doFilter(request, response); } else { //Can just be tokens, 'Bearer ' is just customery String authorizationHeader = request.getHeader(AUTHORIZATION); if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { try { String token = authorizationHeader.substring(7); Algorithm algorithm = Algorithm.HMAC256(TOKEN_SIGNATURE.getBytes()); JWTVerifier verifier = JWT.require(algorithm).build(); DecodedJWT decodedJWT = verifier.verify(token); String username = decodedJWT.getSubject(); String[] roles = decodedJWT.getClaim("roles").asArray(String.class); // String role = decodedJWT.getClaim("role").asString(); Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(); // authorities.add(new SimpleGrantedAuthority(role)); stream(roles).forEach(role -> { authorities.add(new SimpleGrantedAuthority(role)); }); //Building a spring security user and setting the necessary //roles for api access UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities); SecurityContextHolder.getContext().setAuthentication(authenticationToken); //Passing the request to the next filter in the chain filterChain.doFilter(request, response); } catch (Exception e) { System.out.println("Error : logging in: {}" + e.getMessage()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setHeader("error", e.getMessage()); response.setStatus(FORBIDDEN.value()); //response.sendError(FORBIDDEN.value()); Map<String, String> error = new HashMap<>(); error.put("error_message", e.getMessage()); } } else { filterChain.doFilter(request, response); } } } }
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React, { useContext, useEffect, useState } from 'react'; import { Alert, StyleSheet, View } from 'react-native'; import 'react-native-gesture-handler'; import * as firestore from '../../actions/firestore'; import { store } from '../../store'; import { heightPercentageToDP as hp, widthPercentageToDP as wp, } from '../../utils/responsiveLayout'; import Button from '../SignUp/Button'; import Form, { fields, locumFields, ownerFields, signUpFormData } from './Form'; import { User, Locum, Owner, Pharmacy } from '../../models'; const SignUpLocumView = ({ navigation }) => { const { state, dispatch } = useContext(store); const [isLocum, setIsLocum] = useState(true); const [userData, setUserData] = useState({} as signUpFormData); const [allFieldsEntered, setAllFieldsEntered] = useState(false); const [spinnerActive, setSpinnerActive] = useState(false); // form completion verificator useEffect(() => { if ( Object.keys(userData).length === fields.length + (isLocum ? locumFields.length : ownerFields.length) ) { let status = true; for (let value of Object.values(userData)) { if (!value.length) { status = false; break; } } setAllFieldsEntered(status); } }, [userData, isLocum]); useEffect(() => { // feed schools and pharmacies arrays for signup form autocompletes firestore.getSignupData(dispatch); }, [dispatch]); function handleSignUp(data: signUpFormData) { if (allFieldsEntered) { firestore .createUser(data) .then((user: Locum | Owner) => { dispatch({ type: 'SET_CURRENT_USER', currentUser: user, }); if (user.accountType === 'locum') { firestore.initLocumData(user as Locum, dispatch); } else { firestore.initOwnerData(user as Owner, dispatch); } navigation.reset({ index: 0, routes: [{ name: 'Home' }], }); }) .catch((e: Error) => { setSpinnerActive(false); console.error('error trying to signup:', e); Alert.alert(e.message.split(']')[1]); }); } } return ( <View style={styles.container}> <View style={styles.flatListContainer}> <Form isLocum={isLocum} setIsLocum={setIsLocum} setValue={(key: string, value: string) => { setUserData({ ...userData, [key]: value }); }} deleteKeys={(keys: string[]) => { const newUserData = { ...userData }; for (const key of keys) { delete newUserData[key]; } setUserData({ ...newUserData }); }} setUntouchable={() => setAllFieldsEntered(false)} schools={state.schools} pharmacies={state.pharmacies} /> </View> <View style={styles.footer}> <View style={{ marginTop: hp(2) }}> <Button loading={spinnerActive} active={allFieldsEntered} onPress={() => { setSpinnerActive(true); handleSignUp({ ...userData, accountType: isLocum ? 'locum' : 'owner', }); }} text={state.language === 'fr' ? "S'inscrire" : 'Sign Up'} /> </View> </View> </View> ); }; const styles = StyleSheet.create({ container: { height: hp(100), width: wp(100), alignItems: 'center', }, flatListContainer: { height: hp(77), // marginTop: hp(3), alignItems: 'center', }, footer: { position: 'absolute', shadowColor: '#000', shadowOffset: { height: -1, width: 0 }, shadowOpacity: 0.2, shadowRadius: 1, bottom: 0, marginBottom: hp(10), height: hp(13), width: '100%', backgroundColor: '#fff', alignItems: 'center', }, }); export default SignUpLocumView;
import styled from "styled-components"; export const IconSvgContainer = styled.div<{ width: string; height: string; color: string; hoverColor: string; padding: string; position: string; opacity: number; pointer: string; backgroundColor: string; zIndex: number; rotate: number; margin: string; }>` display: flex; position: ${(props) => props.position}; opacity: ${(props) => props.opacity}; width: ${(props) => props.width}; height: ${(props) => props.height}; min-width: ${(props) => props.width}; min-height: ${(props) => props.height}; max-width: ${(props) => props.width}; max-height: ${(props) => props.height}; padding: ${(props) => props.padding}; fill: ${(props) => props.color}; cursor: ${(props) => props.pointer}; background-color: ${(props) => props.backgroundColor}; z-index: ${(props) => props.zIndex}; transform: rotate(${(props) => props.rotate}deg); margin: ${(props) => props.margin}; svg { height: 100%; width: 100%; } &:hover { fill: ${(props) => props.hoverColor}; } `; export default { IconSvgContainer, };
import { Component, OnInit, OnDestroy } from '@angular/core'; import { WaiterService } from '../../services/waiter.service' import { ActivatedRoute, Router } from '@angular/router'; import { QuestionsService } from '../../services/add.question.service' import { Subject } from 'rxjs' import { takeUntil } from 'rxjs/operators' import { isNull } from 'util' import { CommentService } from '../../services/comment.service' import { NotifyService } from '../../services/app.notify.service' import { FirestoreService } from '../../services/firestore.service' import { AuthService } from '../../services/auth.service' import { TIME_OFFSET } from '../../app.params' @Component({ selector: 'app-question-page', templateUrl: './question-page.component.html', styleUrls: ['./question-page.component.scss'] }) export class QuestionPageComponent implements OnInit, OnDestroy { constructor( private waiter: WaiterService, private activateRoute: ActivatedRoute, private router: Router, private questions: QuestionsService, private comments: CommentService, private fstore: FirestoreService, private note: NotifyService, private auth: AuthService ) { this.id = this.activateRoute.snapshot.params['id'] this.date = new Date(1970, 0, 1) } ngOnDestroy() : void { this.destroy$.next() this.destroy$.complete() } async ngOnInit() { this.waiter.waiter() const quests = await this.questions.getQuestions() this.question = (quests.filter((el : any) => el.id === this.id).length > 0) ? quests.filter((el : any) => el.id === this.id)[0] : undefined this.date.setSeconds(this.question['date'] / 1000 + TIME_OFFSET) this.author = (this.question && typeof this.question['owner'] === 'string') ? JSON.parse(this.question['owner']) : {} this.isOwner = (!isNull(this.auth.getUser()) && this.author['id'] === this.auth.getUser().uid) this.tags = (this.question && typeof this.question['tags'] === 'string') ? JSON.parse(this.question['tags']) : [] this.waiter.unwaiter() this.user = this.auth.getUser() this.fstore.isAdminObserver.pipe( takeUntil(this.destroy$) ).subscribe((val) => { this.isAdmin = val }) this.fstore.checkAdmin() await this.refresh() console.log(this.question) } async del(uid: string){ if (confirm('Delete?')){ await this.comments.deleteComment(uid, ()=>this.refresh()).catch(e=>e) } } async add(){ const backup = this.message; this.message = '' if (this.id === undefined) return await this.comments.addComment(this.id, backup) .then(_=>{ this.note.show({ message: 'Commented!', color: 'success' }) }) .catch(_=>{ this.message = backup this.note.show({ message: 'Error!\nTry again or later..', color: 'danger' }) }) this.refresh() } async refresh(){ this.comms = (this.id === undefined) ? [] : await this.comments.getComments(this.id) this.comms.forEach((el : any, i : number)=>{ this.comms[i].owner = JSON.parse(this.comms[i].owner) }) this.comms = this.comms.sort((a,b)=>Number(a.date) - Number(b.date)) } async solution(e : any){ e.currentTarget['disabled'] = true if (!this.isOwner) return false await this.comments.solution(e.currentTarget.id).catch(e=>e) this.refresh() } async approve(){ if (this.question) this.questions.approveQuestion(this.question['id']).then(_=>{ this.approved = true; this.note.show({ message: 'Approved!', color: 'success' }) }).catch(e=>{ this.note.show({ message: 'Something went wrong!', color: 'danger' }) }) } edit() : void{ if (this.question !== undefined) this.router.navigateByUrl(`/edit/${this.question['uid']}`) } async delete(){ if(!this.question && !this.question['id']) return if (confirm('Delete?')) { await this.questions.deleteQuestion(this.question['id']).then(_=>{ this.router.navigateByUrl(`/main`) this.note.show({ message: 'Deleted!', color: 'success' }) }).catch(_=>{ this.note.show({ message: 'Something went wrong!', color: 'danger' }) }) } } private destroy$: Subject<void> = new Subject<void>() approved = false isAdmin: boolean = false isOwner: boolean id : string message : string = '' date : Date tags : Array<any> user : Object question: Object author: Object comms : Array<any> }
import React from 'react' import { withRouter } from 'react-router-dom' import { withSnackbar } from 'notistack' import { TextField, Button, Paper, Tooltip } from '@material-ui/core' import { HelpOutline } from '@material-ui/icons' import { CorporationComboBox, GeographicComboBox, KeywordComboBox, PersonComboBox, SubjectComboBox, SubmitterComboBox, } from '../comboBoxes' import IndexParent from './indexParent' import GPSField from '../validationTextFields/GPSField' import typeDefinitionFile from './corporationTypes.json' import Multiplier from '../Multiplier' import MetadataComboBox from 'components/comboBoxes/MetadataComboBox' import FoldablePaper from '../../components/FoldablePaper' import UniqueTextField from '../../components/UniqueTextField' import UploadFile from '../../components/UploadFile' import StaticComboBox from 'components/comboBoxes/StaticComboBox' import styles from './parent.module.scss' class Corporation extends IndexParent { constructor(props) { super(props) this.state = { helpersVisible: false, } this.indexURL = 'corporation' } getTypeDefinition = (fieldName) => typeDefinitionFile.properties[fieldName] render() { return ( <form onSubmit={this.handleSubmit} className={styles.main} onKeyPress={(event) => { if (event.which === 13) event.preventDefault() }} > <Paper className={styles.header}> {this.props.defaults ? ( <h1>Editace záznamu v Rejstříku korporací</h1> ) : ( <h1>Nový záznam do Rejstříku korporací</h1> )} <Tooltip title={'Zobrazit / Schovat nápovědy'}> <HelpOutline className={styles.allHelpers} onClick={() => this.setState({ helpersVisible: !this.state.helpersVisible, }) } /> </Tooltip> </Paper> <div className={styles.body}> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Preferované označení</h2> <UniqueTextField {...this.createFieldProps('name_main_part')} uniqueSource="CorporationIndex" uniqueField="name_main_part" /> <Multiplier> <TextField {...this.createFieldProps('name_other_part')} /> </Multiplier> <TextField {...this.createFieldProps('jurisdiction')} /> <KeywordComboBox {...this.createFieldProps('general_complement')} /> <GeographicComboBox {...this.createFieldProps( 'geographical_complement' )} /> <TextField {...this.createFieldProps( 'chronological_complement' )} /> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Variantní označení</h2> <Multiplier> <StaticComboBox {...this.createFieldProps('variant_type')} /> <TextField {...this.createFieldProps('variant_value')} /> <KeywordComboBox {...this.createFieldProps( 'variant_general_complement' )} /> <GeographicComboBox {...this.createFieldProps( 'variant_geographical_complement' )} /> <TextField {...this.createFieldProps( 'variant_chronological_complement' )} /> </Multiplier> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Popis</h2> <TextField {...this.createFieldProps('brief_characteristic')} /> <TextField {...this.createFieldProps('history')} /> <TextField {...this.createFieldProps('function')} /> <Multiplier> <TextField {...this.createFieldProps( 'constitutive_standards' )} /> </Multiplier> <Multiplier> <TextField {...this.createFieldProps('scope_standards')} /> </Multiplier> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Souřadnice</h2> <GPSField {...this.createFieldProps('coordinates')} /> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Vztahy a události</h2> <Multiplier> <CorporationComboBox {...this.createFieldProps('parent_corporation')} /> </Multiplier> <Multiplier> <CorporationComboBox {...this.createFieldProps('part_of')} /> </Multiplier> <Multiplier> <CorporationComboBox {...this.createFieldProps( 'precedent_corporation' )} /> </Multiplier> <Multiplier> <GeographicComboBox {...this.createFieldProps('related_country')} /> </Multiplier> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Počátek existence</h2> <PersonComboBox {...this.createFieldProps('founder')} /> <TextField {...this.createFieldProps('founding_document')} /> <GeographicComboBox {...this.createFieldProps('founding_place')} /> <TextField {...this.createFieldProps( 'founding_chronological_specification' )} /> <TextField {...this.createFieldProps('registration_document')} /> <SubjectComboBox {...this.createFieldProps('registration_event')} /> <TextField {...this.createFieldProps( 'registration_chronological_specification' )} /> <PersonComboBox {...this.createFieldProps('cleavage_person')} /> <TextField {...this.createFieldProps('cleavage_document')} /> <GeographicComboBox {...this.createFieldProps('cleavage_place')} /> <TextField {...this.createFieldProps( 'cleavage_chronological_specification' )} /> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Konec existence</h2> <PersonComboBox {...this.createFieldProps('cancellation_person')} /> <TextField {...this.createFieldProps('cancellation_document')} /> <GeographicComboBox {...this.createFieldProps('cancellation_place')} /> <TextField {...this.createFieldProps( 'cancellation_chronological_specification' )} /> <TextField {...this.createFieldProps( 'delete_from_evidence_document' )} /> <SubjectComboBox {...this.createFieldProps( 'delete_from_evidence_event' )} /> <TextField {...this.createFieldProps( 'cancellation_chronological_specification' )} /> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Zařazení</h2> <Multiplier> <KeywordComboBox {...this.createFieldProps('category')} /> </Multiplier> <Multiplier> <KeywordComboBox {...this.createFieldProps('domain_scope')} /> </Multiplier> <Multiplier> <GeographicComboBox {...this.createFieldProps('geographical_scope')} /> </Multiplier> <Multiplier> <KeywordComboBox {...this.createFieldProps('characteristic')} /> </Multiplier> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Vyobrazení</h2> <Multiplier> <MetadataComboBox {...this.createFieldProps('logo')} /> </Multiplier> <Multiplier> <MetadataComboBox {...this.createFieldProps('mark')} /> </Multiplier> <Multiplier> <MetadataComboBox {...this.createFieldProps('flag')} /> </Multiplier> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Poznámky</h2> <Multiplier> <TextField {...this.createFieldProps('public_note')} /> </Multiplier> <Multiplier> <TextField {...this.createFieldProps('nonpublic_note')} /> </Multiplier> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Jiný zdroj</h2> <Multiplier> <TextField {...this.createFieldProps('other_source_name')} /> <TextField {...this.createFieldProps('other_source_id')} /> <TextField {...this.createFieldProps( 'other_source_identificator' )} /> </Multiplier> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Zdroje o heslu</h2> <Multiplier> <TextField {...this.createFieldProps('record_sources')} /> </Multiplier> <Multiplier> <TextField {...this.createFieldProps('editor_note')} /> </Multiplier> <SubmitterComboBox {...this.createFieldProps('submitter')} /> </FoldablePaper> <FoldablePaper className={styles.dataBlock}> {' '} <h2>Přílohy</h2> <Multiplier> <UploadFile {...this.createFieldProps('attachment_url')} /> <TextField {...this.createFieldProps( 'attachment_description' )} /> </Multiplier> </FoldablePaper> </div> <Button className={styles.footer} type="submit" variant="contained" color="secondary" onClick={this.send} > Nahrát </Button> </form> ) } } export default withSnackbar(withRouter(Corporation))