text
stringlengths
184
4.48M
-- future database를 사용하겠다. USE future; -- 중요 ************************************** -- 테이블 수정 전에는 항상 무조건 반드시 ER부터 수정한다. -- 중요 ************************************** -- * <= asteric = all 전체 다 가져온다. 근데 개발에서는 안쓴다. -- 전체 컬럼 조회 SELECT * FROM member2; -- 컬럼 추가 ALTER TABLE member2 ADD COLUMN username varchar(45); -- 컬럼 추가시 위치 설정 (name 뒤에 생성할때의 예시) ALTER TABLE member2 ADD COLUMN nameEng varchar(45) AFTER name; -- 컬럼 타입 변경 -- 컬럼을 변경할때 데이터가 없을땐 괜찮지만 데이터가 있을때 컬럼을 변경하면 내용이 날아가서 곤란해진다. ALTER TABLE member2 MODIFY COLUMN username varchar(100); -- 컬럼 이름 변경 ALTER TABLE member2 CHANGE COLUMN username nickname varchar(45); -- 컬럼 삭제 (보통 삭제하기전에 통채로 백업을 시켜놓는다) ALTER TABLE member2 DROP COLUMN nickname; -- row 삭제 (delete 구문을 쓸때는 테이블 이름을 쓰기 전에 where 구문을 미리 쓰고 테이블 이름을 넣는다. 테이블 drop 방지) -- Seq의 이름이 memberSeq 같은거면 그거에 맞춰야한다. 검색이람 같음 ex) member WHERE memberSeq =11; DELETE FROM member2 WHERE Seq = 11; -- commit / rollback -- 데이터 수정 (delete 구문을 쓸때와 같이 where 구문을 쓰고 테이블 이름을 넣어서 쓴다.) UPDATE member2 SET name = "진휘재" ,nameEng ="Jinhwijae" where seq = 1; -- 문자열 비교 like SELECT * FROM member WHERE 1=1 -- AND name like '공%' -- AND name like '%석' -- AND name like '%소%' -- AND email like '%naver%' -- AND email like '%gmail%' -- AND address1 like '%송파구%' -- AND dob like '199%' -- 08 날짜에 08을 넣는다면 08년, 08월 08일까지 검색되어 월을 검색하고싶다면 %-08-%를 하면 된다. AND dob like '%08%' ; -- 숫자 비교 (between은 숫자 ~ 숫자) SELECT * FROM member WHERE 1=1 -- AND privacy = 1 -- AND privacy > 2 -- AND privacy >= 2 -- AND privacy between 3 and 4 AND dob between '1980-01-01' and '1999-12-31' ; SELECT * FROM member2 WHERE 1=1 AND pwd is null -- AND nameEng = null -- 틀린 표현이다. -- ""은 빈칸을 검색하는거지 null을 검색하는게 아니다 -- AND pwd is = '' ; CREATE TABLE IF NOT EXISTS `future`.`CCG` ( `CGseq` INT NOT NULL AUTO_INCREMENT, `CGName` VARCHAR(45) NULL, `CGUseNy` VARCHAR(45) NULL, `CGorder` VARCHAR(45) NULL, PRIMARY KEY (`CGseq`)) ENGINE = InnoDB ; CREATE TABLE IF NOT EXISTS `future`.`CG` ( `Cseq` INT NOT NULL AUTO_INCREMENT, `CName` VARCHAR(45) NULL, `CUseNy` VARCHAR(45) NULL, `Corder` VARCHAR(45) NULL, `CCG_CGseq` INT NOT NULL, PRIMARY KEY (`Cseq`), INDEX `fk_CG_CCG1_idx` (`CCG_CGseq` ASC) VISIBLE, CONSTRAINT `fk_CG_CCG1` FOREIGN KEY (`CCG_CGseq`) REFERENCES `future`.`CCG` (`CGseq`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB ; CREATE TABLE IF NOT EXISTS `future`.`bookUploaded` ( `bookUSeq` INT NOT NULL AUTO_INCREMENT, `type` TINYINT NULL, `defaultNy` TINYINT NULL, `sort` TINYINT NULL, `originalName` VARCHAR(45) NULL, `uuidName` VARCHAR(45) NULL, `ext` VARCHAR(45) NULL, `size` BIGINT NULL, `delNy` TINYINT NULL, `pSeq` BIGINT NULL, PRIMARY KEY (`bookUSeq`)) ENGINE = InnoDB ; CREATE TABLE IF NOT EXISTS `future`.`writerUploaded` ( `writerUSeq` INT NOT NULL AUTO_INCREMENT, `type` TINYINT NULL, `defaultNy` TINYINT NULL, `sort` TINYINT NULL, `originalName` VARCHAR(45) NULL, `uuidName` VARCHAR(45) NULL, `ext` VARCHAR(45) NULL, `size` BIGINT NULL, `delNy` TINYINT NULL, `pSeq` BIGINT NULL, PRIMARY KEY (`writerUSeq`)) ENGINE = InnoDB ;
# Data Format ## Json Files There are 2 types of Json files included with this data dump - <company_name>-employees.json files and <company_name>-time-entries.json. The formats are described below. ### Employee Files The employee json files each represent data for a single company. "GizmoGram", "LunchRock", and "Night Owls LLC" are each 100 employees large while "Onion Technology" is 2500 employees large. Within each file is a single Json array containing every employee for the company. Each element in the array looks something like this: ```json { "firstName" : "Parker", "lastName" : "Knight", "employeeId" : 2, "email" : "Parker_Knight@gizmogram.com", "companyId" : 3, "companyName" : "GizmoGram", "managerId" : 1, "positionTitle" : "Engineering Manager", "startDate" : "1995-05-27", "isManager" : true, "password" : "knightpa" } ``` Descriptions for each field are as follows: - firstName: The first name of the employee - lastName: The last name of the employee - employeeId: Unique identifier for the employee within the company. Within a company this is guaranteed to be unique but across companies employees may have the same identifier. A combination of companyId and employeeId is guaranteed to be unique across the full data set. - email: Email address for the employee, may be used in combination with the password for authentication - companyId: Unique identification number for the company that this employee belongs to - companyName: The name of the company this employee works for - managerId: employeeId for the manager of this employee. The CEO of a company is the only employee where this field is missing, all other employees will have this field defined. - positionTitle: The name of the position this employee holds - startDate: What date the employee started working for the company - isManager: A boolean field for whether this employee is a manager or not - password: A password that can be used to log into the system as this employee ### Time Files Each company tracks their time in unique ways, and as such the data from each company is formatted slightly differently. The main structure of these json files is similar - each employee has an entry in the array with a number of associated time entries. I would recommend starting with a simpler use case to get things off the ground quickly. As the project evolves, if you're looking for more of a challenge with the data feel free to explore the various time formats and see if your system can handle the various structures. GizmoGram is the simplest use case for time tracking - they just track the number of hours worked each day. This is the company I'd recommend taking a look at first for the sake of simplicity. ```json { "timeEntries" : [ { "date" : "2023-02-01", "hoursWorked" : 7.75 }, { "date" : "2023-02-02", "hoursWorked" : 7.5 }] } ``` Employees of Night Owls LLC only work the night shift in New York. They clock in and out once on a daily basis - even on weekends! The time recorded represents the time of clock on the wall when they punch their card so you'll need to account for daylight savings when processing this data! ```json { "timeEntries" : [ { "date" : "2022-11-01", "clockedIn" : "21:50:00", "clockedOut" : "04:14:00" }, { "date" : "2022-11-02", "clockedIn" : "21:18:00", "clockedOut" : "03:48:00" }] } ``` LunchRock LLC requires employees to punch out for lunchtime so they're not eating on the clock. The format for this data is similar to Night Owls LLC, but you'll see two entries per day for each employee as they punch out for and back in after lunchtime. ```json { "timeEntries" : [ { "date" : "2022-11-01", "clockedIn" : "08:48:00", "clockedOut" : "12:38:00" }, { "date" : "2022-11-01", "clockedIn" : "13:07:00", "clockedOut" : "16:58:00" }, { "date" : "2022-11-02", "clockedIn" : "08:43:00", "clockedOut" : "12:47:30" }, { "date" : "2022-11-02", "clockedIn" : "13:17:30", "clockedOut" : "17:22:00" }] } ``` Onion Technology uses the Unix epoch millisecond to record when their employees clock in and out (very precise!). This number represents the number of milliseconds that have elapsed since midnight on January 1, 1970 at the time the clock was punched. ```json { "timeEntries" : [ { "clockedInEpochMillisecond" : 1675259100000, "clockedOutEpochMillisecond" : 1675288920000 }, { "clockedInEpochMillisecond" : 1675349100000, "clockedOutEpochMillisecond" : 1675380540000 }] } ```
import React, { useState } from "react"; import User from './User'; import { useUsersState, useUsersDispatch, getUsers } from './UsersContext'; function Users() { const [userId, setUserId] = useState(null); const state = useUsersState(); const dispatch = useUsersDispatch(); const { loading, data: users, error } = state.users; const fetchData = () => { getUsers(dispatch); } if (loading) return <div>loading ...</div> if (error) return <div>error...</div> if (!users) return <button onClick={fetchData}>데이터 가져오기</button>; return ( <> <ul> {users.map(user => ( <li key={user.id} onClick={ () => setUserId(user.id) }> {user.id} {user.username} ({user.name}) </li> ))} </ul> <button onClick={fetchData}>reload</button> {userId && <User id={userId} />} </> ); } export default Users;
#include <gtest/gtest.h> #include "datastream.hpp" class DataStreamTest : public ::testing::Test { protected: DataStream* ds; void SetUp() override { ds = new DataStream(); } void TearDown() override { delete ds; } }; /** * @brief Test that a DataStream object can be created successfully. * * This test verifies that the DataStream constructor works correctly and * that the object is initialized with a non-null stream pointer. */ TEST_F(DataStreamTest, createDataStream) { EXPECT_TRUE(ds->stream != nullptr); EXPECT_TRUE(ds != nullptr); EXPECT_TRUE(ds->stream->is_open() == false); } /** * @brief Test that a file can be opened successfully using the DataStream class. * * This test verifies that the DataStream::open function works correctly and * that the file is successfully opened. It also checks that the stream pointer * is non-null and that the file is open. */ TEST_F(DataStreamTest, openfile) { std::string filepath = "/Users/malavpatel/Coding_Projects/StaticGrad/tokenizer/tokens/tinystories.bin"; EXPECT_NO_THROW(ds->open(filepath)); EXPECT_TRUE(ds->stream != nullptr); EXPECT_TRUE(ds->stream->is_open() == true); } /** * @brief Test that attempting to open an invalid file path throws an exception. * * This test verifies that the DataStream::open function throws a std::runtime_error * when attempting to open a file with an invalid path. */ TEST_F(DataStreamTest, openinvalidfile) { std::string filepath = "/invalid/file/path"; EXPECT_THROW(ds->open(filepath), std::runtime_error); } /** * @brief Test that the DataStream class can load a buffer from a file. * * This test verifies that the DataStream::load_buffer function works correctly * and that the buffer is loaded with data from the file. It also checks that * the first token in the buffer is not the GPT-2 EOT token (50256). */ TEST_F(DataStreamTest, loadbuffer) { std::string filepath = "/Users/malavpatel/Coding_Projects/StaticGrad/tokenizer/tokens/tinystories.bin"; ds->open(filepath); ds->init_buffer(64); EXPECT_NO_THROW(ds->load_buffer()); EXPECT_EQ(ds->buffer[0], 50256); // first token is gpt2 eot token // load another batch ds->load_buffer(); EXPECT_NE(ds->buffer[0], 50256); // first token will generally not be the eot token } /** * @brief Test that the load_weights function can load model weights from a file. * * This test verifies that the load_weights function works correctly and that * it can load model weights from a file. It also checks that the function throws * a std::runtime_error when the expected number of bytes does not match the * actual number of bytes in the file. */ TEST_F(DataStreamTest, load_weights) { std::string filepath = "/Users/malavpatel/Coding_Projects/StaticGrad/models/gpt2.bin"; int num_params = 124439808; auto params = new float[num_params]; // num parameters in gpt2 is 124439808 EXPECT_NO_THROW(load_weights(params, filepath)); int wrong_expected_bytes = 10; EXPECT_THROW(load_weights(params, filepath, wrong_expected_bytes), std::runtime_error); int correct_expected_bytes = num_params*sizeof(float); EXPECT_NO_THROW(load_weights(params, filepath, correct_expected_bytes)); delete[] params; } // Main function to run the tests int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
import { SearchType } from "@/interfaces"; import { PlacesSuggestion } from "@/interfaces/places"; import { ArrowPathIcon, MapPinIcon, XCircleIcon, } from "@heroicons/react/24/solid"; import clsx from "clsx"; import { Dispatch, SetStateAction } from "react"; import MapSearchSuggestions from "../MapSearchSuggestions"; interface MapSearchProps { disabled?: boolean; suggestions: PlacesSuggestion[] | []; // TODO: Add profile suggestions searchType: SearchType; setSearchType: Dispatch<SetStateAction<SearchType>>; queryLoading: boolean; handleUpdateQuery: (query: string) => void; handleSelect: (searchType: SearchType, suggestion: PlacesSuggestion) => void; placesQuery: string; profilesQuery: string; isSearching: boolean; handleUpdateIsSearching: (value: boolean) => void; } function MapSearch({ disabled, suggestions, searchType, setSearchType, queryLoading, handleUpdateQuery, handleSelect, placesQuery, profilesQuery, isSearching, handleUpdateIsSearching, }: MapSearchProps) { return ( <div className={clsx( disabled ? "opacity-0" : isSearching ? "w-full sm:w-full max-w-[500px] opacity-100" : "w-44 rounded-lg max-w-[500px] opacity-100", "gap-1 px-[6px] z-20 rounded-lg flex flex-col absolute top-[6px] text-tertiary text-small font-regular transition-all tracking-tighter" )} > <div className={clsx( isSearching ? "h-8 opacity-100" : "h-0 opacity-0", "w-full bg-white flex rounded-t-lg overflow-hidden shadow-lg transition-all" )} > <p onClick={() => setSearchType("PLACES")} className={clsx( searchType === "PLACES" ? "bg-accent text-tertiary" : "bg-white text-primary", "text-small px-3 py-1 text-center w-1/2 tracking-tighter cursor-pointer transition-all" )} > Search </p> <p onClick={() => setSearchType("PROFILES")} className={clsx( searchType === "PROFILES" ? "bg-accent text-tertiary" : "bg-white text-primary", "text-small px-3 text-center py-1 w-1/2 tracking-tighter cursor-pointer transition-all duration-300" )} > Find user </p> </div> <div className={clsx( isSearching ? suggestions.length > 0 ? "rounded-none" : "rounded-b-lg" : "rounded-lg", "flex px-3 py-1 bg-white shadow-lg justify-between transition-all" )} > <div className="flex w-full"> <MapPinIcon width={16} className={clsx( searchType === "PLACES" ? queryLoading ? "hidden" : "block" : isSearching ? "hidden" : "block", "transition-all text-primary" )} /> <p className={clsx( !isSearching ? "hidden" : searchType === "PROFILES" ? queryLoading ? "hidden" : "block" : "hidden", "transition-all text-primary font-bold mt-[-2px]" )} > @ </p> <ArrowPathIcon width={16} className={clsx( queryLoading ? "block animate-spin" : "hidden", "transition-all text-primary" )} /> <p onClick={() => handleUpdateIsSearching(true)} className={clsx( isSearching ? "hidden" : "block", "text-small px-3 text-gray-200 w-full tracking-tighter cursor-pointer" )} > Search... </p> <input disabled={disabled} autoComplete="shipping address-line1" value={ searchType === "PLACES" ? placesQuery ?? "" : profilesQuery ?? "" } onChange={(e) => handleUpdateQuery(e.target.value)} className={clsx( isSearching ? "block" : "hidden", "text-small w-full focus:border-none placeholder:text-gray-200 bg-transparent text-primary px-3 tracking-tighter transition-all focus:outline-none focus:" )} placeholder={ searchType === "PLACES" ? "neighborhood, restaurant, cafe.." : "michaelscott" } /> </div> <XCircleIcon onClick={() => { handleUpdateIsSearching(false); }} className={clsx( isSearching ? "block" : "hidden", "w-5 text-gray-200 cursor-pointer" )} /> </div> <MapSearchSuggestions suggestions={suggestions} searchType={searchType} handleSelect={handleSelect} /> </div> ); } export default MapSearch;
package com.zjq.javabase.base12.demo07Integer; /** * 基本类型与字符串类型之间的相互转换 * 基本类型->字符串(String) * 1.基本类型的值+"" 最简单的方法(工作中常用) * 2.包装类的静态方法toString(参数),不是Object类的toString() 重载 * static String toString(int i) 返回一个表示指定整数的 String 对象。 * 3.String类的静态方法valueOf(参数) * static String valueOf(int i) 返回 int 参数的字符串表示形式。 * 字符串(String)->基本类型 * 使用包装类的静态方法parseXXX("字符串"); * Integer类: static int parseInt(String s) * Double类: static double parseDouble(String s) * @author zjq */ public class Demo03Integer { public static void main(String[] args) { //基本类型->字符串(String) int i1 = 100; String s1 = i1+""; System.out.println(s1+200);//100200 String s2 = Integer.toString(100); System.out.println(s2+200);//100200 String s3 = String.valueOf(100); System.out.println(s3+200);//100200 //字符串(String)->基本类型 int i = Integer.parseInt(s1); System.out.println(i-10); int a = Integer.parseInt("a");//NumberFormatException System.out.println(a); } }
<?php declare(strict_types=1); namespace Parasut\Resources\Request; use Illuminate\Http\Resources\Json\JsonResource; class SalesInvoiceDetailResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array|\Illuminate\Contracts\Support\Arrayable|JsonSerializable */ public function toArray($request) { return [ 'type' => 'sales_invoice_details', 'attributes' => [ 'unit_price' => $this->price, 'quantity' => $this->quantity, 'vat_rate' => $this->product->tax ], 'relationships' => [ 'product' => [ 'data' => [ 'id' => $this->product->remote_id ?? null, 'type' => 'products', 'attributes' => $this->when($this->product->remote_source !== 'Paraşüt', fn () => ProductResource::make($this->product)->resolve()), ] ] ] ]; } }
import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.modeling_outputs import TokenClassifierOutput from transformers import BartModel, BartConfig, BartPretrainedModel class BartEncoderForTokenClassification(BartPretrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.bart = BartModel.from_pretrained("facebook/bart-large") self.encoder = self.bart.encoder self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.init_weights() # @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) # @add_code_sample_docstrings( # tokenizer_class=_TOKENIZER_FOR_DOC, # checkpoint=_CHECKPOINT_FOR_DOC, # output_type=TokenClassifierOutput, # config_class=_CONFIG_FOR_DOC, # ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
import React, { useState } from 'react'; import { View, Text, Switch, StyleSheet, Button, Modal } from 'react-native'; import { RadioButton } from 'react-native-paper'; const Booking = ({ route }) => { const carId = route?.params?.carId; // Optional chaining const [returnToSameLocation, setReturnToSameLocation] = useState(false); const [startDate, setStartDate] = useState('Choose Date'); // Placeholder text const [endDate, setEndDate] = useState('Choose Date'); // Placeholder text const [isDriverAgeSlider, setIsDriverAgeSlider] = useState(false); const [purpose, setPurpose] = useState(''); const [isModalVisible, setModalVisible] = useState(false); const handleConfirmBooking = async () => { try { // Make a POST request to your backend API to add the booking const response = await fetch(`${process.env.EXPO_PUBLIC_IP}${process.env.EXPO_PUBLIC_JSON_PORT}/bookingstest`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ returnToSameLocation, startDate, endDate, isDriverAgeSlider, purpose, carId, }), }); if (response.ok) { setModalVisible(true); } else { console.error('Booking failed:', response.status, response.statusText); } } catch (error) { console.error('Error confirming booking:', error); } }; const handleModalClose = () => { setModalVisible(false); }; return ( <View style={styles.container}> <View style={styles.row}> <Text>Return to Same Location</Text> <Switch value={returnToSameLocation} onValueChange={() => setReturnToSameLocation(!returnToSameLocation)} /> </View> <View style={styles.row}> <Text>Start Date: {startDate}</Text> </View> <View style={styles.row}> <Text>End Date: {endDate}</Text> </View> <View style={styles.row}> <Text>Driver Age (25-70)</Text> <Switch value={isDriverAgeSlider} onValueChange={() => setIsDriverAgeSlider(!isDriverAgeSlider)} /> </View> <View style={styles.row}> <Text>Purpose of the Rental</Text> <View style={styles.radioButtonContainer}> <RadioButton value="Business" status={purpose === 'Business' ? 'checked' : 'unchecked'} onPress={() => setPurpose('Business')} /> <Text>Business</Text> </View> <View style={styles.radioButtonContainer}> <RadioButton value="Personal" status={purpose === 'Personal' ? 'checked' : 'unchecked'} onPress={() => setPurpose('Personal')} /> <Text>Personal</Text> </View> </View> <Button title="Confirm Booking" onPress={handleConfirmBooking} /> <Modal visible={isModalVisible} onRequestClose={handleModalClose}> <View style={styles.modalContainer}> <Text>Booking Successful!</Text> <Button title="Close" onPress={handleModalClose} /> </View> </Modal> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, row: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginVertical: 8, }, radioButtonContainer: { flexDirection: 'row', alignItems: 'center', }, modalContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default Booking;
// Mighter2d // // Copyright (c) 2023 Kwena Mashamaite // // 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 "Mighter2d/graphics/Sprite.h" #include "Mighter2d/graphics/RenderTarget.h" #include "Mighter2d/utility/Helpers.h" #include "Mighter2d/core/resources/ResourceManager.h" #include "Mighter2d/core/scene/Scene.h" #include <SFML/Graphics/Sprite.hpp> #include <memory> namespace mighter2d { // Sprite class implementation struct Sprite::SpriteImpl { explicit SpriteImpl(Sprite& sprite) : animator_{sprite}, texture_{std::make_shared<Texture>()} {} SpriteImpl(const SpriteImpl& other) : sprite_{other.sprite_}, animator_{other.animator_}, texture_{std::make_shared<Texture>(*other.texture_)} {} SpriteImpl& operator=(const SpriteImpl& rhs) { if (this != &rhs) { SpriteImpl temp{rhs}; swap(temp); } return *this; } SpriteImpl(SpriteImpl&& other) noexcept { *this = std::move(other); } SpriteImpl& operator=(SpriteImpl&& rhs) noexcept { if (this != &rhs) { swap(rhs); } return *this; } void swap(SpriteImpl &other) { std::swap(sprite_, other.sprite_); std::swap(animator_, other.animator_); std::swap(texture_, other.texture_); } void setTexture(const Texture &texture) { if (*texture_ != texture) { *texture_ = *std::make_shared<Texture>(texture); sprite_.setTexture(texture_->getInternalTexture(), true); } } void setTexture(const std::string &filename) { texture_ = std::make_shared<Texture>(ResourceManager::getInstance()->getTexture(filename)); sprite_.setTexture(texture_->getInternalTexture(), true); } void setTextureRect(unsigned int left, unsigned int top, unsigned int width,unsigned int height) { if (getTextureRect() == UIntRect{left, top, width, height}) return; sprite_.setTextureRect({static_cast<int>(left), static_cast<int>(top), static_cast<int>(width), static_cast<int>(height)}); } UIntRect getTextureRect() const { return {static_cast<unsigned int>(sprite_.getTextureRect().left), static_cast<unsigned int>(sprite_.getTextureRect().top), static_cast<unsigned int>(sprite_.getTextureRect().width), static_cast<unsigned int>(sprite_.getTextureRect().height)}; } void setPosition(float x, float y) { sprite_.setPosition(x, y); } void setRotation(float angle) { sprite_.setRotation(angle); } void setScale(float factorX, float factorY) { sprite_.setScale(factorX, factorY); } float getRotation() const { return sprite_.getRotation(); } Vector2f getPosition() const { return {sprite_.getPosition().x, sprite_.getPosition().y}; } const Texture &getTexture() const { return *texture_; } FloatRect getLocalBounds() const { return {sprite_.getLocalBounds().left, sprite_.getLocalBounds().top, sprite_.getLocalBounds().width, sprite_.getLocalBounds().height}; } FloatRect getGlobalBounds() const { return {sprite_.getGlobalBounds().left, sprite_.getGlobalBounds().top, sprite_.getGlobalBounds().width, sprite_.getGlobalBounds().height}; } void draw(priv::RenderTarget &renderTarget) const { renderTarget.getThirdPartyWindow().draw(sprite_); } void setColour(Colour colour) { sprite_.setColor(utility::convertToSFMLColour(colour)); } void setOpacity(unsigned int opacity) { const auto& [r, g, b, a] = sprite_.getColor(); sprite_.setColor(sf::Color{r, g, b, opacity < 255 ? sf::Uint8(opacity) : sf::Uint8(255)}); } unsigned int getOpacity() const { return sprite_.getColor().a; } Colour getColour() const { return utility::convertFrom3rdPartyColour(sprite_.getColor()); } void setOrigin(float x, float y) { sprite_.setOrigin(x, y); } Vector2f getOrigin() const { return {sprite_.getOrigin().x, sprite_.getOrigin().y}; } Vector2f getScale() const { return {sprite_.getScale().x, sprite_.getScale().y}; } Animator &getAnimator() { return animator_; } void updateAnimation(Time deltaTime) { animator_.update(deltaTime); } void setAnimationTarget(Sprite& target) { animator_.setTarget(target); } private: sf::Sprite sprite_; //!< Third party sprite Animator animator_; //!< Sprite animator std::shared_ptr<Texture> texture_; //!< Keeps sf::Texture alive for sf::Sprite }; // class Impl /*------------------------------------------------------------------------- # Sprite class =-----------------------------------------------------------------------*/ Sprite::Sprite(Scene& scene) : Drawable(scene), IUpdatable(scene), scene_(&scene), pImpl_{std::make_unique<SpriteImpl>(*this)} {} Sprite::Sprite(Scene& scene, const std::string &texture, const UIntRect& rectangle) : Sprite(scene) { pImpl_->setTexture(texture); setTextureRect(rectangle); } Sprite::Sprite(Scene& scene, const Texture &texture, const UIntRect& rectangle) : Sprite(scene) { pImpl_->setTexture(texture); setTextureRect(rectangle); } Sprite::Sprite(const Sprite& other) : Drawable(other), IUpdatable(other), scene_(other.scene_), pImpl_{std::make_unique<SpriteImpl>(*other.pImpl_)} { pImpl_->setAnimationTarget(*this); } Sprite &Sprite::operator=(const Sprite& other) { if (this != &other) { Sprite temp{other}; std::swap(scene_, temp.scene_); std::swap(pImpl_, temp.pImpl_); pImpl_->setAnimationTarget(*this); } return *this; } Sprite::Sprite(Sprite&& other) noexcept : Drawable(std::move(other)), IUpdatable(std::move(other)), scene_(other.scene_), pImpl_{std::move(other.pImpl_)} { pImpl_->setAnimationTarget(*this); } Sprite &Sprite::operator=(Sprite&& other) noexcept { if (this != &other) { Drawable::operator=(std::move(other)); IUpdatable::operator=(std::move(other)); scene_ = other.scene_; *pImpl_ = std::move(*other.pImpl_); pImpl_->setAnimationTarget(*this); } return *this; } Sprite::Ptr Sprite::create(Scene& scene, const std::string &texture, const UIntRect &rectangle) { return std::make_unique<Sprite>(scene, texture, rectangle); } Sprite::Ptr Sprite::create(Scene& scene, const Texture &texture, const UIntRect &rectangle) { return std::make_unique<Sprite>(scene, texture, rectangle); } Scene &Sprite::getScene() { return *scene_; } const Scene &Sprite::getScene() const { return *scene_; } Sprite::Ptr Sprite::copy() const { return std::make_unique<Sprite>(*this); } std::string Sprite::getClassName() const { return "Sprite"; } void Sprite::swap(Sprite &other) { pImpl_->swap(*other.pImpl_); } void Sprite::setTexture(const Texture &texture) { pImpl_->setTexture(texture); } void Sprite::setTexture(const std::string &filename) { pImpl_->setTexture(filename); emitChange(Property{"texture", filename}); } void Sprite::setTextureRect(const UIntRect& rect) { setTextureRect(rect.left, rect.top, rect.width, rect.height); } void Sprite::setTextureRect(unsigned int left, unsigned int top, unsigned int width, unsigned int height) { if (auto [l, t, w, h] = getTextureRect(); l == left && t == top && w == width && h == height) return; pImpl_->setTextureRect(left, top, width, height); emitChange(Property{"textureRect", getTextureRect()}); } UIntRect Sprite::getTextureRect() const { return pImpl_->getTextureRect(); } void Sprite::setPosition(float x, float y) { Vector2f pos = getPosition(); if (pos.x == x && pos.y == y) return; pImpl_->setPosition(x, y); emitChange(Property{"position", Vector2f{x, y}}); } void Sprite::setPosition(const Vector2f& position) { setPosition(position.x, position.y); } void Sprite::setRotation(float angle) { if (getRotation() == angle) return; pImpl_->setRotation(angle); emitChange(Property{"rotation", angle}); } void Sprite::setScale(float factorX, float factorY) { if (auto [x, y] = getScale(); x == factorX && y == factorY) return; pImpl_->setScale(factorX, factorY); emitChange(Property{"scale", Vector2f{factorX, factorY}}); } void Sprite::setScale(const Vector2f& scale) { setScale(scale.x, scale.y); } void Sprite::setOrigin(const Vector2f& origin) { setOrigin(origin.x, origin.y); } float Sprite::getRotation() const { return pImpl_->getRotation(); } void Sprite::move(const Vector2f& offset) { move(offset.x, offset.y); } void Sprite::scale(const Vector2f& offset) { setScale(offset.x, offset.y); } Vector2f Sprite::getPosition() const { return pImpl_->getPosition(); } const Texture &Sprite::getTexture() const { return pImpl_->getTexture(); } FloatRect Sprite::getLocalBounds() const { return pImpl_->getLocalBounds(); } FloatRect Sprite::getGlobalBounds() const { return pImpl_->getGlobalBounds(); } void Sprite::draw(priv::RenderTarget &renderTarget) const { pImpl_->draw(renderTarget); } void Sprite::rotate(float angle) { setRotation(getRotation() + angle); } void Sprite::setColour(Colour colour) { if (getColour() == colour) return; pImpl_->setColour(colour); emitChange(Property{"colour", colour}); } Colour Sprite::getColour() const { return pImpl_->getColour(); } void Sprite::setOpacity(unsigned int opacity) { if (getOpacity() == opacity) return; pImpl_->setOpacity(opacity); emitChange(Property{"opacity", opacity}); } unsigned int Sprite::getOpacity() const { return pImpl_->getOpacity(); } void Sprite::setOrigin(float x, float y) { Vector2f origin = getOrigin(); if(origin.x == x && origin.y == y) return; pImpl_->setOrigin(x, y); emitChange(Property{"origin", Vector2f{x, y}}); } Vector2f Sprite::getOrigin() const { return pImpl_->getOrigin(); } void Sprite::scale(float xFactor, float yFactor) { setScale(getScale().x * xFactor, getScale().y * yFactor); } void Sprite::move(float xOffset, float yOffset) { setPosition(getPosition().x + xOffset, getPosition().y + yOffset); } Vector2f Sprite::getScale() const { return pImpl_->getScale(); } Animator &Sprite::getAnimator() { return pImpl_->getAnimator(); } const Animator &Sprite::getAnimator() const { return pImpl_->getAnimator(); } void Sprite::update(Time deltaTime) { pImpl_->updateAnimation(deltaTime); } Sprite::~Sprite() { emitDestruction(); } }
// To parse this JSON data, do // // final recentlyProductsModel = recentlyProductsModelFromJson(jsonString); import 'dart:convert'; RecentlyProductsModel recentlyProductsModelFromJson(String str) => RecentlyProductsModel.fromJson(json.decode(str)); String recentlyProductsModelToJson(RecentlyProductsModel data) => json.encode(data.toJson()); class RecentlyProductsModel { RecentlyProductsModel({ required this.data, }); List<Datum> data; factory RecentlyProductsModel.fromJson(Map<String, dynamic> json) => RecentlyProductsModel( data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))), ); Map<String, dynamic> toJson() => { "data": List<dynamic>.from(data.map((x) => x.toJson())), }; } class Datum { Datum({ this.id, this.sku, this.name, this.price, this.discount, this.sp, this.description, this.category, this.picture, }); int? id; String? sku; String? name; double? price; int? discount; double? sp; String? description; int? category; String? picture; factory Datum.fromJson(Map<String, dynamic> json) => Datum( id: json["id"], sku: json["sku"], name: json["name"], price: json["price"].toDouble(), discount: json["discount"], sp: json["sp"].toDouble(), description: json["description"], category: json["category"], picture: json["picture"], ); Map<String, dynamic> toJson() => { "id": id!, "sku": sku!, "name": name!, "price": price!, "discount": discount!, "sp": sp!, "description": description!, "category": category!, "picture": picture!, }; }
@extends('layouts.app') @section('content') <div class="container"> <h2>Crear Nueva Tarea</h2> <form action="{{ route('tareas.store') }}" method="POST"> @csrf <div class="form-group"> <label for="nombre">Nombre</label> <input type="text" name="nombre" id="nombre" class="form-control" value="{{ old('nombre') }}"> </div> <div class="form-group"> <label for="descripcion">Descripción</label> <textarea name="descripcion" id="descripcion" class="form-control">{{ old('descripcion') }}</textarea> </div> <div class="form-group"> <label for="fecha_vencimiento">Fecha de Vencimiento</label> <input type="date" name="fecha_vencimiento" id="fecha_vencimiento" class="form-control" value="{{ old('fecha_vencimiento') }}"> </div> <!-- Agregar un campo de selección para el usuario --> <div class="form-group"> <label for="usuario_id">Usuario</label> <select name="user_id" id="user_id" class="form-control"> @foreach($users as $user) <option value="{{ $user->id }}">{{ $user->name }}</option> @endforeach </select> </div> <!-- Agregar un campo de selección múltiple para etiquetas --> <div class="form-group"> <label for="etiquetas">Etiquetas</label> <select name="etiquetas[]" id="etiquetas" class="form-control" multiple> @foreach($etiquetas as $etiqueta) <option value="{{ $etiqueta->id }}">{{ $etiqueta->nombre }}</option> @endforeach </select> </div> <button type="submit" class="btn btn-primary">Crear Tarea</button> </form> </div> @endsection
import java.util.Scanner; class game { int[][] grid; int count = 0; game() { grid = new int[][] {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }}; } public void display() { String[] units = { "-", "O", "X" }; for (int[] row : grid) { for (int cell : row) { System.out.print(" "+units[cell]); } System.out.print("\n"); } } public void takeinput(int player) { Scanner scanner = new Scanner(System.in); System.out.print("Player " + player + "'s turn: "); try{ String[] split = scanner.nextLine().split(" ", 2); int[] array = new int[2]; for (int i = 0; i < 2; ++i) { array[i] = Integer.parseInt(split[i]); } if(grid[array[0]-1][array[1]-1] == 0){ grid[array[0]-1][array[1]-1] = player; } else{ System.out.println("Value already exists! retry.."); takeinput(player); } }catch(Exception e){ System.out.println("Input format is '{x} {y}' where 1 <= x,y <= 3 .. eg. '2 3'."); takeinput(player); } } int getValue(int[] coordinate){ return grid[coordinate[0]][coordinate[1]]; } int check(){ int [][][]checklist = {{{0,0},{0,1},{0,2}},{{1,0},{1,1},{1,2}},{{2,0},{2,1},{2,2}},{{0,0},{1,0},{2,0}},{{0,1},{1,1},{2,1}},{{0,2},{1,2},{2,2}},{{0,0},{0,1},{0,2}},{{0,0},{1,1},{2,2}},{{2,0},{1,1},{0,2}}}; for(int[][]checkline : checklist){ if(getValue(checkline[0]) == getValue(checkline[1]) && getValue(checkline[1]) == getValue(checkline[2]) && getValue(checkline[2]) != 0){ return getValue(checkline[0]); } } return 0; } public void start() { Scanner scanner = new Scanner(System.in); int flag = 0; for (int i = 0; i < 9; ++i) { display(); count += 1; takeinput((i % 2)+ 1); int checkval = check(); if(checkval!=0){ display(); System.out.println("Player " + checkval + " won!"); flag = 1; break; } } if (flag == 0){ display(); System.out.println("No one won! :("); } System.out.print("Play again? (y/n): "); String answer = scanner.nextLine(); if(answer.equals("y")){ restart(); } } public void restart(){ grid = new int[][]{{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }}; start(); } } class tictactoe{ public static void main(String[] args){ game grid = new game(); grid.start(); } }
<!-- 图标组件 --> <template> <!-- 知识点:ref 在JavaScript中需要通过document.querySelector("#demo")来获取dom节点,然后再获取这个节点的值。 在Vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。 ref被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs对象上。 如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向该子组件实例 --> <div ref="chartDom"></div> </template> <script> // import echarts from "echarts"; // 还非得这样引入:因为echarts 5.0版本接口更新后,echarts引入方式import echarts from ‘echarts’变了 import * as echarts from "echarts"; // 这样会将echarts包全部引入 比较大 // 按需引入echarts包,只使用柱状图 就只引入柱状图包 // import * as echarts from "echarts/lib/echarts"; // 引入必须的核心包(引擎) // import "echarts/lib/chart/bar"; // 引入柱状图 // import "echarts/lib/component/title"; // 配置title的相关代码 /* 引入监听dom尺寸变化的第三方库: addListener: 添加事件监听,用于在监听到dom尺寸变化后 重新渲染chart图表 removeListener: 用于在组件销毁时,移除之前添加的事件监听 (加载图表后,发现图表宽度没有跟随页面自适应。通过在浏览器中给Chart.vue文件的echarts.init初始化断点发现, 在chart渲染完成后,父级的整体页面(可能由于一些异步操作)还没有完成最终的渲染) */ import { addListener, removeListener } from "resize-detector"; // 前提要安装:npm install resize-detector // 防抖动函数: 由于resize变化极短的时间里持续变化,resize()方法会调用很多次 (去抖:如果在间隔时间内,发生新的keydown事件,则不触发Ajax通信,并且重新开始计时。) import debounce from "lodash/debounce"; // 引入lodash中具体的方法,而不是整个lodash,这样包会小一点 // import { debounce } from "lodash"; // 这样会将整个loadsh打包进来 export default { props: { option: { type: Object, default: () => {}, }, }, watch: { /* 监听图表数据option:图表数据变化后,应该要能改变图表 但通常option的结构不会变化,只是数据上有值的变化,这时watch就监听不到了,解决办法:重置图表数据变量 也可以使用深度监听 */ option(val) { this.myChart.setOption(val); }, // 深度监听option (深度监听有个弊端:消耗性能) // option: { // handler(val) { // this.myChart.setOption(val); // }, // deep: true, // }, }, /* 在mounted生命周期中使用 进行图表绘制 created:在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图。 mounted:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。 */ created() { // 将resize进行debounce防抖处理 this.resize = debounce(this.resize, 300); }, mounted() { // 渲染图表 this.renderChart(); // 监听chartDom的尺寸变化 addListener(this.$refs.chartDom, this.resize); }, // 组件销毁方法 beforeDestroy() { removeListener(this.$refs.chartDom, this.resize); // 移除监听事件 this.myChart.dispose(); // 封装三方库时注意:在组件销毁时,要销毁组件中创建的实例对象,防止内存泄漏 this.myChart = null; // 指针nil化 }, // 组件方法列表 methods: { resize() { console.log("resize"); this.myChart.resize(); }, // 将图表渲染 抽象到一个方法里,图表数据有外界传入 renderChart() { // 基于准备好的dom,初始化echarts实例 this.myChart = echarts.init(this.$refs.chartDom); // 绘制图表 this.myChart.setOption(this.option); }, }, }; </script> <style scoped></style>
import React, { useEffect, useState} from "react"; import "./controlPanel.css"; import { BsArrowUpLeft, BsArrowUp, BsArrowUpRight, BsArrowLeft, BsArrowRight, BsArrowDownLeft, BsArrowDown, BsArrowDownRight, BsCircle, BsGithub } from 'react-icons/bs'; import PreviewPanel from './PreviewPanel'; import { CopyToClipboard } from "react-copy-to-clipboard" function ControlPanel () { // Style Variable const [style, setStyle] = useState("linear-gradient") const [linearStyle, setLinearStyle] = useState(true) // Direction Variable const [direction, setDirection] = useState("to right") // Color Variables const [color1, setColor1] = useState("#38DEDB") const [color2, setColor2] = useState("#D499FA") // Output Variables const [output, setOutput] = useState (`backgroundImage: ${style}( ${direction}, ${color1}, ${color2})`) const [hexOutput, setHexOutput] = useState(true) // Text on CSS button variables const getCSSText = "Get CSS" const [buttonText, setButtonText] = useState(getCSSText) // useEffect danger zone useEffect(() => { if(linearStyle === true){ setStyle("linear-gradient") setDirection("to right") } else { setStyle("radial-gradient") setDirection("circle at center") } },[linearStyle]); useEffect(() => { if(hexOutput === true){ setOutput(`backgroundImage: ${style}( ${direction}, ${color1}, ${color2})`) } else { setOutput(`backgroundImage: ${style}( ${direction}, ${convertColor(color1)}, ${convertColor(color2)})`) } }, [hexOutput]); // Random Colors function const randomColors = () => { const newRandomColor1 = "#" + Math.floor(Math.random()*16777215).toString(16); const newRandomColor2 = "#" + Math.floor(Math.random()*16777215).toString(16); setColor1(newRandomColor1); setColor2(newRandomColor2); } // Converting Hex to RGBA const convertColor = (hexCode, opacity = 1) => { let hex = hexCode.replace('#', ''); if (hex.length === 3) { hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`; } const r = parseInt(hex.substring(0, 2), 16); const g = parseInt(hex.substring(2, 4), 16); const b = parseInt(hex.substring(4, 6), 16); if (opacity > 1 && opacity <= 100) { opacity = opacity / 100; } const rgba = `rgba(${r},${g},${b},${opacity})` return rgba } // Function modifying text on Get Css Button function handleClickCSS() { setButtonText("Copied to clipboard!") setTimeout(() =>{ setButtonText(getCSSText) }, 1000) // Set time before changing text back } // Function for conditioning style function changeStyle (changeStyle){ // Get a bool indicating if it's linear if ( changeStyle !== linearStyle ) { // If the new parameter is different than the one already on, changes linearStyle state to the parameter incoming setLinearStyle(changeStyle) } } // Function for conditioning output function changeOutput (changeOutput){ // Get a bool indicating if it's on hex output if (changeOutput !== hexOutput) { // If the new parameter is different than the one already on, changes hexOutput to the parameter incoming setHexOutput(changeOutput) } } return ( <> <section className="panelButtons"> <header className="panelHeader"> <h2>Gradient Party</h2> <h3>CSS Gradient Generator</h3> </header> <div className="styleSection"> <h3 className="panelOption">Style</h3> <div className="styleButtons" > <button onClick={(e) => { changeStyle(true)}} className="generalStyleButton" id="linear" data-style="linear-gradient">Linear</button> <button onClick={(e) => { changeStyle(false) }} className="generalStyleButton" id="radial" data-style="radial-gradient">Radial</button> </div> </div> <div className="directionSection"> <h3 className="panelOption">Direction</h3> <div className="directionButtons" onClick={(e) => { style === "radial-gradient" ? setDirection(e.target.dataset.radialdirection) : setDirection(e.target.dataset.lineardirection) }}> <button data-lineardirection="to top left" data-radialdirection="at top left"><BsArrowUpLeft/></button> <button data-lineardirection="to top" data-radialdirection="at top"><BsArrowUp/></button> <button data-lineardirection="to top right" data-radialdirection="at top right"><BsArrowUpRight/></button> <button data-lineardirection="to left" data-radialdirection="at left"><BsArrowLeft/></button> <button data-radialdirection="circle at center" style={{ visibility: style === "radial-gradient" ? "visible" : "hidden" }}><BsCircle/></button> <button data-lineardirection="to right" data-radialdirection="at right"><BsArrowRight/></button> <button data-lineardirection="to bottom left" data-radialdirection="at bottom left"><BsArrowDownLeft/></button> <button data-lineardirection="to bottom" data-radialdirection="at bottom"><BsArrowDown/></button> <button data-lineardirection="to bottom right" data-radialdirection="at bottom right"><BsArrowDownRight/></button> </div> </div> <div className="colorsButtons"> <h3 className="panelOption">Colors</h3> <div className="styleButtons"> <input type="color" className="colorSelector" value={color1} onChange={(e) => setColor1(e.target.value)}/> <input type="color" className="colorSelector" value={color2} onChange={(e) => setColor2(e.target.value)}/> <button className="generalStyleButton" onClick={randomColors}>Random</button> </div> </div> <div className="outputButtons"> <h3 className="panelOption">Output</h3> <div className="styleButtons"> <button onClick={() => {changeOutput(true)}} className="generalStyleButton">Hex</button> <button onClick={() => {changeOutput(false)}} className="generalStyleButton">RGBA</button> </div> </div> <div className="getResultButtons"> <CopyToClipboard text={output}> <button onClick={handleClickCSS}>{buttonText}</button> </CopyToClipboard> </div> <footer className="panelFooter"> <h4>Join the party! <br></br> <a className="githubLink" href="https://github.com/OromeSenryu"><BsGithub/> OromeSenryu</a> </h4> </footer> </section> <PreviewPanel style={style} direction={direction} color1={color1} color2={color2} /> </> ) } export default ControlPanel;
package com.rodionspringframework.recipeprojectspringbootmvc.domain; import lombok.*; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import java.util.Set; /** * Created by jt on 6/13/17. */ @Data @EqualsAndHashCode(exclude = {"recipes"}) @Entity @NoArgsConstructor @AllArgsConstructor @Builder public class Category { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String description; @ManyToMany(mappedBy = "categories") private Set<Recipe> recipes; }
use crate::{ client::OutboundConnect, message::{Header, InboundFrame, OutboundFrame, Rejection, Reset}, service, }; use core::{fmt, mem, num::NonZeroU16, task::Poll}; use tricky_pipe::{ bidi::SerBiDi, mpsc::error::{RecvError, SerSendError}, oneshot, }; #[derive( Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] #[cfg_attr(test, derive(proptest_derive::Arbitrary))] pub struct Id(NonZeroU16); #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(proptest_derive::Arbitrary))] pub struct LinkId { pub local: Option<Id>, pub remote: Option<Id>, } pub(crate) struct ConnTable<const CAPACITY: usize> { conns: Entries<CAPACITY>, next_id: Id, len: usize, dead_index: Option<Id>, } #[derive(Debug)] enum State { Open { remote_id: Id }, Connecting(oneshot::Sender<Result<(), Rejection>>), } #[derive(Debug)] struct Socket { state: State, channel: SerBiDi<Reset>, } enum Entry { Unused, Closed(Id), Occupied(Socket), } /// Wrapper struct so we can have a `get_mut` that's indexed by `Id`, basically. struct Entries<const CAPACITY: usize>([Entry; CAPACITY]); impl<const CAPACITY: usize> ConnTable<CAPACITY> { const ENTRY_UNUSED: Entry = Entry::Unused; #[must_use] pub(crate) const fn new() -> Self { Self { conns: Entries([Self::ENTRY_UNUSED; CAPACITY]), // ID 0 is the link-control channel next_id: Id(unsafe { NonZeroU16::new_unchecked(1) }), len: 0, dead_index: None, } } /// Returns the next outbound frame. pub(crate) async fn next_outbound(&mut self) -> OutboundFrame<'_> { // remove any dead socket that closed during the previous `next_outbound` call. self.cleanup_dead(); futures::future::poll_fn(|cx| { // TODO(eliza): would be nice if we didn't loop over all sockets // after a wakeup, and could instead use the `Waker` index to more // intelligently track which socket woke us, or something. But // that's Hard... for (idx, entry) in self.conns.0.iter().enumerate() { // Skip entries that are unoccupied or whose sockets are waiting // on the remote to initiate a connection. let Some(Socket { state: State::Open { remote_id }, channel, .. }) = entry.socket() else { continue; }; // poll the socket's local channel to see if it has outbound // data or has closed. match channel.rx().poll_recv(cx) { // a local data frame is ready to send! Poll::Ready(Ok(data)) => { let local_id = Id::from_index(idx); return Poll::Ready(OutboundFrame::data(*remote_id, local_id, data)); } // the local stream has closed, so mark the socket as dead // and generate a reset frame to tell the remote that it's // closed. Poll::Ready(Err(error)) => { self.dead_index = Some(Id::from_index(idx)); let reason = match error { RecvError::Disconnected => Reset::BecauseISaidSo, RecvError::Error(reason) => reason, }; return Poll::Ready(OutboundFrame::reset(*remote_id, reason)); } // nothing to do, move on to the next socket. Poll::Pending => {} } } // if no sockets are ready, yield until one is. Poll::Pending }) .await } fn cleanup_dead(&mut self) { // receiving a data frame from the conn table borrows it, so we must // remove the dead index from the *previous* next_outbound call before // we borrow the whole conn table to poll it. yes, this is confusing and // weird... if let Some(local_id) = self.dead_index.take() { tracing::debug!(id.local = %local_id, "removing closed stream from dead index"); self.remove(local_id); } } /// Process an inbound frame. pub async fn process_inbound( &mut self, registry: &'_ impl service::Registry, frame: InboundFrame<'_>, ) -> Option<OutboundFrame<'_>> { let span = tracing::trace_span!("process_inbound", id = %frame.header.link_id()); let _enter = span.enter(); match frame.header { // Inbound data frame from remote. Header::Data { local_id, remote_id, } => { tracing::trace!( id.remote = %local_id, id.local = %remote_id, len = frame.body.len(), "process_inbound: DATA", ); // the remote peer's remote ID is our local ID. let id = remote_id; let socket = match self.conns.get_mut(id).and_then(|entry| entry.socket()) { None => { tracing::debug!( id.remote = %local_id, id.local = %id, "process_inbound(DATA): connection does not exist, resetting...", ); return Some(OutboundFrame::reset(local_id, Reset::NoSuchConn)); } Some(Socket { state: State::Open { remote_id }, .. }) if &local_id != remote_id => { tracing::warn!( id.remote = %local_id, id.remote.actual = %remote_id, id.local = %id, "process_inbound(DATA): wrong remote ID, resetting...", ); return Some(OutboundFrame::reset(local_id, Reset::NoSuchConn)); } Some(Socket { state: State::Connecting(..), .. }) => { tracing::warn!( id.remote = %local_id, id.local = %id, "process_inbound(DATA): recieved DATA on a socket that was not ACKed", ); return Some(OutboundFrame::reset(local_id, Reset::NoSuchConn)); } Some(socket) => socket, }; // try to reserve send capacity on this socket. let reset = match socket.channel.tx().send(frame.body).await { Ok(_) => return None, Err(SerSendError::Deserialize(error)) => { // TODO(eliza): possibly it would be better if we // just sent the deserialize error to the local peer // and let it decide whether this should kill the // connection or not? maybe by turning the server's // client-to-server stream into `Result<ClientMsg, // DecodeError>`s? tracing::debug!( id.remote = %local_id, id.local = %id, %error, "process_inbound(DATA): failed to deserialize; resetting...", ); Reset::bad_frame(error) } // channel closed gracefully. Err(SerSendError::Disconnected) => Reset::BecauseISaidSo, // remote server reset the connection. Err(SerSendError::Error(error)) => error, }; tracing::trace!( id.remote = %local_id, id.local = %id, reason = %reset, "process_inbound(DATA): connection reset", ); self.remove(id); Some(OutboundFrame::reset(local_id, reset)) } Header::Ack { local_id, remote_id, } => { tracing::trace!(id.remote = %local_id, id.local = %remote_id, "process_inbound: ACK"); self.process_ack(remote_id, local_id) } Header::Reject { remote_id, reason } => { tracing::trace!(id.local = %remote_id, ?reason, "process_inbound: REJECT"); self.reject(remote_id, reason); None } Header::Reset { remote_id, reason } => { tracing::trace!(id.local = %remote_id, %reason, "process_inbound: RESET"); let _closed = self.reset(remote_id, reason).await; tracing::trace!(id.local = %remote_id, closed = _closed, "process_inbound(RESET): connection closed"); None } Header::Connect { local_id, identity } => { tracing::trace!(id.remote = %local_id, ?identity, "process_inbound: CONNECT"); match registry.connect(identity, frame.body).await { Ok(channel) => Some(self.accept(local_id, channel)), Err(reason) => Some(OutboundFrame::reject(local_id, reason)), } } } } /// Start a locally-initiated connecting socket, returning the frame to send /// in order to initiate that connection. #[must_use] pub(crate) fn start_connecting( &mut self, connect: OutboundConnect, ) -> Option<OutboundFrame<'_>> { let OutboundConnect { hello, identity, channel, rsp, } = connect; let local_id = match self.reserve_id() { Some(id) => id, None => { // if the local initiator dropped the response channel, that's // fine, we're bailing anyway! let _ = rsp.send(Err(Rejection::ConnTableFull(CAPACITY))); return None; } }; self.insert_at( local_id, Socket { state: State::Connecting(rsp), channel, }, ); Some(OutboundFrame::connect(local_id, identity, hello)) } /// Process an ack for a locally-initiated connecting socket with `local_id`. fn process_ack(&mut self, local_id: Id, remote_id: Id) -> Option<OutboundFrame<'static>> { let Some(Entry::Occupied(ref mut sock)) = self.conns.get_mut(local_id) else { tracing::debug!(id.local = %local_id, id.remote = %remote_id, "process_ack: no such socket"); return Some(OutboundFrame::reset(remote_id, Reset::NoSuchConn)); }; match sock.state { State::Open { remote_id: real_remote_id, } => { // this socket is already open locally! tracing::debug!( id.local = %local_id, id.remote = %remote_id, id.actual_remote = %real_remote_id, "process_ack: socket is not connecting" ); Some(OutboundFrame::reset(remote_id, Reset::YesSuchConn)) } ref mut state @ State::Connecting(_) => { let State::Connecting(rsp) = mem::replace(state, State::Open { remote_id }) else { unreachable!( "if this match arm matched, then the state should already be connecting!" ); }; // tell the local connection initiator that they're okay if rsp.send(Ok(())).is_err() { // local initiator is no longer there, reset! tracing::debug!( id.remote = %local_id, id.local = %remote_id, "process_ack: local initiator is no longer there; resetting" ); return Some(OutboundFrame::reset(remote_id, Reset::BecauseISaidSo)); } tracing::trace!( id.remote = %local_id, id.local = %remote_id, "process_ack: connection established", ); None } } } /// Accept a remote initiated connection with the provided `remote_id`. #[must_use] fn accept(&mut self, remote_id: Id, channel: SerBiDi<Reset>) -> OutboundFrame<'_> { let sock = Socket { state: State::Open { remote_id }, channel, }; match self.insert(sock) { // Accepted, we got a local ID! Some(local_id) => OutboundFrame::ack(local_id, remote_id), // Conn table is full, can't accept this stream. None => OutboundFrame::reject(remote_id, Rejection::ConnTableFull(CAPACITY)), } } fn reject(&mut self, local_id: Id, rejection: Rejection) -> bool { match self.remove(local_id) { Some(Socket { state: State::Open { .. }, .. }) => { tracing::warn!( iid.local = %local_id, ?rejection, "reject: tried to REJECT an established connection. the remote *should* have sent a RESET instead", ); false } Some(Socket { state: State::Connecting(rsp), .. }) => rsp.send(Err(rejection)).is_ok(), None => { tracing::warn!( id.local = %local_id, ?rejection, "reject: tried to REJECT a non-existent connection", ); false } } } async fn reset(&mut self, local_id: Id, reason: Reset) -> bool { tracing::trace!(id.local = %local_id, %reason, "reset: resetting connection..."); let Some(Socket { state, channel }) = self.remove(local_id) else { tracing::warn!( id.local = %local_id, %reason, "reset: tried to RESET a non-existent connection", ); return false; }; if matches!(state, State::Connecting(..)) { tracing::warn!( id.local = %local_id, %reason, "reset: tried to RESET an establishing connection. the remote *should* have sent a REJECT instead", ); // TODO(eliza): send some kinda rejection? return false; } channel.close_with_error(reason) } /// Returns `true` if a connection with the provided ID was closed, `false` if /// no conn existed for that ID. fn remove(&mut self, local_id: Id) -> Option<Socket> { match self.conns.get_mut(local_id) { None => { tracing::trace!(?local_id, "close: ID greater than max conns ({CAPACITY})"); None } Some(entry @ Entry::Occupied(_)) => { tracing::trace!(?local_id, self.len, "close: closing connection"); let Entry::Occupied(sock) = mem::replace(entry, Entry::Closed(self.next_id)) else { unreachable!("what the fuck, we just matched this as an occupied entry!"); }; // if let Some(nak) = nak { // match entry { // Entry::Occupied(Socket { // state: State::Connecting(rsp), // .. // }) => { // let nacked = rsp.send(Err(nak)).is_ok(); // tracing::trace!(?local_id, ?nak, nacked, "close: sent nak"); // } // Entry::Occupied(..) => { // // } // _ => unreachable!("we just matched an occupied entry!"), // } // } self.next_id = local_id; self.len -= 1; Some(sock) } Some(_) => { tracing::trace!(?local_id, "close: no connection for ID"); None } } } #[must_use] fn insert(&mut self, socket: Socket) -> Option<Id> { let local_id = self.reserve_id()?; self.insert_at(local_id, socket); Some(local_id) } #[must_use] fn reserve_id(&mut self) -> Option<Id> { // conn table full if self.len == CAPACITY { tracing::trace!(capacity = CAPACITY, "insert: conn table full"); return None; } Some(self.next_id) } fn insert_at(&mut self, local_id: Id, socket: Socket) { let entry = self.conns.get_mut(local_id).expect("ID should be present"); self.next_id = match mem::replace(entry, Entry::Occupied(socket)) { Entry::Unused => self.next_id.checked_add(1).expect("connection ID overflow"), Entry::Closed(next) => next, Entry::Occupied(_) => { unreachable!("we should never reassign to an occupied connection") } }; self.len += 1; tracing::trace!(?local_id, self.len, "insert: added connection"); } } // === impl Id === impl Id { #[cfg(test)] pub(crate) fn new(n: u16) -> Self { Self(NonZeroU16::new(n).expect("IDs must be non-zero")) } #[cfg(not(debug_assertions))] #[must_use] fn from_index(idx: usize) -> Self { let id = (idx as u16).saturating_add(1); Self(unsafe { NonZeroU16::new_unchecked(id) }) } #[cfg(debug_assertions)] #[must_use] fn from_index(idx: usize) -> Self { let id = match u16::try_from(idx) { Ok(x) => x, Err(_) => { unreachable!("conn table indices may not exceed u16::MAX; tried to convert {idx}") } }; let id = NonZeroU16::new(id.saturating_add(1)) .expect("we just added 1 to the index, so it must be greater than 0"); Self(id) } #[inline] #[must_use] fn to_index(self) -> usize { // subtract 1 because the link-control channel is at index 0 self.0.get() as usize - 1 } #[inline] fn checked_add(self, n: u16) -> Option<Self> { self.0.checked_add(n).map(Self) } } impl fmt::UpperHex for Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::UpperHex::fmt(&self.0, f) } } impl fmt::LowerHex for Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) } } impl fmt::Display for Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{self:04x}") } } impl fmt::Debug for Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Id({self:04x})") } } // === impl LinkId === impl LinkId { pub const INTERFACE: Self = Self { local: None, remote: None, }; } impl fmt::UpperHex for LinkId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { local, remote } = self; let local = local.map(|Id(x)| x.get()).unwrap_or(0); let remote = remote.map(|Id(x)| x.get()).unwrap_or(0); write!(f, "{remote:04X}:{local:04X}") } } impl fmt::LowerHex for LinkId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { local, remote } = self; let local = local.map(|Id(x)| x.get()).unwrap_or(0); let remote = remote.map(|Id(x)| x.get()).unwrap_or(0); write!(f, "{remote:04x}:{local:04x}") } } impl fmt::Display for LinkId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::LowerHex::fmt(self, f) } } // === impl Entries === impl<const CAPACITY: usize> Entries<CAPACITY> { // #[inline] // // #[must_use] // // fn get(&self, local_id: Id) -> Option<&Entry> { // // self.0.get(local_id.to_index()) // // } #[inline] #[must_use] fn get_mut(&mut self, local_id: Id) -> Option<&mut Entry> { self.0.get_mut(local_id.to_index()) } } // === impl Entry === impl Entry { fn socket(&self) -> Option<&Socket> { match self { Entry::Occupied(ref sock) => Some(sock), _ => None, } } } // #[cfg(test)] // mod tests { // use super::*; // use proptest::prelude::*; // proptest! { // #[test] // fn id_deserializes(local: Option<Id>, remote: Option<Id>) { // let data = b"hello world"; // let id = dbg!(LinkId { local, remote }); // let frame = dbg!(OutboundFrame { id, body: Body::Data(data) }); // let bytes = postcard::to_allocvec(&frame).unwrap(); // let actual_id = dbg!(postcard::from_bytes::<LinkId>(&bytes).unwrap()); // prop_assert_eq!(id, actual_id); // } // } // }
import type { MetaFunction, LinksFunction, LoaderFunctionArgs } from "@remix-run/node"; import { json } from "@remix-run/node"; import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData, useOutlet, useLocation } from "@remix-run/react"; import { Flip, ToastContainer } from "react-toastify"; import { AnimatePresence, motion } from "framer-motion"; import tostifyStylesheet from "react-toastify/dist/ReactToastify.css"; import stylesheet from "~/tailwind.css"; import { Sidebar } from "./components/Sidebar"; import { createSupabaseServerClient } from "./utils/supabase.server"; import { getToast, jsonWithError } from "remix-toast"; import { FloatingBtn } from "./components/FloatingBtn"; export const links: LinksFunction = () => [ { rel: "stylesheet", href: stylesheet }, { rel: "stylesheet", href: tostifyStylesheet } ]; export const meta: MetaFunction = () => [ { property: "og:title", content: "Feeder" }, { name: "description", content: "A simple RSS reader built with Remix and Supabase." } ]; export const loader = async ({ request }: LoaderFunctionArgs) => { const supabase = createSupabaseServerClient({ request }); const { toast, headers } = await getToast(request); const { data, error } = await supabase .from("rss") .select("*") .order("created_at", { ascending: false }); if (error || !data) { return jsonWithError(null, "Something went wrong!", { headers }); } return json({ data, toast }, { headers }); }; export default function App() { const loaderData = useLoaderData<typeof loader>(); const outlet = useOutlet(); const feeds = loaderData?.data.map((feed) => { return { name: feed.name, href: feed.id }; }) ?? []; return ( <html lang="en"> <head> <meta charSet="utf-8" /> <title>Feeder</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <Meta /> <Links /> </head> <body className="h-full"> <div> <Sidebar feeds={feeds} /> <AnimatePresence mode="wait" initial={false}> <motion.main key={useLocation().pathname} initial={{ x: "10%", opacity: 0 }} animate={{ x: "0", opacity: 1 }} exit={{ x: "-40%", opacity: 0 }} className="py-10 lg:pl-72 bg-slate-100 min-h-screen" > <div className="px-4 sm:px-6 lg:px-8"> <Outlet /> </div> </motion.main> </AnimatePresence> </div> <FloatingBtn /> <ToastContainer autoClose={3000} transition={Flip} hideProgressBar={true} /> <ScrollRestoration /> <Scripts /> <LiveReload /> </body> </html> ); }
//See Low Level for Command Definitions //Define Pins int enableA = 10; int pinA1 = 9; int pinA2 = 8; int enableB = 5; int pinB1 = 6; int pinB2 = 7; char serial; //Define Run variable boolean run; void setup() { Serial.begin(9600); // inicializa a Serial delay(1000); // esperar a serial subir o mini firmware externo pinMode(enableA, OUTPUT); pinMode(pinA1, OUTPUT); pinMode(pinA2, OUTPUT); pinMode(enableB, OUTPUT); pinMode(pinB1, OUTPUT); pinMode(pinB2, OUTPUT); enableMotors(); run = false; } //command sequence void loop() { if (Serial.available()) { serial = Serial.read(); Serial.println(serial); switch (serial) { //segmento do controle de locomocao case ' ': // parar motores brake(0); break; case 'W': // ir para frente forward(0); break; case 'S': // ir para tras backward(0); break; case 'D': // ir para direita turnRight(0); break; case 'A': // ir para esquerda turnLeft(0); break; case 'P': // Play the Demo mode run = true; break; // TRECO DE ICMU // case 'V': // ir para esquerda Serial.println("#v_receipt"); break; case 'B': // ir para esquerda Serial.println("#b_receipt"); break; case 'N': // ir para esquerda Serial.println("#n_receipt"); break; case 'M': // ir para esquerda Serial.println("#m_receipt"); break; default: // comando fora do protocolo Serial.println("Comando desconhecido"); } Serial.flush();// preciso mesmo disso? sera que se perde pacotes nisso? sinais que tenham chego no processamento dos comendos... Bem, so uma ideia }// final do if de serial disponivel if(run) { //delay(2000); //enableMotors(); forward(1000); coast(500); backward(1500); coast(500); forward(500); brake(500); turnLeft(500); turnRight(500); //disableMotors(); run = false; brake(0); } } //Define Low Level H-Bridge Commands //enable motors void motorAOn() { digitalWrite(enableA, HIGH); } void motorBOn() { digitalWrite(enableB, HIGH); } //disable motors void motorAOff() { digitalWrite(enableB, LOW); } void motorBOff() { digitalWrite(enableA, LOW); } //motor A controls void motorAForward() { digitalWrite(pinA1, HIGH); digitalWrite(pinA2, LOW); } void motorABackward() { digitalWrite(pinA1, LOW); digitalWrite(pinA2, HIGH); } //motor B contorls void motorBForward() { digitalWrite(pinB1, HIGH); digitalWrite(pinB2, LOW); } void motorBBackward() { digitalWrite(pinB1, LOW); digitalWrite(pinB2, HIGH); } //coasting and braking void motorACoast() { digitalWrite(pinA1, LOW); digitalWrite(pinA2, LOW); } void motorABrake() { digitalWrite(pinA1, HIGH); digitalWrite(pinA2, HIGH); } void motorBCoast() { digitalWrite(pinB1, LOW); digitalWrite(pinB2, LOW); } void motorBBrake() { digitalWrite(pinB1, HIGH); digitalWrite(pinB2, HIGH); } //Define High Level Commands void enableMotors() { motorAOn(); motorBOn(); } void disableMotors() { motorAOff(); motorBOff(); } void forward(int time) { motorAForward(); motorBForward(); delay(time); } void backward(int time) { motorABackward(); motorBBackward(); delay(time); } void turnLeft(int time) { motorABackward(); motorBForward(); delay(time); } void turnRight(int time) { motorAForward(); motorBBackward(); delay(time); } void coast(int time) { motorACoast(); motorBCoast(); delay(time); } void brake(int time) { motorABrake(); motorBBrake(); delay(time); }
import { Form } from 'antd'; import { useTranslation } from 'react-i18next'; import { Modal } from '@/components/share-components/modal'; import { IntlMessage } from '@/components/util-components/intl-message'; import { useNotifications } from '@/stores/notifications'; import { useCreateBackupData } from '../../api/create-backup-data'; import { BackupDataForm } from '../backup-data-form'; type BackupDataCreateModalProps = { open: boolean; onCancel?: () => void; }; export const BackupDataCreateModal = ({ open, onCancel, }: BackupDataCreateModalProps) => { const [form] = Form.useForm(); const { t } = useTranslation(); const { showNotification } = useNotifications(); const creatBackupData = useCreateBackupData({ onSuccess: () => { showNotification({ type: 'success', message: t( 'logManagement.notification.created' ) as string, }); onCancel?.(); }, }); const onSubmit = async () => { await form.validateFields(); const values = form.getFieldsValue(); const { config, logs } = values.backup; creatBackupData.submit({ ...values, backup: { config: !!config, logs: !!logs }, }); }; return ( <Modal width={670} open={open} onCancel={onCancel} centered title={ <IntlMessage id="logManagement.backupData.create.title" /> } onOk={onSubmit} okText={<IntlMessage id="logManagement.create" />} bodyStyle={{ padding: '24px 0' }} okButtonProps={{ loading: creatBackupData.isLoading, }} afterClose={() => form.resetFields()} destroyOnClose > <BackupDataForm form={form} /> </Modal> ); };
SuperCalculadora - por Marcos Arana --------------- <¿Que es?> SuperCalculadora es una herramienta de ayuda cuando se van a realizar las compras en el supermercado. Permite llevar un control de los gastos, calcular rapidamente distintos descuentos y promociones, y comparar entre dos opciones para elegir la mas economica. --------------- <Funciones principales> - Llevar un listado de lo que se esta comprando, calculando los valores totales con descuentos. - Comparar 2 productos de distintos tamaños, precio, y descuentos, para elegir el mas economico. - Crear sus propios descuentos personalizados. --------------- <Ventajas> - Saber cuanto va a gastar antes de llegar a la caja. - Poder comprobar si le cobraron correctamente y si hay diferencias encontrarlas rapidamente. - Ahorrar tiempo al realizar de forma facil los calculos de cualquier tipo de descuentos (ejemplo: 30%, 3x2, 2do al 70%, etc). - Poder elegir la opcion mas economica entre diferentes productos. --------------- <Instructivo de uso> La pagina tiene 4 secciones. A las 3 primeras se puede acceder desde el menu superior (desplegable en la version mobile) o bien desde los botones centrales ubicados en la pagina principal. A la ultima seccion, "Configuracion", solo se accede desde el menu superior. 1) Agregar al Carrito Es donde se toma nota de cada articulo que va comprando en el supermercado. Se debe ingresar un nombre de producto (ejemplo: yerba), el precio, y la cantidad a comprar. Adicionalmente, en "aplicar descuento", se abren 2 menu desplegables para aplicar hasta 2 descuentos diferentes (ejemplo, en el primero le aplico un 2do al 80 que corresponde a la promocion del producto, y adicionalmente en el segundo le pongo 20% por descuento con la tarjeta de credito). Cada descuento se aplica sobre el precio total sin descuentos, y luego se restan ambos descuentos. Si no encuentra el descuento que necesita puede ir a crear uno personalizado en la seccion "configuracion". Para confirmar la carga se debe presionar el boton "Agregar al Carrito" ubicado en la parte inferior. De esta forma ese producto ya queda cargado en el carrito. 2) Ver Carrito: Es donde se puede ver el detalle de los producto que esta comprando y que fueron previamente cargados en la seccion "agregar al carrito". En la parte inferior hay un boton rojo para borrar productos, si hay alguno seleccionado lo borra, si no hay ninguno seleccionado borra todo el carrito. En la parte superior derecha de color verde se puede observar el total del carrito (suma de todos los productos). En la tabla: -1er columna, aparece un cuadrado al lado de cada producto, se usa como seleccion para marcar los productos que quiero borrar, una vez seleccionados se presiona el boton rojo. -2da columna, "producto" se puede ver en negrita el nombre de cada producto, y debajo de cada uno el detalle del gasto (cantidad de unidades multiplicado por precio unitario y el total, y debajo los descuentos aplicados si los tuviera). -3er columna, "total" se ve el precio final del producto (precio por cantidad menos descuentos). -4ta columna, "+/-", el titulo de la columna es un boton que habilita un boton "+" y "-" en cada uno de los productos, estos sirven para sumar o restar 1 unidad de su producto (el nuevo total se recalcula automaticamente). 3) Comparar productos: Es donde puede comparar 2 productos de diferentes tamaños, precios, y descuentos, para saber cual es la opcion mas economica y cuanto puede ahorrar. Hay 2 columnas, producto A y producto B, donde se cargan los datos de los 2 productos a comparar. Cantidad por envase sirve para comparar 2 productos de diferente tamaño, si son iguales puede ingresar 1 en cada uno. Algunos ejemplos: Ejemplo 1: Si esta comparando queso crema de 300 gramos contra uno de 400 gramos, ingrese 300 y 400. Ejemplo 2: Si esta comparando un paquete de galletitas individual contra uno familiar que trae 3 paquetes adentro, ingrese 1 y 3. Ejemplo 3: Si los dos paquetes son iguales, ingrese 1 y 1. A continuacion debe ingresar el precio y seleccionar un descuento si corresponde. Para finalizar la comparacion presione el boton "Comparar", va a aparecer un mensaje con la opcion mas economica y cuanto esta ahorrando. Para borrar todos los datos de la comparacion presione el boton rojo. 4) Configuracion: Es donde puede crear descuentos personalizados o borrar descuentos. Esta seccion solo esta visible en la parte superior de la pagina (menu desplegable en version mobile). A esta seccion solo se puede acceder desde el menu superior (menu desplegable para la version mobile) en la pagina principal. -Crear descuento: Selecciona el tipo de descuento a crear (porcentaje de descuento, lleva X paga Y, o X% de descuento en la segunda unidad). Esto le habilita un campo para que cargue el porcentaje de descuento o el lleva X paga Y que necesite para su descuento personalizado. Para crearlo presione el boton verde. -Borrar descuento: En el menu desplegable seleccione el descuento que quiere borrar y presione el boton rojo. En la parte inferior tiene un boton azul para volver a los descuentos originales cargados por defecto (10%, 20%, 30%, 2x1, 3x2, 4x3, 2do al 50%, 2do al 70%, 2do al 80%). En la parte inferior de la pagina principal puede ver el valor total de su carrito. El carrito queda guardado en memoria, puede salir de la pagina y volver a entrar y va a poder continuar con su carrito (va a aparecer un mensaje al iniciar preguntando si quiere continuar con su carrito o iniciar uno nuevo) --------------- <Programacion> Para el proyecto se utilizaron... - Bootstrap y Sass para el diseño. - Operadores condicionales (if, else, switch), y ciclos (for, forEach) - Funciones, con y sin parametros, funciones flecha. - Variables locales y globales. - Clases con distintas propiedades y metodos, y constructores para crear items del carrito y opciones de descuentos. - Arrays, con distintos metodos y propiedades (lenght, push, indexOf, splice, etc). - Metodos de busqueda y transformacion (forEach, find, filter, reduce, sort), para ordenar, buscar, y modificar. - Manejo de DOM para crear las interacciones dinamicas, tales como mostrar el carrito, las respuestas a la comparacion de productos, sumar o restar unidades de forma dinamica, etc. - Control de eventos en botones, menu desplegables, y checkbox, con onClick y onChange. - Almacenamiento en localStorage, usando JSON, para almacenar y recuperar el carrito y las opciones de descuentos. - Operadores avanzados (++, operador ternario, or ||, etc). - Validacion de datos ingresados. - Asincronia comunicando con API usando fetch y Async Await. Sobre la API... Se uso la API de https://newsapi.org/ para traer noticias que se muestran en un carousel en el menu principal. IMPORTANTE: Para usar la API de forma gratuita se utilizo el plan Developer. Este plan restringe cualquier origen que no sea localhost, por lo que solo se mostraran cuando se corra en localhost. Se recomienda que para ver el funcionamiento se corra desde localhost. --------------- <Pendientes para futuras versiones> - Un boton para que se pueda ordenar el carrito (por orden de carga, precio, o alfabeticamente) - Una barra de buscar a medida que se vaya escribiendo. - Una opcion para elegir como calcular el 2do descuento, si sobre el subtotal o sobre el subtotal menos el primer descuento. - Una opcion para que quede fijo el segundo descuento si se necesita, por ejemplo por si tengo un descuento que aplica a todos los productos no tener que ingresarlo todas las veces que cargo un producto. - Poder calcular con un 2do descuento en la parte de comparar productos. --------------- <Github Pages> https://aranamarcos.github.io/supercalculadora/
SUBROUTINE AID(MM, M, N, A, CLAB, RLAB, JP, TH, K, DMIWRK, IWORK, * DMWRK1, WORK1, WORK2, OUNIT) C C<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> C C PURPOSE C ------- C C FORMS A TREE OF CLUSTERS BY SPLITTING CASES ON VALUES OF C INDIVIDUAL VARIABLES TO MINIMIZE THE SUM OF THE SQUARED C DEVIATIONS FROM THE CLUSTER MEANS. THE TREE CAN BE USED TO C PREDICT THE VALUE OF A DIFFERENT VARIABLE FOR A NEW CASE. C C DESCRIPTION C ----------- C C 1. THE ROUTINE STARTS WITH ONE CLUSTER OF ALL CASES, AND AT EACH C ITERATION SPLITS A CLUSTER INTO TWO CLUSTERS OF CASES ACCORDING C AS A(I,J) > C OR A(I,J) <= C, WHERE A IS THE DATA MATRIX AND I C ARE THE CASES. THE VARIABLE J AND THE CONSTANT C ARE CHOSEN C WHICH MINIMIZE THE SUM OF THE SQUARED WITHIN-CLUSTER DEVIATIONS C OF THE VARIABLE TO BE PREDICTED. IF THE REDUCTION IN THE SUM C OF SQUARES FOR THE CLUSTER WHICH WAS SPLIT IS GREATER THAN THE C THRESHOLD, THE SPLIT IS PERFORMED, OTHERWISE IT IS IGNORED. C THIS ROUTINE STOPS WHEN NO CLUSTER CAN BE SPLIT SUCH THAT THE C SUM OF SQUARES IS REDUCED BY MORE THAN THE THRESHOLD. C C 2. THE CASES ARE SORTED SUCH THAT EACH CLUSTER IS CONTIGUOUS IN C THE ORDER. THE OUTPUT IS WRITTEN ON FORTRAN UNIT OUNIT AND C BEGINS WITH THE PRINTING OF THE SORTED LIST OF THE CASES. C THEN, A TREE OF CLUSTERS ARE PRINTED OUT ALONG WITH THEIR C SUMMARY STATISTICS. THE CASES BELONGING TO EACH CLUSTER ARE C THE CASES IN THE SORTED ORDER THAT ARE BETWEEN THE FIRST AND C LAST CASE. THE VARIABLE THAT PRODUCES THE OPTIMUM SPLIT OF THE C CLUSTER, THE SPLIT POINT, AND THE REDUCTION IN THE SUM OF C SQUARES BY THE SPLIT ARE PRINTED. IF THE REDUCTION IS C NEGATIVE, THE SPLIT WAS PERFORMED; OTHERWISE, THE SPLIT WAS C IGNORED. THE MEAN AND THE VARIANCE OF THE PREDICTED VARIABLE C AND THE NUMBER OF ELEMENTS FOR EACH CLUSTER ARE ALSO DISPLAYED. C C 3. TO PRODUCE THE TREE, USE THE FIRST CLUSTER AS THE ROOT. IF THE C SUM OF SQUARES REDUCTION IS NEGATIVE, THIS CLUSTER WAS SPLIT ON C THE GIVEN SPLIT VARIABLE AT THE SPLIT POINT. LOOK FOR THE NEXT C CLUSTER WITH THE SAME FIRST CASE AND MAKE THAT CLUSTER THE LEFT C SON OF THE ROOT. THIS BRANCH CORRESPONDS TO CASES WHOSE SPLIT C VARIABLE HAS A VALUE LESS THAN OR EQUAL TO THE SPLIT POINT. C THE RIGHT SON IS THE FIRST CLUSTER IN THE LIST WHOSE LAST CASE C IS THE SAME AS THE LAST CASE OF THE ROOT CLUSTER, AND HAS THE C VALUE OF THE SPLIT VARIABLE GREATER THAN THE SPLIT POINT. C CONTINUE FOR EACH CLUSTER UNTIL NO CLUSTERS ARE SPLIT. THE C NODES AT THE BOTTOM OF THE TREE ARE THE FINAL CLUSTERS. C C 4. FOR AN EXISTING CASE, FIND THE FINAL CLUSTER IT BELONGS TO BY C MOVING DOWN THE TREE DETERMINED BY THE SPLITS USING THE KNOWN C VALUES. THEN, THE VALUE FOR THE VARIABLE TO BE PREDICTED FOR C THIS CASE IS THE MEAN OF THAT VARIABLE FOR THE CASES IN THAT C FINAL CLUSTER. THIS MEAN VALUE AND ITS VARIANCE IS PRINTED IN C THE LAST TWO COLUMNS OF THE OUTPUT. C C INPUT PARAMETERS C ---------------- C C MM INTEGER SCALAR (UNCHANGED ON OUTPUT). C THE LEADING DIMENSION OF MATRIX A. MUST BE AT LEAST M. C C M INTEGER SCALAR (UNCHANGED ON OUTPUT). C THE NUMBER OF CASES. C C N INTEGER SCALAR (UNCHANGED ON OUTPUT). C THE NUMBER OF VARIABLES. C C A REAL MATRIX WHOSE FIRST DIMENSION MUST BE MM AND SECOND C DIMENSION MUST BE AT LEAST M (CHANGED ON OUTPUT). C THE DATA MATRIX. C C A(I,J) IS THE VALUE FOR THE J-TH VARIABLE FOR THE I-TH CASE. C C CLAB VECTOR OF 4-CHARACTER VARIABLES DIMENSIONED AT LEAST N C (CHANGED ON OUTPUT). C ORDERED LABELS OF THE COLUMNS. C C RLAB VECTOR OF 4-CHARACTER VARIABLES DIMENSIONED AT LEAST M C (CHANGED ON OUTPUT). C ORDERED LABELS OF THE ROWS. C C JP INTEGER SCALAR (UNCHANGED ON OUTPUT). C NUMBER OF VARIABLE TO BE PREDICTED. MUST BE BETWEEN 1 AND N. C C TH REAL SCALAR (UNCHANGED ON OUTPUT). C THRESHOLD VARIANCE FOR SUM OF SQUARES REDUCTION. C C K INTEGER SCALAR (UNCHANGED ON OUTPUT). C MAXIMUM NUMBER OF CLUSTERS TO BE FORMED. SHOULD BE LESS C THAN 2*M. C C DMIWRK INTEGER SCALAR (UNCHANGED ON OUTPUT). C THE LEADING DIMENSION OF MATRIX IWORK. MUST BE AT LEAST 2. C C IWORK INTEGER MATRIX WHOSE FIRST DIMENSION MUST BE DMIWRK AND SECOND C DIMENSION MUST BE AT LEAST K. C WORK MATRIX. C C DMWRK1 INTEGER SCALAR (UNCHANGED ON OUTPUT). C THE LEADING DIMENSION OF MATRIX WORK1. MUST BE AT LEAST 6. C C WORK1 REAL MATRIX WHOSE FIRST DIMENSION MUST BE DMWRK1 AND SECOND C DIMENSION MUST BE AT LEAST K. C WORK MATRIX. C C WORK2 REAL VECTOR DIMENSIONED AT LEAST 2*M. C WORK VECTOR. C C OUNIT INTEGER SCALAR (UNCHANGED ON OUTPUT). C UNIT NUMBER FOR OUTPUT. C C REFERENCES C ---------- C C HARTIGAN, J. A. (1975). CLUSTERING ALGORITHMS, JOHN WILEY & C SONS, INC., NEW YORK. PAGES 330-346. C C SONQUIST, J. A. (1971). "MULTIVARIATE MODEL BUILDING: THE C VALIDATION OF A SEARCH STRATEGY." INSTITUTE FOR SOCIAL C RESEARCH, THE UNIVERSITY OF MICHIGAN, ANN ARBOR, MICH. C C<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> C
=== Responsive Sliding Menu === Contributors: lekciewp Tags: menu, responsive, sliding menu, lekcie, slide menu, mobile menu, elementor, elementor widget, elementor menu Requires at least: 5.7 Tested up to: 5.9 Stable tag: 1.4.4 Requires PHP: 7.4 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Responsive Sliding Menu is a plugin that generates a side-opening menu shortcode. The menu is fully customizable == Description == Responsive Sliding Menu allows you to generate a shortcode to integrate into your site via a page builder (Elementor, Oxygen, Divi, Gutenberg...) or via PHP. A preview of the rendering is available in the WordPress plugin settings interface. In particular, you can modify the colors, font sizes or even the icon of the burger menu (responsive). You can also use Elementor Widget RSM Menu to display (or not) your Responsive Sliding Menu. == Installation == 1. Download the Responsive Sliding Menu plugin ZIP file 2. Unzip the plugin in the /wp-content/plugins folder 3. On the WordPress plugins page, select the plugin and activate it == Frequently Asked Questions == = Can I change everything in my menu? = In plugin v1, you can change menu colors, font sizes, mobile burger menu icon, screen size from which mobile menu will display. It is not yet possible to modify the inside of the menu that opens sideways, but we are working on it for the next version = How do I modify the content of my menu? = The menus are found in Appearance>Menus. You just need to select or create a menu to modify its content. Don't forget to save your changes! = Not all of the submenus of my menu are displayed. Is it normal ? = Responsive Sliding Menu only displays 3 menu levels. If your submenus itself contains submenus, these will not be displayed. If you have other display concerns, please contact us plugins@lekcie.com == Screenshots == 1. Modify the general settings of Responsive Sliding Menu 2. Menu preview on the plugin page 3. Change the menu style 4. Overview of the submenu and sub-submenu 5. Icon of the burger menu chosen on the frontend 6. Display of the menu in mobile version on the frontend 7. Choose to display RSM using Elementor == Changelog == = 1.4.4 = * code fix: adding condition on size of array * php8 compatibility check = 1.4.3 = * compatibility check with WP core 5.9 * fix: review banner hides when clicked = 1.4.2 = * compatibility check with WP core 5.8.2 = 1.4.1 = * compatibility check with WP core 5.8.1 = 1.4.0 = * feature: Elementor compatible - allows to add RSM widget using Elementor widgets * compatibility check with WP core 5.8 = 1.3.2 = * patch: loads dashicons = 1.3.1 = * CSS box shadow mobile menu * add chevrons to submenus * remove fontawesome = 1.3.0 = * change fontawesome with dashicons * add "always" and "never" choices to mobile menu icon = 1.2.0 = * translation ready * CSS fix = 1.1.0 = * add a review notice after 7 days = 1.0.4 = * compatibility check with WP core 5.7.2 * edit US pot file * JS translation * fix backend css = 1.0.3 = * compatibility check with WP core 5.7.1 * add language pot file * add EN_US language mo file * fix css transitions = 1.0.2 = * compatibility check with WP core 5.6.1 = 1.0.1 = * compatibility check with WP core 5.5 = 1.0.0 = * plugin creation == Upgrade Notice == = 1.0 = Création du plugin de personnalisation de Responsive Sliding Menu == A brief Markdown Example == 1. Modify Responsive Sliding Menu settings 2. Save the changes 3. Copy/paste the [responsive_slider_menu] shortcode into your page builder 4. You can also copy/paste the instruction <?php echo do_shortcode("[responsive_slider_menu]"); ?> in your PHP header.php file
import java.util.*; public class OLN{ public static void main(String[] args) { int[] numeroSet = new int[50]; long[] tiemposCounting = new long[50]; long[] tiemposRadix = new long[50]; long[] tiemposBucket = new long[50]; long[] tiemposHeap = new long[50]; for (int i = 0 ; i != 10000000 ;){ i= i+200000; numeroSet[(i/200000)-1]=i; } for (int i = 0 ; i < numeroSet.length ; i++){ int[] Au = llenaAleatorio(numeroSet[i]); int[] Ad = new int[Au.length]; int[] At = new int[Au.length]; int[] Ac = new int[Au.length]; for (int o = 0 ; o<Au.length ; o++ ){ Ad[o]=Au[o]; At[o]=Au[o]; Ac[o]=Au[o]; } int k = maxIn(Au); /* long aC = System.currentTimeMillis(); countingSort(Au,k); long bC = System.currentTimeMillis(); long tC = bC-aC; tiemposCounting[i] = tC; long aR = System.currentTimeMillis(); radixSort(Ad,k); long bR = System.currentTimeMillis(); long tR = bR-aR; tiemposRadix[i] = tR; */ int w = bNumber(At); long aB = System.currentTimeMillis(); bucketSort(At, w); long bB = System.currentTimeMillis(); long tB = bB-aB; tiemposBucket[i] = tB; /* long aH = System.currentTimeMillis(); heapSort(Ac); long bH = System.currentTimeMillis(); long tH = bH-aH; tiemposHeap[i] = tH; */ } /* System.out.println("CountingSort"); imprime(tiemposCounting); System.out.println("RadixSort"); imprime(tiemposRadix); */ System.out.println("BucketSort"); imprime(tiemposBucket); /* System.out.println("HeapSort"); imprime(tiemposHeap); */ } //------------------------------------------------------------------------------------------- HEAPSORT public static void heapSort(int A[]){ int n = A.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(A, n, i); // One by one extract an element from heap for (int i=n-1; i>0; i--){ // Move current root to end int temp = A[0]; A[0] = A[i]; A[i] = temp; // call max heapify on the reduced heap heapify(A, i, 0); } } // To heapify a subtree rooted with node i which is // an index in A[]. n is size of heap public static void heapify(int A[], int n, int i){ int largest = i; // Initialize largest as root int l = 2*i + 1; // left = 2*i + 1 int r = 2*i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && A[l] > A[largest]) largest = l; // If right child is larger than largest so far if (r < n && A[r] > A[largest]) largest = r; // If largest is not root if (largest != i){ int swap = A[i]; A[i] = A[largest]; A[largest] = swap; // Recursively heapify the affected sub-tree heapify(A, n, largest); } } /*--------------------------------CountingSort--------------------------------*/ static void countingSort(int[] A, int k)// k -> maxIn(A) { int i; int[] B = new int[A.length]; int[] C = new int[k + 1]; for (i = 0; i < A.length; i++) C[A[i]] += 1; for (i = 1; i < C.length; i++) C[i] += C[i - 1]; for (i = A.length-1; i >= 0; i--) B[--C[A[i]]] = A[i]; for (i = 0; i < A.length; i++) A[i] = B[i]; } /*--------------------------------RadixSort--------------------------------*/ static void countingR(int[] A, int d)// d -> i^digito corriente { int[] B = new int[A.length]; int[] C = new int[10]; int i; for (i = 0; i < A.length; i++) C[(A[i] / d) % 10] += 1; for (i = 1; i < C.length; i++) C[i] += C[i - 1]; for (i = A.length - 1; i >= 0; i--) B[--C[(A[i] / d) % 10]] = A[i]; for (i = 0; i < A.length; i++) A[i] = B[i]; } public static void radixSort(int[] A, int k)// k -> maxIn(A), ordena { for (int i = 1; k/i > 0 ; i= i*10) countingR(A,i); } /*--------------------------------BucketSort--------------------------------*/ private static void bucketSort(int[] A, int bNumber) { List<Integer>[] buckets = new List[bNumber];// Create bucket array for(int i = 0; i < bNumber; i++)// Associate a list with each index buckets[i] = new LinkedList<>(); // in the bucket array for(int j : A)// Assign numbers from array to the proper bucke { buckets[j/bNumber].add(j);// by using hashing function } int c=0; for(List<Integer> bucket : buckets)// sort buckets { int i = 0; int[] temp = new int[bucket.size()]; for(int j : bucket) temp[i++] = j; quickSort(temp,0,temp.length-1); for(int k : temp) A[c++] = k; } } public static int bNumber (int[] A)//cantidad de buckets { return (int)Math.sqrt(A.length)+1; } /*--------------------------------UTILIDADES--------------------------------*/ static void imprime(long[] x){ for (int i = 0; i < x.length ; i++ ) System.out.println(x[i]); } public static int maxIn (int[] A) { int n = A[0]; for (int i = 1; i < A.length ; ++i ) if (A[i]>n) n=A[i]; return n; } public static int[] llenaAleatorio(int a){ Random aleatorio = new Random(); int[] memoria = new int[a]; for(int i = 0 ; i < a ; i++) memoria[i] = aleatorio.nextInt(a); return memoria; //2147483647 } //------------------------------------------------------------------------------------------- QUICKSORT static int particion(int[] A, int p, int r){ int x = A[r]; int i = (p-1); for ( int j = p ; j < r ; j++ ){ if (A[j] < x){ i++; cambia(A,i,j); } } cambia(A,(i+1),r); return i+1; } static void cambia(int[] A, int i, int j){ int temp = A[i]; A[i] = A[j]; A[j] = temp; } static void quickSort(int[] A, int p, int r){ if (p < r){ int z = particion(A, p, r); quickSort(A, p, z-1); quickSort(A, z+1, r); } } }
import { Injectable, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { LocalStorageService } from './local-storage.service'; import { switchMap, tap } from 'rxjs/operators'; import { accessTokenKey, BASE_URL, usernameKey } from './constants'; import { User, UserService } from '@api'; import { Observable, ReplaySubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { private readonly _currentUserSubject: ReplaySubject<User> = new ReplaySubject(1); readonly currentUser$: Observable<User> = this._currentUserSubject.asObservable(); constructor( @Inject(BASE_URL) private _baseUrl: string, private _httpClient: HttpClient, private _localStorageService: LocalStorageService, private _userService: UserService ) {} public logout() { this._localStorageService.put({ name: accessTokenKey, value: null}); this._localStorageService.put({ name: usernameKey, value: null }); } public tryToLogin(options: { username: string; password: string }) { return this._httpClient.post<any>(`${this._baseUrl}api/user/token`, options) .pipe( tap(response => { this._localStorageService.put({ name: accessTokenKey, value: response.accessToken }); this._localStorageService.put({ name: usernameKey, value: options.username}); }), switchMap(_ => this._userService.getCurrent()), tap(x => this._currentUserSubject.next(x)) ); } }
//设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 // // 实现 MinStack1 类: // // // MinStack1() 初始化堆栈对象。 // void push(int val) 将元素val推入堆栈。 // void pop() 删除堆栈顶部的元素。 // int top() 获取堆栈顶部的元素。 // int getMin() 获取堆栈中的最小元素。 // // // // // 示例 1: // // //输入: //["MinStack1","push","push","push","getMin","pop","top","getMin"] //[[],[-2],[0],[-3],[],[],[],[]] // //输出: //[null,null,null,null,-3,null,0,-2] // //解释: //MinStack1 minStack = new MinStack1(); //minStack.push(-2); //minStack.push(0); //minStack.push(-3); //minStack.getMin(); --> 返回 -3. //minStack.pop(); //minStack.top(); --> 返回 0. //minStack.getMin(); --> 返回 -2. // // // // // 提示: // // // -2³¹ <= val <= 2³¹ - 1 // pop、top 和 getMin 操作总是在 非空栈 上调用 // push, pop, top, and getMin最多被调用 3 * 10⁴ 次 // // 👍 1301 👎 0 package cn import "math" //leetcode submit region begin(Prohibit modification and deletion) type MinStack struct { stack []int minStack []int n int } func Constructor() MinStack { return MinStack{make([]int, 0), make([]int, 0), 0} } func (this *MinStack) Push(val int) { this.stack = append(this.stack, val) this.minStack = append(this.minStack, min(val, this.GetMin())) this.n++ } func min(a, b int) int { if a < b { return a } return b } func (this *MinStack) Pop() { this.minStack = this.minStack[:this.n-1] this.stack = this.stack[:this.n-1] this.n-- } func (this *MinStack) Top() int { return this.stack[this.n-1] } func (this *MinStack) GetMin() int { if this.n == 0 { return math.MaxInt } return this.minStack[this.n-1] } type MinStack1 struct { data []int min int empty bool index int } func ConstructorMinStack() MinStack1 { return MinStack1{data: make([]int, 1), index: -1, empty: true} } func (this *MinStack1) Push(val int) { if this.empty { this.min = val this.empty = false } else { if val < this.min { this.min = val } } this.index++ if len(this.data)-1 < this.index { this.data = append(this.data, make([]int, this.index)...) } this.data[this.index] = val } func (this *MinStack1) Pop() { if this.Top() == this.min { min := this.data[0] for i := 0; i < this.index; i++ { if this.data[i] < min { min = this.data[i] } } this.min = min } this.index-- if this.index == -1 { this.empty = true } } func (this *MinStack1) Top() int { return this.data[this.index] } func (this *MinStack1) GetMin() int { return this.min } /** * Your MinStack1 object will be instantiated and called as such: * obj := Constructor(); * obj.Push(val); * obj.Pop(); * param_3 := obj.Top(); * param_4 := obj.GetMin(); */ //leetcode submit region end(Prohibit modification and deletion)
<template> <div data-tag="tiny-popconfirm" class="inline-block"> <tiny-popover ref="popover" tiny_mode="mobile-first" v-model="state.showPopover" :placement="placement" trigger="manual" :width="width" :title="title" :popper-class="m('min-w-[theme(spacing.44)] max-w-[theme(spacing.96)]', customClass)" :reference="reference" @show="handleEmit('show')" @hide="handleEmit('hide')" > <template #header> <div data-tag="tiny-popconfirm-header" class="flex items-center leading-6 sm:pt-1"> <component v-if="type" :is="state.getIcon" :class=" m( 'h-6 w-6 mr-2', { 'fill-color-info-secondary': type === 'info' }, { 'fill-color-error': type === 'error' }, { 'fill-color-warning': type === 'warning' }, { 'fill-color-success': type === 'success' } ) " > </component> <div class="flex-auto">{{ title }}</div> </div> </template> <template #default> <div data-tag="tiny-popconfirm-content"> <div class="sm:leading-6 sm:text-xs sm:text-color-text-secondary">{{ message }}</div> </div> </template> <template #footer> <div data-tag="tiny-popconfirm-footer" class="sm:pb-1"> <div class="hidden sm:flex mt-4 justify-end"> <slot name="footer"> <tiny-button v-if="cancelButton" class="mr-2 w-16" size="mini" tiny_mode="mobile-first" @click="hide">{{ t('ui.buttonMessage.cancel') }}</tiny-button> <tiny-button class="w-16" size="mini" tiny_mode="mobile-first" type="primary" @click="confirm">{{ t('ui.buttonMessage.confirm') }}</tiny-button> </slot> </div> <div class="flex sm:hidden text-base justify-center"> <slot name="footer"> <tiny-button v-if="cancelButton" custom-class="flex-1 text-color-text-secondary" tiny_mode="mobile-first" type="text" @click="hide" >{{ t('ui.buttonMessage.cancel') }}</tiny-button > <span v-if="cancelButton" class="border-r border-r-color-border-separator"></span> <tiny-button custom-class="flex-1 text-color-brand tiny-modal-mf-button" tiny_mode="mobile-first" type="text" @click="confirm" >{{ t('ui.buttonMessage.confirm') }}</tiny-button > </slot> </div> </div> </template> <template #reference> <div class="inline-block" @click="show('click')" @mouseover="show('hover')"> <slot name="reference"></slot> </div> </template> </tiny-popover> </div> </template> <script> import { setup, $prefix, defineComponent } from '@opentiny/vue-common' import { renderless, api } from '@opentiny/vue-renderless/popconfirm/vue' import Popover from '@opentiny/vue-popover' import Button from '@opentiny/vue-button' import { iconError, iconInfoSolid, iconWarning, iconSuccess } from '@opentiny/vue-icon' const $constants = { ICON_MAP: { success: 'icon-success', error: 'icon-error', info: 'icon-info-solid', warning: 'icon-warning' } } export default defineComponent({ name: $prefix + 'Popconfirm', components: { TinyPopover: Popover, TinyButton: Button, IconSuccess: iconSuccess(), IconInfoSolid: iconInfoSolid(), IconWarning: iconWarning(), IconError: iconError() }, props: { _constants: { type: Object, default: () => $constants }, message: String, customClass: String, trigger: { type: String, default: 'hover', validator: (value) => ~['click', 'hover'].indexOf(value) }, cancelButton: { type: Boolean, default: true }, title: String, placement: { type: String, default: 'top' }, width: { type: [String, Number], default: '' }, type: [String, Object], reference: {}, events: Object }, emits: ['hide', 'show', 'confirm', 'handleEmit'], setup(props, context) { return setup({ props, context, renderless, api }) } }) </script>
document.addEventListener("DOMContentLoaded", main);//ativando a nossa função principal const library = [//array library {// objeto categoria category: "Comunismo", books: [//array de livros {//cada livro é um objeto title: "O Manifesto do Partido Comunista", author: "Karl Marx e Fredrich Engles" }, {//objeto livro title: "Do Socialismo Científico ao Socialismo Utópico", author: "Fredrich Engels" }, {//objeto livro title: "O Capital", author: "Karl Marx" }, {//objeto livro title: "A sagrada família", author: "Karl Marx" }, { title: "Manuscritos econômico-filosóficos", author: "Karl Marx" } ] }, {//objeto categoria 2 category: "Política", books: [//array de livros {//objeto livro title: "Direita e Esquerda", author: "Norberto Bob" } ] }, { category: "Computação", books: [ { title: "Entendendo Algoritmos", author: "Aditya Y. Bhargava" } ] } ] //livros disponíveis function books_available() { for (let categorias of library) { for (let livros of categorias.books) { console.log(`${livros.title} - ${livros.author}`) } } } // Quantidade de categorias function countCategory() { console.log(`Número de categorias : ${library.length}`) for (let categories of library) { console.log(`Categoria : ${categories.category}`) } } //Buscar author e livros function findAuhor(author) { let booksByAuthor = []; for (let categorias of library) {//acessando o primeiro nível : categoria for (let books of categorias.books) { if (books.author === author) { booksByAuthor.push(books.title); } } } return booksByAuthor;//retorna o array } // Quantidade autores function amountAuthor() { let authors = [];//autores for (let categorias of library) {//acessando o 1º nível :categoria for (let autor of categorias.books) {//acessando o segundo nível : books if (authors.indexOf(autor.author) == -1) {//se não localizar o nome do autor dentro do nosso array, ele joga o author pro array authors.push(autor.author) } } } return authors; } //função principal function main() { let arrayAuthor = amountAuthor();//variável do escopo amountAuthor. Retorna um array dos autores existentes let author = "Karl Marx";//author buscado let arrayBooksByAuthor = findAuhor(author);// função que passa o nome do autor e retorna um array com suas obras countCategory();//categorias da biblioteca books_available();//livros disponíveis na library //condição usada para validar a existência de um array com os livros do author pesquisado if (arrayBooksByAuthor.length > 0) { console.log(`Livros de ${author} :\n ${arrayBooksByAuthor.join(", ")}`) } else { console.log(`Não foi encontrado livros do author ${author}`) } // autores de livros da nossa biblioteca console.log(`Autores de nossa biblioteca : ${arrayAuthor.join(", ")}`) }
/* * This code is sample code, provided as-is, and we make no * warranties as to its correctness or suitability for any purpose. * * We hope that it's useful to you. Enjoy. * Copyright LearningPatterns Inc. */ package com.hr.personnel.client; import com.hr.personnel.Department; import com.hr.personnel.HourlyEmployee; import com.hr.personnel.SalariedEmployee; import java.time.LocalDate; /** * Application main-class. */ class HRClient { public static void main(String[] args) { // create Department object Department dept = new Department("Sales", "Seattle"); System.out.println(dept); // add Employees to it dept.addEmployee(new SalariedEmployee("Jason", LocalDate.of(1990, 8, 24),200000)); dept.addEmployee(new HourlyEmployee("Julie", LocalDate.of(2000, 2, 2),53,40)); dept.addEmployee(new SalariedEmployee("Jimmy", LocalDate.of(2020, 3, 20),110000)); dept.addEmployee(new HourlyEmployee("John", LocalDate.of(2010, 9, 24),50.3,40)); // list its Employees System.out.println("\nList employees:"); dept.listEmployees(); // make its Employees work System.out.println("\nMake employees work:"); dept.workEmployees(); System.out.println("\nPay employees:"); dept.payEmployees(); } }
<template> <div class="post-list"> <div class="post" v-for="post in posts" :key="post.id" > <div v-if="userById(post.userId)" class="user-info" > <a href="#" class="user-name"> {{ userById(post.userId).name }} </a> <a href="#"> <img class="avatar-large" :src="userById(post.userId).avatar" alt="" /> </a> <p class="desktop-only text-small">{{ userById(post.userId).postsCount }} posts</p> <p class="desktop-only text-small">{{ userById(post.userId).threadsCount }} threads</p> </div> <div class="post-content"> <div class="col-full"> <PostEditor v-if="editing === post.id" :post="post" @save="handleUpdate" > edit mode </PostEditor> <p v-else>{{ post.text }}</p> </div> <a v-if="post.userId === $store.state.authId" @click.prevent="toggleEditMode(post.id)" href="#" style="margin-left: auto; padding-left: 10px" class="link-unstyled" title="Make a change" > <fa icon="fa-solid fa-pencil-alt" /> </a> </div> <div class="post-date text-faded"> <div v-if="post.edited?.at" class="edition-info">edited</div> <AppDate :timestamp="post.publishedAt" /> </div> </div> </div> </template> <script> import PostEditor from '@/components/PostEditor'; import { mapActions } from 'vuex'; export default { name: 'PostList', components: { PostEditor }, props: { posts: { type: Array, required: true, }, }, data() { return { editing: null, }; }, methods: { ...mapActions([ 'updatePost', ]), userById(id) { return this.$store.getters.user(id); }, toggleEditMode(id) { this.editing = id === this.editing ? null : id; }, handleUpdate(event) { this.updatePost(event.post); this.editing = null; }, }, }; </script> <style scoped> </style>
package com.mark.springbootmall.controller; import com.mark.springbootmall.dto.UserLoginRequest; import com.mark.springbootmall.dto.UserRegisterRequest; import com.mark.springbootmall.model.User; import com.mark.springbootmall.service.UserService; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; //註冊功能 @PostMapping("/users/register") public ResponseEntity<User> register(@RequestBody @Valid UserRegisterRequest userRegisterRequest) { Integer userId = userService.register(userRegisterRequest); User user = userService.getUserById(userId); return ResponseEntity.status(HttpStatus.CREATED).body(user); } //登入功能 @PostMapping("/users/login") public ResponseEntity<User> login(@RequestBody @Valid UserLoginRequest userLoginRequest){ User user = userService.login(userLoginRequest); return ResponseEntity.ok().body(user); } }
<template> <div class="chat-room"> <div class="message-box"> <message-container :messages="messages"></message-container> </div> <div class="message-input"> <input type="text" v-model="message" class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6 px-4" /> </div> <div> <button @click="sendMessage">Gửi</button> </div> </div> </template> <script setup lang="ts"> import { Message } from '@/entities/message'; import { ref } from 'vue'; import MessageContainer from './MessageContainer.vue'; const messages = defineModel<Message[]>('messages', { default: [], }); const emit = defineEmits<{ (e: 'sendMessage', message: string): void; }>(); const message = ref<string>(''); function sendMessage() { emit('sendMessage', message.value); } </script> <style scoped lang="scss"> .chat-room { margin: auto; width: 400px; } </style>
package com.skillstorm; import java.util.Objects; public class GasTank implements Fillable{ private final double GALLONS; private double gas; public GasTank() { this.GALLONS = 20; } public GasTank(double gallons, double gas) { this.GALLONS = gallons; this.gas = gas; } @Override public void fill() { this.gas = this.GALLONS; } @Override public void empty() { this.gas = 0; } @Override public void fill(double quantity) { if(this.gas != this.GALLONS && quantity <= this.GALLONS - this.gas) { this.gas += quantity; } else { System.out.println("Too much gas!"); } } @Override public void empty(double quantity) { if(this.gas != 0 && quantity <= this.GALLONS - this.gas) { this.gas += quantity; } else { System.out.println("Not enough gas!"); } } @Override public String toString() { return "GasTank [GALLONS=" + GALLONS + ", gas=" + gas + "]"; } @Override public int hashCode() { return Objects.hash(GALLONS, gas); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GasTank other = (GasTank) obj; return Double.doubleToLongBits(GALLONS) == Double.doubleToLongBits(other.GALLONS) && Double.doubleToLongBits(gas) == Double.doubleToLongBits(other.gas); } }
%% ----- CONFIGURATION OPTIONS ----- clear, clc, clf, hold on; % ----- PARAMETERS & INITIAL CONDITIONS ----- mc = [1; 1]; % mass of cores ns = [1000; 1000]; % number of stars for each core rc0 = [-1, 1, 0; 1, -1, 0]; % initial position of cores vc0 = [0, -1, 0; 0, 1, 0]; % initial velocity of cores range_rs = [0.1, 0.8; 0.2, 0.8]; % range of initial star radii for each core range_thetas = [pi/2, pi/2; pi/2, pi/2]; % range of initial star thetas for each core range_phis = [0, 2 * pi; 0, 2 * pi]; % range of initial star phis for each core range_alphas = [pi/2, pi/2; pi/2, pi/2]; % range of initial star alphas for each core % ----- DISCRETIZATION ----- tmax = 4; level = 9; % ----- ANIMATE AND SAVE OPTIONS ----- do_save = true; trace_cores = true; delay = 0; padding = 2; save_name = 'toomre.avi'; color_cores = [[9, 18, 110] / 255; [173, 3, 3] / 255]; color_stars = ['b'; 'r']; size_cores = 10 * mc .^ (1 / 3); % scale core size with its mass size_stars = 3; %% ----- SIMULATION CODE ----- % ----- SOME DEFINITIONS FOR EASE ----- nc = length(mc); nt = 2 ^ level + 1; t = linspace(0, tmax, nt); dt = t(2) - t(1); plot_lims = [-max(rc0, [], 1) - padding; max(rc0, [], 1) + padding]'; % ----- RANDOM SAMPLING OF STAR POSITIONS AND VELOCITIES ----- rs0 = zeros(0, 3); vs0 = zeros(0, 3); for i = 1: nc rs = randsInRange(range_rs(i, :), ns(i)); thetas = randsInRange(range_thetas(i, :), ns(i)); phis = randsInRange(range_phis(i, :), ns(i)); alphas = randsInRange(range_alphas(i, :), ns(i)); [x, y, z] = sph2cart(phis, pi / 2 - thetas, rs); vhats = [-sin(alphas) .* sin(phis) - cos(alphas) .* cos(thetas) .* cos(phis), ... sin(alphas) .* cos(phis) - cos(alphas) .* cos(thetas) .* sin(phis), ... cos(alphas) .* sin(thetas)]; rs0 = cat(1, rs0, [x, y, z] + rc0(i, :)); vs0 = cat(1, vs0, sqrt(mc(i) ./ rs) .* vhats + vc0(i, :)); end % ----- INITIALIZE CORE AND STAR POSITIONS ----- rc = zeros(nc, 3, nt); rs = zeros(sum(ns), 3, nt); rc(:, :, 1) = rc0; rs(:, :, 1) = rs0; rc(:, :, 2) = rc0 + dt * vc0 + 0.5 * dt ^ 2 * accelCores(mc, rc(:, :, 1)); rs(:, :, 2) = rs0 + dt * vs0 + 0.5 * dt ^ 2 * accelStars(mc, rc(:, :, 1), rs(:, :, 1)); % ----- DEFINE MAP FROM CORE TO ITS STARS ----- c2s = cell(1, nc); for j = 1: nc prev = sum(ns(1: j - 1)); c2s{j} = prev + 1: prev + ns(j); end % ----- 4-LEVEL CONVERGENCE TEST ----- levels = [level - 3, level - 2, level - 1, level]; [t1, x1] = trackX(rc, rs, mc, tmax, levels(1)); [t2, x2] = trackX(rc, rs, mc, tmax, levels(2)); [~, x3] = trackX(rc, rs, mc, tmax, levels(3)); [~, x4] = trackX(rc, rs, mc, tmax, levels(4)); dx12 = x1 - x2(1: 2: end); dx23 = (x2(1: 2: end) - x3(1: 4: end)) * 4; dx34 = (x3(1: 4: end) - x4(1: 8: end)) * 16; plot(t1, dx12, 'g'); plot(t1, dx23, 'r'); plot(t1, dx34, 'k'); xlabel('time'); ylabel('scaled \Deltax between adjacent levels'); legend(sprintf('\\Deltax_{%d,%d}', levels(1), levels(2)), ... sprintf('4\\Deltax_{%d,%d}', levels(2), levels(3)), ... sprintf('16\\Deltax_{%d,%d}', levels(3), levels(4)), 'interpreter', 'tex'); pause(5); % ----- ANIMATE AND SAVE ----- if do_save writer = VideoWriter(save_name); open(writer); for i = 2: nt clf, hold on, box on, axis equal, axis manual; xlim(plot_lims(1, :)); ylim(plot_lims(2, :)); zlim(plot_lims(3, :)); xlabel('x'); ylabel('y'); title(sprintf('step: %d of %d, time: %.2f', i - 1, nt - 1, t(i))); plot(0, 0, 'ok', 'MarkerSize', 3); for j = 1: nc plot(rs(c2s{j}, 1, i), rs(c2s{j}, 2, i), '.', 'MarkerSize', size_stars, 'MarkerEdgeColor', color_stars(j, :)); plot(rc(j, 1, i), rc(j, 2, i), '.', 'MarkerSize', size_cores(j), 'MarkerEdgeColor', color_cores(j, :)); if trace_cores trace = reshape(rc(j, :, 1: i), 3, []); plot(trace(1, :), trace(2, :), '--', 'Color', color_cores(j, :)); end end drawnow; writeVideo(writer, getframe(gcf)); pause(delay); [rc, rs] = iterate(i, rc, rs, mc, dt); end close(writer); end close all;
package main import ( "fmt" "math/rand/v2" "sort" ) type MyStruct struct { Id int } func SliceMax(structures []MyStruct) MyStruct { MaxValStruct := structures[0] for _, s := range structures { if s.Id > MaxValStruct.Id { MaxValStruct = s } } return MaxValStruct } func SliceToSet(structures []MyStruct) (setStructures []MyStruct) { setStructures = make([]MyStruct, 0, len(structures)) var ( LenInput int = len(structures) maxSorted MyStruct = MyStruct{Id: -1} minUnsortedS MyStruct = SliceMax(structures) ) for i := 0; i < LenInput; i++ { minUnsortedIter := minUnsortedS for _, s := range structures { if s.Id > maxSorted.Id && s.Id < minUnsortedIter.Id { minUnsortedIter = s } } if minUnsortedIter.Id == maxSorted.Id { return setStructures } setStructures = append(setStructures, minUnsortedIter) maxSorted = minUnsortedIter } return setStructures } func SliceToSet_v2(structures []MyStruct) (setStructures []MyStruct) { setStructures = make([]MyStruct, 0, len(structures)) sort.SliceStable(structures, func(i, j int) bool { return structures[i].Id < structures[j].Id }) var lastValue MyStruct = MyStruct{Id: -1} for _, v := range structures { if v == lastValue { continue } setStructures = append(setStructures, v) lastValue = v } return setStructures } func main() { lenStruct := 20 workStruct := [20]MyStruct{} for i, _ := range workStruct { structIter := MyStruct{Id: rand.IntN(lenStruct / 3)} workStruct[i] = structIter } fmt.Println(workStruct) inputFunc := workStruct[0:6] fmt.Println(inputFunc) funcRes := SliceToSet(inputFunc) fmt.Println(funcRes) funcRes2 := SliceToSet_v2(inputFunc) fmt.Println(funcRes2) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <canvas id="dessin" width="640" height="480"> text pour le navigateur qui se ne supportons pas canvas </canvas> <script> var monCanvas = document.getElementById('dessin'); if(monCanvas.getContext){ var ctx = monCanvas.getContext('2d'); }else{ alert('canvas non supporté par ce navigateur'); } function Animer() { /* effaçage */ ctx.clearRect(0, 0, monCanvas.width,monCanvas.height); /* translation du contexte et dessin du premier rectangle */ ctx.translate(2,2); ctx.fillStyle = "blue"; ctx.fillRect(-10, -10, 20, 20); /* rotation puis translation du contexte et dessin du cercle */ ctx.rotate( 0.5 ); ctx.translate(50,0); /* arc : x, y, radius, startAngle, endAngle, antiClockwise */ ctx.beginPath(); ctx.arc(0, 0, 10, 0, 2 * Math.PI, false); ctx.fillStyle = 'green'; ctx.fill(); ctx.lineWidth = 1; ctx.strokeStyle = '#003300'; ctx.stroke(); } function Stopper() { clearInterval(inter); } var inter = setInterval(Animer, 100); setTimeout(Stopper, 20000); </script> </body> </html>
import { useState, useEffect, Suspense} from "react" import { Link, Outlet, useParams, useLocation, } from "react-router-dom"; import { getMovies } from "../../services/API" import MovieDetails from "../../components/MovieDetails/MovieDetails"; import Styles from "./MovieDetailsPage.module.css" const MovieDetailsPage = () => { const [movie, setMovie] = useState({}) const {movieId} = useParams() const location = useLocation(); const backLink = location.state?.from ?? '/'; const camefrom = location?.state?.from ?? '/'; useEffect(() => { const fetchMovie = async () => { const {movieData} = await getMovies("", "", movieId) setMovie(movieData); } fetchMovie() }, [movieId]) const { title, poster_path, overview, vote_average, genres } = movie || {} const userScore = Math.round(vote_average * 10) return ( <div> <div className={Styles.linkBtn }> <Link to={backLink}> Go Back </Link> </div> <div className={Styles.infoWrap}> {poster_path ? ( <img className={Styles.poster} src={`https://image.tmdb.org/t/p/w185/${poster_path}`} alt="Movie backdrop" width="200" height="auto" /> ) : ( <img className={Styles.poster} src={`https://th.bing.com/th/id/R.6486b7c738f4ee5dd3d0f74debbcf58b?rik=Ai9QxajK3PUhkg&pid=ImgRaw&r=0`} alt="Movie backdrop" width="200" height="auto" /> )} <div className={Styles.textWrap}> <h2 className={Styles.title}>{title}</h2> <p>user Score: {userScore}%</p> <h3>Overview</h3> <p>{overview}</p> <h3>Genres</h3> <ul className={Styles.genresList}> {genres && genres.map((genre) => ( <li key={genre.id}>{genre.name}</li> ))} </ul> </div> </div> <MovieDetails camefrom={camefrom} /> <Suspense fallback={<div>Loading subpage...</div>}> <Outlet /> </Suspense> </div> ); } export default MovieDetailsPage;
import React, { ReactElement } from 'react'; import { ButtonPropsInterface } from './ButtonPropsInterface'; import ButtonStyled from './ButtonStyled'; import Theme from './Theme'; import ButtonLabelStyled from './ButtonLabelStyled'; import { FIXME } from '../models/FixMe.model'; import ObjectHelper from '../helpers/ObjectHelper'; import ButtonIconStyled from './ButtonIconStyled'; import Ripple from './Ripple'; import ButtonAvatarStyled from './ButtonAvatarStyled'; const Button: React.FC<ButtonPropsInterface> = ({ attrType = 'button', children, color, disabled, flat, onClick, pill, raised, size, stroked, }: ButtonPropsInterface) => { const hasOnClick = () => (onClick ? onClick() : null); /** * Check if the children is an array and has elements */ const hasMultipleChildren = () => { return Array.isArray(children) && children.length; }; const getAvatarPosition = () => { if (hasMultipleChildren()) { return children.map((child: FIXME) => child?.type?.name).indexOf('Avatar') + 1; } if (!hasMultipleChildren() && children?.type?.name === 'Avatar') { return 1; } return 0; }; /** * Check if children consists of a label (string type) */ const hasAvatar = () => { if (hasMultipleChildren()) { return children.some((child: FIXME) => child?.type?.name === 'Avatar'); } if (!hasMultipleChildren() && children?.type?.name === 'Avatar') { return true; } return false; }; /** * Check if children consists of an Icon */ const hasIcon = (): boolean => { /** * Is of type Array and has multiple children where at least one is Icon */ if (hasMultipleChildren()) { return children.some((child: FIXME) => child?.type?.name === 'Icon'); } /** * Children is of type Object and element is Icon */ if (!hasMultipleChildren() && ObjectHelper.isObject(children)) { return children?.type?.name === 'Icon'; } /** * Children don't consist of an Icon element */ return false; }; /** * Check if children consists of a label (string type) */ const hasLabel = () => { if (hasMultipleChildren()) { return children.some((child: FIXME) => typeof child === 'string'); } if (!hasMultipleChildren() && typeof children === 'string') { return true; } return false; }; /** * Retrieves the Icon from children if it exists */ const getIcon = (): ReactElement | null => { if (hasIcon() && hasMultipleChildren()) { return children.filter((child: FIXME) => child?.type?.name === 'Icon'); } if (hasIcon() && !hasMultipleChildren() && ObjectHelper.isObject(children) && children?.type?.name === 'Icon') { return children; } return null; }; /** * Retrieves the label from children if it exists */ const getLabel = (): string | null => { if (hasLabel() && hasMultipleChildren()) { return children.filter((child: FIXME) => typeof child === 'string'); } if (hasLabel() && !hasMultipleChildren() && typeof children === 'string') { return children; } return null; }; return ( <Theme> <ButtonStyled avatarPosition={hasAvatar() ? getAvatarPosition() : 0} color={color} stroked={stroked} flat={flat} disabled={disabled} iconOnly={!hasMultipleChildren() && hasIcon()} onClick={hasOnClick} pill={hasAvatar() || pill} raised={raised} size={size} type={attrType} > <Ripple color={color} /> {hasMultipleChildren() ? children.map((child: FIXME) => { if (typeof child === 'string') { return <ButtonLabelStyled>{getLabel()}</ButtonLabelStyled>; } if (child?.type?.name === 'Icon') { return <ButtonIconStyled>{getIcon()}</ButtonIconStyled>; } if (child?.type?.name === 'Avatar') { return ( <ButtonAvatarStyled> {child} {getAvatarPosition().toString()} {hasAvatar().toString()} </ButtonAvatarStyled> ); } return child; }) : ''} {!hasMultipleChildren() ? ( <> {hasIcon() ? <ButtonIconStyled>{getIcon()}</ButtonIconStyled> : ''} {hasLabel() ? <ButtonLabelStyled>{getLabel()}</ButtonLabelStyled> : ''} {!hasIcon() && !hasLabel() ? children : ''} </> ) : ( '' )} </ButtonStyled> </Theme> ); }; export default Button;
package Practice_20_11; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.ToString; @AllArgsConstructor @Setter @Getter @ToString public abstract class ElectricDevice { float voltage; boolean worksOnBatteries; boolean isFaulty; public ElectricDevice( boolean worksOnBatteries) { this.worksOnBatteries = worksOnBatteries; this.isFaulty = false; } public void turnOn() { System.out.println("Turning device on..."); } public final void insertNewBatteries(){ if (worksOnBatteries){ System.out.println("Inserting new batteries to device"); }else { System.out.println("This device doesn't use batteries!"); } } public abstract void useDevice(); public abstract void fixDevice(); }
import { assert } from 'chai'; import * as Web3 from 'web3'; import { ProductDeregistered, ProductRegistered, ProductRegistry, ProjectArtifacts } from 'project'; import { ContractContextDefinition } from 'truffle'; import { assertNumberEqual, assertReverts, findLastLog, ZERO_ADDRESS } from './helpers'; declare const web3: Web3; declare const artifacts: ProjectArtifacts; declare const contract: ContractContextDefinition; const ProductRegistryContract = artifacts.require('./ProductRegistry.sol'); contract('ProductRegistry', accounts => { const owner = accounts[9]; const nonOwner = accounts[8]; const product1 = accounts[7]; const product2 = accounts[6]; let registry: ProductRegistry; beforeEach(async () => { registry = await ProductRegistryContract.new({ from: owner }); }); describe('Constructor', () => { it('should create with empty product set', async () => { assert.isOk(registry); const addresses = await registry.getProductAddresses(); assert.isEmpty(addresses); }); }); describe('Registration', () => { it('should revert registering product as non-owner', async () => { await assertReverts(async () => { await registry.registerProduct(product1, 100, { from: nonOwner }); }); }); it('should register product as owner and emit', async () => { const tx1 = await registry.registerProduct(product1, 100, { from: owner }); const tx2 = await registry.registerProduct(product2, 200, { from: owner }); const log1 = findLastLog(tx1, 'ProductRegistered'); const log2 = findLastLog(tx2, 'ProductRegistered'); const addresses = await registry.getProductAddresses(); assert.equal(addresses.length, 2); assert.equal(addresses[0], product1); assert.equal(addresses[1], product2); assert.isOk(log1); assert.isOk(log2); const event1 = log1.args as ProductRegistered; const event2 = log2.args as ProductRegistered; assert.equal(event1.at, product1); assert.equal(event1.price, 100); assert.equal(event2.at, product2); assert.equal(event2.price, 200); }); it('should overwrite when registering existing product', async () => { const tx1 = await registry.registerProduct(product1, 100, { from: owner }); const tx2 = await registry.registerProduct(product1, 101, { from: owner }); const tx3 = await registry.registerProduct(product2, 200, { from: owner }); const tx4 = await registry.registerProduct(product2, 201, { from: owner }); const log2 = findLastLog(tx2, 'ProductRegistered'); const log4 = findLastLog(tx4, 'ProductRegistered'); const addresses = await registry.getProductAddresses(); assert.equal(addresses.length, 2); assert.equal(addresses[0], product1); assert.equal(addresses[1], product2); assert.isOk(log2); assert.isOk(log4); const event2 = log2.args as ProductRegistered; const event4 = log4.args as ProductRegistered; assert.equal(event2.at, product1); assert.equal(event2.price, 101); assert.equal(event4.at, product2); assert.equal(event4.price, 201); }); }); describe('Deregistration', () => { it('should revert deregistering product as non-owner', async () => { await registry.registerProduct(product1, 100, { from: owner }); await assertReverts(async () => { await registry.deregisterProduct(product1, { from: nonOwner }); }); }); it('should deregister product as owner and emit', async () => { await registry.registerProduct(product1, 100, { from: owner }); await registry.deregisterProduct(product1, { from: owner }); assert.isEmpty(await registry.getProductAddresses()); }); it('should not emit deregistering product from empty set', async () => { const tx = await registry.deregisterProduct(product1, { from: owner }); const log = findLastLog(tx, 'ProductDeregistered'); assert.isUndefined(log); }); it('should not emit deregistering product never registered', async () => { const tx1 = await registry.registerProduct(product1, 100, { from: owner }); const tx2 = await registry.deregisterProduct(product2, { from: owner }); const log2 = findLastLog(tx2, 'ProductDeregistered'); assert.isUndefined(log2); }); it('should not emit deregistering when already deregistered', async () => { await registry.registerProduct(product1, 100, { from: owner }); await registry.registerProduct(product2, 200, { from: owner }); await registry.deregisterProduct(product1, { from: owner }); await registry.deregisterProduct(product2, { from: owner }); const tx1 = await registry.deregisterProduct(product1, { from: owner }); const tx2 = await registry.deregisterProduct(product2, { from: owner }); const log1 = findLastLog(tx1, 'ProductDeregistered'); const log2 = findLastLog(tx2, 'ProductDeregistered'); assert.isUndefined(log1); assert.isUndefined(log2); }); }); describe('Querying', () => { it('for product should return false on empty set', async () => { const isRegistered = await registry.isProductRegistered(product1); assert.isFalse(isRegistered); }); it('for not registered product on non-empty set', async () => { await registry.registerProduct(product1, 100, { from: owner }); const isRegistered = await registry.isProductRegistered(product2); assert.isFalse(isRegistered); }); it('for registered product should return true', async () => { await registry.registerProduct(product1, 100, { from: owner }); const isRegistered = await registry.isProductRegistered(product1); assert.isTrue(isRegistered); }); it('for deregistered product should return false', async () => { await registry.registerProduct(product1, 100, { from: owner }); await registry.deregisterProduct(product1, { from: owner }); const isRegistered = await registry.isProductRegistered(product1); assert.isFalse(isRegistered); }); it('for price on registered product', async () => { await registry.registerProduct(product1, 100, { from: owner }); const price = await registry.getProductPrice(product1); assert.equal(price, 100); }); }); });
<!DOCTYPE html> <html> <head> <title> HTML5 Media </title> <meta charset="utf-8"> <meta name="description" content="Web-site that uses HTML5 media functionality"> <meta name="author" content="Dzanan Bajgoric"> <script> function handlePlayPause() { var video = document.getElementById("video"); if (video.paused) { video.play(); } else { video.pause(); } } function setVolume() { document.getElementById("video").volume = document.getElementById("volume_control").value; } function setLoopState() { document.getElementById("video").loop = document.getElementById("should_loop").checked; } </script> </head> <body> <button id="play_pause" onclick="handlePlayPause()"> Play/Pause </button><br> Volume: <input type="range" id="volume_control" min="0" max="1" step="0.1" value="1.0" onchange="setVolume()"><br> Auto replay: <input id="should_loop" type="checkbox" onchange="setLoopState()"><br><br> <video id="video" width="420" controls> <source src="multimedia/mov_bbb.mp4" type="video/mp4"> Your browser doesn't support the HTML5 video element. </video> <hr> <iframe width="420" height="320" src="https://www.youtube.com/embed/_3x6_doymmw" frameBorder="0" allow="fullscreen"> </iframe> <hr> <audio id="audio" controls> <source src="multimedia/horse.ogg" type="audio/ogg"> Your browser doesn't support the HTML5 audio element. </audio> </body> </html>
import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import { prisma } from "@/server/db"; import CredentialsProvider from "next-auth/providers/credentials"; import bcrypt from "bcrypt"; /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. * * @see https://next-auth.js.org/getting-started/typescript#module-augmentation */ declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; } & DefaultSession["user"]; } // interface User { // // ...other properties // // role: UserRole; // } } /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * * @see https://next-auth.js.org/configuration/options */ export const authOptions: NextAuthOptions = { adapter: PrismaAdapter(prisma), providers: [ CredentialsProvider({ id: "user", name: "credentials", credentials: { email: { label: "email", type: "text" }, password: { label: "password", type: "password" }, }, async authorize(credentials) { if (!credentials?.email || !credentials?.password) { throw new Error("Invalid credentials"); } const user = await prisma.user.findUnique({ where: { email: credentials.email, }, }); if (!user || !user?.hashedPassword) { throw new Error("User not found"); } const isCorrectPassword = await bcrypt.compare( credentials.password, user.hashedPassword ); if (!isCorrectPassword) { throw new Error("Wrong password"); } return user; }, }), CredentialsProvider({ id: "admin", name: "credentials", credentials: { email: { label: "email", type: "text" }, password: { label: "password", type: "password" }, }, async authorize(credentials) { if (!credentials?.email || !credentials?.password) { throw new Error("Invalid credentials"); } const user = await prisma.admin.findUnique({ where: { email: credentials.email, }, }); if (!user || !user?.hashedPassword) { throw new Error("User not found"); } const isCorrectPassword = await bcrypt.compare( credentials.password, user.hashedPassword ); if (!isCorrectPassword) { throw new Error("Wrong password"); } return user; }, }), ], pages: { signIn: "/", }, debug: process.env.NODE_ENV === "development", session: { strategy: "jwt", }, secret: process.env.NEXTAUTH_SECRET, }; /** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); };
using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace WinterGameJam { [CreateAssetMenu()] public class MusicProperties : ScriptableObject { [SerializeField] private AudioClip[] musicFiles; public AudioClip this[MusicType s] => musicFiles[(int)s]; #if UNITY_EDITOR [CustomEditor(typeof(MusicProperties))] public class MusicInspector : Editor { private static readonly int musicCount = Enum.GetValues(typeof(MusicType)).Length; private new MusicProperties target => base.target as MusicProperties; public override void OnInspectorGUI() { if (target.musicFiles.Length < musicCount) { Array.Resize(ref target.musicFiles, musicCount); } for (int i = 0; i < target.musicFiles.Length; i++) { target.musicFiles[i] = EditorGUILayout.ObjectField( $"{(MusicType)i}: ", target.musicFiles[i], typeof(AudioClip), false) as AudioClip; } EditorUtility.SetDirty(target); } } #endif } }
import { formatDistance, parseISO } from "date-fns"; import { useSelector } from "react-redux"; import emptyPp from "../../assets/emptyPp.jpg"; import useAxiosPrivate from "../../hooks/usePrivateAxios"; import { useState } from "react"; import toast from "react-hot-toast"; import { SlOptions } from "react-icons/sl"; const Comment = ({ comment, fetchComments }) => { const userComments = useSelector((state) => state.auth.user.comments); const user_id = useSelector((state) => state.auth.user.id); const dbDate = parseISO(comment.created_at); const timeAgo = formatDistance(dbDate, new Date(), { addSuffix: true, }); const userCommentIds = userComments?.split(",").map(Number) || []; const hasAccess = Boolean( userCommentIds.find((p) => p === comment.commentId) ); const [showOptions, setShowOptions] = useState(false); const privateAxios = useAxiosPrivate(); const toggleOptions = () => { setShowOptions(!showOptions); }; const deleteComment = async () => { try { const req = await privateAxios.delete("/addComment", { data: { user_id, comment_id: comment.commentId }, }); setShowOptions(!showOptions); toast.success("Comment deleted successfully", { style: { borderRadius: "10px", background: "#333", color: "#fff", }, }); fetchComments(); console.log("delete post delete: ", req.data); } catch (error) { console.error("Error delete Comment Comment", error); toast.error("Could not delete the comment", { style: { borderRadius: "10px", background: "#333", color: "#fff", }, }); } }; return ( <div className="flex justify-between"> <div className="flex gap-6 items-start"> <img src={comment.profilePic} alt="profilepic" className=" w-8 aspect-square rounded-full" /> <div className="w-full"> <h2 className=" text-sm font-semibold truncate"> {comment.username} </h2> <p className="text-sm truncate ">{comment.content}</p> </div> </div> <div className="flex gap-3 items-start"> <p className="text-sm">{timeAgo}</p> <div className=" relative w-fit"> <button className="text-xl" onClick={toggleOptions}> <SlOptions /> </button> {showOptions && ( <div className="bg-gray text-white p-2 rounded-xl pl-4 pr-8 absolute top-100 right-0 "> <ul> {hasAccess && ( <li className=" cursor-pointer hover:text-accentc">Edit</li> )} {hasAccess && ( <li className=" cursor-pointer hover:text-accentc" onClick={deleteComment} > Delete </li> )} <li className=" cursor-pointer hover:text-accentc">Report</li> </ul> </div> )} </div> </div> </div> ); }; export default Comment;
import { AppBar, Box, InputAdornment, TextField } from "@mui/material"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faBars } from "@fortawesome/pro-solid-svg-icons"; import { faMagnifyingGlass, faArrowRight } from "@fortawesome/pro-regular-svg-icons"; import profilePicture from '../../asset/picture/Sourav.png'; export default function HeaderBar() { return ( <AppBar position="sticky" className="bg-blue-500 p-2"> <Box className="flex items-center justify-between"> <Box className="flex items-center"> <Box className="mr-4"> <FontAwesomeIcon icon={faBars} size="lg" /> </Box> <Box className="text-2xl font-semibold"> To Do App </Box> </Box> <Box className="flex items-center"> <TextField variant="standard" className="pl-5 pr-5 pt-2 pb-2 bg-gray-100 rounded-full" placeholder="Search here" InputProps={{ startAdornment: <InputAdornment position="start"> <FontAwesomeIcon icon={faMagnifyingGlass} size="lg" /> </InputAdornment>, endAdornment: <InputAdornment position="end" > <FontAwesomeIcon icon={faArrowRight} size="lg" /> </InputAdornment>, disableUnderline: true, }} /> </Box> <Box className="flex items-center"> <Box className="mr-4"> <img className="object-cover object-top h-14 w-14 rounded-full" src={profilePicture} alt="profilePicture" /> </Box> <Box className="flex flex-col items-center"> <Box className="text-sm"> Welcome </Box> <Box className="text-2xl font-semibold"> Sourav </Box> </Box> </Box> </Box> </AppBar> ) }
<template> <div class="create-exam-page xs:px-8 py-6 px-4"> <div class="page-top flex flex-row items-center justify-between"> <button @click="goBack()" class="go-back transition-all flex items-center justify-center text-white text-2xl ease-linear duration-75 hover:-translate-y-1 mr-5 hover:shadow-lg font-bold bg-blue rounded px-3 py-2" > <ion-icon name="chevron-back-outline" class="m-1"></ion-icon> </button> <h1 class="title text-xl font-bold">Imtihon ochish</h1> </div> <div v-if="loading" class="loading text-center mt-4 text-2xl"> Loading... </div> <div v-else-if="notFound" class="not-found text-center mt-4"> <p class="text-xl"> Imtihon ochishdan oldin savollar to'plamini yaratish zarur </p> <router-link to="/create/subject" class="text-blue underline mt-2" >To'plam yaratish</router-link > </div> <div v-else class="exam-container mt-6"> <div class="select-group mb-5"> <p class="mb-2">Fanni tanlang</p> <select v-model="exam.name" class="bg-white border-2 outline-none w-full rounded p-3 mb-3 px-3 py-2 focus:border-blue transition-all cursor-pointer" > <option v-for="(subject, index) in all.names" :key="index" :value="subject" class="cursor-pointer px-3 py-2" > {{ subject }} </option> </select> </div> <div class="select-group mb-5"> <p class="mb-2">Sinfni tanlang</p> <select v-model="exam.classNum" class="bg-white border-2 outline-none w-full rounded p-3 mb-3 px-3 py-2 focus:border-blue transition-all cursor-pointer" > <option v-for="(classNum, index) in all.classes" :key="index" :value="classNum" class="cursor-pointer px-3 py-2" > {{ classNum }} - sinf </option> </select> </div> <div class="input-group mb-5"> <p class="mb-2">Tugash vaqtini yozing</p> <input v-model="exam.timeOut" class="bg-white border-2 outline-none w-full rounded p-3 mb-3 px-3 py-2 focus:border-blue transition-all" placeholder="Misol: 02:30:00" /> </div> <button @click="createExam()" :disabled="disableBtn" class="submit-btn border bg-blue text-white font-bold px-5 py-3 rounded w-full transition-all ease-linear duration-75 hover:-translate-y-1 hover:shadow-lg disabled:bg-gray" type="button" > OCHISH </button> </div> </div> </template> <script> import { computed, onBeforeMount, reactive, ref } from "vue"; import { useRouter } from "vue-router"; import { useStore } from "vuex"; import { api } from "@/http/api"; import { useToast } from "vue-toastification"; export default { setup() { document.title = `Imtihon ochish`; const toast = useToast(); const router = useRouter(); let loading = ref(false); let disableBtn = ref(false); let notFound = ref(false); const examId = computed(() => { let oneId = Math.random().toString(12).substring(2, 8) + exam.name.substring(0, 3) + exam.classNum.substring(0, 3); return oneId; }); const calculateMilliseconds = (h, m, s) => { return (h * 60 * 60 + m * 60 + s) * 1000; }; let exam = reactive({ name: "", classNum: "", timeOut: "", }); let all = reactive({ classes: [], names: [], }); const getAll = async () => { try { loading.value = true; api.get("/subjects/all").then((res) => { if (res.data.status === "bad") { loading.value = false; notFound.value = true; } else { all.classes = res.data.subject_classes; all.names = res.data.subject_names; } loading.value = false; }); } catch (error) { console.log(error); } }; const createExam = async () => { try { disableBtn.value = true; if (!exam.name) { disableBtn.value = false; toast.warning("Fanni tanlang!", { timeout: 4000, icon: true }); } else if (!exam.classNum) { disableBtn.value = false; toast.warning("Sinfni tanlang!", { timeout: 4000, icon: true }); } else if (!exam.timeOut) { disableBtn.value = false; toast.warning("Tugash vaqtini yozing!", { timeout: 4000, icon: true, }); } else { let timeOut = exam.timeOut.split(":"); let timeOutMilliseconds = calculateMilliseconds( +timeOut[0], +timeOut[1], +timeOut[2] ); api .post("/exams/create", { name: exam.name, classNum: exam.classNum, timeOut: timeOutMilliseconds, timeOutOriginal: exam.timeOut, oneId: examId.value, }) .then((resp) => { if (resp.data.status === "bad") { disableBtn.value = false; toast.warning(resp.data.msg, { timeout: 5000, icon: true }); } else { toast.success(resp.data.msg, { timeout: 4000, icon: true }); router.push("/"); disableBtn.value = false; } }); } } catch (error) { console.log(error.message); toast.error(error.message, { timeout: 4000 }); } }; onBeforeMount(() => { getAll(); }); const goBack = () => { router.go(-1); }; return { goBack, loading, notFound, exam, all, createExam, disableBtn }; }, }; </script> <style></style>
--- title: "\"2024 Approved Twitch Integration with Social Media Facebook Guide\"" date: 2024-05-20T13:25:59.082Z updated: 2024-05-21T13:25:59.082Z tags: - ai video - ai facebook - ai facebook video categories: - ai - facebook description: "\"This Article Describes 2024 Approved: Twitch Integration with Social Media: Facebook Guide\"" excerpt: "\"This Article Describes 2024 Approved: Twitch Integration with Social Media: Facebook Guide\"" keywords: "Twitch Streaming,Social Media Links,Facebook Integration,Live Stream Update,Twitch Social Tools,Connect to FB,Join Platforms Seamlessly" thumbnail: https://www.lifewire.com/thmb/Dp9islCb9GD3RtQaIU23WoKYMSs=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/001_best-lgbt-movies-on-netflix-right-now-5069913-92c9bcd3792548908be32c420bc4fa27.jpg --- ## Twitch Integration with Social Media: Facebook Guide ##### Facebook Video Maker - Wondershare Filmora Provide abundant video effects - A creative video editor Powerful color correction and grading Detailed tutorials provided by the official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Social networking has been around the corner since the early 21st Century. Different social media platforms have taken charge and provided the community with an impressive amount of network connectivity throughout the world. This has tempted users into shifting towards such sources that would help them connect across the world with their loved ones. While catering to the community as a whole, different platforms have provided room for a specific community. From offering celebrities a platform across Instagram to make their daily updates viral to helping the general community gain traction with TikTok, specific communities have taken advantage of the platforms that have been designed to incorporate within the social community. Twitch is one such platform that has offered the gaming community a source to stream effectively. Different features make it interactive and effective while allowing gamers to publish their gameplay across the platform. One such example is to **share Twitch stream on Facebook.** As this streaming platform interacts with one of the most utilized social media platforms, this article features a discussion of its process. #### In this article Part 1: [What is Twitch and How is it Helpful?](#step1) Part 2: [Share Twitch Stream on Facebook Through PC or Mac](#step2) Part 3: [How to Share Twitch Stream on Facebook across Android?](#step3) ## Part 1: What is Twitch and How is it Helpful? Twitch has been an appealing platform for the gaming community, where it has provided them with a variety of features to work with. As this platform connects the community together, different tools make it effective for them to work through the platform. The platform's primary focus is across video games, where the complete process involves playing, interacting, or live-streaming the gameplay across the world. ![what is twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-1.jpg) Along with the focused streaming services, users can work through the chat rooms and direct messages tool offered across this gaming service. The variety of services offered within these tools makes it quite extensive to explain the process. However, this article has discussed how to **connect Facebook to Twitch.** ## Part 2: Share Twitch Stream on Facebook Through PC or Mac Users looking forward to **sharing Twitch stream on Facebook** through their PC or Mac can follow a set of different procedures. These procedures, if followed properly, can help users set up the platform and share the video of their choice across Facebook. Look into the steps provided to understand the procedure to **embed Twitch stream on Facebook.** **Step 1:** To start, you are advised to install OBS Studio across your device. Access your browser and download the setup for sharing streams across Facebook. Tap on the “Download” tab on the top-right corner of the screen and proceed to select the operating system of your choice. ![click on download button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-2.jpg) **Step 2:** On selecting the appropriate OS, you will be redirected to a new window to download the setup across your device. Launch the installer and follow the installation procedure to install OBS Studio across your device successfully. ![install the obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-3.jpg) **Step 3:** As OBS Studio successfully installs itself across your device, the user will be redirected across the Auto-Configuration Wizard for setting up the platform according to the desired options. The user can set up the settings according to streaming and recording screens. On the other hand, they can only look forward to optimizing options according to recording the screens. For connecting and configuring audio and video across OBS, set up the sources across the Auto-Configuration Wizard and proceed towards finalization. ![configure obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-4.jpg) **Step 4:** On configuring the settings, run OBS Studio and test the streaming services before **stream Twitch to Facebook Live.** It is impossible to perform cross-sharing across Twitch exact; thus, there is a need to configure an applet for Twitch and Facebook to help share the stream with Facebook. ![check your obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-5.jpg) **Step 5:** Get started by setting up the free IFTTT account. You can choose any of the sign-in methods to proceed across the platform. Pick Google or Facebook from the available options and finish the on-screen settings to link the Facebook account and Twitch for sharing videos across the platform. ![login with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-6.jpg) **Step 6:** To set Facebook for the sharing content across the applet, the user will be directed to a new window where they are advised to provide their credentials. On completing the setup of the account, you need to provide IFTTT with permission to access your Facebook account. For this, tap on the "Continue as (Username)" option. IFTTT will get permission to share content and videos across the account from Twitch. ![connect with facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-7.jpg) **Step 7:** On completing the log-in of Facebook, proceed to provide the credentials for Twitch to connect the platform with Facebook for sharing content. Enter the important credentials for Twitch across the applet and tap on the log-in button once done. ![login twitch account](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-8.jpg) **Step 8:** Successfully connect the account with IFTTT and configure Twitch across Facebook to proceed successfully. ![connect twitch with fb](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-9.jpg) **Step 9:** You need to initiate a stream for posting it across Facebook. Start the Twitch stream and look forward to generating a URL that will be put across the link that will be posted across Facebook. Create a link post by providing information within the Stream Information. Add the information across the section under the required headings and include a particular message across the window along with a title. ![add stream information](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-10.jpg) **Step 10:** Hit on "Create Action" to set up a link to your Twitch stream that can be easily shared with the users for allowing them access across multiple platforms. ![tap on create account button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-11.jpg) ## Part 3: How to Share Twitch Stream on Facebook across Android? While working across Android, the user can consider operating through different methods for sharing Twitch stream across Facebook. If you look forward to **share Twitch stream on Facebook** using an Android, you need to look across the following methods for a better understanding of the procedure. ### Sharing Another Live Stream Across Facebook **Step 1:** Download and install Twitch across your Android successfully. On launching the platform, search through the stream and find the one that is to be shared. ![open twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-12.jpg) **Step 2:** You need to select the “Sharing” icon on the top of the window to lead to a set of different options that can be used to share the Twitch stream. ![click on share icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-13.jpg) **Step 3:** Select Facebook from the provided options and initiate by posting the stream across the platform by creating a new post. Post the selected stream with a clear description and tap “Post.” ![create the post](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-14.jpg) ### Sharing Personal Stream Across Facebook **Step 1:** Launch Twitch on your Android device and select the “Camera” icon that appears on the top of the screen. You will be led to different live streaming options across the platform. ![click on camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-15.jpg) **Step 2:** You can select either option from 'Stream Games' or 'Stream IRL' to stream the game if it is across the screen or stream personal video or audio from the mobile's camera, respectively. ![select one option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-16.jpg) **Step 3:** Provide the stream details with an appropriate name and tags. After setting up the title details and other appropriate details of the stream, select the “Share” icon on the top of the window to access the sharing menu of the Android. ![add the stream info details](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-17.jpg) **Step 4:** Select Facebook from the options and create a post with the details of the post to publish the link for the users to join the gameplay. Now, lead back to Twitch and initiate streaming across the platform, which can be accessed directly from Facebook. ![select facebook option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-18.jpg) ### Automatically Save Stream Across Facebook **Step 1:** Access the Play Store on your Android and install the official IFTTT application across your device. Open the application once it is installed. ![install ifttt app ](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-19.jpg) **Step 2:** You can sign in across the account using the Facebook or Google account. Follow the instructions to set up the account across the platform. ![connect with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-20.jpg) **Step 3:** Search for Twitch on the main screen of the application and select the option of "Automatically post on your official Facebook Page when you start streaming on Twitch." Share the link across the platform directly. ![search for twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-21.jpg) **Step 4:** Before redirecting to the next procedure, tap “Connect” to share details with other users. ![tap on connect button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-22.jpg) **Step 5:** Sign in on Twitch and Facebook to link the account with the mobile application. Provide appropriate permissions to the applications once installed for the stream. Access Twitch from your Android and tap on the “Camera” icon to initiate streaming. Set up the stream details and start the stream, as required by the users. ![tap camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-23.jpg) ## Conclusion This article has introduced Twitch to the users and provided a detailed explanation of how a Twitch stream is shared across the platform. While understanding how to **share Twitch stream on Facebook,** it is convenient to understand that the process exists for both Android and PC devices. To look more into how this is executed, look into the detailed discussion of the article and make a conclusive understanding of what exactly is to be followed for making a perfect Twitch stream. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Social networking has been around the corner since the early 21st Century. Different social media platforms have taken charge and provided the community with an impressive amount of network connectivity throughout the world. This has tempted users into shifting towards such sources that would help them connect across the world with their loved ones. While catering to the community as a whole, different platforms have provided room for a specific community. From offering celebrities a platform across Instagram to make their daily updates viral to helping the general community gain traction with TikTok, specific communities have taken advantage of the platforms that have been designed to incorporate within the social community. Twitch is one such platform that has offered the gaming community a source to stream effectively. Different features make it interactive and effective while allowing gamers to publish their gameplay across the platform. One such example is to **share Twitch stream on Facebook.** As this streaming platform interacts with one of the most utilized social media platforms, this article features a discussion of its process. #### In this article Part 1: [What is Twitch and How is it Helpful?](#step1) Part 2: [Share Twitch Stream on Facebook Through PC or Mac](#step2) Part 3: [How to Share Twitch Stream on Facebook across Android?](#step3) ## Part 1: What is Twitch and How is it Helpful? Twitch has been an appealing platform for the gaming community, where it has provided them with a variety of features to work with. As this platform connects the community together, different tools make it effective for them to work through the platform. The platform's primary focus is across video games, where the complete process involves playing, interacting, or live-streaming the gameplay across the world. ![what is twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-1.jpg) Along with the focused streaming services, users can work through the chat rooms and direct messages tool offered across this gaming service. The variety of services offered within these tools makes it quite extensive to explain the process. However, this article has discussed how to **connect Facebook to Twitch.** ## Part 2: Share Twitch Stream on Facebook Through PC or Mac Users looking forward to **sharing Twitch stream on Facebook** through their PC or Mac can follow a set of different procedures. These procedures, if followed properly, can help users set up the platform and share the video of their choice across Facebook. Look into the steps provided to understand the procedure to **embed Twitch stream on Facebook.** **Step 1:** To start, you are advised to install OBS Studio across your device. Access your browser and download the setup for sharing streams across Facebook. Tap on the “Download” tab on the top-right corner of the screen and proceed to select the operating system of your choice. ![click on download button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-2.jpg) **Step 2:** On selecting the appropriate OS, you will be redirected to a new window to download the setup across your device. Launch the installer and follow the installation procedure to install OBS Studio across your device successfully. ![install the obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-3.jpg) **Step 3:** As OBS Studio successfully installs itself across your device, the user will be redirected across the Auto-Configuration Wizard for setting up the platform according to the desired options. The user can set up the settings according to streaming and recording screens. On the other hand, they can only look forward to optimizing options according to recording the screens. For connecting and configuring audio and video across OBS, set up the sources across the Auto-Configuration Wizard and proceed towards finalization. ![configure obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-4.jpg) **Step 4:** On configuring the settings, run OBS Studio and test the streaming services before **stream Twitch to Facebook Live.** It is impossible to perform cross-sharing across Twitch exact; thus, there is a need to configure an applet for Twitch and Facebook to help share the stream with Facebook. ![check your obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-5.jpg) **Step 5:** Get started by setting up the free IFTTT account. You can choose any of the sign-in methods to proceed across the platform. Pick Google or Facebook from the available options and finish the on-screen settings to link the Facebook account and Twitch for sharing videos across the platform. ![login with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-6.jpg) **Step 6:** To set Facebook for the sharing content across the applet, the user will be directed to a new window where they are advised to provide their credentials. On completing the setup of the account, you need to provide IFTTT with permission to access your Facebook account. For this, tap on the "Continue as (Username)" option. IFTTT will get permission to share content and videos across the account from Twitch. ![connect with facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-7.jpg) **Step 7:** On completing the log-in of Facebook, proceed to provide the credentials for Twitch to connect the platform with Facebook for sharing content. Enter the important credentials for Twitch across the applet and tap on the log-in button once done. ![login twitch account](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-8.jpg) **Step 8:** Successfully connect the account with IFTTT and configure Twitch across Facebook to proceed successfully. ![connect twitch with fb](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-9.jpg) **Step 9:** You need to initiate a stream for posting it across Facebook. Start the Twitch stream and look forward to generating a URL that will be put across the link that will be posted across Facebook. Create a link post by providing information within the Stream Information. Add the information across the section under the required headings and include a particular message across the window along with a title. ![add stream information](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-10.jpg) **Step 10:** Hit on "Create Action" to set up a link to your Twitch stream that can be easily shared with the users for allowing them access across multiple platforms. ![tap on create account button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-11.jpg) ## Part 3: How to Share Twitch Stream on Facebook across Android? While working across Android, the user can consider operating through different methods for sharing Twitch stream across Facebook. If you look forward to **share Twitch stream on Facebook** using an Android, you need to look across the following methods for a better understanding of the procedure. ### Sharing Another Live Stream Across Facebook **Step 1:** Download and install Twitch across your Android successfully. On launching the platform, search through the stream and find the one that is to be shared. ![open twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-12.jpg) **Step 2:** You need to select the “Sharing” icon on the top of the window to lead to a set of different options that can be used to share the Twitch stream. ![click on share icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-13.jpg) **Step 3:** Select Facebook from the provided options and initiate by posting the stream across the platform by creating a new post. Post the selected stream with a clear description and tap “Post.” ![create the post](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-14.jpg) ### Sharing Personal Stream Across Facebook **Step 1:** Launch Twitch on your Android device and select the “Camera” icon that appears on the top of the screen. You will be led to different live streaming options across the platform. ![click on camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-15.jpg) **Step 2:** You can select either option from 'Stream Games' or 'Stream IRL' to stream the game if it is across the screen or stream personal video or audio from the mobile's camera, respectively. ![select one option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-16.jpg) **Step 3:** Provide the stream details with an appropriate name and tags. After setting up the title details and other appropriate details of the stream, select the “Share” icon on the top of the window to access the sharing menu of the Android. ![add the stream info details](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-17.jpg) **Step 4:** Select Facebook from the options and create a post with the details of the post to publish the link for the users to join the gameplay. Now, lead back to Twitch and initiate streaming across the platform, which can be accessed directly from Facebook. ![select facebook option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-18.jpg) ### Automatically Save Stream Across Facebook **Step 1:** Access the Play Store on your Android and install the official IFTTT application across your device. Open the application once it is installed. ![install ifttt app ](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-19.jpg) **Step 2:** You can sign in across the account using the Facebook or Google account. Follow the instructions to set up the account across the platform. ![connect with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-20.jpg) **Step 3:** Search for Twitch on the main screen of the application and select the option of "Automatically post on your official Facebook Page when you start streaming on Twitch." Share the link across the platform directly. ![search for twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-21.jpg) **Step 4:** Before redirecting to the next procedure, tap “Connect” to share details with other users. ![tap on connect button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-22.jpg) **Step 5:** Sign in on Twitch and Facebook to link the account with the mobile application. Provide appropriate permissions to the applications once installed for the stream. Access Twitch from your Android and tap on the “Camera” icon to initiate streaming. Set up the stream details and start the stream, as required by the users. ![tap camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-23.jpg) ## Conclusion This article has introduced Twitch to the users and provided a detailed explanation of how a Twitch stream is shared across the platform. While understanding how to **share Twitch stream on Facebook,** it is convenient to understand that the process exists for both Android and PC devices. To look more into how this is executed, look into the detailed discussion of the article and make a conclusive understanding of what exactly is to be followed for making a perfect Twitch stream. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Social networking has been around the corner since the early 21st Century. Different social media platforms have taken charge and provided the community with an impressive amount of network connectivity throughout the world. This has tempted users into shifting towards such sources that would help them connect across the world with their loved ones. While catering to the community as a whole, different platforms have provided room for a specific community. From offering celebrities a platform across Instagram to make their daily updates viral to helping the general community gain traction with TikTok, specific communities have taken advantage of the platforms that have been designed to incorporate within the social community. Twitch is one such platform that has offered the gaming community a source to stream effectively. Different features make it interactive and effective while allowing gamers to publish their gameplay across the platform. One such example is to **share Twitch stream on Facebook.** As this streaming platform interacts with one of the most utilized social media platforms, this article features a discussion of its process. #### In this article Part 1: [What is Twitch and How is it Helpful?](#step1) Part 2: [Share Twitch Stream on Facebook Through PC or Mac](#step2) Part 3: [How to Share Twitch Stream on Facebook across Android?](#step3) ## Part 1: What is Twitch and How is it Helpful? Twitch has been an appealing platform for the gaming community, where it has provided them with a variety of features to work with. As this platform connects the community together, different tools make it effective for them to work through the platform. The platform's primary focus is across video games, where the complete process involves playing, interacting, or live-streaming the gameplay across the world. ![what is twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-1.jpg) Along with the focused streaming services, users can work through the chat rooms and direct messages tool offered across this gaming service. The variety of services offered within these tools makes it quite extensive to explain the process. However, this article has discussed how to **connect Facebook to Twitch.** ## Part 2: Share Twitch Stream on Facebook Through PC or Mac Users looking forward to **sharing Twitch stream on Facebook** through their PC or Mac can follow a set of different procedures. These procedures, if followed properly, can help users set up the platform and share the video of their choice across Facebook. Look into the steps provided to understand the procedure to **embed Twitch stream on Facebook.** **Step 1:** To start, you are advised to install OBS Studio across your device. Access your browser and download the setup for sharing streams across Facebook. Tap on the “Download” tab on the top-right corner of the screen and proceed to select the operating system of your choice. ![click on download button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-2.jpg) **Step 2:** On selecting the appropriate OS, you will be redirected to a new window to download the setup across your device. Launch the installer and follow the installation procedure to install OBS Studio across your device successfully. ![install the obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-3.jpg) **Step 3:** As OBS Studio successfully installs itself across your device, the user will be redirected across the Auto-Configuration Wizard for setting up the platform according to the desired options. The user can set up the settings according to streaming and recording screens. On the other hand, they can only look forward to optimizing options according to recording the screens. For connecting and configuring audio and video across OBS, set up the sources across the Auto-Configuration Wizard and proceed towards finalization. ![configure obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-4.jpg) **Step 4:** On configuring the settings, run OBS Studio and test the streaming services before **stream Twitch to Facebook Live.** It is impossible to perform cross-sharing across Twitch exact; thus, there is a need to configure an applet for Twitch and Facebook to help share the stream with Facebook. ![check your obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-5.jpg) **Step 5:** Get started by setting up the free IFTTT account. You can choose any of the sign-in methods to proceed across the platform. Pick Google or Facebook from the available options and finish the on-screen settings to link the Facebook account and Twitch for sharing videos across the platform. ![login with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-6.jpg) **Step 6:** To set Facebook for the sharing content across the applet, the user will be directed to a new window where they are advised to provide their credentials. On completing the setup of the account, you need to provide IFTTT with permission to access your Facebook account. For this, tap on the "Continue as (Username)" option. IFTTT will get permission to share content and videos across the account from Twitch. ![connect with facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-7.jpg) **Step 7:** On completing the log-in of Facebook, proceed to provide the credentials for Twitch to connect the platform with Facebook for sharing content. Enter the important credentials for Twitch across the applet and tap on the log-in button once done. ![login twitch account](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-8.jpg) **Step 8:** Successfully connect the account with IFTTT and configure Twitch across Facebook to proceed successfully. ![connect twitch with fb](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-9.jpg) **Step 9:** You need to initiate a stream for posting it across Facebook. Start the Twitch stream and look forward to generating a URL that will be put across the link that will be posted across Facebook. Create a link post by providing information within the Stream Information. Add the information across the section under the required headings and include a particular message across the window along with a title. ![add stream information](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-10.jpg) **Step 10:** Hit on "Create Action" to set up a link to your Twitch stream that can be easily shared with the users for allowing them access across multiple platforms. ![tap on create account button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-11.jpg) ## Part 3: How to Share Twitch Stream on Facebook across Android? While working across Android, the user can consider operating through different methods for sharing Twitch stream across Facebook. If you look forward to **share Twitch stream on Facebook** using an Android, you need to look across the following methods for a better understanding of the procedure. ### Sharing Another Live Stream Across Facebook **Step 1:** Download and install Twitch across your Android successfully. On launching the platform, search through the stream and find the one that is to be shared. ![open twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-12.jpg) **Step 2:** You need to select the “Sharing” icon on the top of the window to lead to a set of different options that can be used to share the Twitch stream. ![click on share icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-13.jpg) **Step 3:** Select Facebook from the provided options and initiate by posting the stream across the platform by creating a new post. Post the selected stream with a clear description and tap “Post.” ![create the post](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-14.jpg) ### Sharing Personal Stream Across Facebook **Step 1:** Launch Twitch on your Android device and select the “Camera” icon that appears on the top of the screen. You will be led to different live streaming options across the platform. ![click on camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-15.jpg) **Step 2:** You can select either option from 'Stream Games' or 'Stream IRL' to stream the game if it is across the screen or stream personal video or audio from the mobile's camera, respectively. ![select one option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-16.jpg) **Step 3:** Provide the stream details with an appropriate name and tags. After setting up the title details and other appropriate details of the stream, select the “Share” icon on the top of the window to access the sharing menu of the Android. ![add the stream info details](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-17.jpg) **Step 4:** Select Facebook from the options and create a post with the details of the post to publish the link for the users to join the gameplay. Now, lead back to Twitch and initiate streaming across the platform, which can be accessed directly from Facebook. ![select facebook option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-18.jpg) ### Automatically Save Stream Across Facebook **Step 1:** Access the Play Store on your Android and install the official IFTTT application across your device. Open the application once it is installed. ![install ifttt app ](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-19.jpg) **Step 2:** You can sign in across the account using the Facebook or Google account. Follow the instructions to set up the account across the platform. ![connect with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-20.jpg) **Step 3:** Search for Twitch on the main screen of the application and select the option of "Automatically post on your official Facebook Page when you start streaming on Twitch." Share the link across the platform directly. ![search for twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-21.jpg) **Step 4:** Before redirecting to the next procedure, tap “Connect” to share details with other users. ![tap on connect button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-22.jpg) **Step 5:** Sign in on Twitch and Facebook to link the account with the mobile application. Provide appropriate permissions to the applications once installed for the stream. Access Twitch from your Android and tap on the “Camera” icon to initiate streaming. Set up the stream details and start the stream, as required by the users. ![tap camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-23.jpg) ## Conclusion This article has introduced Twitch to the users and provided a detailed explanation of how a Twitch stream is shared across the platform. While understanding how to **share Twitch stream on Facebook,** it is convenient to understand that the process exists for both Android and PC devices. To look more into how this is executed, look into the detailed discussion of the article and make a conclusive understanding of what exactly is to be followed for making a perfect Twitch stream. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Social networking has been around the corner since the early 21st Century. Different social media platforms have taken charge and provided the community with an impressive amount of network connectivity throughout the world. This has tempted users into shifting towards such sources that would help them connect across the world with their loved ones. While catering to the community as a whole, different platforms have provided room for a specific community. From offering celebrities a platform across Instagram to make their daily updates viral to helping the general community gain traction with TikTok, specific communities have taken advantage of the platforms that have been designed to incorporate within the social community. Twitch is one such platform that has offered the gaming community a source to stream effectively. Different features make it interactive and effective while allowing gamers to publish their gameplay across the platform. One such example is to **share Twitch stream on Facebook.** As this streaming platform interacts with one of the most utilized social media platforms, this article features a discussion of its process. #### In this article Part 1: [What is Twitch and How is it Helpful?](#step1) Part 2: [Share Twitch Stream on Facebook Through PC or Mac](#step2) Part 3: [How to Share Twitch Stream on Facebook across Android?](#step3) ## Part 1: What is Twitch and How is it Helpful? Twitch has been an appealing platform for the gaming community, where it has provided them with a variety of features to work with. As this platform connects the community together, different tools make it effective for them to work through the platform. The platform's primary focus is across video games, where the complete process involves playing, interacting, or live-streaming the gameplay across the world. ![what is twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-1.jpg) Along with the focused streaming services, users can work through the chat rooms and direct messages tool offered across this gaming service. The variety of services offered within these tools makes it quite extensive to explain the process. However, this article has discussed how to **connect Facebook to Twitch.** ## Part 2: Share Twitch Stream on Facebook Through PC or Mac Users looking forward to **sharing Twitch stream on Facebook** through their PC or Mac can follow a set of different procedures. These procedures, if followed properly, can help users set up the platform and share the video of their choice across Facebook. Look into the steps provided to understand the procedure to **embed Twitch stream on Facebook.** **Step 1:** To start, you are advised to install OBS Studio across your device. Access your browser and download the setup for sharing streams across Facebook. Tap on the “Download” tab on the top-right corner of the screen and proceed to select the operating system of your choice. ![click on download button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-2.jpg) **Step 2:** On selecting the appropriate OS, you will be redirected to a new window to download the setup across your device. Launch the installer and follow the installation procedure to install OBS Studio across your device successfully. ![install the obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-3.jpg) **Step 3:** As OBS Studio successfully installs itself across your device, the user will be redirected across the Auto-Configuration Wizard for setting up the platform according to the desired options. The user can set up the settings according to streaming and recording screens. On the other hand, they can only look forward to optimizing options according to recording the screens. For connecting and configuring audio and video across OBS, set up the sources across the Auto-Configuration Wizard and proceed towards finalization. ![configure obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-4.jpg) **Step 4:** On configuring the settings, run OBS Studio and test the streaming services before **stream Twitch to Facebook Live.** It is impossible to perform cross-sharing across Twitch exact; thus, there is a need to configure an applet for Twitch and Facebook to help share the stream with Facebook. ![check your obs studio](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-5.jpg) **Step 5:** Get started by setting up the free IFTTT account. You can choose any of the sign-in methods to proceed across the platform. Pick Google or Facebook from the available options and finish the on-screen settings to link the Facebook account and Twitch for sharing videos across the platform. ![login with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-6.jpg) **Step 6:** To set Facebook for the sharing content across the applet, the user will be directed to a new window where they are advised to provide their credentials. On completing the setup of the account, you need to provide IFTTT with permission to access your Facebook account. For this, tap on the "Continue as (Username)" option. IFTTT will get permission to share content and videos across the account from Twitch. ![connect with facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-7.jpg) **Step 7:** On completing the log-in of Facebook, proceed to provide the credentials for Twitch to connect the platform with Facebook for sharing content. Enter the important credentials for Twitch across the applet and tap on the log-in button once done. ![login twitch account](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-8.jpg) **Step 8:** Successfully connect the account with IFTTT and configure Twitch across Facebook to proceed successfully. ![connect twitch with fb](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-9.jpg) **Step 9:** You need to initiate a stream for posting it across Facebook. Start the Twitch stream and look forward to generating a URL that will be put across the link that will be posted across Facebook. Create a link post by providing information within the Stream Information. Add the information across the section under the required headings and include a particular message across the window along with a title. ![add stream information](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-10.jpg) **Step 10:** Hit on "Create Action" to set up a link to your Twitch stream that can be easily shared with the users for allowing them access across multiple platforms. ![tap on create account button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-11.jpg) ## Part 3: How to Share Twitch Stream on Facebook across Android? While working across Android, the user can consider operating through different methods for sharing Twitch stream across Facebook. If you look forward to **share Twitch stream on Facebook** using an Android, you need to look across the following methods for a better understanding of the procedure. ### Sharing Another Live Stream Across Facebook **Step 1:** Download and install Twitch across your Android successfully. On launching the platform, search through the stream and find the one that is to be shared. ![open twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-12.jpg) **Step 2:** You need to select the “Sharing” icon on the top of the window to lead to a set of different options that can be used to share the Twitch stream. ![click on share icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-13.jpg) **Step 3:** Select Facebook from the provided options and initiate by posting the stream across the platform by creating a new post. Post the selected stream with a clear description and tap “Post.” ![create the post](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-14.jpg) ### Sharing Personal Stream Across Facebook **Step 1:** Launch Twitch on your Android device and select the “Camera” icon that appears on the top of the screen. You will be led to different live streaming options across the platform. ![click on camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-15.jpg) **Step 2:** You can select either option from 'Stream Games' or 'Stream IRL' to stream the game if it is across the screen or stream personal video or audio from the mobile's camera, respectively. ![select one option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-16.jpg) **Step 3:** Provide the stream details with an appropriate name and tags. After setting up the title details and other appropriate details of the stream, select the “Share” icon on the top of the window to access the sharing menu of the Android. ![add the stream info details](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-17.jpg) **Step 4:** Select Facebook from the options and create a post with the details of the post to publish the link for the users to join the gameplay. Now, lead back to Twitch and initiate streaming across the platform, which can be accessed directly from Facebook. ![select facebook option](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-18.jpg) ### Automatically Save Stream Across Facebook **Step 1:** Access the Play Store on your Android and install the official IFTTT application across your device. Open the application once it is installed. ![install ifttt app ](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-19.jpg) **Step 2:** You can sign in across the account using the Facebook or Google account. Follow the instructions to set up the account across the platform. ![connect with google or facebook](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-20.jpg) **Step 3:** Search for Twitch on the main screen of the application and select the option of "Automatically post on your official Facebook Page when you start streaming on Twitch." Share the link across the platform directly. ![search for twitch](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-21.jpg) **Step 4:** Before redirecting to the next procedure, tap “Connect” to share details with other users. ![tap on connect button](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-22.jpg) **Step 5:** Sign in on Twitch and Facebook to link the account with the mobile application. Provide appropriate permissions to the applications once installed for the stream. Access Twitch from your Android and tap on the “Camera” icon to initiate streaming. Set up the stream details and start the stream, as required by the users. ![tap camera icon](https://images.wondershare.com/filmora/article-images/2022/02/twitch-stream-on-facebook-23.jpg) ## Conclusion This article has introduced Twitch to the users and provided a detailed explanation of how a Twitch stream is shared across the platform. While understanding how to **share Twitch stream on Facebook,** it is convenient to understand that the process exists for both Android and PC devices. To look more into how this is executed, look into the detailed discussion of the article and make a conclusive understanding of what exactly is to be followed for making a perfect Twitch stream. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://facebook-video-files.techidaily.com/new-in-2024-digital-disappointment-unexpected-deletion/"><u>[New] In 2024, Digital Disappointment Unexpected Deletion</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/perfecting-live-social-media-facebook-livestream-tutorials-for-tech-for-2024/"><u>Perfecting Live Social Media Facebook Livestream Tutorials for Tech for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-in-2024-unlocking-fb-content-effortless-mp4-conversion/"><u>[New] In 2024, Unlocking FB Content Effortless MP4 Conversion</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/streamlining-the-experience-accessing-facebooks-video-features-through-apple-tv-for-2024/"><u>Streamlining the Experience Accessing Facebook's Video Features Through Apple TV for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/navigating-facebooks-updated-algorithm-preparation-checklist-for-2024/"><u>Navigating Facebook's Updated Algorithm Preparation Checklist for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-tips-to-incorrante-tv-with-facebook-live-integration/"><u>[Updated] Tips to Incorrante TV with Facebook Live Integration</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-optimize-your-online-visuals-learn-and-adjust-facebook-video-sizes-and-ratios/"><u>[New] Optimize Your Online Visuals Learn and Adjust Facebook Video Sizes & Ratios</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/2024-approved-unveiling-tricky-feed-functions-more-vids-please/"><u>2024 Approved Unveiling Tricky Feed Functions More Vids Please</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-enabling-youtube-and-facebook-on-apple-tv-for-2024/"><u>[Updated] Enabling YouTube and Facebook on Apple TV for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/2024-approved-hide-and-seek-with-fb-episodes/"><u>2024 Approved Hide-and-Seek with FB Episodes</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-expert-recommended-editors-for-crafting-top-facebook-videos-for-2024/"><u>[New] Expert-Recommended Editors for Crafting Top Facebook Videos for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/revisit-and-refine-your-past-editing-fbs-look-back-videos/"><u>Revisit and Refine Your Past Editing FB's Look Back Videos</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-in-2024-no-cost-top-tunes-in-your-library-today/"><u>[New] In 2024, No Cost Top Tunes in Your Library Today</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-2024-approved-facebook-video-downloader-application-for-mobilewinmac/"><u>[New] 2024 Approved Facebook Video Downloader Application for Mobile/Win/Mac</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-2023s-most-popular-online-video-hub-on-facebook/"><u>[Updated] 2023'S Most Popular Online Video Hub on Facebook</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-expert-tips-to-correct-video-transmission-problem-on-mobile-messengers-for-2024/"><u>[Updated] Expert Tips to Correct Video Transmission Problem on Mobile Messengers for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-facebook-linking-method-for-youtube-video-content/"><u>[Updated] Facebook Linking Method for YouTube Video Content</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-experience-the-best-download-options-for-fb-lite-videos-2023-ranking/"><u>[New] Experience the Best Download Options for FB Lite Videos - 2023 Ranking</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-2024-approved-the-ultimate-list-of-untapped-facebook-meme-havens/"><u>[Updated] 2024 Approved The Ultimate List of Untapped Facebook Meme Havens</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-2024-approved-boosting-facebook-ad-revenue-with-strategic-animated-content-design/"><u>[Updated] 2024 Approved Boosting Facebook Ad Revenue with Strategic Animated Content Design</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/in-2024-instagram-storytelling-using-videos-effectively/"><u>In 2024, Instagram Storytelling Using Videos Effectively</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-in-2024-rights-and-recourse-following-sudden-account-suspension-on-fb/"><u>[Updated] In 2024, Rights and Recourse Following Sudden Account Suspension on FB</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-2024-approved-eliminate-non-existent-fb-ad-impressions/"><u>[New] 2024 Approved Eliminate Non-Existent FB Ad Impressions</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-legal-framework-the-fine-print-for-facebook-video-postings-for-2024/"><u>[Updated] Legal Framework The Fine Print for Facebook Video Postings for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-2024-approved-best-practices-for-livestreaming-full-spheres-on-facebook/"><u>[New] 2024 Approved Best Practices for Livestreaming Full Spheres on Facebook</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/updated-customizing-video-space-on-facebook-platforms/"><u>[Updated] Customizing Video Space on Facebook Platforms</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/2024-approved-elevating-social-media-interaction-via-fb-story-links/"><u>2024 Approved Elevating Social Media Interaction via FB Story Links</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-the-ultimate-guide-to-high-definition-hd-youtube-and-fb-videos-for-2024/"><u>[New] The Ultimate Guide to High Definition (HD) YouTube & FB Videos for 2024</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/2024-approved-prime-video-converter-for-social-media-platforms/"><u>2024 Approved Prime Video Converter for Social Media Platforms</u></a></li> <li><a href="https://facebook-video-files.techidaily.com/new-in-2024-a-comprehensive-look-at-youtube-to-facebook-file-transfers/"><u>[New] In 2024, A Comprehensive Look at YouTube-to-Facebook File Transfers</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/in-2024-best-ideas-on-using-filmora-green-screen/"><u>In 2024, Best Ideas on Using Filmora Green Screen</u></a></li> <li><a href="https://audio-shaping.techidaily.com/updated-in-2024-keyboard-kings-and-queens-a-premium-free-royalty-free-collection-of-film-ready-piano-soundtracks/"><u>Updated In 2024, Keyboard Kings & Queens A Premium, Free Royalty-Free Collection of Film-Ready Piano Soundtracks</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-3-ways-to-erase-apple-iphone-se-2020-when-its-locked-within-seconds-drfone-by-drfone-ios/"><u>In 2024, 3 Ways to Erase Apple iPhone SE (2020) When Its Locked Within Seconds | Dr.fone</u></a></li> <li><a href="https://screen-activity-recording.techidaily.com/in-2024-notable-substitutes-to-obs-for-screencasts/"><u>In 2024, Notable Substitutes to OBS for Screencasts</u></a></li> <li><a href="https://voice-adjusting.techidaily.com/tips-and-tricks-to-use-clownfish-voice-changer-on-discord-fortnite-skype-for-2024/"><u>Tips and Tricks to Use Clownfish Voice Changer on Discord/ Fortnite/ Skype for 2024</u></a></li> <li><a href="https://video-creation-software.techidaily.com/updated-s-best-free-audio-editors-for-m4a-files-for-2024/"><u>Updated S Best Free Audio Editors for M4A Files for 2024</u></a></li> <li><a href="https://remote-screen-capture.techidaily.com/detailed-insights-into-camstudio-capture-functionality/"><u>Detailed Insights Into CamStudio Capture Functionality</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-catchemall-celebrate-national-pokemon-day-with-virtual-location-on-oppo-reno-9a-drfone-by-drfone-virtual-android/"><u>In 2024, CatchEmAll Celebrate National Pokémon Day with Virtual Location On Oppo Reno 9A | Dr.fone</u></a></li> <li><a href="https://activate-lock.techidaily.com/easy-fixes-how-to-recover-forgotten-icloud-password-on-your-iphone-14-pro-by-drfone-ios/"><u>Easy Fixes How To Recover Forgotten iCloud Password On your iPhone 14 Pro</u></a></li> <li><a href="https://screen-recording.techidaily.com/prime-choices-beyond-obs-for-video-capture-for-2024/"><u>Prime Choices Beyond OBS for Video Capture for 2024</u></a></li> <li><a href="https://fake-location.techidaily.com/thinking-about-changing-your-netflix-region-without-a-vpn-on-oppo-reno-10-5g-drfone-by-drfone-virtual-android/"><u>Thinking About Changing Your Netflix Region Without a VPN On Oppo Reno 10 5G? | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/how-to-move-custom-ringtones-from-apple-iphone-8-plus-to-android-drfone-by-drfone-transfer-from-ios/"><u>How to Move Custom Ringtones from Apple iPhone 8 Plus to Android? | Dr.fone</u></a></li> <li><a href="https://remote-screen-capture.techidaily.com/new-in-2024-leading-free-capture-software-top-15-recommendations/"><u>[New] In 2024, Leading Free Capture Software Top 15 Recommendations</u></a></li> <li><a href="https://ai-video-tools.techidaily.com/new-revolutionize-your-visuals-8-best-photo-animation-tools-for-2024/"><u>New Revolutionize Your Visuals 8 Best Photo Animation Tools for 2024</u></a></li> <li><a href="https://phone-solutions.techidaily.com/failed-to-play-hevc-files-on-motorola-razr-40-by-aiseesoft-video-converter-play-hevc-video-on-android/"><u>Failed to play HEVC files on Motorola Razr 40</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/new-introduction-to-luts-their-overview-and-benefits/"><u>New Introduction to LUTs Their Overview and Benefits</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-unlock-vivo-y100i-phone-without-password-by-drfone-android/"><u>How To Unlock Vivo Y100i Phone Without Password?</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/updated-revolutionize-your-video-editing-workflow-with-64-bit-technology-for-2024/"><u>Updated Revolutionize Your Video Editing Workflow with 64-Bit Technology for 2024</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-rescue-lost-messages-from-oneplus-by-fonelab-android-recover-messages/"><u>How to Rescue Lost Messages from OnePlus</u></a></li> <li><a href="https://video-content-creator.techidaily.com/updated-in-2024-latest-free-game-video-editing-software-you-need-to-try/"><u>Updated In 2024, Latest Free Game Video Editing Software You Need to Try</u></a></li> <li><a href="https://remote-screen-capture.techidaily.com/elevate-your-recordings-selecting-top-pc-and-mac-apps/"><u>Elevate Your Recordings Selecting Top PC & Mac Apps</u></a></li> <li><a href="https://unlock-android.techidaily.com/7-ways-to-unlock-a-locked-vivo-y100i-power-5g-phone-by-drfone-android/"><u>7 Ways to Unlock a Locked Vivo Y100i Power 5G Phone</u></a></li> <li><a href="https://video-creation-software.techidaily.com/new-in-2024-get-filmora-13-video-editor-free-download/"><u>New In 2024, Get Filmora 13 Video Editor Free Download</u></a></li> <li><a href="https://screen-video-capture.techidaily.com/unpacking-manycams-revolutionary-recording-features/"><u>Unpacking ManyCam's Revolutionary Recording Features</u></a></li> </ul></div>
import React from 'react' import {Box, Flex, Heading, Text, Spacer, Button, SimpleGrid} from '@chakra-ui/react' import {SectionHeader} from '../../components' import {MainContainer} from '../../layouts' import {SpaceCard} from './SpaceCard' const SpaceTypeData = [ { bgImage: "/assets/images/hub/spaceType1.png", spaceTypeName: "Work Station", spaceTypeIcon: "/assets/images/hub/spaceTypeIcon1.svg", spaceTypeDescription: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.", spaceTypePrice: "₦1,500", link: "/", }, { bgImage: "/assets/images/hub/spaceType2.png", spaceTypeName: "Boardroom", spaceTypeIcon: "/assets/images/hub/spaceTypeIcon2.svg", spaceTypeDescription: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.", spaceTypePrice: "₦10,000", link: "/", } ] export const SpaceType = () => { return ( <Box> <MainContainer> <Box px="5%" > <SectionHeader subTitle="Type of space we offer" title="Flexible Solutions for You - Choose What Works Best for You." /> </Box> <SimpleGrid columns={[1, 1, 2, 2]} spacing={["1.25rem","1.875rem"]} px="0" py="2rem"> { SpaceTypeData.map((data, index) => ( <SpaceCard key={index} bgImage={data.bgImage} spaceTypeName={data.spaceTypeName} spaceTypeIcon={data.spaceTypeIcon} spaceTypeDescription={data.spaceTypeDescription} spaceTypePrice={data.spaceTypePrice} link={data.link} /> )) } </SimpleGrid> </MainContainer> </Box> ) }
import React from 'react'; import { useNavigate } from 'react-router-dom'; const SingleTools = ({ tool }) => { const navigate = useNavigate() const { name, _id, quantity, availableQuantity, minimumQuantity, description, picture, price } = tool; const handlePurchase = id => { navigate(`/purchase/${id}`) console.log(id); } return ( <div className="card w-96 bg-base-100 shadow-xl"> <figure className="px-10 pt-10"> <img src={picture} alt="Shoes" className="rounded-xl" /> </figure> <div className="card-body items-center text-center"> <h2 className="card-title">{name}</h2> <p>{description.slice(0, 70)}</p> <p>Available Tools: <span className='font-semiBold'> {availableQuantity}</span> unit</p> <p>Minimum Order: <span className='font-semiBold'>{minimumQuantity}</span> unit</p> <h5 className='text-xl'>Price: <span className='text-orange-500'> ${price}/unit</span></h5> <div class="card-actions justify-center"> <button onClick={() => handlePurchase(_id)} className="btn px-8 btn-primary ">Purchase</button> </div> </div> </div> ); }; export default SingleTools;
+++ title="fa-dot-circle icon in font awesome icons" summary="fa-dot-circle icon in font awesome icons has 2 variants regular (far) and solid (fas)" keywords=["fa-dot-circle,f192,fa-dot-circle"] date="25-07-2020T22:59:20" lastmod="25-07-2020T22:59:20" type="docs" parentdoc="fontawesome" featured='font-awesome-icons.png' categories=['faicons'] prev="fa-door-open" next="fa-dove" linktitle="fa-dot-circle" [menu.fontawesome] parent="fontawesome" weight=20 draft=false +++ fa-dot-circle icon in font awesome icons has 2 variants regular (far) and solid (fas) <div class='table-responsive'><table class='table'><thead><tr><th>Name</th><th>Class Name</th><th>Css Content Code</th></tr></thead><tbody><tr><td>fa-dot-circle</td><td>fa-dot-circle</td><td>f192</td></tr></tbody></table></div> {{% toc %}} ## fa-dot-circle icon Usage To display fa-dot-circle icon add predefined class name i.e.,fa-dot-circle (with prefix fa-) to the 'i' tag. Here 'i' tag represents icon. And we need to add corresponding category for fa-dot-circle icon. i.e., fas,far. ``` <i class='fas fa-dot-circle'>fa-dot-circle</i> <i class='far fa-dot-circle'>fa-dot-circle</i> ``` <i class='fas fa-dot-circle'>fa-dot-circle</i> <i class='far fa-dot-circle'>fa-dot-circle</i> ## Change fa-dot-circle icon size To increase fa-dot-circle font awesome icon size, use the fa-lg (33% increase), fa-2x, fa-3x, fa-4x, or fa-5x classes along with icon class fa-dot-circle. Increase in icon size will be relative to their parent container. ``` <i class='fas fa-dot-circle fa-lg'>fa-lg</i><br/> <i class='fas fa-dot-circle fa-2x'>fa-2x</i><br/> <i class='fas fa-dot-circle fa-3x'>fa-3x</i><br/> <i class='fas fa-dot-circle fa-4x'>fa-4x</i><br/> <i class='fas fa-dot-circle fa-5x'>fa-5x</i><br/> ``` <i class='fas fa-dot-circle fa-lg'>fa-lg</i><br/> <i class='fas fa-dot-circle fa-2x'>fa-2x</i><br/> <i class='fas fa-dot-circle fa-3x'>fa-3x</i><br/> <i class='fas fa-dot-circle fa-4x'>fa-4x</i><br/> <i class='fas fa-dot-circle fa-5x'>fa-5x</i><br/> ## fa-dot-circle Icon with Fixed Width All the font awesome icons does not have same width. For example fa-dot-circle icon and fa-home may not have same height and width. So to display two icons with fixed width and height we can use fa-fw class. ``` <i class='fas fa-dot-circle fa-fw fa-3x'></i>Fixed Width<i class='fas fa-dot-circle fa-3x'></i>Normal<br/> <i class='fas fa-home fa-fw fa-3x'></i>Fixed Width<i class='fas fa-home fa-3x'></i>Normal<br/> ``` <i class='fas fa-dot-circle fa-fw fa-3x'></i>Fixed Width<i class='fas fa-dot-circle fa-3x'></i>Normal<br/> <i class='fas fa-home fa-fw fa-3x'></i>Fixed Width<i class='fas fa-home fa-3x'></i>Normal<br/> ## fa-dot-circle Icon Border To add border to fa-dot-circle icon, use fa-border class. ``` <i class='fas fa-dot-circle fa-border fa-3x'></i> ``` <i class='fas fa-dot-circle fa-border fa-3x'></i> ## Pull fa-dot-circle icon To the left To pull icon fa-dot-circle to the left of the container use fa-pull-left class.\n ``` <div style='width: 200px;'> <i class='fas fa-dot-circle fa-pull-left fa-3x'></i> ... The text after fa-dot-circle Icon will be displayed on the right side of the icons </div> <div style = 'clear: both;'></div> ``` <div style='width: 200px;'> <i class='fas fa-dot-circle fa-pull-left fa-3x'></i> ... The text after fa-dot-circle Icon will be displayed on the right side of the icons </div> <div style = 'clear: both;'></div> ## Pull fa-dot-circle icon To the right To pull icon fa-dot-circle to the right of the container use fa-pull-right class. ``` <div style='width: 200px;'> <i class='fas fa-dot-circle fa-pull-right fa-3x'></i> ... The text after fa-dot-circle Icon will be displayed on the left side of the icons </div> <div style = 'clear: both;'></div> ``` <div style='width: 200px;'> <i class='fas fa-dot-circle fa-pull-right fa-3x'></i> ... The text after fa-dot-circle Icon will be displayed on the left side of the icons </div> <div style = 'clear: both;'></div> These two classes can used to add single quotes or double quotes to the text. ## Animate fa-dot-circle icon using fa-spin To animate font awesome fa-dot-circle icon, use fa-spin class. ``` <i class='fas fa-dot-circle fa-spin fa-3x'></i> ``` <i class='fas fa-dot-circle fa-spin fa-3x'></i> ## Animate fa-dot-circle icon with steps While animating the font awesome icon,We can rotate fa-dot-circle icon in 8 steps instead of uniform rotation. To animate font awesome fa-dot-circle icon with 8 step rotation, use fa-pulse icon along with fa-spin class. ``` <i class='fas fa-dot-circle fa-pulse fa-spin fa-3x'></i> ``` <i class='fas fa-dot-circle fa-pulse fa-spin fa-3x'></i> ## Rotate fa-dot-circle Icon using fa-rotate-x To rotate the font awesome icon fa-dot-circle, Use fa-rotate-x class Where 'x' represents degree of rotation. ``` <div> <i class='fas fa-dot-circle fa-3x'>R</i>normal<br/><br/> <i class='fas fa-dot-circle fa-rotate-90 fa-3x'>R</i> fa-rotate-90<br/><br/> <i class='fas fa-dot-circle fa-rotate-180 fa-3x'>R</i> fa-rotate-180<br/><br/> <i class='fas fa-dot-circle fa-rotate-270 fa-3x'>R</i> fa-rotate-270<br/><br/> </div> ``` <div> <i class='fas fa-dot-circle fa-3x'>R</i>normal<br/><br/> <i class='fas fa-dot-circle fa-rotate-90 fa-3x'>R</i> fa-rotate-90<br/><br/> <i class='fas fa-dot-circle fa-rotate-180 fa-3x'>R</i> fa-rotate-180<br/><br/> <i class='fas fa-dot-circle fa-rotate-270 fa-3x'>R</i> fa-rotate-270<br/><br/> </div> ## Flip fa-dot-circle Icon using fa-flip-* To flip fa-dot-circle font awesome icon horizontally and vertically use fa-flip-horizontal and fa-flip-vertical classes. ``` <i class='fas fa-dot-circle fa-3x'>F</i> Normal <br> <i class='fas fa-dot-circle fa-flip-horizontal fa-3x'>F</i> fa-flip-horizontal<br> <i class='fas fa-dot-circle fa-flip-vertical fa-3x'>F</i> fa-flip-vertical<br> ``` <i class='fas fa-dot-circle fa-3x'>F</i> Normal <br> <i class='fas fa-dot-circle fa-flip-horizontal fa-3x'>F</i> fa-flip-horizontal<br> <i class='fas fa-dot-circle fa-flip-vertical fa-3x'>F</i> fa-flip-vertical<br> ## Combine fa-dot-circle icon with other font awesome icons In font awesome icons,using stacking we can combine multiple icons and display it as one icon To do that use the fa-stack class on the parent, the fa-stack-1x for the regularly sized icon, and fa-stack-2x for the larger icon. And use class fa-inverse for an alternative icon color. In the below example, I am displaying fa-dot-circle on top of icons like fa-square,fa-circle and fa-ban. And used fa-inverse in the second example to invert the color of the icon. ``` <div> <span class='fa-stack fa-lg'> <i class='far fa-square fa-stack-2x'></i> <i class='fas fa-dot-circle fa-stack-1x'></i> </span> fa-dot-circle on fa-square<br> <span class='fa-stack fa-lg'> <i class='fas fa-circle fa-stack-2x'></i> <i class='fas fa-dot-circle fa-stack-1x fa-inverse'></i> </span> fa-dot-circle on fa-circle<br> <span class='fa-stack fa-lg'> <i class='fas fa-dot-circle fa-stack-1x'></i> <i class='fas fa-ban fa-stack-2x'></i> </span> fa-dot-circle on fa-ban </div> ``` <div> <span class='fa-stack fa-lg'> <i class='far fa-square fa-stack-2x'></i> <i class='fas fa-dot-circle fa-stack-1x'></i> </span> fa-dot-circle on fa-square<br> <span class='fa-stack fa-lg'> <i class='fas fa-circle fa-stack-2x'></i> <i class='fas fa-dot-circle fa-stack-1x fa-inverse'></i> </span> fa-dot-circle on fa-circle<br> <span class='fa-stack fa-lg'> <i class='fas fa-dot-circle fa-stack-1x'></i> <i class='fas fa-ban fa-stack-2x'></i> </span> fa-dot-circle on fa-ban </div>
import { NFTStorage } from 'nft.storage' import * as ls from '~/helpers/ls' export function useNFTStorage() { const NFT_STORAGE_TOKEN = import.meta.env.VITE_NFT_STORAGE_TOKEN const client = new NFTStorage({ token: NFT_STORAGE_TOKEN }) const checkExist = async (file) => { try { const { cid } = await NFTStorage.encodeBlob(file) const isExist = await client.check(cid) if (isExist) { return { cid: `ipfs://${cid}`, } } } catch (err) { // nothing todo, as the file just do not store yet return false } } const storeBlob = async (file) => { const cid = await client.storeBlob(file) return `ipfs://${cid}` } const storeNFTMetadata = async (data) => { const metadata = await client.store(data) return metadata } const storeJson = async (data) => { data = unref(data) const blob = new Blob([JSON.stringify(data)], { type: 'application/json', }) return storeBlob(blob) } // https://api.nft.storage/bafkreidivzimqfqtoqxkrpge6bjyhlvxqs3rhe73owtmdulaxr5do5in7u const getInfo = async (cid) => { const url = cid.replace('ipfs://', 'https://api.nft.storage/') const response = await fetch(url, { headers: { Authorization: `Bearer ${NFT_STORAGE_TOKEN}`, }, }) return response.json() } const getIpfsUrl = cid => `${cid.replace('ipfs://', 'https://')}.ipfs.nftstorage.link/` const getJson = async (cid) => { if (!cid) return false if (!cid.startsWith('ipfs://')) cid = `ipfs://${cid}` let data = ls.getItem(cid, false) if (data) return data const url = getIpfsUrl(cid) const response = await fetch(url) data = await response.json() ls.setItem(cid, data) return data } const getStatus = async (cid) => { const key = `status-${cid}` let status = ls.getItem(key, false) if (status) return status status = await client.status(cid.replace('ipfs://', '')) ls.setItem(key, status) return status } return { checkExist, storeBlob, client, storeNFTMetadata, storeJson, getInfo, getJson, getStatus, getIpfsUrl } }
<!DOCTYPE html> <html lang="en" xml:lang="en"> <!-- PAGINA PER LA REGISTRAZIONE --> <head> <!-- Meta --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Titolo --> <title>Sign Up | Job Finder </title> <meta name="title" content="Sign Up | Job Finder"> <!-- Meta --> <meta name="author" content="Tommaso Berlaffa Milo Spadotto Pietro Lauriola Alberto Matterazzo"> <meta name="language" content="english eng"> <meta name="description" content="Sign up to Find a Job or look for a professionist!"> <meta name="keywords" content="SignUp, Sign up, Username, Password, Job, Job Finder"> <!-- Javascript --> <script type="text/javascript" src="../JS/SignUp.js"></script> <!-- Fogli di Stile --> <link rel="stylesheet" type="text/css" href="../CSS/StyleSheet.css" media="screen"> <link rel="stylesheet" type="text/css" href="../CSS/Print.css" media="print"> <link rel="stylesheet" type="text/css" href="../CSS/Mobile.css" media="screen"> <!-- Icona --> <link rel="icon" type="image/png" href="../IMG/JF_64.png"/> </head> <body> <!-- Header con Link per altre Pagine del Sito--> <header id="header"> <ul class="hiddenHelp"> <li><a href="#menu">Move to Main Menu</a></li> <li><a href="#main">Move to the Login</a></li> </ul> <!-- Logo Job Finder --> <img src="../IMG/TempLogo.png" id="Logo" alt=""> <!-- Menu Hypertext (riempito da pagina Index.php ) --> <ul> <li><a href="../PHP/Index.php"><img src="../IMG/Icons/home.png" class="icons" alt=""> Home</a></li> <li><a href="../PHP/FindJob.php"><img src="../IMG/Icons/search.png" class="icons" alt=""> Find a Job</a></li> <li><a href="../PHP/Login.php"><img src="../IMG/Icons/login.png" class="icons" alt=""> Login</a></li> <li><img src="../IMG/Icons/book.png" class="icons" alt=""><span> Sign up</span></li> </ul> </header> <!-- Breadcrumb --> <nav class="breadcrumb"> <!-- Non serve aggiungere altro per la pagina di Registrazione --> ..\ <a href="../PHP/Index.php">Home</a> \ Sign Up </nav> <noscript> <div class="resultfail"> <p>This Website uses functions written in Javascript language. Those functions are indispensable for the correct visualization and navigation of the website. Please enable the use of Javascript in the settings of your browser.</p> </div> </noscript> <!-- Main Content --> <main id="main"> <p class="hiddenHelp"><a href="#footer">Skip the content and go to footer</a></p> <messaggiForm /> <form id="SignUp" action="../PHP/SignUp.php" onsubmit="checkRequiredInputs('SignUp')" method="post" enctype="multipart/form-data"> <!-- attributo for serve per indicare l'input quando clicco sulla label --> <fieldset id="Form_1"> <legend> Sign Up - Login Informations </legend> <p> Please fill this form to create a new account 1/3</p> <p> Only the field with a * are required</p> <!-- Nickname --> <label for="Username" class="Enter">Username* : </label> <input type="text" id="Username" name="Username" class="Enter" maxlength="48" value="<Username />" required /> <p id="UsernameTaken" class="error"></p> <!-- Mail --> <label for="Email" >Email* : </label> <input type="email" id="Email" name="Email" maxlength="48" value="<Email />" required /> <p id="EmailTaken" class="error"></p> <!-- Password --> <label for="Password" class="Enter">Password*:<br />-must be at least 8 characters long,<br />-have one lower case letter,<br />-have one upper case letter,<br />-have one digit</label> <input type="password" id="Password" name="Password" class="Enter" maxlength="48" required /> <p id="Security" class="error"></p> <!-- Password ( Check ) --> <label for="Repeat-Password" class="Enter">Repeat Password* :</label> <input type="password" id="Repeat-Password" name="Repeat-Password" maxlength="48" class="Enter" required /> <p id="Match" class="error"></p> <!-- Icon Image --> <label for="Picture" class="Enter">Profile Picture :</label> <input type="file" id="Picture" name="Picture" accept="image/jpeg, image/png, image/gif" class="Enter"/> <!-- Next Page --> <label id="Missing1" for="Next1" class="error"></label> <input type="button" id="Next1" value="Next"/> </fieldset> <fieldset id="Form_2"> <legend> Sign Up - Personal Informations </legend> <p> Please fill this form to create a new account 2/3</p> <p> Only the field with a * are required</p> <p> You are already half way there</p> <!-- Name --> <label for="Firstname" class="Enter">Name* :</label> <input type="text" id="Firstname" name="Firstname" class="Enter" maxlength="64" value="<Firstname />" required /> <!-- Surname --> <label for="Lastname" class="Enter">Surname* :</label> <input type="text" id="Lastname" name="Lastname" class="Enter" maxlength="64" value="<Lastname />" required /> <!-- Birthday --> <label for="Birthday" >Birthday* : </label> <input type="date" id="Birthday" name="Birthday" value="<Birthday />" required> <!-- Country e Nationality da rivedere, l'utente può inserire quello che vuole--> <!-- Nationality --> <label for="Country">Nationality* : </label> <input type="text" id="Country" name="Country" minlength="4" maxlength="56" value="<Country />" required /> <!-- City --> <label for="City">City* : </label> <input type="text" id="City" name="City" maxlength="45" value="<City />" required /> <!-- Address --> <label for="Address">Address : </label> <input type="text" id="Address" name="Address" maxlength="75" value="<Address />" /> <!-- Tel --> <!-- Si può fare controllo con un'espressione regolare --> <label for="Tel">Telephone Number : </label> <input type="tel" id="Tel" name="Tel" minlength="7" maxlength="15" value="<Phone />" /> <!-- Codice JS, probabilmente TO REPLACE with PHP--> <input type="button" id = "Back1" value="Go Back" /> <label id="Missing2" for="Next2" class="error"></label> <input type="button" id="Next2" value="Next" class="Next"/> </fieldset> <fieldset id="Form_3"> <legend> Sign Up - Your Skills </legend> <p> Please fill this form to create a new account 3/3</p> <p> Only the field with a * are required</p> <p> One last step! </p> <p>Here you can select your tags. Select up to 20 tags by searching them in the <a href="#searchTag">searching box</a> and add the tags that represents your skills or the skills you are looking for when searching for a worker!</p> <p>All the available tags will be shown after you search for them in the <a href="#tagsList">Available Tags Area</a>!</p> <!--<tags/>--> <TagModule/> <p class="hiddenHelp"><a href="#searchTag">add more tags to your search</a></p> <!-- Curriculum pattern="https://*" --> <label id="labelCurr" for="Curr">Link To a Curriculum : </label> <input type="url" maxlength="128" value="<Curriculum />" id="Curr" name="Curr"/> <!-- Description --> <label for="Desc">Describe Yourself *:</label> <textarea id="Desc" name="Desc" minlength="10" maxlength="4096" required><Description /></textarea> <input type="button" id = "Back2" value="Go Back"/> <label id="Missing3" for="Next3" class="error"></label> <input type="button" id = "Next3" value="Next" class="Next"/> </fieldset> <fieldset id="Form_4"> <legend> Sign Up - Finish the Sign Up</legend> <p> Complete the Sign Up</p> <p> Check all your submitted data</p> <p id="Fpfp">Profile Picture : </p> <img src="" id="newpfp" alt="your new profile picture"> <p id="FNickname">Username : </p> <p id="FName">Name : </p> <p id="FSurname">Surname : </p> <p id="FBirth">Birth : </p> <p id="FEmail">Email : </p> <p id="FNationality">Nationality : </p> <p id="FCity">City : </p> <p id="FAddress">Address : </p> <p id="FTel">Telephone Number : </p> <p id="FLink">Link to a Curriculum : </p> <p >Skills : </p> <ul id="FSkill"></ul> <p id="FDesc">Description : </p> <input type="button" id = "Back3" value="Go Back"/> <button type="submit" name="Sign_Up" id="Sign_Up" value="Sign_Up">Sign Up!</button> </fieldset> </form> </main> <!-- Footer --> <footer id="footer"> <!-- Info Admin --> <p class="hiddenHelp"><a href="#header">Go back to the header</a></p> <p> Check out the <a href="FAQ.php">FAQ</a> for any question - To report any issue contact our Admin at admin@JobFinder.mail.com</p> </footer> <!-- Javascript --> <script type="text/javascript" src="../JS/searchTag.js"></script> </body> </html>
# ************************** Instance variables vs Class variables ************************** # Instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class. # Example class Employee: company = "Newgen" # class variable def __init__(self, name, age): self.name = name # instance variable self.age = age def show_info(self): print(f"The name of the employee is {self.name} and age is {self.age} and company is {self.company}") print("Without creating any instance -> ", Employee.company) # In python Whenever any class is created python by default create a object of that class and store all the class variables in that object. Thus we can access class variables even without creating any instance of the class. e1 = Employee("Akshay", "21") e2 = Employee("Abhay", "19") print(1, e1.company) e2.company = "Google" # This will create a new instance variable for e2 and will not change the class variable print(2, e2.company) # Python first checks if there is an instance variable with the name company in e2, if not then it checks for class variable with the name company in Employee class. print(3, e1.company) Employee.company = "Microsoft" # This will change the class variable for all instances print(4, e1.company) e1.roll_no = 59 # Here python doesn't finds both instance and class variable for this name. So it will create a new instance variable for e1 print(5, e1.roll_no)
package com.example.sendlocationdata import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Build import androidx.core.content.ContextCompat fun Context.hasLocationPermission(): Boolean{ return ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED } fun isNetworkAvailable(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val network = connectivityManager.activeNetwork ?: return false val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) } else { // For below Android Q @Suppress("DEPRECATION") val activeNetwork = connectivityManager.activeNetworkInfo ?: return false return activeNetwork.isConnected }}
/****************************************************************** Stylesheet: Main Stylesheet Here's where the magic happens. Here is where you import all of your Sass files so they can compile into one CSS file. ******************************************************************/ /* * Scut, a collection of Sass utilities * to ease and improve our implementations of common style-code patterns. * v1.4.0 * Docs at http://davidtheclark.github.io/scut */ @import url("https://use.typekit.net/znn6aqz.css"); .assistive-text, .visuallyhidden, .screen-reader-text { position: absolute !important; clip: rect(1px, 1px, 1px, 1px); padding: 0 !important; border: 0 !important; height: 1px !important; width: 1px !important; overflow: hidden; } @keyframes imageAnimation { 0% { animation-timing-function: ease-in; opacity: 0; } 7% { animation-timing-function: ease-out; opacity: 1; } 44% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 0; } } * { box-sizing: border-box; } html { font-size: 62.5%; } body { font-size: 18px; margin: 0; background-color: #F2F2F2; color: #202020; font-family: "soleil", sans-serif; font-style: normal; font-weight: 300; max-width: 100vw; overflow-x: hidden; -webkit-tap-highlight-color: #ff0; display: -ms-flexbox; display: flex; min-height: 100vh; -ms-flex-direction: column; flex-direction: column; } @media (max-width: 600px) { body { font-size: calc( 18px / 1.3); line-height: 1.2; } } .highlight, ::-moz-selection { background: #ff0; } .highlight, ::selection { background: #ff0; } div.site-content { -ms-flex: 1; flex: 1; } a { color: #B42125; transition: all 400ms ease-in-out; } a:hover, a:focus, a:active { color: #89191c; } blockquote { position: relative; padding: 1rem; } blockquote:before { content: "\201C"; font-family: Georgia, serif; font-size: 90px; font-weight: bold; opacity: 0.2; position: absolute; left: -1.5rem; top: -1.5rem; } .hide-this { visibility: hidden; height: 0; width: 0; position: absolute; } .hide-this svg { display: none; } .inverse { color: #fff; } .inverse a, .inverse a:visited { color: #F4CA1A; } .inverse a:hover, .inverse a:focus, .inverse a:active, .inverse a:visited:hover, .inverse a:visited:focus, .inverse a:visited:active { color: #F2F2F2; } .inverse a.button:hover, .inverse a:visited.button:hover { color: #fff !important; } .inverse svg { fill: #fff !important; } .button, input[type="submit"], button { background: rgba(171, 38, 38, 0.9); padding: 1rem 2rem; text-align: center; text-decoration: none; color: #fff !important; border-radius: 4px; display: inline-block; border: 1px solid #581313; text-shadow: 1px 1px 0 rgba(0, 0, 0, 0.43); box-shadow: 0 0 3px rgba(171, 38, 38, 0.5); transition: all 400ms ease-in-out; text-shadow: none; font-weight: bold; border: none; outline: none; } .button:hover, .button:focus, .button:visited:hover, input[type="submit"]:hover, input[type="submit"]:focus, input[type="submit"]:visited:hover, button:hover, button:focus, button:visited:hover { background: transparent; color: #B42125 !important; } .button.full, input[type="submit"].full, button.full { display: block; text-align: center; } .learn-more-button { padding-bottom: 2rem; } .padding { padding: 4rem; } .centered-text { text-align: center; } a.no-style { color: #202020; text-decoration: none; } svg.icon { max-width: 32px; max-height: 32px; } svg.icon + text { position: absolute !important; clip: rect(1px, 1px, 1px, 1px); padding: 0 !important; border: 0 !important; height: 1px !important; width: 1px !important; overflow: hidden; } .acf-map { width: 100%; height: 300px; border: #ccc solid 1px; margin: 20px 0; } /* fixes potential theme css conflict */ .acf-map img { max-width: inherit !important; } h1, h2, h3, h4, h5 { font-family: "soleil", sans-serif; font-weight: 800; text-transform: capitalize; margin-bottom: 0.2em; line-height: 1.1; } h1 { font-size: 48.6px; } @media (max-width: 600px) { h1 { font-size: calc( 48.6px / 1.3); } } h2 { font-size: 41.4px; } @media (max-width: 600px) { h2 { font-size: calc( 41.4px / 1.3); } } h3 { font-size: 36px; } @media (max-width: 600px) { h3 { font-size: calc( 36px / 1.3); } } h4 { font-size: 30.6px; } @media (max-width: 600px) { h4 { font-size: calc( 30.6px / 1.3); } } h5 { font-size: 25.2px; } @media (max-width: 600px) { h5 { font-size: calc( 25.2px / 1.3); } } h6 { font-size: 19.8px; margin: 1em 0 0 0; line-height: 1.1; } @media (max-width: 600px) { h6 { font-size: calc( 19.8px / 1.3); } } .plain-background, .none-background { color: #202020; text-shadow: none; background: #F2F2F2; } .plain-background a, .plain-background a:visited, .none-background a, .none-background a:visited { color: #B42125; } .plain-background a:hover, .plain-background a:focus, .plain-background a:active, .plain-background a:visited:hover, .plain-background a:visited:focus, .plain-background a:visited:active, .none-background a:hover, .none-background a:focus, .none-background a:active, .none-background a:visited:hover, .none-background a:visited:focus, .none-background a:visited:active { color: #89191c; } .plain-background a.button:hover, .plain-background a:visited.button:hover, .none-background a.button:hover, .none-background a:visited.button:hover { color: #202020 !important; } .plain-background svg, .none-background svg { fill: #202020 !important; } .inverse-background { color: #fff; background-color: #202020; } .inverse-background a, .inverse-background a:visited { color: #F4CA1A; } .inverse-background a:hover, .inverse-background a:focus, .inverse-background a:active, .inverse-background a:visited:hover, .inverse-background a:visited:focus, .inverse-background a:visited:active { color: #F2F2F2; } .inverse-background a.button:hover, .inverse-background a:visited.button:hover { color: #fff !important; } .inverse-background svg { fill: #fff !important; } .dark-blue-background { color: #fff; background-color: #071A33; } .dark-blue-background a, .dark-blue-background a:visited { color: #F4CA1A; } .dark-blue-background a:hover, .dark-blue-background a:focus, .dark-blue-background a:active, .dark-blue-background a:visited:hover, .dark-blue-background a:visited:focus, .dark-blue-background a:visited:active { color: #F2F2F2; } .dark-blue-background a.button:hover, .dark-blue-background a:visited.button:hover { color: #fff !important; } .dark-blue-background svg { fill: #fff !important; } .green-background { color: #202020; text-shadow: none; background-color: #9fde10; } .green-background a, .green-background a:visited { color: #B42125; } .green-background a:hover, .green-background a:focus, .green-background a:active, .green-background a:visited:hover, .green-background a:visited:focus, .green-background a:visited:active { color: #89191c; } .green-background a.button:hover, .green-background a:visited.button:hover { color: #202020 !important; } .green-background svg { fill: #202020 !important; } .yellow-background { color: #202020; text-shadow: none; background-color: #F4CA1A; } .yellow-background a, .yellow-background a:visited { color: #B42125; } .yellow-background a:hover, .yellow-background a:focus, .yellow-background a:active, .yellow-background a:visited:hover, .yellow-background a:visited:focus, .yellow-background a:visited:active { color: #89191c; } .yellow-background a.button:hover, .yellow-background a:visited.button:hover { color: #202020 !important; } .yellow-background svg { fill: #202020 !important; } .red-background { color: #fff; background-color: #ab2626; } .red-background a, .red-background a:visited { color: #F4CA1A; } .red-background a:hover, .red-background a:focus, .red-background a:active, .red-background a:visited:hover, .red-background a:visited:focus, .red-background a:visited:active { color: #F2F2F2; } .red-background a.button:hover, .red-background a:visited.button:hover { color: #fff !important; } .red-background svg { fill: #fff !important; } .blue-gradient-background { color: #fff; background-image: linear-gradient(-60deg, rgba(0, 213, 251, 0.85) 0%, rgba(7, 26, 51, 0.85) 100%); } .blue-gradient-background a, .blue-gradient-background a:visited { color: #F4CA1A; } .blue-gradient-background a:hover, .blue-gradient-background a:focus, .blue-gradient-background a:active, .blue-gradient-background a:visited:hover, .blue-gradient-background a:visited:focus, .blue-gradient-background a:visited:active { color: #F2F2F2; } .blue-gradient-background a.button:hover, .blue-gradient-background a:visited.button:hover { color: #fff !important; } .blue-gradient-background svg { fill: #fff !important; } .red-gradient-background { color: #fff; background-image: linear-gradient(-60deg, rgba(244, 92, 17, 0.9) 0%, rgba(171, 38, 38, 0.9) 100%); } .red-gradient-background a, .red-gradient-background a:visited { color: #F4CA1A; } .red-gradient-background a:hover, .red-gradient-background a:focus, .red-gradient-background a:active, .red-gradient-background a:visited:hover, .red-gradient-background a:visited:focus, .red-gradient-background a:visited:active { color: #F2F2F2; } .red-gradient-background a.button:hover, .red-gradient-background a:visited.button:hover { color: #fff !important; } .red-gradient-background svg { fill: #fff !important; } .green-gradient-background { color: #202020; text-shadow: none; background-image: linear-gradient(120deg, #9fde10 0%, #d5f419 100%); } .green-gradient-background a, .green-gradient-background a:visited { color: #B42125; } .green-gradient-background a:hover, .green-gradient-background a:focus, .green-gradient-background a:active, .green-gradient-background a:visited:hover, .green-gradient-background a:visited:focus, .green-gradient-background a:visited:active { color: #89191c; } .green-gradient-background a.button:hover, .green-gradient-background a:visited.button:hover { color: #202020 !important; } .green-gradient-background svg { fill: #202020 !important; } .light-gradient-background { color: #202020; text-shadow: none; background-image: linear-gradient(-60deg, rgba(244, 241, 28, 0.9) 0%, rgba(244, 202, 26, 0.95) 100%); } .light-gradient-background a, .light-gradient-background a:visited { color: #B42125; } .light-gradient-background a:hover, .light-gradient-background a:focus, .light-gradient-background a:active, .light-gradient-background a:visited:hover, .light-gradient-background a:visited:focus, .light-gradient-background a:visited:active { color: #89191c; } .light-gradient-background a.button:hover, .light-gradient-background a:visited.button:hover { color: #202020 !important; } .light-gradient-background svg { fill: #202020 !important; } .red-text { color: #B42125; } .blue-text { color: #071A33; } .yellow-text { color: #F4CA1A; } .yellow-line { border: 1px dashed #F4CA1A; color: #F4CA1A; margin: 1em 0; } .blue-line { border: 1px dashed #00d5fb; margin: 1em 0; } .red-line { border: 1px dashed #B42125; margin: 1em 0; } .green-line { border: 1px dashed #9fde10; margin: 1em 0; } .container { width: 90%; margin: 0 auto; max-width: 1150px; } @media (min-width: 900px) { .row { display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; -ms-flex-wrap: wrap; flex-wrap: wrap; } .row .full-width { width: 100%; } .main-column { width: 66.8%; padding-right: 30px; } .secondary-column { width: 33.2%; padding-left: 30px; padding-top: 5vh; padding-bottom: 8rem; } .individual-chapter-page .secondary-column { padding-top: 0; } } img { display: block; max-width: 100%; height: auto; } .alignleft { float: left; margin: 0.8rem 1.6rem 0.8rem 0; } .alignright { float: right; margin: 0.8rem 0 0.8rem 1.6rem; } .wp-caption { text-align: center; } div.wp-caption { background: #F2F2F2; border: 1px solid rgba(244, 202, 26, 0.5); border-radius: 0 0 0 20px; max-width: calc( 100% - 2px); } div.wp-caption.alignright { max-width: 50%; } div.wp-caption.alignleft { max-width: 50%; } img.alignright { float: right; margin: 2rem 0 2rem 2rem; max-width: 50%; } img.alignleft { float: left; margin: 2rem 2rem 2rem 0; max-width: 50%; } img.aligncenter { width: 95%; clear: both; height: auto; margin: 2rem auto; max-width: none; } .gallery { display: -ms-flexbox; display: flex; -ms-flex-flow: row wrap; flex-flow: row wrap; width: 100%; padding: 2rem; margin: 2rem auto; -ms-flex-align: stretch; align-items: stretch; } .gallery dl, .gallery li { display: -ms-inline-flexbox; display: inline-flex; -ms-flex: 33.333%; flex: 33.333%; margin: 0; max-height: 250px; overflow: hidden; } .gallery dl dt, .gallery li dt { height: 100%; width: 100%; } .gallery dl img, .gallery li img { min-width: 100%; height: auto; min-height: 100%; width: auto; object-fit: cover; } .gallery a { display: block; height: 100%; } .gallery .gallery-item { position: relative; } .gallery .gallery-item dd.gallery-caption { position: absolute; bottom: 0; background: rgba(255, 255, 255, 0.5); margin: 0; padding: 1em 0.5em; width: 100%; text-align: center; font-size: 80%; opacity: 0; } .gallery .gallery-item:hover dd.gallery-caption { opacity: 1; } /** * base form styles */ input[type="email"], input[type="number"], input[type="password"], input[type="search"], input[type="tel"], input[type="text"], input[type="url"], input[type="month"], input[type="week"], input[type="date"], input[type="datetime"], input[type="datetime-local"], select, textarea { padding: 0.5rem 1rem; outline: none; border: 1px solid rgba(32, 32, 32, 0.2); border-radius: 3px; background: #F2F2F2; font-size: 18px; font-family: "soleil", sans-serif; margin-left: 1rem; box-shadow: none; -webkit-appearance: none; } input[type="email"]:hover, input[type="number"]:hover, input[type="password"]:hover, input[type="search"]:hover, input[type="tel"]:hover, input[type="text"]:hover, input[type="url"]:hover, input[type="month"]:hover, input[type="week"]:hover, input[type="date"]:hover, input[type="datetime"]:hover, input[type="datetime-local"]:hover, select:hover, textarea:hover { border: 1px solid #071A33; } input[type="email"]:focus, input[type="number"]:focus, input[type="password"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="text"]:focus, input[type="url"]:focus, input[type="month"]:focus, input[type="week"]:focus, input[type="date"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, select:focus, textarea:focus { outline: none; border: 1px dotted #F4CA1A; background: #F2F2F2; } input[type="submit"] { font-size: 18px; font-family: "soleil", sans-serif; } .frm_form_field.frm_left_container input:not([type=radio]):not([type=checkbox]), .frm_form_field.frm_left_container:not(.frm_dynamic_select_container) select, .frm_form_field.frm_left_container textarea, .frm_form_field.frm_left_container .wp-editor-wrap, .frm_form_field.frm_left_container .frm_opt_container, .frm_form_field.frm_left_container .frm_dropzone, .frm_form_field.frm_left_container .frm-g-recaptcha, .frm_form_field.frm_left_container .g-recaptcha, .frm_form_field.frm_left_container .chosen-container, .frm_form_field.frm_left_container .frm_combo_inputs_container, .frm_form_field.frm_right_container input:not([type=radio]):not([type=checkbox]), .frm_form_field.frm_right_container:not(.frm_dynamic_select_container) select, .frm_form_field.frm_right_container textarea, .frm_form_field.frm_right_container .wp-editor-wrap, .frm_form_field.frm_right_container .frm_opt_container, .frm_form_field.frm_right_container .frm_dropzone, .frm_form_field.frm_right_container .frm-g-recaptcha, .frm_form_field.frm_right_container .g-recaptcha, .frm_form_field.frm_right_container .chosen-container, .frm_form_field.frm_right_container .frm_combo_inputs_container { max-width: 100%; } .frm_form_field.frm_left_container label.frm_primary_label { max-width: 90%; } .frm_repeat_sec { padding-bottom: 1em; border-bottom: 2px dashed #232D45; } .with_frm_style .chosen-container-single .chosen-search { margin-right: 20px; } .with_frm_style .chosen-container-single .chosen-single { min-height: 3.5rem; } .with_frm_style .chosen-container-single .chosen-single span { margin-top: 3px; } .widget_search form.search-form { display: -ms-flexbox; display: flex; } .widget_search form.search-form label { -ms-flex: 1; flex: 1; } .widget_search input[type="search"] { margin: 0 -2px 0 0; width: 100%; } .widget_search input[type="submit"] { font-size: 80%; padding: 8px 10px; margin: 0 0 0 -5px; } .yellow-fill { fill: #F4CA1A; } .main-letter-color-fill { fill: #232D45; } .red-fill { fill: #B42125; } .site-header { background: #071A33; min-height: 40vh; transition: all 1500ms ease-in-out; transform: rotate(-2.1deg) skew(-2.1deg); padding-top: 8vh; margin-top: -7vh; margin-bottom: -3vh; z-index: 1000; } .site-header .header-content { transform: rotate(2.1deg); transition: all 1500ms ease-in-out; } .site-header .logo { height: 12vh; width: auto; margin: 9vh auto 2vh auto; transform: skew(2.1deg); transition: all 1500ms ease-in-out; } .site-header .logo svg { max-height: 100%; } .site-header .logo .main-letter-color-fill { fill: #fff; } .site-header .main-navigation { background-color: #F4CA1A; position: absolute; bottom: 0; left: 0; width: 100%; display: inline-block; transform: translateY(1px); font-size: 85%; } .site-header .main-navigation ul { list-style: none; margin: 0; padding: 0; display: -ms-flexbox; display: flex; transition: all 400ms ease-in-out; } .site-header .main-navigation ul > li { -ms-flex: 1; flex: 1; text-align: center; transition: all 400ms ease-in-out; position: relative; } .site-header .main-navigation ul > li.nav-item-small { -ms-flex: none; flex: none; } .site-header .main-navigation ul > li.current_page_item { background: rgba(242, 242, 242, 0.6); } .site-header .main-navigation ul > li:hover { background: rgba(242, 242, 242, 0.6); } .site-header .main-navigation ul > li:hover ul { height: auto; background: #F4CA1A; } .site-header .main-navigation ul > li:hover ul ul { position: relative; background: rgba(242, 242, 242, 0.05); border-left: 8px solid #F4CA1A; } .site-header .main-navigation ul > li:hover ul ul li { border: 1px solid rgba(244, 202, 26, 0.5); margin-top: -1px; } .site-header .main-navigation ul > li:hover ul ul a { padding: 0.35em 1em 0.35em 3em; } .site-header .main-navigation ul > li ul { width: 100%; display: block; height: 0; overflow: hidden; transition: all 400ms ease-in-out; } @media (min-width: 900px) { .site-header .main-navigation ul > li ul { position: absolute; } } .site-header .main-navigation ul > li ul li { text-align: left; } .site-header .main-navigation a { color: #202020; text-decoration: none; padding: 1em; display: block; transform: rotate(2.1deg); transition: all 400ms ease-in-out; } .site-header.smaller { background-color: #F2F2F2; transform: rotate(0deg) skew(0deg); } .site-header.smaller .header-content { transform: rotate(0deg); } .site-header.smaller .logo { transform: skew(0deg); height: 9vh; margin: 16vh auto 1vh auto; } .site-header.smaller .logo svg .main-letter-color-fill { fill: #232D45; } .site-header.smaller .main-navigation a, .site-header.smaller .main-navigation-sticky a { transform: rotate(0deg); padding: 0.5em 1em; } .main-navigation-sticky { position: fixed; width: 100%; left: 0; top: 0; z-index: 100; border-top: 0; display: none; font-size: 85%; } @media (min-width: 900px) { .main-navigation-sticky { background-color: #F4CA1A; } } @media (min-width: 900px) { .main-navigation-sticky { top: 30px; } } .logged-in.admin-bar .main-navigation-sticky { top: 32px; } @media (min-width: 900px) { .logged-in.admin-bar .main-navigation-sticky { top: 62px; } } .main-navigation-sticky.show { display: inline-block; } .main-navigation-sticky ul { list-style: none; margin: 0; padding: 0; display: -ms-flexbox; display: flex; transition: all 400ms ease-in-out; } .main-navigation-sticky ul > li { -ms-flex: 1; flex: 1; text-align: center; transition: all 400ms ease-in-out; position: relative; } .main-navigation-sticky ul > li.current_page_item { background: rgba(242, 242, 242, 0.6); } .main-navigation-sticky ul > li.nav-item-small { -ms-flex: none; flex: none; } .main-navigation-sticky ul > li:hover { background: rgba(242, 242, 242, 0.6); } .main-navigation-sticky ul > li:hover ul { height: auto; background: #F4CA1A; } .main-navigation-sticky ul > li:hover ul ul { position: relative; background: rgba(242, 242, 242, 0.05); border-left: 8px solid #F4CA1A; } .main-navigation-sticky ul > li:hover ul ul li { border: 1px solid rgba(244, 202, 26, 0.5); margin-top: -1px; } .main-navigation-sticky ul > li:hover ul ul a { padding: 0.35em 1em 0.35em 3em; } .main-navigation-sticky ul > li ul { position: absolute; width: 100%; display: block; height: 0; overflow: hidden; transition: all 400ms ease-in-out; } .main-navigation-sticky ul > li ul li { text-align: left; } .main-navigation-sticky a { color: #202020; text-decoration: none; padding: 0.5em 1em; display: block; transition: all 400ms ease-in-out; } nav.utility-navigation { position: absolute; width: 0; height: 0; overflow: hidden; } @media (min-width: 900px) { nav.utility-navigation { position: fixed; width: 100%; height: 30px; background: #010810; top: 0; left: 0; right: 0; z-index: 99998; border-top: 1px solid #010810; overflow: visible; transition: all 400ms ease-in-out; } .logged-in.admin-bar nav.utility-navigation { top: 32px; } nav.utility-navigation .user-welcome { position: absolute; font-size: 70%; color: rgba(244, 202, 26, 0.8); } nav.utility-navigation .user-welcome svg.icon:hover { fill: rgba(244, 202, 26, 0.8); cursor: auto; } nav.utility-navigation ul { margin: 0; padding: 0; list-style: none; display: -ms-flexbox; display: flex; -ms-flex-pack: end; justify-content: flex-end; } nav.utility-navigation li { margin: 0; padding: 0 5px 2px 5px; text-align: center; position: relative; } nav.utility-navigation svg.icon { fill: rgba(244, 202, 26, 0.8); max-height: 19px; transition: all 400ms ease-in-out; margin: 0 auto; cursor: pointer; overflow: visible; position: relative; vertical-align: text-bottom; } nav.utility-navigation svg.icon text.tooltip { display: block !important; opacity: 0 !important; background: #202020; fill: rgba(242, 242, 242, 0.7) !important; transition: all 400ms ease-in-out; z-index: 1900000; font-family: "soleil", sans-serif !important; font-size: 1.2rem !important; text-anchor: middle !important; } nav.utility-navigation svg.icon:hover { fill: rgba(180, 33, 37, 0.9); } nav.utility-navigation svg.icon:hover text.tooltip { opacity: 1 !important; } nav.utility-navigation .search-form-area { font-size: 80%; width: 0; overflow: hidden; transition: all 400ms ease-in-out; } nav.utility-navigation .search-form-area input[type="search"], nav.utility-navigation .search-form-area input[type="submit"] { font-size: 12px; opacity: 0; padding: 3px; transition: all 400ms ease-in-out; } nav.utility-navigation .search-form-area input[type="search"] { background: rgba(242, 242, 242, 0.1); color: #F2F2F2; width: 0; } nav.utility-navigation .search-form-area.show-search-form { width: 50%; } nav.utility-navigation .search-form-area.show-search-form input[type="search"] { opacity: 1; font-size: 12px; padding: 3px; width: 80%; background: rgba(242, 242, 242, 0.1); color: #F2F2F2; } nav.utility-navigation .search-form-area.show-search-form input[type="submit"] { opacity: 1; font-size: 12px; padding: 5px 4px; } .mobile-only-utility-navigation { display: none; height: 0; width: 0; opacity: 0; } } @media (max-width: 900px) { .site-header { position: relative; } .site-header nav.main-navigation { height: 10px; } .site-header nav.main-navigation ul { display: none; } .mobile-nav-button { width: 35px; position: fixed; margin: 2rem; right: 0; top: 0; z-index: 999999; cursor: pointer; height: 30px; } .mobile-nav-button .mobile-nav-button__line { width: 100%; height: 4px; background: #F4CA1A; position: relative; transition: 1s ease; } .mobile-nav-button .mobile-nav-button__line:nth-of-type(2) { margin: 0.5rem 0; } .mobile-nav-button .mobile-nav-button__line--1 { transform: rotate(45deg); top: 13px; position: absolute; background: #202020; } .mobile-nav-button .mobile-nav-button__line--2 { display: none; } .mobile-nav-button .mobile-nav-button__line--3 { transform: rotate(135deg); top: 13px; position: absolute; background: #202020; } .mobile-menu { display: block; max-width: 100vw; width: 100%; right: -100%; height: auto; min-height: 100vh; background: #F4CA1A; position: fixed; z-index: -1; transition: 0.6s ease; overflow-y: scroll; overflow-x: hidden; top: 0; opacity: 0; font-size: 3rem; } .mobile-menu > ul { position: relative; top: 55px; display: block; padding: 0; } .mobile-menu > ul > li { list-style: none; } .mobile-menu > ul > li a { width: 100%; max-width: 1200px; margin: 0 auto; display: block; text-align: left; text-decoration: none; color: #202020; font-size: 2.2rem; font-weight: bold; position: relative; cursor: pointer; } .mobile-menu > ul > li a:hover { background-color: rgba(242, 242, 242, 0.05); } .mobile-menu > ul > li ul { position: relative; height: auto; background: rgba(242, 242, 242, 0.05); } .mobile-menu > ul > li ul a { font-size: 1.5rem; } .mobile-menu > ul > li ul ul { position: relative; background: rgba(242, 242, 242, 0.05); border-left: 8px solid #F4CA1A; } .mobile-menu > ul > li ul ul li { border: 1px solid rgba(244, 202, 26, 0.5); margin-top: -1px; } .mobile-menu > ul > li ul ul a { padding: 0.35em 1em 0.35em 3em; font-weight: normal; font-size: 2rem; } .mobile-menu > ul ul { margin: 0; padding: 0; } .mobile-menu > ul ul li a { padding-left: 4rem; } .mobile-menu--open { right: 0; opacity: 1; z-index: 9999; } .mobile-only-utility-navigation { display: block; } .mobile-only-utility-navigation nav.utility-navigation { height: auto; width: 100%; position: absolute; bottom: 0; left: 0; right: 0; } .mobile-only-utility-navigation nav.utility-navigation a, .mobile-only-utility-navigation nav.utility-navigation span { display: block; padding: 0.2em 0; } .mobile-only-utility-navigation nav.utility-navigation ul { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } .mobile-only-utility-navigation nav.utility-navigation li { -ms-flex: 1; flex: 1; } .mobile-only-utility-navigation nav.utility-navigation li.mobile-search-form-area { width: 0; overflow: hidden; -ms-flex: none; flex: none; } .mobile-only-utility-navigation nav.utility-navigation li.mobile-search-form-area input { width: 0; transition: all 400ms ease-in-out; font-size: 16px; padding: 0; height: 0; opacity: 0; margin: 0; } .mobile-only-utility-navigation nav.utility-navigation li.mobile-search-form-area.show-search-form { width: 80%; } .mobile-only-utility-navigation nav.utility-navigation li.mobile-search-form-area.show-search-form input[type="search"] { width: 95%; padding: 4px; opacity: 1; height: auto; min-height: 24px; } .mobile-only-utility-navigation nav.utility-navigation li.mobile-search-form-area.show-search-form input[type="submit"] { display: none; } } #main { width: 100%; } body:not(.has-featured-image) #main > section:first-of-type:not(.type-hero), body:not(.has-featured-image) #main > article:first-of-type { padding-top: 5vh; } body.has-featured-image .featured-image-background-container { position: fixed; top: 0; left: 0; right: 0; width: 100%; height: 100vh; z-index: 0; overflow: hidden; } body.has-featured-image .featured-image-background-container .featured-image-background { width: 100%; height: 100%; background-repeat: no-repeat; background-size: cover; background-position: center center; } body.has-featured-image .featured-image-background-container .featured-image-cover { position: fixed; top: 0; left: 0; right: 0; width: 100%; height: 100%; z-index: 2; opacity: 0.86; } body.has-featured-image #content { margin-top: 45vh; position: relative; z-index: 5; background: #F2F2F2; } body.has-featured-image #content .page-title { margin: 0.5em 0; padding: 0; } iframe, iframe.wp-embedded-content { max-width: 100%; } .sidebar h4.widget-title { display: block; background: #ab2626; color: #F2F2F2; padding: 8px 15px; line-height: 1; font-size: 2.3rem; border-radius: 3px; } .sidebar .widget { margin-bottom: 3rem; padding-bottom: 3rem; border-bottom: 1px dotted rgba(7, 26, 51, 0.25); font-size: 85%; } .sidebar .widget:nth-of-type(5n-4) h4.widget-title { background: #071A33; color: #F2F2F2; } .sidebar .widget:nth-of-type(5n-3) h4.widget-title { background: #F4CA1A; color: #202020; } .sidebar .widget:nth-of-type(5n-2) h4.widget-title { background: #9fde10; color: #202020; } .sidebar .widget:nth-of-type(5n-1) h4.widget-title { background: #00d5fb; color: #202020; } .sidebar .widget ul { list-style: none; margin: 0; padding: 0 15px; } footer.site-footer { background: #202020; padding: 2rem 0; color: #F2F2F2; position: relative; z-index: 5; } footer.site-footer a { color: #F4CA1A; } footer.site-footer a:hover { color: #F2F2F2; } footer.site-footer .footer-widget-area { display: -ms-flexbox; display: flex; -ms-flex-align: stretch; align-items: stretch; -ms-flex-pack: justify; justify-content: space-between; } @media (max-width: 900px) { footer.site-footer .footer-widget-area { display: block; } } footer.site-footer .footer-widget-area > div { -ms-flex: 1; flex: 1; margin: 2em 0; padding: 2em 1em 2em 1.2em; border-right: 1px solid rgba(242, 242, 242, 0.3); } @media (max-width: 900px) { footer.site-footer .footer-widget-area > div { max-width: 100%; display: block; clear: both; border-right: none; border-bottom: 1px solid rgba(242, 242, 242, 0.3); text-align: center; } } footer.site-footer .footer-widget-area > div:last-child { border-right: none; } @media (max-width: 900px) { footer.site-footer .footer-widget-area > div:last-child { border-bottom: none; } } footer.site-footer .footer-widget-area .widget_nav_menu ul { margin: 0; padding: 0; list-style: none; } footer.site-footer .footer-widget-area h4.widgettitle { text-align: center; } footer.site-footer .footer-widget-area div.column div.widget:first-child h4.widgettitle { margin-top: 0; } footer.site-footer .social-links { margin: 0; padding: 0; list-style: none; float: right; clear: both; } footer.site-footer .social-links li { display: inline; } footer.site-footer .social-links li span { padding: 1rem; } footer.site-footer .social-links li a { text-decoration: none; } footer.site-footer .social-links li svg.icon { opacity: 0.67; transition: all 400ms ease-in-out; } footer.site-footer .social-links li svg.icon:hover { opacity: 1; } footer.site-footer .container p { padding: 0; } .page-section { padding: 0; } .section-title { margin-top: 0; text-align: center; padding: 4rem 10px 0 10px; line-height: 1.2; } .type-none .section-title { margin: 0; padding: 4rem 10px; } @media (max-width: 600px) { .section-title { font-size: 1.5em; } } .section-intro-text { text-align: center; } .type-hero .hero { min-height: 75vh; background-size: cover; background-position: 50% 20%; position: relative; z-index: 0; } .type-hero .hero .hero-text-container { font-size: 1.5em; padding: 7vw 1em 1em 1em; margin: 0 55vw 0 4vw; overflow: hidden; } .type-hero .hero .hero-text-container p:first-child { margin-top: 0; } @media (max-width: 600px) { .type-hero .hero { min-height: 60vh; background-size: auto 100%; background-repeat: no-repeat; } .type-hero .hero .hero-text-container { margin: 30vh 0 0 0; position: relative; float: right; padding: 0.5em; } } .featured-blog-post-container, .text-image-grid-container { display: -ms-flexbox; display: flex; } @media (max-width: 600px) { .featured-blog-post-container, .text-image-grid-container { display: block; } } .featured-blog-post-container.image-text, .text-image-grid-container.image-text { -ms-flex-direction: row-reverse; flex-direction: row-reverse; } .featured-blog-post-container.thirds > div, .text-image-grid-container.thirds > div { -ms-flex: auto; flex: auto; } .featured-blog-post-container.thirds > div.text-side, .text-image-grid-container.thirds > div.text-side { width: 66.8%; } @media (max-width: 600px) { .featured-blog-post-container.thirds > div.text-side, .text-image-grid-container.thirds > div.text-side { width: 100%; } } .featured-blog-post-container.thirds > div.image-side, .text-image-grid-container.thirds > div.image-side { width: calc( 100vw - 66.8%); } @media (max-width: 600px) { .featured-blog-post-container.thirds > div.image-side, .text-image-grid-container.thirds > div.image-side { width: 100%; } } .featured-blog-post-container > div, .text-image-grid-container > div { -ms-flex: 1; flex: 1; } .featured-blog-post-container > div.text-side, .text-image-grid-container > div.text-side { background: #F2F2F2; color: #202020; text-shadow: none; text-shadow: none; } .featured-blog-post-container > div.text-side a, .featured-blog-post-container > div.text-side a:visited, .text-image-grid-container > div.text-side a, .text-image-grid-container > div.text-side a:visited { color: #B42125; } .featured-blog-post-container > div.text-side a:hover, .featured-blog-post-container > div.text-side a:focus, .featured-blog-post-container > div.text-side a:active, .featured-blog-post-container > div.text-side a:visited:hover, .featured-blog-post-container > div.text-side a:visited:focus, .featured-blog-post-container > div.text-side a:visited:active, .text-image-grid-container > div.text-side a:hover, .text-image-grid-container > div.text-side a:focus, .text-image-grid-container > div.text-side a:active, .text-image-grid-container > div.text-side a:visited:hover, .text-image-grid-container > div.text-side a:visited:focus, .text-image-grid-container > div.text-side a:visited:active { color: #89191c; } .featured-blog-post-container > div.text-side a.button:hover, .featured-blog-post-container > div.text-side a:visited.button:hover, .text-image-grid-container > div.text-side a.button:hover, .text-image-grid-container > div.text-side a:visited.button:hover { color: #202020 !important; } .featured-blog-post-container > div.text-side svg, .text-image-grid-container > div.text-side svg { fill: #202020 !important; } .featured-blog-post-container > div.text-side h2, .text-image-grid-container > div.text-side h2 { line-height: 1.2; } .featured-blog-post-container > div.text-side h2 a, .text-image-grid-container > div.text-side h2 a { color: #202020 !important; text-decoration: none; } .featured-blog-post-container > div.text-side .padding, .text-image-grid-container > div.text-side .padding { padding: 4em; } .featured-blog-post-container > div.image-side, .text-image-grid-container > div.image-side { background-size: cover; background-position: 50% 50%; } @media (max-width: 600px) { .featured-blog-post-container > div.image-side, .text-image-grid-container > div.image-side { min-height: 45vh; } } /** * WYSIWYG */ .type-wysiwyg .container { padding: 4rem 0; } .type-wysiwyg .container .padding { padding-left: 0; padding-right: 0; } /** * Columns section */ .type-three_col .columns-wrapper { display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: stretch; align-items: stretch; width: 90%; margin: 0 auto; padding: 3rem 0; } @media (max-width: 600px) { .type-three_col .columns-wrapper { display: block; } } .type-three_col .columns-wrapper .column { width: 33%; display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; -ms-flex-align: stretch; align-items: stretch; -ms-flex-pack: end; justify-content: flex-end; border-radius: 4px; } @media (max-width: 600px) { .type-three_col .columns-wrapper .column { width: 100%; display: block; } } .type-three_col .columns-wrapper .column > div { padding: 0 3rem 1rem 3rem; -ms-flex: 1; flex: 1; } @media (max-width: 600px) { .type-three_col .columns-wrapper .column > div { display: block; } } .type-three_col .columns-wrapper .column > div:last-child { -ms-flex-item-align: center; align-self: center; text-align: center; } .type-three_col .columns-wrapper .column .column-title { margin: 0; padding: 2rem 0 0 0; line-height: 1.1; text-align: center; } .type-three_col .columns-wrapper .column .column-body { -ms-flex: 1; flex: 1; -ms-flex-positive: 3; flex-grow: 3; } .type-three_col .columns-wrapper div.column ~ div.column { margin-left: 30px; } @media (min-width: 600px) and (max-width: 1200px) { .type-three_col .columns-wrapper div.column ~ div.column { margin-left: calc( 30px / 2); } } @media (max-width: 600px) { .type-three_col .columns-wrapper div.column ~ div.column { margin: 0; } } /** * Content collection */ .type-content_collection .content-collection.archive-grid { display: -ms-flexbox; display: flex; -ms-flex-line-pack: distribute; align-content: space-around; -ms-flex-pack: distribute; justify-content: space-around; -ms-flex-wrap: wrap; flex-wrap: wrap; width: calc( 90% - 3ch); margin: 0 auto; } @media (max-width: 600px) { .type-content_collection .content-collection.archive-grid { display: block; width: 90%; } } .type-content_collection .content-collection.archive-grid > article { -ms-flex: 1; flex: 1; min-width: 25ch; max-width: 50ch; margin: 1.5ch; } @media (max-width: 600px) { .type-content_collection .content-collection.archive-grid > article { border-top: 1px dotted #202020; padding-top: 2rem; margin: 0; } } .type-content_collection .content-collection.archive-grid > article .article-header { display: block; } .type-content_collection .content-collection.archive-grid > article .article-header img { border-radius: 0 0 0 25px; } .type-content_collection .content-collection.archive-grid > article h2 { margin: 0; line-height: 1.2; font-size: 4rem; } .type-content_collection .content-collection.archive-grid > article h2 a { text-decoration: none; } .type-content_collection .content-collection.archive-grid > article p.byline { padding: 0; font-size: 80%; } .type-content_collection .content-collection.archive-list { width: calc( 90% - 3ch); margin: 0 auto; } /** * Page Grid */ .type-page_grid .page-grid-container { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; width: 100%; } .type-page_grid .page-grid-container > div { -ms-flex: 1; flex: 1; min-height: 40vh; background-size: cover; position: relative; min-width: 400px; } @media (max-width: 600px) { .type-page_grid .page-grid-container > div { -ms-flex: none; flex: none; display: block; min-height: 30vh; min-width: 0; width: 100%; } } .type-page_grid .page-grid-container > div :after { content: ''; position: absolute; pointer-events: none; top: 15px; bottom: 15px; left: 15px; right: 15px; border: 2px solid rgba(242, 242, 242, 0.5); } .type-page_grid .page-grid-container > div a, .type-page_grid .page-grid-container > div a:visited { height: 100%; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; text-decoration: none; font-weight: 800; color: #F2F2F2; font-size: 3rem; background-color: rgba(32, 32, 32, 0.5); text-shadow: 1px 1px 2px rgba(32, 32, 32, 0.3); } .type-page_grid .page-grid-container > div a:hover, .type-page_grid .page-grid-container > div a:visited:hover { background-color: rgba(242, 242, 242, 0.2); color: #fff; text-shadow: 1px 1px 4px rgba(32, 32, 32, 0.5); } .type-page_grid .page-grid-container > div a strong, .type-page_grid .page-grid-container > div a:visited strong { text-align: center; padding: 0.5em 1em; font-size: 4rem; margin: 5em 0; background: #f2f2f2; transition: all 0.75s ease 0s; } @media (max-width: 600px) { .type-page_grid .page-grid-container > div a strong, .type-page_grid .page-grid-container > div a:visited strong { margin: 3em 0; font-size: 3rem; padding: 0.4em 0.9em; } } /** * CHILDREN Page Grid */ .page-children-grid { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -ms-flex-align: start; align-items: flex-start; justify-items: center; -ms-flex-pack: center; justify-content: center; } .page-children-grid .child-page-box { text-align: center; margin: 1em 3vw; width: 15vw; min-width: 200px; max-width: 390px; } @media (max-width: 600px) { .page-children-grid .child-page-box { width: auto; } } .page-children-grid .child-page-box h6 { padding-top: 0.75em; margin: 0; line-height: 1.2; } .page-children-grid .child-page-box h6 a { color: #202020; text-decoration: none; } .page-children-grid .child-page-box h6 a:hover { color: #89191c; } .page-children-grid .child-page-box .child-page-link { width: 15vw; height: 15vw; min-width: 200px; min-height: 200px; max-width: 390px; max-height: 390px; transition: all 300ms ease-in-out; } .page-children-grid .child-page-box .child-page-link.no-icon a { display: block; height: 100%; width: 100%; } .page-children-grid .child-page-box .child-page-link.round { border-radius: 50%; box-shadow: 1px 1px 0 rgba(0, 0, 0, 0.5); } .page-children-grid .child-page-box .child-page-link.round svg { fill: #F2F2F2 !important; height: 65%; width: 65%; margin: 18% auto; filter: drop-shadow(0 1px 0 rgba(0, 0, 0, 0.25)) url(#inset-shadow); } .page-children-grid .child-page-box .child-page-link:hover { transform: scale(1.1); } .landing-page-section { background-size: cover; background-position: center center; } .landing-page-section .container { padding-top: 3em; padding-bottom: 3em; } .landing-page-section .section-title { margin-bottom: 1.5rem; } .landing-page-section.break { padding-top: 2em; padding-bottom: 2em; } .landing-page-section.bottom-curve { padding-bottom: 5em; border-bottom-left-radius: 50% 20%; border-bottom-right-radius: 50% 20%; } .landing-page-section.top-curve { padding-top: 5em; border-top-left-radius: 50% 20%; border-top-right-radius: 50% 20%; } .landing-page-section.bottom-fade { padding-bottom: 4em; -webkit-mask-image: linear-gradient(to top, transparent 0, black 5em); mask-image: linear-gradient(to top, transparent 0, black 5em); -webkit-mask-mode: luminance; mask-mode: luminance; margin-bottom: -2em; } .landing-page-section.top-fade { padding-top: 4em; -webkit-mask-image: linear-gradient(transparent 0, black 5em); mask-image: linear-gradient(transparent 0, black 5em); -webkit-mask-mode: luminance; mask-mode: luminance; } .landing-page-section.bottom-angle { padding-bottom: 3em; -webkit-clip-path: polygon(0 0, 100% 0, 100% 92%, 0 100%); clip-path: polygon(0 0, 100% 0, 100% 92%, 0 100%); margin-bottom: -2em; } .landing-page-section.top-angle { padding-top: 3em; -webkit-clip-path: polygon(0 0, 100% 8%, 100% 100%, 0 100%); clip-path: polygon(0 0, 100% 8%, 100% 100%, 0 100%); } .landing-page-section.full-height { min-height: 90vh; } @media (min-width: 900px) { .landing-page-section .full { width: 100%; } .landing-page-section .golden-large { width: 66.8%; } .landing-page-section .half { width: 50%; } .landing-page-section .golden-small { width: calc( 100% - 66.8%); } } .landing-page-section p { padding: 0; } .landing-page-section p img.alignright { margin-right: 0; } .landing-page-section p img.alignleft { margin-left: 0; } .landing-page-section p img.aligncenter { width: auto; margin: 2rem auto; } .landing-page-section .cta-button-area { text-align: center; } .landing-page-section .cta-container { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } .landing-page-section .cta-container > div { -ms-flex: 1; flex: 1; } .landing-page-section .cta-container > div.cta-button { text-align: center; } .landing-page-section .landing-page-section-content.content-type_freeform { overflow: hidden; clear: both; } .landing-page-section .landing-page-section-content.content-type_grid { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -ms-flex-align: stretch; align-items: stretch; -ms-flex-pack: space-evenly; justify-content: space-evenly; -ms-flex-line-pack: distribute; align-content: space-around; } .landing-page-section .landing-page-section-content.content-type_grid .block { min-width: 330px; padding: 1rem 2rem; -ms-flex: 1; flex: 1; background-size: cover; background-position: center center; } .landing-page-section .landing-page-section-content.content-type_grid .block h6 { margin: 0.5em 0; text-align: center; } .page-title { display: block; text-align: center; position: relative; margin: 1em 0 0 0; padding-top: 3rem; line-height: 1.2; font-size: 4em; letter-spacing: -1px; } @media (max-width: 600px) { .page-title { font-size: 3.3em; } } .page-title .smaller { font-size: 3rem; display: block; clear: both; letter-spacing: 0; font-family: "soleil", sans-serif; font-weight: normal; margin-bottom: -3rem; } @media (max-width: 600px) { .page-title .smaller { font-size: 2rem; margin-bottom: -1rem; } } .centered-title { text-align: center; } #content form.gmw-form .address-locator-wrapper { width: 40%; } #content form.gmw-form .address-locator-wrapper input[type="text"] { font-size: 1.3rem; width: 100%; } #content form.gmw-form input[type="submit"] { padding: 0.3rem 0.8rem; font-size: 1.4rem; } #content .gmw-pt-per-page-dropdown { height: auto !important; } #content .wppl-single-result { display: -ms-flexbox; display: flex; -ms-flex-align: stretch; align-items: stretch; box-sizing: border-box; } #content .wppl-single-result > div { -ms-flex: 1; flex: 1; width: auto; } #content .wppl-single-result .wppl-title-holder { width: 50%; margin: 1rem 0 1rem 1rem; padding: 1rem; border-right: none; } #content .wppl-single-result #wppl-taxes-wrapper { display: none; } #content .wppl-single-result h2.wppl-h2 { line-height: 1.2; font-size: 30.6px; } @media (max-width: 600px) { #content .wppl-single-result h2.wppl-h2 { font-size: calc( 30.6px / 1.2); } } #content .wppl-single-result h2.wppl-h2 a { text-decoration: none; } #content .wppl-single-result .wppl-info { width: auto; font-size: 1.8rem; line-height: 1.3; margin: 1rem 1rem 1rem 0; padding: 1rem; border-left: none; } #content .wppl-single-result .wppl-info div span { font-size: 1.8rem; line-height: 1.3; } @media (max-width: 900px) { #content .wppl-single-result { display: block; } #content .wppl-single-result .wppl-title-holder, #content .wppl-single-result .wppl-info { width: auto; display: block; margin: 0 1rem; border: 1px solid #ccc; } #content .wppl-single-result .wppl-title-holder { margin-top: 1rem; border-bottom: none; } #content .wppl-single-result .wppl-info { margin-bottom: 1rem; border-top: none; } } .home section.homepage-hero { min-height: 70vh; color: #fff; background-image: linear-gradient(-60deg, rgba(0, 213, 251, 0.85) 0%, rgba(7, 26, 51, 0.85) 100%); padding: 12vh 2vw 5vh 2vw; margin-top: -7vh; background-size: cover; background-position: center center; position: relative; } .home section.homepage-hero a, .home section.homepage-hero a:visited { color: #F4CA1A; } .home section.homepage-hero a:hover, .home section.homepage-hero a:focus, .home section.homepage-hero a:active, .home section.homepage-hero a:visited:hover, .home section.homepage-hero a:visited:focus, .home section.homepage-hero a:visited:active { color: #F2F2F2; } .home section.homepage-hero a.button:hover, .home section.homepage-hero a:visited.button:hover { color: #fff !important; } .home section.homepage-hero svg { fill: #fff !important; } .home section.homepage-hero .video-container { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 59vh; z-index: -1; } .home section.homepage-hero .slideshow-container { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; z-index: -1; } .home section.homepage-hero .slideshow-container > figure { animation: imageAnimation 30s linear infinite 0s; backface-visibility: hidden; background-size: cover; background-position: center center; color: transparent; height: 100%; left: 0; opacity: 0; position: absolute; top: 0; width: 100%; padding: 0; margin: 0; } .home section.homepage-hero .hero-content { padding: 5vh 5vw; margin: 0 auto; line-height: 1.3; text-shadow: 1px 1px 3px rgba(32, 32, 32, 0.6); } @media (min-width: 900px) { .home section.homepage-hero .hero-content { width: 65%; max-width: 850px; } } .home section.homepage-hero .hero-content h1 { margin: 0; padding: 0; font-size: 7rem; } .home section.homepage-hero .hero-content h2 { margin: 0; padding: 0; text-transform: uppercase; font-size: 4rem; } body.has-featured-image.search-results #content { margin-top: 0; } article.archive { display: -ms-flexbox; display: flex; margin-bottom: 2rem; min-height: 15rem; } article.archive > section { -ms-flex: auto; flex: auto; } article.archive > section.featured-image { width: 25%; background-size: cover; background-position: center center; } article.archive > section.featured-image a { display: block; width: 100%; height: 100%; opacity: 0.9; } article.archive > section.archive-content-container { width: 75%; padding: 1rem 0 1rem 2%; } article.archive > section.archive-content-container h3 { margin-top: 0; font-size: 3rem; } .archive-grid { display: -ms-flexbox; display: flex; -ms-flex-line-pack: distribute; align-content: space-around; -ms-flex-pack: distribute; justify-content: space-around; } .archive-grid .grid { min-width: 400px; min-height: 400px; background-size: cover; background-position: center center; display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; -ms-flex-line-pack: end; align-content: flex-end; -ms-flex-align: stretch; align-items: stretch; } .archive-grid .grid:hover { box-shadow: 1px 1px 3px rgba(32, 32, 32, 0.2); } .archive-grid .grid:hover .top-space a, .archive-grid .grid:hover .top-space a:visited { background: rgba(242, 242, 242, 0.2); } .archive-grid .grid:hover .article-header a, .archive-grid .grid:hover .article-header a:visited { color: #F4CA1A; } .archive-grid .grid .top-space { -ms-flex: 1; flex: 1; display: -ms-flexbox; display: flex; } .archive-grid .grid .top-space a { display: block; -ms-flex: 1; flex: 1; } .archive-grid .grid .article-header { background-image: linear-gradient(-60deg, rgba(0, 213, 251, 0.85) 0%, rgba(7, 26, 51, 0.85) 100%); padding: 2rem; text-align: center; color: #F2F2F2; } .archive-grid .grid .article-header h3, .archive-grid .grid .article-header h6 { margin: 0; padding: 0; line-height: 1; text-shadow: 1px 1px 3px rgba(32, 32, 32, 0.2); } .archive-grid .grid .article-header a, .archive-grid .grid .article-header a:visited { color: #F2F2F2; text-decoration: none; } .archive-grid .grid .article-header a:hover, .archive-grid .grid .article-header a:visited:hover { color: #F4CA1A; } header.article-header .byline { padding: 0 0 1rem 0; font-size: 80%; } nav.next-and-previous-posts { display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; -ms-flex-align: stretch; align-items: stretch; } nav.next-and-previous-posts > div { padding: 2rem; } span.pulled-right { display: block; float: right; clear: right; padding: 0 0 0 10px; margin: 0 0 20px 20px; width: 230px; font-size: 1.5em; line-height: 1.3; text-align: right; color: #3a3a3a; border-left: 3px solid rgba(7, 26, 51, 0.5); } @media (max-width: 900px) { span.pulled-right { width: 200px; font-size: 1.3em; } } span.pulled-left { display: block; float: left; clear: left; padding: 0 10px 0 0; margin: 0 20px 20px 0; width: 230px; font-size: 1.5em; line-height: 1.3; text-align: left; color: #3a3a3a; border-right: 3px solid rgba(7, 26, 51, 0.5); } @media (max-width: 900px) { span.pulled-left { width: 200px; font-size: 1.3em; } } #comments { display: block; clear: both; margin-top: 4rem; padding-top: 2rem; border-top: 1px solid rgba(7, 26, 51, 0.3); } #respond h3 { font-size: 3rem; } #respond h3 small { font-size: 18px; font-family: "soleil", sans-serif; font-weight: normal; } ol.commentlist { margin: 1em 0; padding: 0; list-style: none; } ol.commentlist li { padding: 0; margin: 0; } ol.commentlist li .media-object { padding: 1em; display: -ms-flexbox; display: flex; } ol.commentlist li .media-object .media-object-section > article { padding: 0.5em 1em; background: rgba(244, 202, 26, 0.065); border-radius: 0 0 0 20px; } ol.commentlist li .media-object .media-object-section p { padding: 0; } ol.commentlist li .media-object .media-object-section p label { left: 1.5rem; top: -1.5rem; background: #F2F2F2; } @media (max-width: 900px) { ol.commentlist li .media-object .media-object-section p label { left: 1.25rem; } } ol.commentlist li .media-object .media-object-section:last-child { -ms-flex: 1; flex: 1; } ol.commentlist li ul { list-style: none; margin: 0 0 0 3em; padding: 0; } .single-person .person-photo-container { height: 400px; width: 400px; margin: -370px auto -30px auto; box-shadow: 1px 1px 5px rgba(32, 32, 32, 0.5); } .single-person .person-photo-container img { width: 100%; height: 100%; object-fit: cover; object-position: center center; border-radius: 6px; } .single-person .person-header { padding: 3rem 1rem; text-shadow: 1px 1px 3px rgba(32, 32, 32, 0.2); } .single-person h1.person-name { margin: 0; padding: 0; } .single-person h2.person-title { margin: 0; padding: 0; font-size: 3.5rem; } @media (max-width: 600px) { .single-person h2.person-title { font-size: 2.5rem; } } .single-person ul.person-additional-details { margin: 0; padding: 3rem 2rem; } .single-person ul.person-additional-details li { display: -ms-flexbox; display: flex; -ms-flex-align: start; align-items: flex-start; border-bottom: 1px dotted #F4CA1A; padding: 0 2rem; } .single-person ul.person-additional-details li > span { -ms-flex: 1; flex: 1; } .mec-container, #main-content { padding-top: 5vh; } .mec-container .mec-wrap, #main-content .mec-wrap { font-family: "soleil", sans-serif; } .mec-container .mec-wrap h1, .mec-container .mec-wrap h2, .mec-container .mec-wrap h3, .mec-container .mec-wrap h4, .mec-container .mec-wrap h5, .mec-container .mec-wrap h6, .mec-container .mec-wrap div, #main-content .mec-wrap h1, #main-content .mec-wrap h2, #main-content .mec-wrap h3, #main-content .mec-wrap h4, #main-content .mec-wrap h5, #main-content .mec-wrap h6, #main-content .mec-wrap div { font-family: "soleil", sans-serif; } .mec-wrap { overflow: hidden; } .mec-wrap .mec-events-masonry-cats a { text-decoration: none; background: #232D45; color: #fff !important; border-color: #fff; opacity: 0.6; transition: all 500ms ease-in-out; } .mec-wrap .mec-events-masonry-cats a[data-filter="*"] { background: #00d5fb; color: #202020 !important; } .mec-wrap .mec-events-masonry-cats a[data-filter=".mec-t32"] { background: #B42125; color: #fff !important; } .mec-wrap .mec-events-masonry-cats a[data-filter=".mec-t8"] { background: #F4CA1A; color: #202020 !important; } .mec-wrap .mec-events-masonry-cats a:hover, .mec-wrap .mec-events-masonry-cats a.mec-masonry-cat-selected { border-color: #00d5fb; opacity: 1; } .mec-events-event-image img { width: 100%; height: auto; } .mec-single-event .mec-event-content { background: #fff; padding: 2rem 3rem; margin-bottom: 30px; } .mec-single-event .mec-event-content p { color: #202020; font-family: "soleil", sans-serif; font-style: normal; font-weight: 300; font-size: 18px; line-height: 1.4; } .mec-single-event h3.mec-frontbox-title { font-size: 30.6px; } .mec-single-event .mec-event-schedule-content dl { font-size: 1.4rem; } .mec-single-event .mec-event-schedule-content dl dt.mec-schedule-title { font-size: 1.4rem; } .mec-single-event input[type="text"] { margin-left: 0; } .mec-events-meta-group-countdown .countdown-w .block-w { font-size: 2.5rem; } .individual-chapter-page .return-to-main-site { display: inline-block; width: auto; text-align: center; max-width: 35%; } .individual-chapter-page .return-to-main-site a, .individual-chapter-page .return-to-main-site a:visited { text-decoration: none; padding: 3px 3px 0 3px; font-size: 80%; } .individual-chapter-page .return-to-main-site .logo { width: 270px; max-width: 100%; height: auto; padding: 1rem 2rem; } .individual-chapter-page .return-to-main-site .logo svg .main-letter-color-fill { fill: #fff; } .individual-chapter-page h1.page-title { margin: 0; padding: 0 2rem 3rem 2rem; } .individual-chapter-page h2.section-title { padding-top: 0; } .individual-chapter-page nav.chapter-page-navigation { padding: 1rem 2rem; border-top: 3px solid rgba(180, 33, 37, 0.96); border-bottom: 1px solid rgba(180, 33, 37, 0.6); box-shadow: 0 1px 3px rgba(32, 32, 32, 0.38); margin-bottom: 5rem; } .individual-chapter-page nav.chapter-page-navigation ul { margin: 0; padding: 0; display: -ms-flexbox; display: flex; list-style: none; -ms-flex-pack: center; justify-content: center; -ms-flex-wrap: wrap; flex-wrap: wrap; } .individual-chapter-page nav.chapter-page-navigation ul li { padding: 0; margin: 0; } .individual-chapter-page nav.chapter-page-navigation ul li a, .individual-chapter-page nav.chapter-page-navigation ul li a:visited { text-decoration: none; padding: 1rem 2rem; border: 1px solid #e0b70b; margin-left: -1px; display: inline-block; color: #202020; } .individual-chapter-page nav.chapter-page-navigation ul li a:hover, .individual-chapter-page nav.chapter-page-navigation ul li a:visited:hover { background: #B42125; color: #fff; } .individual-chapter-page .chapter-list { margin: 1rem; list-style: none; padding: 0; } .individual-chapter-page .chapter-list li.row { display: -ms-flexbox; display: flex; padding: 1rem; border-bottom: 1px solid rgba(0, 213, 251, 0.25); } .individual-chapter-page .chapter-list li.row:hover { background: rgba(149, 239, 255, 0.1); } .individual-chapter-page .chapter-list li.row > span { width: 50%; } .individual-chapter-page .chapter-address, .individual-chapter-page .meeting-times, .individual-chapter-page .chapter-contact-information { padding: 2px 1.5rem; display: block; } .individual-chapter-page .chapter-address span, .individual-chapter-page .meeting-times span, .individual-chapter-page .chapter-contact-information span { display: block; } .individual-chapter-page .chapter-address p:first-of-type, .individual-chapter-page .meeting-times p:first-of-type, .individual-chapter-page .chapter-contact-information p:first-of-type { margin-top: 3px; } .individual-chapter-page .chapter-address p:last-of-type, .individual-chapter-page .meeting-times p:last-of-type, .individual-chapter-page .chapter-contact-information p:last-of-type { margin-bottom: 0; } .individual-chapter-page .chapter-social-media-profiles { margin: 1rem 1.5rem; padding: 0; text-align: center; } .individual-chapter-page .chapter-social-media-profiles li { display: inline-block; margin: 1rem; } .icon-calendar-dims { width: 100px; height: 100px; } .icon-email-dims { width: 100px; height: 100px; } .icon-etsy-dims { width: 32px; height: 32px; } .icon-facebook-dims { width: 32px; height: 32px; } .icon-flickr-dims { width: 32px; height: 32px; } .icon-folder-dims { width: 100px; height: 100px; } .icon-googleplus-dims { width: 32px; height: 32px; } .icon-instagram-dims { width: 32px; height: 32px; } .icon-linkedin-dims { width: 32px; height: 32px; } .icon-location-dims { width: 100px; height: 100px; } .icon-mail-dims { width: 100px; height: 100px; } .icon-paypal-dims { width: 32px; height: 32px; } .icon-rss-dims { width: 32px; height: 32px; } .icon-search-dims { width: 100px; height: 100px; } .icon-spotify-dims { width: 32px; height: 32px; } .icon-tags-dims { width: 100px; height: 100px; } .icon-twitter-dims { width: 32px; height: 32px; } .icon-user-dims { width: 100px; height: 100px; } .icon-wordpressdotcom-dims { width: 32px; height: 32px; } .icon-youtube-dims { width: 32px; height: 32px; } /****************************************************************** Stylesheet: Print Stylesheet This is the print stylesheet. There's probably not a lot of reasons to edit this stylesheet. Remember to add things that won't make sense to print at the bottom. Things like nav, ads, and forms shouldbe set to display none. ******************************************************************/ @media print { * { background: transparent !important; color: black !important; text-shadow: none !important; filter: none !important; -ms-filter: none !important; } a, a:visited { color: #444 !important; text-decoration: underline; } a:after, a:visited:after { content: " (" attr(href) ")"; } a abbr[title]:after, a:visited abbr[title]:after { content: " (" attr(title) ")"; } .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } @page { margin: 0.5cm; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } .sidebar, .page-navigation, .wp-prev-next, .respond-form, nav { display: none; } }
package com.lyczkul.taskmanager.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.lyczkul.security.model.User; import javax.persistence.*; import java.util.Set; /** * Created by Tomek on 08.06.2017. */ @Entity @Table(name = "company") public class Company { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String lead; @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) @JoinTable(name = "user_company", joinColumns = @JoinColumn(name = "company_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) @JsonIgnoreProperties("companies") private Set<User> users; @OneToMany(targetEntity = Project.class, mappedBy = "company", fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JsonManagedReference(value = "project_company") private Set<Project> projects; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLead() { return lead; } public void setLead(String lead) { this.lead = lead; } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } public Set<Project> getProjects() { return projects; } public void setProjects(Set<Project> projects) { this.projects = projects; } }
import 'package:church/core/constant/move.dart'; import 'package:flutter/material.dart'; import '../../../../core/constant/color.dart'; import '../../../../core/constant/size.dart'; class TodaySermonPageBody extends StatelessWidget { const TodaySermonPageBody({super.key}); @override Widget build(BuildContext context) { final List<List<String>> sermon = [ ["2023.11.30", "넘치는 축복과 감사 [23년 성탄감사예배] / 김철수 목사 / 마태복음 7:7~8"], ["2023.11.30", "넘치는 축복과 감사 [23년 성탄감사예배] / 김철수 목사 / 마태복음 7:7~8"], [ "2023.11.30", "넘치는 축복과 감사 [23년 성탄감사예배] / 김철수 목사 / 마태복음 7:7~8 길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐" ], [ "2023.11.30", "넘치는 축복과 감사 [23년 성탄감사예배] / 김철수 목사 / 마태복음 7:7~8 길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐길어짐" ], ]; return ListView.separated( itemCount: sermon.length, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: InkWell( onTap: () { Navigator.pushNamed(context, Move.todaySermonDetailPage); }, child: Container( height: MediaQuery.of(context).size.height * 0.12, child: Row( children: [ Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( sermon[index][0], style: TextStyle( color: kC8Color, fontSize: size12, ), ), Container( width: MediaQuery.of(context).size.width * 0.8, child: Text( sermon[index][1], style: TextStyle( color: k3DColor, fontSize: size16, ), maxLines: 2, overflow: TextOverflow.ellipsis, ), ) ], ), Spacer(), Icon( Icons.arrow_forward_ios, color: k3DColor, ), ], ), ), ), ); }, separatorBuilder: (context, index) { return const Divider(color: kEEColor); }, ); } }
import { declareStep } from '@ts-pipeline/core' import { sequence } from '../src/shared/sequence' import { setupStep } from '../src/shared/setup-step/setupStep' describe('step-declaration', () => { const noInputOutput = declareStep({ name: 'no-input-output', action: async () => { // do something }, }) const stringInput = declareStep({ name: 'string-input', action: async (_, string: string) => { string }, }) test('should ts error when next-input want something that doesn`t exists from previous step', async () => { await sequence( // @ts-expect-error unable to run stringInput, because it require 'string' as argument, but 'noInputOutput' returns void noInputOutput, stringInput, ) }) test('primitive data as input not supported', async () => { await sequence( noInputOutput, // @ts-ignore primitive data as input not supported setupStep(stringInput, 'data'), ) }) test('we can setup this step with complex data', async () => { interface ComplexProps { size: number command: string } const complexPropsInput = declareStep<ComplexProps>({ name: 'complex-props', action: async () => { // }, }) await sequence( noInputOutput, setupStep(complexPropsInput, { command: 'command from setup', size: 1, }), ) }) test('we can setup this step with partial complex data, but previous should warn', async () => { interface ComplexProps { size: number command: string } const complexPropsInput = declareStep<ComplexProps>({ name: 'complex-props', action: async () => { // }, }) const setupped = setupStep(complexPropsInput, { command: 'command from setup', }) await sequence( // @ts-expect-error should return 'size' that not filled in setupStep noInputOutput, setupped, ) const returnSizeStep = declareStep({ name: 'return-size', action: async () => { return { size: 4, } }, }) await sequence( // no error, because `returnSizeStep` return 'size' and 'setupStep' prefilled with 'command' returnSizeStep, setupStep(complexPropsInput, { command: 'command from setup', }), ) }) })
import { BaseSyntheticEvent, useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { ICategoryDTO, ICategoryInputDTO, ICategoryTreeNode, ISubCategoryCreateDTO, ISubCategoryDTO } from '../../common/dto/CategoryDTOs'; import NotEmpty from '../../common/validation/NotEmpty'; import ValidUnit from '../../common/validation/ValidUnit'; import ValueBetween from '../../common/validation/ValueBetween'; import useInput from '../../hooks/use-input'; import ButtonCard from '../UI/Card/ButtonCard'; import FlexContainer from '../UI/Container/FlexContainer'; import Button, { ButtonType } from '../UI/Control/Button'; import Input from '../UI/Control/Input'; import Headline, { HeadlineType } from '../UI/Misc/Headline'; import classes from './CategoryForm.module.css'; import SubCategoryForm from './SubCategory/SubCategoryForm'; interface CategoryFormProps { onSubmitHandler: (updateEventData: CategoryUpdateEventData) => void; create?: boolean; initialValue: ICategoryDTO; subCategories: ICategoryTreeNode[]; } export interface CategoryUpdateEventData { categoryInputDTO: ICategoryInputDTO; addedSubCategoryDTOs: ISubCategoryCreateDTO[]; updatedSubCategoryDTOs: ISubCategoryDTO[]; deletedSubCategoryIds: string[]; } const CategoryForm = (props: CategoryFormProps) => { const navigate = useNavigate(); const [subCategoryFormIsValid, setSubCategoryFormIsValid] = useState(false); const [addedSubCategories, setAddedSubCategories] = useState<ISubCategoryDTO[]>([]); const [updatedSubCategories, setUpdatedSubCategories] = useState<ISubCategoryDTO[]>([]); const [deletedSubCategoryIds, setDeletedSubCategoryIds] = useState<string[]>([]); const { value: nameValue, hasError: nameHasError, isValid: nameIsValid, inputBlurHandler: nameBlurHandler, valueChangeHandler: nameChangeHandler, } = useInput(NotEmpty, props.initialValue.name); const { value: goalValue, hasError: goalHasError, isValid: goalIsValid, inputBlurHandler: goalBlurHandler, valueChangeHandler: goalChangeHandler, } = useInput((value: number) => ValueBetween(value, 0.01, 10000), props.initialValue.goal); const { value: unitValue, hasError: unitHasError, isValid: unitIsValid } = useInput(ValidUnit, props.initialValue.unit); let formIsValid = nameIsValid && goalIsValid && unitIsValid && subCategoryFormIsValid; const onSubmitHandler = async (event: BaseSyntheticEvent) => { event.preventDefault(); const eventData: CategoryUpdateEventData = { categoryInputDTO: { name: nameValue, goal: +goalValue, unit: props.initialValue.unit, }, addedSubCategoryDTOs: addedSubCategories.map((category: ISubCategoryDTO) => { return { name: category.name, parent: category.parent }; }), updatedSubCategoryDTOs: updatedSubCategories, deletedSubCategoryIds, }; props.onSubmitHandler(eventData); }; const addOrUpdate = (list: any[], key: string, value: object): any[] => { const index = list.findIndex((category: ISubCategoryDTO) => category.id === key); const elements = [...list]; if (index !== -1) { elements[index] = value; } else { elements.push(value); } return elements; }; const onSubCategoryAddedHandler = (added: ISubCategoryDTO) => { setSubCategoryFormIsValid(formIsValid); setAddedSubCategories(addOrUpdate(addedSubCategories, added.id, added)); }; const onSubCategoryUpdatedHandler = (updated: ISubCategoryDTO) => { setSubCategoryFormIsValid(formIsValid); setUpdatedSubCategories(addOrUpdate(updatedSubCategories, updated.id, updated)); }; const onSubCategoryDeletedHandler = (categoryId: string, tempCategory: boolean) => { // Remove only temporary categories from queue (not saved yet) if (tempCategory) { const categories = [...addedSubCategories]; const index = addedSubCategories.findIndex((category) => category.id === categoryId); categories.splice(index, 1); setUpdatedSubCategories(categories); } else { // Add deletion operation to queue const deletedIds = [...deletedSubCategoryIds]; deletedIds.push(categoryId); setDeletedSubCategoryIds(deletedIds); // Remove also from updated queue const index = updatedSubCategories.findIndex((category) => category.id === categoryId); if (index !== -1) { const categories = [...updatedSubCategories]; categories.splice(index, 1); } } }; // Prevent stucking on scroll position on mobile devices after the software keyboard opens. // In that case scrolling would only be possible when the keyboard remains open. // Scroll happens automatically when the user focused the input and the keyboard opens. useEffect(() => { document.body.style.overflowY = 'auto'; return () => { document.body.style.overflowY = 'hidden'; }; }, []); return ( <form onSubmit={onSubmitHandler} className={classes['category-form']}> <Input id="name" label="Name" inputHasErrors={nameHasError} inputProps={{ type: 'text', required: true, placeholder: 'Name eingeben', value: nameValue, onBlur: nameBlurHandler, onChange: nameChangeHandler, onFocus: (event: BaseSyntheticEvent) => event.target.select(), }} noticeProps={{ show: true, text: 'Bitte einen gültigen Wert für "Name" eingeben.', }} /> <FlexContainer> <Input id="goal" label="Ziel" inputHasErrors={goalHasError} inputProps={{ type: 'number', step: '0.10', required: true, placeholder: 'Ziel eingeben', value: goalValue, onBlur: goalBlurHandler, onChange: goalChangeHandler, onFocus: (event: BaseSyntheticEvent) => event.target.select(), }} noticeProps={{ show: true, text: 'Bitte einen gültigen Wert für "Ziel" eingeben.', }} /> <Input id="unit" label="Einheit" inputHasErrors={unitHasError} inputProps={{ type: 'text', required: true, readOnly: true, value: unitValue, }} noticeProps={{ show: false, text: '', }} /> </FlexContainer> <Headline type={HeadlineType.PRIMARY} caption={`bearbeiten`}> Unter-Kategorien </Headline> <SubCategoryForm parentCategoryId={props.initialValue.id} subCategories={props.subCategories} onAddedHandler={onSubCategoryAddedHandler} onUpdatedHandler={onSubCategoryUpdatedHandler} onDeletedHandler={onSubCategoryDeletedHandler} onFormStateChanged={(state: boolean) => setSubCategoryFormIsValid(state)} /> <ButtonCard> <Button buttonType={ButtonType.BACK} onClickHandler={() => navigate(-1)}> ABBRECHEN </Button> <Button buttonType={formIsValid ? ButtonType.PRIMARY : ButtonType.DISABLED} buttonProps={{ type: 'submit', disabled: !formIsValid }} > {props.create ? 'ERSTELLEN' : 'ÄNDERN'} </Button> </ButtonCard> </form> ); }; export default CategoryForm;
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "erc721a/contracts/ERC721A.sol"; abstract contract ParentContract { function ownerOf(uint256 tokenId) public view virtual returns (address); function balanceOf(address owner) public view virtual returns (uint256); } contract ERC721ABreeding is ERC721A, Ownable { using Strings for uint256; // struct Baby { // uint16 mom; // uint16 dad; // } struct Parent { uint16 id; bool canBreed; } ParentContract public momContract; ParentContract public dadContract; uint16 public maxSupply; mapping(uint256 => bool) public isMom; mapping(uint256 => bool) public isDad; // mapping(uint256 => Baby) public babies; // mapping(uint256 => uint256) public birthdays; bool public claimIsActive; string private baseURI; constructor( string memory _name, string memory _symbol, string memory _uri, address _owner, uint16 _maxSupply, address _momContract, address _dadContract ) ERC721A(_name, _symbol) { baseURI = _uri; maxSupply = _maxSupply; momContract = ParentContract(_momContract); dadContract = ParentContract(_dadContract); transferOwnership(_owner); } function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseURI, _tokenId.toString())); } function canBreed(address _owner, uint _type) external view returns (Parent[] memory) { ParentContract parentContract = _type == 1 ? dadContract : momContract; unchecked { uint tokenIdsIdx; uint tokenIdsLength = parentContract.balanceOf(_owner); Parent[] memory tokenIds = new Parent[](tokenIdsLength); for (uint16 i = 0; tokenIdsIdx != tokenIdsLength; i++) { if (parentContract.ownerOf(i) == _owner) { tokenIds[tokenIdsIdx].id = i; tokenIds[tokenIdsIdx++].canBreed = !(_type == 1 ? isDad[i] : isMom[i]); } } return tokenIds; } } function setClaimState(bool _claimIsActive) public onlyOwner { claimIsActive = _claimIsActive; } function setBaseTokenURI(string memory _uri) public onlyOwner { baseURI = _uri; } function breed(uint16[] memory dadIds, uint16[] memory momIds) public { require(claimIsActive, "Claim inactive"); require(momIds.length == dadIds.length, "Array lengths don't match"); uint256 _quantity = momIds.length; uint256 _currentSupply = totalSupply(); require(_currentSupply + _quantity <= maxSupply, "Insufficient supply"); for (uint16 i = 0; i < _quantity; i++) { require(momContract.ownerOf(momIds[i]) == msg.sender, "Not owner of mom"); require(dadContract.ownerOf(dadIds[i]) == msg.sender, "Not owner of dad"); require(!isMom[momIds[i]], "Already a mom"); require(!isDad[dadIds[i]], "Already a dad"); } uint256 _currentIndex = _currentSupply; for (uint16 i = 0; i < _quantity; i++) { isMom[momIds[i]] = true; isDad[dadIds[i]] = true; // babies[_currentIndex].mom = momIds[i]; // babies[_currentIndex].dad = dadIds[i]; // birthdays[_currentIndex++] = block.timestamp; } _safeMint(msg.sender, _quantity); } function reserve(address _address, uint16 _quantity) public onlyOwner { require(totalSupply() + _quantity <= maxSupply, "Insufficient supply"); _safeMint(_address, _quantity); } }
import type { GetStaticProps, NextLayoutPage } from 'next' import Head from 'next/head' import { Form } from '~/src/components/base/molecules/Form' import { ErrorFormMessage } from '~/src/components/case/error/ErrorFormMessage' import { FormType } from '~/src/types/microCMS/Form' import { getForm } from '~/src/utils/cms/getContents' type Props = { form: FormType errors?: string[] } const customFieldMap = new Map([ ['name', 'お名前'], ['email', 'メールアドレス'], ['tel', '電話番号'], ['organization', '会社名'], ['postalCodeAndAddress', '郵便番号+住所'], ['address', '住所'], ]) export const getStaticProps: GetStaticProps<Props> = async ({ preview, previewData }) => { const { form } = await getForm({ draftKey: preview ? (previewData as { [key: string]: string }).draftKey : undefined, }) if (!preview) { return { props: { form }, } } const fieldIds = form.map(({ fieldId }) => fieldId) const isDuplication = new Set(fieldIds).size !== fieldIds.length const isDuplicationAddress = fieldIds.includes('postalCodeAndAddress') && fieldIds.includes('address') if (!isDuplication && !isDuplicationAddress) { return { props: { form }, } } const errors: string[] = [] if (isDuplication) { const messages = fieldIds .map((id) => { if (fieldIds.indexOf(id) !== fieldIds.lastIndexOf(id) && customFieldMap.get(id) !== undefined) { return `「${customFieldMap.get(id)}」フィールドは複数使用できません。` } return null }) .filter((message): message is string => typeof message === 'string') new Set(messages).forEach((message) => { errors.push(message) }) } if (isDuplicationAddress) { errors.push('「郵便番号+住所」フィールドと「住所」フィールドは併用できません。') } return { props: { form, errors }, } } const IndexPage: NextLayoutPage<Props> = ({ form, errors }) => { return ( <> <Head> <title>カスタムフォームデモサイト</title> <meta name="description" content="microcmsを用いて、フォームをカスタマイズするデモサイト" /> </Head> <div className="py-10"> <h1 className="text-center text-3xl font-bold">カスタムフォーム(仮)</h1> <p className="mt-8 text-center">※スタイルは仮です。自由にカスタマイズできます。</p> {errors === undefined || errors.length === 0 ? ( <Form list={form} className="container mx-auto mt-16 sm:max-w-2xl" /> ) : ( <ErrorFormMessage errors={errors} /> )} </div> </> ) } export default IndexPage
import React from 'react'; import {View, StyleSheet} from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; function NavigationBar({ handleButtonPress, }: { handleButtonPress: (buttonName: string) => void; }): JSX.Element { return ( <View style={styles.container}> <View style={styles.section}> <Icon name="home" size={24} color="red" onPress={() => handleButtonPress('home')} style={styles.icon} /> </View> <View style={styles.section}> <Icon name="search" size={24} color="green" onPress={() => handleButtonPress('search')} style={styles.icon} /> </View> <View style={styles.section}> <Icon name="user" size={24} color="blue" onPress={() => handleButtonPress('user')} style={styles.icon} /> </View> </View> ); } const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'space-between', backgroundColor: 'lightgrey', paddingTop: 10, paddingBottom: 10, }, section: { flex: 1, alignItems: 'center', }, icon: { alignSelf: 'center', }, }); export default NavigationBar;
\documentclass[journal,12pt,twocolumn]{IEEEtran} \usepackage{setspace} \usepackage{gensymb} \singlespacing \usepackage[cmex10]{amsmath} \usepackage{multirow} \usepackage{amsthm} \usepackage{mathrsfs} \usepackage{txfonts} \usepackage{stfloats} \usepackage{bm} \usepackage{cite} \usepackage{cases} \usepackage{subfig} \usepackage{longtable} \usepackage{enumitem} \usepackage{mathtools} \usepackage{steinmetz} \usepackage{tikz} \usepackage{circuitikz} \usepackage{verbatim} \usepackage{tfrupee} \usepackage[breaklinks=true]{hyperref} \usepackage{graphicx} \usepackage{tkz-euclide} \usetikzlibrary{calc,math} \usepackage{listings} \usepackage{color} %% \usepackage{array} %% \usepackage{longtable} %% \usepackage{calc} %% \usepackage{multirow} %% \usepackage{hhline} %% \usepackage{ifthen} %% \usepackage{lscape} \usepackage{multicol} \usepackage{chngcntr} \DeclareMathOperator*{\Res}{Res} \renewcommand\thesection{\arabic{section}} \renewcommand\thesubsection{\thesection.\arabic{subsection}} \renewcommand\thesubsubsection{\thesubsection.\arabic{subsubsection}} \renewcommand\thesectiondis{\arabic{section}} \renewcommand\thesubsectiondis{\thesectiondis.\arabic{subsection}} \renewcommand\thesubsubsectiondis{\thesubsectiondis.\arabic{subsubsection}} \hyphenation{op-tical net-works semi-conduc-tor} \def\inputGnumericTable{} %% \lstset{ %language=C, frame=single, breaklines=true, columns=fullflexible } \graphicspath{{./Figures/}} \begin{document} \newtheorem{theorem}{Theorem}[section] \newtheorem{problem}{Problem} \newtheorem{proposition}{Proposition}[section] \newtheorem{lemma}{Lemma}[section] \newtheorem{corollary}[theorem]{Corollary} \newtheorem{example}{Example}[section] \newtheorem{definition}[problem]{Definition} \newcommand{\BEQA}{\begin{eqnarray}} \newcommand{\EEQA}{\end{eqnarray}} \newcommand{\define}{\stackrel{\triangle}{=}} \bibliographystyle{IEEEtran} \raggedbottom \setlength{\parindent}{0pt} \providecommand{\mbf}{\mathbf} \providecommand{\pr}[1]{\ensuremath{\Pr\left(#1\right)}} \providecommand{\qfunc}[1]{\ensuremath{Q\left(#1\right)}} \providecommand{\sbrak}[1]{\ensuremath{{}\left[#1\right]}} \providecommand{\lsbrak}[1]{\ensuremath{{}\left[#1\right.}} \providecommand{\rsbrak}[1]{\ensuremath{{}\left.#1\right]}} \providecommand{\brak}[1]{\ensuremath{\left(#1\right)}} \providecommand{\lbrak}[1]{\ensuremath{\left(#1\right.}} \providecommand{\rbrak}[1]{\ensuremath{\left.#1\right)}} \providecommand{\cbrak}[1]{\ensuremath{\left\{#1\right\}}} \providecommand{\lcbrak}[1]{\ensuremath{\left\{#1\right.}} \providecommand{\rcbrak}[1]{\ensuremath{\left.#1\right\}}} \theoremstyle{remark} \newtheorem{rem}{Remark} \newcommand{\sgn}{\mathop{\mathrm{sgn}}} \providecommand{\abs}[1]{\left\vert#1\right\vert} \providecommand{\res}[1]{\Res\displaylimits_{#1}} \providecommand{\norm}[1]{\left\lVert#1\right\rVert} %\providecommand{\norm}[1]{\lVert#1\rVert} \providecommand{\mtx}[1]{\mathbf{#1}} \providecommand{\mean}[1]{E\left[ #1 \right]} \providecommand{\fourier}{\overset{\mathcal{F}}{ \rightleftharpoons}} %\providecommand{\hilbert}{\overset{\mathcal{H}}{ \rightleftharpoons}} \providecommand{\system}{\overset{\mathcal{H}}{ \longleftrightarrow}} %\newcommand{\solution}[2]{\textbf{Solution:}{#1}} \newcommand{\solution}{\noindent \textbf{Solution: }} \newcommand{\cosec}{\,\text{cosec}\,} \providecommand{\dec}[2]{\ensuremath{\overset{#1}{\underset{#2}{\gtrless}}}} \newcommand{\myvec}[1]{\ensuremath{\begin{pmatrix}#1\end{pmatrix}}} \newcommand{\mydet}[1]{\ensuremath{\begin{vmatrix}#1\end{vmatrix}}} \newcommand*{\permcomb}[4][0mu]{{{}^{#3}\mkern#1#2_{#4}}} \newcommand*{\perm}[1][-3mu]{\permcomb[#1]{P}} \newcommand*{\comb}[1][-1mu]{\permcomb[#1]{C}} \numberwithin{equation}{subsection} \makeatletter \@addtoreset{figure}{problem} \makeatother \let\StandardTheFigure\thefigure \let\vec\mathbf \renewcommand{\thefigure}{\theproblem} \def\putbox#1#2#3{\makebox[0in][l]{\makebox[#1][l]{}\raisebox{\baselineskip}[0in][0in]{\raisebox{#2}[0in][0in]{#3}}}} \def\rightbox#1{\makebox[0in][r]{#1}} \def\centbox#1{\makebox[0in]{#1}} \def\topbox#1{\raisebox{-\baselineskip}[0in][0in]{#1}} \def\midbox#1{\raisebox{-0.5\baselineskip}[0in][0in]{#1}} \vspace{3cm} \title{Assignment 4} \author{Sujal - AI20BTECH11020} \maketitle \newpage \bigskip \renewcommand{\thefigure}{\theenumi} \renewcommand{\thetable}{\theenumi} Download all python codes from \begin{lstlisting} https://github.com/sujal100/Probability_and_Random_variable/tree/main/exercise_4/codes \end{lstlisting} and latex codes from \begin{lstlisting} https://github.com/https://github.com/sujal100/Probability_and_Random_variable/blob/main/exercise_4/exercise_4_main_tex.tex \end{lstlisting} \section{Problem [GATE(2012)CS-63]} An automobile plant contracted to buy shock absorbers from two suppliers $X$ and $Y . X$ supplies $60 \%$ and $Y$ supplies $40 \%$ of the shock absorbers. All shock absorbers are subjected to a quality test. The ones that pass the quality test are considered reliable. Of X's shock absorbers, $96 \%$ are reliable. Of Y's shock absorbers, $72 \%$ are reliable. The probability that a randomly chosen shock absorber, which is found to be reliable, is made by $Y$ is (A) 0.288 (B) 0.334 (C) 0.667 (D) 0.720 \section{Solution} \begin{figure}[htb!] \begin{center} \includegraphics[width=0.5\textwidth]{A_4_1.png} \end{center} \end{figure} Let Consider, Bernoulli random variables say $X,Y$ and $R$. \begin{table}[h] \resizebox{\columnwidth}{!}{ \begin{tabular}{|l|l|l|} \hline & Refer to probability that product & Result \\ \hline $Pr(X=1)$ & from supplier $X$ & $0.6$ \\ \hline $Pr(Y=1)$ & from supplier $X$ & $0.4$ \\ \hline $Pr(R=1)$ & is reliable & \\ \hline $Pr(R=0)$ & is faulty & \\ \hline $Pr(R=1/X=1)$ & from supplier $X$ is reliable & $0.96$ \\ \hline $Pr(R=1/Y=1)$ & from supplier $Y$ is reliable & $0.72$ \\ \hline \end{tabular}} \caption{probability of random variables.} \label{tab:my-table} \end{table} Required probability is $Pr(Y=1|R=1)$.So, \begin{align} &Pr(Y=1|R=1)=\frac{Pr(Y=1,R=1)}{Pr(R=1)}\\ &=\frac{Pr(Y=1)Pr(R=1/Y=1)}{Pr(X=1)Pr(R=1/X=1)+Pr(Y=1)P(R=1/Y=1)}\\ &=\frac{(0.4)(0.72)}{(0.6)(0.96)+(0.4)(0.72)}=0.334 \end{align} \begin{figure}[htb!] \begin{center} \includegraphics[width=0.6\textwidth]{A_4_2.png} \caption{Theoretical Vs Simulation} \end{center} \end{figure} Hence $(\mathrm{B})$ is correct option. \end{document}
<TeXmacs|1.99.12> <style|generic> <\body> <with|font-series|bold|Variational Autonencoder (VAE) implementation notes> Tomas Ukkonen, 2020 \<less\>tomas.ukkonen@novelinsight.fi\<gtr\> \; Based on paper <with|font-shape|italic|Auto-Encoding Variational Bayes. Diedrik Kingma and Max Welling. 2012(?).> We assume we know neural network encoder <math|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>\<thicksim\>N<around*|(|\<b-mu\><rsub|\<b-z\>><around*|(|\<b-x\>|)>,\<b-sigma\><rsub|\<b-z\>><around*|(|\<b-x\>|)>\<b-I\>|)>> and decoder <math|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|\<nobracket\>>|)>\<thicksim\>N<around*|(|\<b-mu\><rsub|\<b-x\>><around*|(|\<b-z\>|)>,c*\<b-I\>|)>> for hidden parameters <math|\<b-z\>> as well as that we have decided distribution of hidden parameters <math|\<b-z\>>, <math|p<around*|(|\<b-z\>|)>\<thicksim\>N<around*|(|\<b-0\>,\<b-I\>|)>>.\ ADDITION: Additionally we have parameter mapping function <math|f<around*|(|\<b-x\>|)>=\<b-y\>> which assigns metadata to data. We want to have that <math|*<around*|\<\|\|\>|f<around*|(|\<b-x\><rsub|1>|)>-f<around*|(|\<b-x\><rsub|2>|)>|\<\|\|\>>=\<alpha\><around*|\<\|\|\>|\<b-z\><rsub|1>-\<b-z\><rsub|2>|\<\|\|\>>>, that is that distances between metadata resembles those distances in encoded data. <math|\<b-d\><rsub|i*j>=f<around*|(|\<b-x\><rsub|i>|)>-f<around*|(|\<b-x\><rsub|j>|)>=><math|\<b-z\><rsub|i>-\<b-z\><rsub|j>\<thicksim\>N<around*|(|\<b-mu\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|i>|)>-\<b-mu\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|j>|)>,<around*|(|\<b-sigma\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|i>|)>+\<b-sigma\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|j>|)>|)>\<b-I\>|)>> where <math|f<around*|(|\<b-x\><rsub|>|)>> metadata has been scaled to be <math|N<around*|(|\<b-0\>,\<b-I\>|)>>. This will mean we will have <math|log<around*|(|p<around*|(|\<b-d\><rsub|i*j><around*|\|||\<nobracket\>>\<b-mu\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|i>|)>-\<b-mu\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|j>|)>,<around*|(|\<b-sigma\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|i>|)>+\<b-sigma\><rsub|\<b-z\>><around*|(|\<b-x\><rsub|j>|)>|)>\<b-I\>|)>|)>> terms which gradient one needs to solve. \; We maximize probability of data which can be written as: <\math> log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\>|)>|)>=D<rsub|KL><around*|(|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)><around*|\|||\|>p<rsub|\<theta\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>|)>+L<around*|(|\<b-theta\>,\<b-phi\>,\<b-x\>|)>\<geqslant\>L<around*|(|\<b-theta\>,\<b-phi\>,\<b-x\>|)> L<around*|(|\<b-theta\>,\<b-phi\>,\<b-x\>|)>=log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\>|)>|)>+<big|int>q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>*log<around*|(|<frac|p<rsub|\<theta\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>>|)>d\<b-z\> =<big|int><around*|(|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\>,\<b-z\>|)>|)>-log<around*|(|*q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>|)>|)>q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>d\<b-z\> </math> <math|D<rsub|KL>> is positive and near constant <math|C> if distributions <math|p<around*|(|\<b-z\>|)>> and <math|q<around*|(|\<b-z\>|)>> are roughly same, so we ignore it and maximize lower bound <math|L> instead which can be rewritten as <math|L<around*|(|\<b-theta\>,\<b-phi\>,\<b-x\>|)>=-<big|int>><math|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>log<around*|(|<frac|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>|p<rsub|\<theta\>><around*|(|\<b-z\>|)>>|)>*d\<b-z\>+<big|int>log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|\<nobracket\>>|)>|)>*q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>*d\<b-z\>=-D<rprime|'><rsub|KL>+E<rsub|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\|>|)>><around*|[|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|\<nobracket\>>|)>|)>|]>> In the formula distributions are only distributions which we know so we can maximize it using gradient descent (<math|\<nabla\><rsub|\<b-theta\>,\<b-phi\>>L<around*|(|\<b-x\>|)>>). However, calculating direct gradient don't work very well because of high-variance of expected values/integrals so extra techniques are needed. \; Now we assume out probability distributions are gaussians so that analytical computations are tractable as discussed initially. The term <math|D<rprime|'><rsub|KL>> can be computed analytically and it is <\math> -D<rprime|'><rsub|KL>=<frac|1|2><big|sum><rsup|<rsup|D>><rsub|i=1><around*|(|1+log<around*|(|\<sigma\><rsub|\<b-z\>,i><around*|(|\<b-x\>|)><rsup|2>|)>-\<mu\><rsup|2><rsub|\<b-z\>,i>-\<sigma\><rsup|2><rsub|\<b-z\>,i>|)>=<frac|1|2>D+<frac|1|2>log<around*|(|det<around*|(|\<b-Sigma\><rsub|\<b-z\>><around*|(|\<b-x\>|)>|)>|)>-<frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2>tr<around*|(|\<b-Sigma\><rsub|\<b-z\>><around*|(|\<b-x\>|)>|)> =<frac|1|2>D+<big|sum><rsup|<rsup|D>><rsub|i=1>log<around*|(|\<sigma\><rsub|\<b-z\>,i><around*|(|\<b-x\><rsup|<rsup|>>|)>|)>-<frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2><around*|\<\|\|\>|\<sigma\><rsup|><rsub|\<b-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2><rsup|> </math> And the gradient of the first term of lower bound <math|L> is: <\padded-center> <math|inv<around*|(|\<sigma\><rsub|\<b-z\>><around*|(|\<b-z\>|)>|)>=<around*|[|<frac|1|\<sigma\><rsub|\<b-z\>,i><around*|(|\<b-x\>|)>>|]>> </padded-center> <\padded-center> <math|\<nabla\><rsub|\<phi\>><around*|(|-D<rprime|'><rsub|KL>|)>=-\<b-mu\><rsup|T><rsub|\<b-z\>><around*|(|\<b-x\>|)>*\<nabla\><rsub|\<phi\>>\<b-mu\><rsub|\<b-z\>><around*|(|\<b-x\>|)>-*<around*|(|\<sigma\><rsub|\<b-z\>><around*|(|\<b-x\>|)>-inv<around*|(|\<sigma\><rsub|\<b-z\>>|)>|)><rsup|T>\<nabla\><rsub|\<phi\>>*\<sigma\><rsub|\<b-z\>><around*|(|\<b-x\>|)>> <math|\<nabla\><rsub|\<theta\>><around*|(|-D<rprime|'><rsub|KL>|)>=\<b-0\>> </padded-center> \; \; This leaves us with the second term <math|E<rsub|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\|>|)>><around*|[|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|\<nobracket\>>|)>|)>|]>=<big|int>log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|\<nobracket\>>|)>|)>*q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>*d\<b-z\>> \; As discussed in the paper, we use reparametrization trick and rewrite <math|\<b-z\>=\<b-g\><rsub|\<phi\>><around*|(|\<b-varepsilon\>,\<b-x\>|)>=\<b-mu\><rsub|\<phi\>><around*|(|\<b-x\>|)>+\<b-varepsilon\>*\<sigma\><rsub|\<phi\>><around*|(|\<b-x\>|)>> where <math|\<b-varepsilon\>\<thicksim\>N<around*|(|\<b-0\>,\<b-I\>|)>> so we can rewrite integral term as <math|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\<nobracket\>>|)>d\<b-z\>=p<around*|(|\<b-varepsilon\>|)>*d\<b-varepsilon\>> and sample extra variables from <math|p<around*|(|\<b-varepsilon\>|)>> and write: <\math> E<rsub|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\|>|)>><around*|[|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|\<nobracket\>>|)>|)>|]>=<big|int>log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-mu\><rsub|\<b-x\>><around*|(|\<b-z\>|)>,\<sigma\><rsub|\<b-x\>>|(>\<b-z\>|)>|)>*p<around*|(|\<b-varepsilon\>|)>*d\<b-varepsilon\> =<frac|1|N><big|sum><rsub|i><rsup|N>log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-mu\><rsub|\<b-x\>,\<theta\>><around*|(|\<b-mu\><rsub|\<b-z\>,\<phi\>><around*|(|\<b-x\>|)>+\<b-varepsilon\>*<rsub|i>\<sigma\><rsub|\<phi\>,\<b-z\>><around*|(|\<b-x\>|)>|)>,c*\<b-I\>|\<nobracket\>>|\<nobracket\>>|)>* </math> We can further calculate logarithm of the normal distribution to remove exponentation. Additionally, the data variance <math|\<sigma\><rsup|2>> is normalized to be <math|1> so <math|c=1> (<math|c=1> doesn't work well so variance is set to normalize error <math|c=D<rsub|\<b-x\>>>) <\math> p<around*|(|\<b-x\>|)>=<around*|(|2*\<pi\>|)><rsup|-D<rsub|x>/2>*det<around*|(|\<b-Sigma\>|)><rsup|-1/2>*exp<around*|(|-<frac|1|2><around*|(|\<b-x\>-\<b-mu\>|)><rsup|T>*\<b-Sigma\><rsup|-1><around*|(|\<b-x\>-\<b-mu\>|)>|)> </math> <math|log<around*|(|p<around*|(|\<b-x\>|)>|)>=<around*|(|-D<rsub|x>/2|)>*log<around*|(|2*\<pi\>|)>+log<around*|(|det<around*|(|\<b-Sigma\>|)><rsup|-1/2>|)>><math|-<frac|1|2><around*|(|\<b-x\>-\<b-mu\>|)><rsup|T>*\<b-Sigma\><rsup|-1><around*|(|\<b-x\>-\<b-mu\>|)>> <math|log<around*|(|p<around*|(|\<b-x\>|)>|)>=<around*|(|-D<rsub|x>/2|)>*log<around*|(|2*\<pi\>c|)>><math|-<frac|1|2*c><around*|(|\<b-x\>-\<b-mu\>|)><rsup|T>*<around*|(|\<b-x\>-\<b-mu\>|)>><math|> Now the gradients are <math|\<nabla\><rsub|\<theta\>>E<rsub|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\|>|)>><around*|[|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|)>|)>|]>=*<frac|1|N*c><big|sum><rsup|N><rsub|i><around*|(|\<b-x\>-\<b-mu\><rsub|\<b-x\>>|)><rsup|T>*<around*|\<nobracket\>|\<nabla\><rsub|\<theta\>>\<b-mu\><rsub|\<b-x\>,\<theta\>>|(>\<b-z\><rsub|i><around*|(|\<b-x\>|)>|)>> <math|\<nabla\><rsub|\<phi\>>E<rsub|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\|>|)>><around*|[|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|)>|)>|]>=*<frac|1*|N*c><big|sum><rsup|N><rsub|i><around*|(|\<b-x\>-\<b-mu\><rsub|\<b-x\>>|)><rsup|T>*<around*|\<nobracket\>|J<rsub|\<b-z\>>*\<b-mu\><rsub|\<b-x\>,\<theta\>>|(>\<b-z\><rsub|i><around*|(|\<b-x\>|)>|)>*<around*|(|\<nabla\><rsub|\<phi\>>\<b-mu\><rsub|\<b-z\>,\<phi\>><around*|(|\<b-x\>|)>+\<b-varepsilon\>*<rsub|i>\<nabla\><rsub|\<phi\>>*\<sigma\><rsub|\<phi\>,\<b-z\>><around*|(|\<b-x\>|)>|)>> \; NEEDED(?): <with|font-series|bold|NOTE: CALCULATING LOGARITHM OF VARIANCE DON'T WORK WITH SMART INITIALIZATION BUT WORKS WITH RANDOM INITIALIZATION!> To handle parameter sigma <math|\<sigma\><rsub|\<phi\>,\<b-z\>><around*|(|\<b-x\>|)>> better we will remap proper values from <math|<around*|[|0,\<infty\>|)>> to open interval <math|<around*|(|-\<infty\>,\<infty\>|)>> by using mapping <math|\<sigma\><around*|(|\<b-x\>|)>=e<rsup|s<around*|(|\<b-x\>|)>>>.\ \; <\math> <around*|(|-D<rprime|'><rsub|KL>|)>==<frac|1|2>D+<big|sum><rsup|<rsup|D>><rsub|i=1>log<around*|(|\<sigma\><rsub|\<b-z\>,i><around*|(|\<b-x\><rsup|<rsup|>>|)>|)>-<frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2><around*|\<\|\|\>|\<sigma\><rsup|><rsub|\<b-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2><rsup|> =<frac|1|2>D+\<b-1\><rsup|T>s<around*|(|\<b-x\>|)>-<frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2><around*|\<\|\|\>|e<rsup|\<b-s\><around*|(|\<b-x\>|)>>|\<\|\|\>><rsup|2><rsup|> \<nabla\><rsub|\<phi\>><around*|(|-D<rprime|'><rsub|KL>|)>=\<b-1\><rsup|T>\<nabla\><rsub|\<phi\>>s<around*|(|\<b-x\>|)>-\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)><rsup|T>\<nabla\><rsub|\<phi\>>*\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>-e<rsup|2*\<b-s\><around*|(|\<b-x\>|)><rsup|T>>\<nabla\><rsub|\<phi\>>*e<rsup|\<b-s\><around*|(|\<b-x\>|)>><rsup|>* </math> \; This means our gradients will be: <math|\<b-z\><rsub|i><around*|(|\<b-x\>|)>=\<b-mu\><rsub|\<b-z\>,\<phi\>><around*|(|\<b-x\>|)>+diag<around*|(|\<b-varepsilon\><rsub|i>|)>*e<rsup|\<b-s\><rsub|\<phi\>><around*|(|\<b-x\>|)>>> <math|\<nabla\><rsub|\<theta\>>E<rsub|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\|>|)>><around*|[|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|)>|)>|]>=*<frac|1|N*c><big|sum><rsup|N><rsub|i><around*|(|\<b-x\>-\<b-mu\><rsub|\<b-x\>>|)><rsup|T>*<around*|\<nobracket\>|\<nabla\><rsub|\<theta\>>\<b-mu\><rsub|\<b-x\>,\<theta\>>|(>\<b-z\><rsub|i><around*|(|\<b-x\>|)>|)>> [not modified] <math|\<nabla\><rsub|\<phi\>>E<rsub|q<rsub|\<phi\>><around*|(|\<b-z\><around*|\||\<b-x\>|\|>|)>><around*|[|log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-z\>|)>|)>|]>=*<frac|1|N*c><big|sum><rsup|N><rsub|i><around*|(|\<b-x\>-\<b-mu\><rsub|\<b-x\>>|)><rsup|T>*<around*|\<nobracket\>|J<rsub|\<b-z\>>*\<b-mu\><rsub|\<b-x\>,\<theta\>>|(>\<b-z\><rsub|i><around*|(|\<b-x\>|)>|)>*<around*|(|\<nabla\><rsub|\<phi\>>\<b-mu\><rsub|\<b-z\>,\<phi\>><around*|(|\<b-x\>|)>+diag<around*|(|\<b-varepsilon\><rsub|i>*e<rsup|\<b-s\><around*|(|\<b-x\>|)>>|)>*\<nabla\><rsub|\<phi\>>*s<rsub|\<phi\>,\<b-z\>><around*|(|\<b-x\>|)>|)>> <math|=> <math|\<nabla\><rsub|\<phi\>><around*|(|-D<rprime|'><rsub|KL>|)>=\<b-1\><rsup|T>*\<nabla\><rsub|\<phi\>>\<b-s\><around*|(|\<b-x\>|)>-\<b-mu\><rsup|T><rsub|\<b-z\>><around*|(|\<b-x\>|)>*\<nabla\><rsub|\<phi\>>\<b-mu\><rsub|\<b-z\>><around*|(|\<b-x\>|)>-<around*|[|e<rsup|2*\<b-s\><around*|(|\<b-x\>|)>>|]><rsup|<rsup|T>>*<around*|[|*\<nabla\><rsub|\<phi\>>s<rsub|i><around*|(|\<b-x\>|)>|]>> \; <\math> <around*|(|-D<rprime|'><rsub|KL>|)>=<frac|1|2>D+<big|sum><rsup|<rsup|D>><rsub|i=1>log<around*|(|\<sigma\><rsub|\<b-z\>,i><around*|(|\<b-x\><rsup|<rsup|>>|)>|)>-<frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2><around*|\<\|\|\>|\<sigma\><rsup|><rsub|\<b-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>=\<b-1\><rsup|T>*\<b-s\><around*|(|\<b-x\>|)>-<rsup|><frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2><around*|\<\|\|\>|e<rsup|\<b-s\><around*|(|\<b-x\>|)>>|\<\|\|\>><rsup|2> </math> \; <with|font-series|bold|NOTE> As a preset encoder and decoder are preset using data <math|DATA=<around*|{|\<b-x\><rsub|i>|}><rsup|N><rsub|i=1>> by setting weight values <math|\<b-W\><around*|(|k,:|)>=\<b-x\><rsub|k><rsup|T>,k=RANDOM<around*|(|0,N-1|)><infix-and>bias values to zero.> The final layer is optimized using linear optimization to target values. The target and source values for preset encoder/decoder is set using PCA dimension reduction to three parameter values and encoder's variance/sigma values was set to constant <math|log<around*|(|\<sigma\>|)>=log<around*|(|0.2/sqrt<around*|(|D|)>|)>\<approx\>log<around*|(|0.115|)>,D=3>. This will give approximately <math|\<sigma\>=0.2> error distance in <math|D> dimensional space. <with|font-series|bold|Experiments> version 0.80: <math|log<around*|(|\<sigma\>|)>=log<around*|(|0.2/sqrt<around*|(|D|)>|)>\<approx\>log<around*|(|0.115|)>,D=3> - doesn't work so well. version 0.82: <math|log<around*|(|\<sigma\>|)>=log<around*|(|0.866/sqrt<around*|(|D|)>|)>\<approx\>log<around*|(|0.50|)>,D=3>:\ complexity=10 worked, 10 don't work, 20 worked, 20 worked, 10 did not work, .. <with|font-series|bold|Correct error measure> / aprox loglikelihood Currently, VAE code (in VAE.cpp) uses reconstruction error <math|<big|sum><rsub|i><around*|\<\|\|\>|\<b-x\><rsub|i>-decoder<around*|(|encoder<around*|(|\<b-x\><rsub|i>|)>|)>|\<\|\|\>><rsup|2>> instead of log likelihood when estimating error. In practice we should use <math|<big|sum><rsub|i>log<around*|(|p<around*|(|\<b-x\><rsub|i>|)>|)>> so the error measure should be: <math|L<around*|(|\<b-theta\>,\<b-phi\>,\<b-x\>|)>=<frac|1|2>D<rsub|z>+\<b-1\><rsup|T>s<around*|(|\<b-x\>|)>-<frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2><around*|\<\|\|\>|e<rsup|\<b-s\><around*|(|\<b-x\>|)>>|\<\|\|\>><rsup|2><rsup|>+<frac|1|N><big|sum><rsub|i><rsup|N>log<around*|(|p<rsub|\<theta\>><around*|(|\<b-x\><around*|\||\<b-mu\><rsub|\<b-x\>,\<theta\>><around*|(|\<b-mu\><rsub|\<b-z\>,\<phi\>><around*|(|\<b-x\>|)>+\<b-varepsilon\>*<rsub|i>\<sigma\><rsub|\<phi\>,\<b-z\>><around*|(|\<b-x\>|)>|)>,c*\<b-I\>|\<nobracket\>>|\<nobracket\>>|)>><math|> <math|=**C+\<b-1\><rsup|T>s<around*|(|\<b-x\>|)>-<frac|1|2><around*|\<\|\|\>|\<b-mu\><rsub|\<cal-z\>><around*|(|\<b-x\>|)>|\<\|\|\>><rsup|2>-<frac|1|2><around*|\<\|\|\>|e<rsup|\<b-s\><around*|(|\<b-x\>|)>>|\<\|\|\>><rsup|2><rsup|>-<frac|1|2N*c><big|sum><rsup|N><rsub|i>><math|<around*|\<\|\|\>|\<b-x\>-\<b-mu\><rsub|\<b-x\>,\<theta\>><around*|(|\<b-mu\><rsub|\<b-z\>,\<phi\>><around*|(|\<b-x\>|)>+\<b-varepsilon\>*<rsub|i>\<sigma\><rsub|\<phi\>,\<b-z\>><around*|(|\<b-x\>|)>|)>|\<\|\|\>><rsup|2>> <math|C=<frac|1|2>D<rsub|z>-<frac|1|2>D<rsub|x>*log<around*|(|2*\<pi\>*c|)>> Here the maximization of <math|L> means that the last term will be minimized (mean reconstruction error). Max <math|s>: <math|f<around*|(|s|)>=s-0.5*e<rsup|2*s>>,<math|f<rprime|'><around*|(|s|)>=1-e<rsup|2*s>=0\<Rightarrow\>s=0\<Rightarrow\>\<sigma\>=1<rsup|>> \; TODO: add <math|\<b-c\>> variance term to the VAE.cpp code. TODO: we have normalized <math|\<b-x\>\<sim\>N<around*|(|0,\<sigma\><rsup|2>=1|)>> so <math|c=0.05> might be good target for <math|\<sigma\><rsub|error<around*|(|\<b-x\>|)>><rsup|2>>. This means VAE should have small reconstruction error which on the other side can mean bad generalization errror. (model complexity=20 and PCA prelearned z st.dev. is 0.1) c=DIMZ/DIMX doesn't give very good results c=0.05 results? sound on average a bit better c=0.05^2*DIMZ/DIMX: results? results are mostly good (tunefish3 give's bad results) c=0.05^2 results? results are maybe better than in other cases. <with|font-series|bold|Use this as the default.> c=0.05^2*DIMX/DIMZ results? \V \; </body> <initial|<\collection> </collection>>
import { useState } from "react"; import ApplicationForm from "./components/ApplicationForm"; import CVPreview from "./components/CVPreview"; import Header from "./components/Header"; import "./styles/App.css"; function App() { const [inputValues, setInputValues] = useState({ "General Information": { "name": "", "email": "", "phone": "", "address": "", "linkedin": "" }, "Education": { "school": "", "degree": "", "graduation-date": "", "description": "" }, "Experience": { "job-title": "", "employer": "", "start-date": "", "end-date": "", "location": "", "description": "" } }); const handleInputChange = (section, field, value) => { setInputValues((prevValues) => ({ ...prevValues, [section]: { ...(prevValues[section] || {}), [field]: value }, })); }; return ( <div className="App"> <Header /> <div className="Main"> <ApplicationForm inputValues={inputValues} onInputChange={handleInputChange} /> <CVPreview General={inputValues["General Information"]} Education={inputValues["Education"]} Experience={inputValues["Experience"]} /> </div> </div> ); } export default App;
/* ---------------------------------- */ /* Operators */ /* ---------------------------------- */ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence /* ---------------------------------- */ //! ARITHMETIC OPERATORS */ /* ---------------------------------- */ let a = 10; let b = 2; console.log(a + b); // 12 (addition operator) console.log(a - b); // 8 (subtraction operator) console.log(a / b); // 5 (division operator) console.log(a * b); // 20 (multiplication operator) console.log(a ** b); // 100 (exponentiation operator) console.log(a % b); // 0 (remainder operator) //? Modulus - Remainder Operator let c = 3; console.log(a / c); // 3.333333333 console.log(a % c); // 1 (tek sayi) console.log(a % b); // 0 (cift sayi) /* let d = +prompt("Enter a number: "); if (isNaN(d)) { console.log("Sayi girmediniz"); } else if (d % 2 == 0) { console.log("Girilen sayi cift"); } else { console.log("Girilen sayi tek"); } */ let u = 1 + 2 * (5 - 4 / 2) ** 2; console.log(u); // 19 - islem onceligi: () > ** > * > / > + - //? Saat let sure = 225; let saat = parseInt(sure / 60); let dakika = sure % 60; console.log(`${sure} dakika, ${saat}saat ${dakika} dakikadir`); //? Increment Decrement //& post increment / decrement let d = 3; console.log(d++); // 3 - once yazdir sonra 1 arttir console.log(d); // 4 - guncel d yi yazdir let f = 5; console.log(f--); // 5 - once yazdir sonra 1 azalt console.log(f); // 4 - guncel f yi yazdir //& pre increment / decrement let e = 3; console.log(++e); // 4 - once 1 arttir sonra yazdir console.log(e); // 4 - guncel e yi yazdir let g = 5; console.log(--g); // 4 - once 1 azalt sonra yazdir console.log(g); // 4 - guncel g yi yazdir /* ---------------------------------- */ //! ASSIGNMENT OPERATORS */ /* ---------------------------------- */ let h = 10; let i = 2; let j = i; console.log(j); // 2 i = 3; // primitiveler immutable dir. Stack de yeni bir atama yapilirsa degisir. Aksi takdirde yeni kayit acilarak kaydedilir. console.log(j); // 2 - j nin degeri i degisti diye degismez // console.log((h += i)); // 13 - j=10 , i=3 // console.log((h -= i)); // 7 // console.log((h *= i)); // 30 //console.log((h /= i)); // 3.333333333 // console.log((h %= i)); // 1 // console.log((h **= i)); // 1000 /* ---------------------------------- */ //! COMPRASSION OPERATORS */ /* ---------------------------------- */ let k = 2; let l = "2"; let m = 2; console.log(k == l); //& true - tipe bakmaksizin degere bakar console.log(k === l); //& false - hem tipe hem degere bakar console.log(k === m); //& true console.log(k != l); //& false console.log(k !== l); //& true console.log(k !== m); //& false let n = true; console.log(!n); // false let o; if (o) { console.log("if calisti"); // calismaz cunku (o) true degil } else { console.log("else calisti"); // calisir cunku (o) false } let p = 100; let q = 100; console.log(p > q); // false console.log(p >= q); // true console.log("A" > "a"); // false - ASCII degerine bakar = A:65, a:97 /* ---------------------------------- */ //! LOGICAL OPERATORS */ /* ---------------------------------- */ // && - AND // tum sartlari saglamali ki dogru ciksin let a1 = true; // karakter sayisi 8 den buyuk mu let b1 = true; // kucuk harf var mi let c1 = false; // buyuk harf var mi let d1 = true; // karakter sayisi 16 dan buyuk mu let y = a1 && b1 && c1; console.log(y); // false //& || - OR let z = d1 || (b1 && c1); console.log(z); // true //& ! OLUMSUZLUK
using System.Collections.Generic; using Cysharp.Threading.Tasks; using Sirenix.OdinInspector; using UnityEngine; using VMFramework.Core; using VMFramework.Core.Pool; namespace VMFramework.Examples { public class AudioSpawner : UniqueMonoBehaviour<AudioSpawner> { #region Config /// <summary> /// The default transform parent for the AudioSource components. /// </summary> [SerializeField] private Transform audioSourceDefaultContainer; #endregion // The pool dictionary for the AudioSource components. [ShowInInspector] private static Dictionary<AudioClip, IComponentPool<AudioSource>> audioSourcePoolDictionary = new(); private static IComponentPool<AudioSource> CreatePool(AudioClip audioClip) { return new StackComponentPool<AudioSource>(() => { var audioSource = new GameObject(audioClip.name).AddComponent<AudioSource>(); audioSource.clip = audioClip; return audioSource; }, onReturnCallback: audioSource => { audioSource.transform.SetParent(instance.audioSourceDefaultContainer); audioSource.SetActive(false); }); } [Button] public static AudioSource Play(AudioClip audioClip, Vector3 position, bool autoCheckStop, Transform parent = null) { if (audioClip == null) { Debug.LogError("AudioClip is null"); return null; } if (audioSourcePoolDictionary.TryGetValue(audioClip, out var audioSourcePool) == false) { audioSourcePool = CreatePool(audioClip); audioSourcePoolDictionary.Add(audioClip, audioSourcePool); } var audioSource = audioSourcePool.Get(parent); audioSource.transform.position = position; audioSource.loop = false; audioSource.Play(); if (autoCheckStop) { _ = CheckStop(audioSource); } return audioSource; } [Button] public static void Return(AudioSource audioSource) { audioSource.Stop(); if (audioSource.gameObject.activeSelf) { audioSource.transform.SetParent(instance.audioSourceDefaultContainer); if (audioSource.clip == null) { Debug.LogError("AudioSource.clip is null"); return; } if (audioSourcePoolDictionary.TryGetValue(audioSource.clip, out var audioSourcePool) == false) { audioSourcePool = CreatePool(audioSource.clip); audioSourcePoolDictionary.Add(audioSource.clip, audioSourcePool); } audioSourcePool.Return(audioSource); } } /// <summary> /// Check if the audio has ended and return it if it has. /// </summary> /// <param name="audioSource"></param> /// <returns></returns> private static async UniTaskVoid CheckStop(AudioSource audioSource) { await UniTask.WaitUntil(() => audioSource.isPlaying == false); Return(audioSource); } } }
package testcode; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.RepetitionInfo; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; class PhoneScreenReceiverTest { PhoneScreenReceiverEdit psr = new PhoneScreenReceiverEdit(); @BeforeEach void beforeEach(TestInfo testInfo) { System.out.println(testInfo.getDisplayName()); String methodName = testInfo.getTestMethod().get().getName(); System.out.println(methodName); } @RepeatedTest(value = 6) @DisplayName("TS001 : noAttempt = 1-6 and isCorrectPwd = true, Expected result = true") void TS001(TestInfo testInfo, RepetitionInfo repetitionInfo) { int currentRepetition = repetitionInfo.getCurrentRepetition(); boolean bl = true; psr.onReceive(currentRepetition, bl); boolean screen = psr.isScreenOn; //System.out.println(testInfo.getDisplayName() + ": " + repetitionInfo.getCurrentRepetition()); System.out.println("noAttempt = "+currentRepetition+" and isCorrectPwd = "+bl+", Expected result = true, "+"Actual result = "+screen); assertEquals(true,screen); } @RepeatedTest(value = 6) @DisplayName("TS002 : noAttempt = 1-6 and isCorrectPwd = false, Expected result = false") void TS002(TestInfo testInfo, RepetitionInfo repetitionInfo) { int currentRepetition = repetitionInfo.getCurrentRepetition(); boolean bl = false; psr.onReceive(currentRepetition, bl); boolean screen = psr.isScreenOn; //System.out.println(testInfo.getDisplayName() + ": " + repetitionInfo.getCurrentRepetition()); System.out.println("noAttempt = "+currentRepetition+" and isCorrectPwd = "+bl+", Expected result = false, "+"Actual result = "+screen); assertEquals(false,screen); } @RepeatedTest(value = 6) @DisplayName("TS003 : noAttempt = 1-5 and isCorrectPwd = false AND noAttempt = 6 and isCorrectPwd = true , Expected result = false") void TS003(TestInfo testInfo, RepetitionInfo repetitionInfo) { boolean bl; int currentRepetition = repetitionInfo.getCurrentRepetition(); if(currentRepetition <=5) { bl = false; } else { bl = true; } psr.onReceive(currentRepetition, bl); boolean screen = psr.isScreenOn; //System.out.println(testInfo.getDisplayName() + ": " + repetitionInfo.getCurrentRepetition()); System.out.println("noAttempt = "+currentRepetition+" and isCorrectPwd = "+bl+", Expected result = false, "+"Actual result = "+screen); assertNotEquals(true,screen); } @AfterEach void afterEach() { System.out.println("=====Test by 633020389-3====="); } }
package provider import ( "regexp" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccResourceMetricImpactSource(t *testing.T) { if err := testAccCheckOrganization(); err != nil { t.Skipf("Skipping because %s.", err.Error()) } resource.UnitTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: testAccResourceMetricImpactSource, Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( "sleuth_metric_impact_source.mysource", "name", regexp.MustCompile("^My dd source blah")), ), }, { ResourceName: "sleuth_metric_impact_source.mysource", ImportState: true, ImportStateVerify: false, }, }, }) } const testAccResourceMetricImpactSource = ` resource "sleuth_project" "myproject" { name = "My project blah" } resource "sleuth_environment" "myenv" { project_slug = "${sleuth_project.myproject.id}" name = "Production" } resource "sleuth_metric_impact_source" "mysource" { project_slug = "${sleuth_project.myproject.id}" environment_slug = "${sleuth_environment.myenv.id}" name = "My dd source blah" provider_type = "datadog" query = "aws.ecs.memory_utilization" manually_set_health_threshold = 50 } `
#pragma once // Big Ol' list of opcodes #define INST(mnemonic, hexvalue) const unsigned char mnemonic = hexvalue namespace instruction { INST( nop, 0x00); // 0 : do nothing INST( aconst_null, 0x01); // 1 : push null reference INST( iconst_m1, 0x02); // 2 : push int constant (implicitly -1) INST( iconst_0, 0x03); // 3 : push int constant (implicitly 0) INST( iconst_1, 0x04); // 4 : push int constant (implicitly 1) INST( iconst_2, 0x05); // 5 : push int constant (implicitly 2) INST( iconst_3, 0x06); // 6 : push int constant (implicitly 3) INST( iconst_4, 0x07); // 7 : push int constant (implicitly 4) INST( iconst_5, 0x08); // 8 : push int constant (implicitly 5) INST( lconst_0, 0x09); // 9 : push long constant (implicitly 0) INST( lconst_1, 0x0a); // 10 : push long constant (implicitly 1) INST( fconst_0, 0x0b); // 11 : push float (impicitly 0) INST( fconst_1, 0x0c); // 12 : push float (impicitly 1) INST( fconst_2, 0x0d); // 13 : push float (impicitly 2) INST( dconst_0, 0x0e); // 14 : push double (implicitly 0) INST( dconst_1, 0x0f); // 15 : push double (implicitly 1) INST( bipush, 0x10); // 16 : push byte INST( sipush, 0x11); // 17 : push short INST( ldc, 0x12); // 18 : push item from run-time constant pool INST( ldc_w, 0x13); // 19 : push item from run-time constant pool (wide) INST( ldc2_w, 0x14); // 20 : push long or double from run-time constant pool (wide) INST( iload, 0x15); // 21 : load int from local var INST( lload, 0x16); // 22 : load long from local var INST( fload, 0x17); // 23 : load float from local var INST( dload, 0x18); // 24 : load double from local var INST( aload, 0x19); // 25 : load ref from local var INST( iload_0, 0x1a); // 26 : load int from local var (implicitly 0) INST( iload_1, 0x1b); // 27 : load int from local var (implicitly 1) INST( iload_2, 0x1c); // 28 : load int from local var (implicitly 2) INST( iload_3, 0x1d); // 29 : load int from local var (implicitly 3) INST( lload_0, 0x1e); // 30 : load long from local var (implicitly 0) INST( lload_1, 0x1f); // 31 : load long from local var (implicitly 1) INST( lload_2, 0x20); // 32 : load long from local var (implicitly 2) INST( lload_3, 0x21); // 33 : load long from local var (implicitly 3) INST( fload_0, 0x22); // 34 : load float from local var (impicitly 0) INST( fload_1, 0x23); // 35 : load float from local var (impicitly 1) INST( fload_2, 0x24); // 36 : load float from local var (impicitly 2) INST( fload_3, 0x25); // 37 : load float from local var (impicitly 3) INST( dload_0, 0x26); // 38 : load double from local var (implicitly 0) INST( dload_1, 0x27); // 39 : load double from local var (implicitly 1) INST( dload_2, 0x28); // 40 : load double from local var (implicitly 2) INST( dload_3, 0x29); // 41 : load double from local var (implicitly 3) INST( aload_0, 0x2a); // 42 : load ref from local var (implicitly 0) INST( aload_1, 0x2b); // 43 : load ref from local var (implicitly 1) INST( aload_2, 0x2c); // 44 : load ref from local var (implicitly 2) INST( aload_3, 0x2d); // 45 : load ref from local var (implicitly 3) INST( iaload, 0x2e); // 46 : load int from array INST( laload, 0x2f); // 47 : load long from array INST( faload, 0x30); // 48 : load float from array INST( daload, 0x31); // 49 : load double from array INST( aaload, 0x32); // 50 : load ref from array INST( baload, 0x33); // 51 : load byte/bool from array INST( caload, 0x34); // 52 : load char from array INST( saload, 0x35); // 53 : load short from array INST( istore, 0x36); // 54 : store int into local var INST( lstore, 0x37); // 55 : store long into local var INST( fstore, 0x38); // 56 : store float into local var INST( dstore, 0x39); // 57 : store double into local var INST( astore, 0x3a); // 58 : store ref into local var INST( istore_0, 0x3b); // 59 : store int into local var (implicitly 0) INST( istore_1, 0x3c); // 60 : store int into local var (implicitly 1) INST( istore_2, 0x3d); // 61 : store int into local var (implicitly 2) INST( istore_3, 0x3e); // 62 : store int into local var (implicitly 3) INST( lstore_0, 0x3f); // 63 : store long into local var (implicitly 0) INST( lstore_1, 0x40); // 64 : store long into local var (implicitly 1) INST( lstore_2, 0x41); // 65 : store long into local var (implicitly 2) INST( lstore_3, 0x42); // 66 : store long into local var (implicitly 3) INST( fstore_0, 0x43); // 67 : store float into local var (implicitly 0) INST( fstore_1, 0x44); // 68 : store float into local var (implicitly 1) INST( fstore_2, 0x45); // 69 : store float into local var (implicitly 2) INST( fstore_3, 0x46); // 70 : store float into local var (implicitly 3) INST( dstore_0, 0x47); // 71 : store double into local var (implicitly 0) INST( dstore_1, 0x48); // 72 : store double into local var (implicitly 1) INST( dstore_2, 0x49); // 73 : store double into local var (implicitly 2) INST( dstore_3, 0x4a); // 74 : store double into local var (implicitly 3) INST( astore_0, 0x4b); // 75 : store ref into local var (implicitly 0) INST( astore_1, 0x4c); // 76 : store ref into local var (implicitly 1) INST( astore_2, 0x4d); // 77 : store ref into local var (implicitly 2) INST( astore_3, 0x4e); // 78 : store ref into local var (implicitly 3) INST( iastore, 0x4f); // 79 : store into int array INST( lastore, 0x50); // 80 : store into long array INST( fastore, 0x51); // 81 : store float into array INST( dastore, 0x52); // 82 : store double into array INST( aastore, 0x53); // 83 : store ref into array INST( bastore, 0x54); // 84 : store byte/bool into array INST( castore, 0x55); // 85 : store char into array INST( sastore, 0x56); // 86 : store into short array INST( pop, 0x57); // 87 : pop top operand stack value INST( pop2, 0x58); // 88 : pop the top one or two operand stack values INST( dup, 0x59); // 89 : duplicate top of operand stack INST( dup_x1, 0x5a); // 90 : duplicate top operand stack value and insert two values down INST( dup_x2, 0x5b); // 91 : duplicate top operand stack value and insert two or three values down INST( dup2, 0x5c); // 92 : duplicate the top one or two operand stack values INST( dup2_x1, 0x5d); // 93 : duplicate the top one or two operand stack values and insert two or three values down INST( dup2_x2, 0x5e); // 94 : duplicate the top one or two operand stack values and insert two, three, or four values down INST( _swap, 0x5f); // 95 : swap the top two operand stack values INST( iadd, 0x60); // 96 : add int INST( ladd, 0x61); // 97 : add long INST( fadd, 0x62); // 98 : add float INST( dadd, 0x63); // 99 : add double INST( isub, 0x64); // 100 : subtract int INST( lsub, 0x65); // 101 : subtract long INST( fsub, 0x66); // 102 : subtract float INST( dsub, 0x67); // 103 : subtract double INST( imul, 0x68); // 104 : multiply int INST( lmul, 0x69); // 105 : multiply long INST( fmul, 0x6a); // 106 : multiply float INST( dmul, 0x6b); // 107 : multiply double INST( idiv, 0x6c); // 108 : divide int INST( _ldiv, 0x6d); // 109 : divide long ## ldiv is part of the c stdlib INST( fdiv, 0x6e); // 110 : divide float INST( ddiv, 0x6f); // 111 : divide double INST( irem, 0x70); // 112 : remainder int INST( lrem, 0x71); // 113 : remainder long INST( frem, 0x72); // 114 : remainder float INST( drem, 0x73); // 115 : remainder double INST( ineg, 0x74); // 116 : negate int INST( lneg, 0x75); // 117 : negate long INST( fneg, 0x76); // 118 : negate float INST( dneg, 0x77); // 119 : negate double INST( ishl, 0x78); // 120 : shift left int INST( lshl, 0x79); // 121 : shift left long INST( ishr, 0x7a); // 122 : arithmetic shift right int INST( lshr, 0x7b); // 123 : arithmetic shift right long INST( iushr, 0x7c); // 124 : logical shift right int INST( lushr, 0x7d); // 125 : logical shift right long INST( iand, 0x7e); // 126 : boolean and int INST( land, 0x7f); // 127 : boolean and long INST( ior, 0x80); // 128 : boolean or int INST( lor, 0x81); // 129 : boolean or long INST( ixor, 0x82); // 130 : boolean xor int INST( lxor, 0x83); // 131 : boolean xor long INST( iinc, 0x84); // 132 : increment local var by constant INST( i2l, 0x85); // 133 : convert int to long INST( i2f, 0x86); // 134 : convert int to float INST( i2d, 0x87); // 135 : convert int to double INST( l2i, 0x88); // 136 : convert long to int INST( l2f, 0x89); // 137 : convert long to float INST( l2d, 0x8a); // 138 : convert long to double INST( f2i, 0x8b); // 139 : convert float to int INST( f2l, 0x8c); // 140 : convert float to long INST( f2d, 0x8d); // 141 : convert float to double INST( d2i, 0x8e); // 142 : convert double to int INST( d2l, 0x8f); // 143 : convert double to long INST( d2f, 0x90); // 144 : convert double to float INST( i2b, 0x91); // 145 : convert int to byte INST( i2c, 0x92); // 146 : convert int to char INST( i2s, 0x93); // 147 : convert int to short INST( lcmp, 0x94); // 148 : compare long INST( fcmpl, 0x95); // 149 : compare float INST( fcmpg, 0x96); // 150 : compare float INST( dcmpl, 0x97); // 151 : compare double INST( dcmpg, 0x98); // 152 : compare double INST( ifeq, 0x99); // 153 : branch if compare with zero succeeds (equal) INST( ifne, 0x9a); // 154 : branch if compare with zero succeeds (not equal) INST( iflt, 0x9b); // 155 : branch if compare with zero succeeds (less than) INST( ifge, 0x9c); // 156 : branch if compare with zero succeeds (greater than or equal) INST( ifgt, 0x9d); // 157 : branch if compare with zero succeeds (greater than) INST( ifle, 0x9e); // 153 : branch if compare with zero succeeds (less than or equal) INST( if_icmpeq, 0x9f); // 159 : branch if int compare succeeds (equal) INST( if_icmpne, 0xa0); // 160 : branch if int compare succeeds (not equal) INST( if_icmplt, 0xa1); // 161 : branch if int compare succeeds (less than) INST( if_icmpge, 0xa2); // 162 : branch if int compare succeeds (greater than or equal) INST( if_icmpgt, 0xa3); // 163 : branch if int compare succeeds (greater than) INST( if_icmple, 0xa4); // 164 : branch if int compare succeeds (less than or equal) INST( if_acmpeq, 0xa5); // 165 : branch if refs equal INST( if_acmpne, 0xa6); // 166 : branch if refs not equal INST( _goto, 0xa7); // 167 : branch always INST( jsr, 0xa8); // 168 : jump subroutine INST( ret, 0xa9); // 169 : return from subroutine INST( tableswitch, 0xaa); // 170 : access jump table by index and jump INST( lookupswitch, 0xab); // 171 : access jump table by key match and jump INST( ireturn, 0xac); // 172 : return int from method INST( lreturn, 0xad); // 173 : return long from method INST( freturn, 0xae); // 174 : return float from method INST( dreturn, 0xaf); // 175 : return double from method INST( areturn, 0xb0); // 176 : return reference from method INST( _return, 0xb1); // 177 : return void from method INST( getstatic, 0xb2); // 178 : get static field from class INST( putstatic, 0xb3); // 179 : set static field in class INST( getfield, 0xb4); // 180 : fetch field from object INST( putfield, 0xb5); // 181 : set field in object INST( invokevirtual, 0xb6); // 182 : invoke instance method, dispatch based on class INST( invokespecial, 0xb7); // 183 : invoke instance method INST( invokestatic, 0xb8); // 184 : invoke a class/static method INST( invokeinterface, 0xb9); // 185 : invoke interface method INST( invokedynamic, 0xba); // 186 : invoke dynamic method INST( _new, 0xbb); // 187 : create new object INST( newarray, 0xbc); // 188 : create new array INST( anewarray, 0xbd); // 189 : create a new array with specified number of elements INST( arraylength, 0xbe); // 190 : get length of array INST( athrow, 0xbf); // 191 : throw exception or error INST( checkcast, 0xc0); // 192 : check whether object is of given type INST( instanceof, 0xc1); // 193 : determine whether object is of given type INST( monitorenter, 0xc2); // 194 : enter monitor for object INST( monitorexit, 0xc3); // 195 : exit monitor for object INST( _wide, 0xc4); // 196 : extend local var index by additional bytes INST( multianewarray, 0xc5); // 197 : create a new multidimensional array INST( ifnull, 0xc6); // 198 : branch if reference null INST( ifnonnull, 0xc7); // 199 : branch if reference not null INST( goto_w, 0xc8); // 200 : branch always (wide) INST( jsr_w, 0xc9); // 201 : jump subroutine (wide) INST( breakpoint, 0xca); // 202 : implementation defined, for debugging INST( impdep1, 0xfe); // 254 : implementation dependent INST( impdep2, 0xff); // 255 : implementation dependent } // end of namespace instruction
import { createAppContainer } from 'react-navigation'; import { createStackNavigator } from 'react-navigation-stack'; import HomeScreen from './src/screens/HomeScreen'; import ComponentsScreen from './src/screens/ComponentsScreen'; import ListScreen from './src/screens/ListScreen'; import ImageScreen from './src/screens/imageScreen'; import CounterScreenReducer from './src/screens/CounterScreenReducer'; import ColourScreen from './src/screens/ColourScreen'; import SquareScreenReducer from './src/screens/SqaureScreenReducer'; import TextScreen from './src/screens/TextScreen'; const navigator = createStackNavigator( { Home: HomeScreen, Components: ComponentsScreen, List: ListScreen, Image: ImageScreen, Counter: CounterScreenReducer, Colour: ColourScreen, Sqaure: SquareScreenReducer, Text: TextScreen, }, { initialRouteName: 'Home', defaultNavigationOptions: { title: 'App', }, } ); export default createAppContainer(navigator);
import io import os import string import torch import torch.nn as nn import torchvision.transforms as transforms from torchvision import models from flask import Flask, jsonify, request, render_template from PIL import Image app = Flask(__name__) # Modelling Task model = models.resnet18() num_inftr = model.fc.in_features model.fc = nn.Linear(num_inftr, 4) model.load_state_dict(torch.load('./fix_resnet18.pth')) model.eval() class_names = ['Apple Scab', 'Black Rot', 'Cedar Apple Rust', 'Healthy'] def transform_image(image_bytes): my_transforms = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) image = Image.open(io.BytesIO(image_bytes)) return my_transforms(image).unsqueeze(0) def get_prediction(image_bytes): tensor = transform_image(image_bytes=image_bytes) outputs = model.forward(tensor) _, prediction = torch.max(outputs, 1) return class_names[prediction] diseases = { "Healthy": "Kamu tidak perlu khawatir karena tanamanmu sehat, terus pertahankan yaa!", "Apple Scab": "Kudis apel mengganggu bagian tanaman yang terdapat di atas tanah. Gejala awal terdapat pada daun, \ bunga, dan buah. Bercak berkembang pada daun hingga daun menjadi berubah bentuk. Tepi pada daun umumnya \ tampak melepuh dan bersisik dengan batas tepi antara jaringan daun yang sehat dan sakit terlihat jelas. \ Beberapa buah terinfeksi rusak hingga jatuh dari rantingnya sebelum buah matang.", "Cedar Apple Rust": "Cedar apple rust, atau CAR, adalah penyakit jamur aneh yang mempengaruhi pohon apel dan cedar merah. Penyakit ini dapat dengan cepat merusak pohon apel dan \ menyebabkan noda pada buah.Pertama kali muncul di dedaunan sebagai bintik-bintik kuning kehijauan kecil yang secara bertahap membesar, menjadi oranye-kuning menjadi berwarna karat \ dengan pita merah. Bagian bawah daun mulai membentuk lesi yang menghasilkan spora ", "Black Rot": "Penyebaran penyakit busuk hitam disebabkan jamur Gloeosporium sp dan bisa melalui udara, percikan air dan alat pertanian yang terkontaminasi. \ Faktor kelembaban dan kurangnya intensitas matahari yang masuk ke tanaman berakibat jamur cepat untuk berkembang terlebih disaat musim penghujan seperti ini.Seiring waktu,\ bintik-bintik melebar dan daun-daun yang terinfeksi berat jatuh dari pohon. cabang yang mengalami penyakit busuk hitam mungkin dapat menginfeksi bagian tumbuhan lain." } # Treat the web process @app.route('/deteksi', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': if 'file' not in request.files: return redirect(request.url) file = request.files.get('file') if not file: return img_bytes = file.read() prediction_name = get_prediction(img_bytes) return render_template('result.html', name=prediction_name.lower(), description=diseases[prediction_name]) return render_template('index.html') @app.route('/') def home(): return render_template('home.html') @app.route('/about') def about(): return render_template('about.html') if __name__ == '__main__': app.run(debug=True)
import 'package:book_shelf/screens/book_detail_page.dart'; import 'package:book_shelf/screens/book_finder_page.dart'; import 'package:book_shelf/service/google_books_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); runApp(const AuthExampleApp()); } class AuthExampleApp extends StatelessWidget { const AuthExampleApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<GoogleBooksProvider>( create: (_) => GoogleBooksProvider(" ")), ], child: MaterialApp( title: 'Firebase Example App', debugShowCheckedModeBanner: false, home: BookFinderPage(), onGenerateRoute: (settings) { return MaterialPageRoute( builder: (context) { return _buildRoute( context: context, routeName: settings.name, arguments: settings.arguments); }, maintainState: true, fullscreenDialog: false, ); }, )); } } Widget _buildRoute({ required BuildContext context, required String? routeName, Object? arguments, }) { switch (routeName) { case '/home': return BookFinderPage(); case '/detail': final map = arguments as Map<String, dynamic>; final _book = map['book']; final _fav = map['fav']; return BookDetailsPage(book: _book, fav: _fav); default: return Container(); } }
A '''headache''' is when your head hurts. It is not when you hit your head with something and made it hurt that way, but when your head hurts from inside. A headache can be caused by one of several things, which are listed here: * [[Fever]] * Watching [[television]] or looking at a [[computer]] [[screen]] for a long time. * Being tired or sleepy. * As an effect of [[wikt:stress|stress]] * By other [[neurological]] conditions ('neurological' means touching the [[nerve]]s and the [[brain]]), like with [[epilepsy]] The 2nd Edition of the International Headache Classification (ICHD-2) defines more than 220 different types of headaches in three categories:<ref>Headache Classification Committee of the International Headache Society. The International Classification of Headache Disorders. Second Edition. ''Cephalalgia.'' 2004; (Suppl 1):1-160. [http://www.ihs-classification.org/en/ Online version.]</ref> * Primary Headaches, for example [[Migraine]], [[Tension headache]] and [[Cluster headache]]. * Secondary Headaches * Cranial Neuralgias, Central and Primary Facial Pain And Other Headaches A headache can also be used as a figure of speech, to describe something that is very difficult to do. Many headaches can be relieved with [[painkiller]]s like [[aspirin]]. == Causes == * [[Brain tumor]] * [[Lyme disease]] * [[Influenza]] * [[Brain metastasis]] * [[Sinusitis]] * [[Meningitis]]<ref>http://www.mayoclinic.com/health/meningitis/DS00118/DSECTION=symptoms</ref> * [[Encephalitis]]<ref>http://www.mayoclinic.com/health/encephalitis/DS00226/DSECTION=symptoms</ref> == Treatments == In many cases headaches can be relieved naturally. Many methods such as massaging the temples near the eye, exercising your eyes ( blinking, palming,) and walking can all help relieve the tension of headaches. Maintaining a healthy diet, with rich proteins and iron can keep your brain awake and healthy. One of the main factors is drinking plenty of water. These natural techniques tend to give you long-term relief whilst medication can often give you short term relief. There are many medicines which an treat mild headaches such as Paracetamol, Co-codamol, Ibruprofen but you should always consult your doctor or pharmacist first. == References == {{Wiktionary|headache}} <references /> {{med-stub}} [[Category:Symptoms]]
#+TITLE: How I Do My Computing #+AUTHOR: Ramsay Carslaw * Introduction I decided to make this document on how I use my computer, in the hopes it is useful to someone. * System and Tooling I use macOS for everything. I find the built in Apple apps to be more than good enough for most tasks. There are a few execptions. The default window manager is horrible, for this reason I use rectangle to control my windows. * Principles I follow some general principles when I use my computer ** 1. Avoid the mouse The mouse is slower for almost every task, try and avoid using it. ** 2. Avoid fullscreen Use vertical windows on the homepage, managed with Rectangle. This way I can use the keyboard to _temporarily_ enlarge windows and then snap them back. Opening multiple windows is better then clicking on a large full screen window. ** 3. Minimise Apps It is better to have one program you know well (vim, emacs) then one for each problem (IntelliJ, CLion etc). You can learn this program more deeply. ** 4. Configurability is king The best programs are the ones that let you customise them completely ** 5. Plain text is king It is always better to work with plain text files then using non standard file formats, the exception being PDF. ** 6. Consistency Try and use the same colorscheme everywhere, I use github dark. Also try to match font sizes, font faces and anything else. ** 7. Startup time is important Every tool you use should be able to have an instance open near instantly and be closed quickly. Every tool you use should be able to be launched from the command line. vim is perfect for this, as is server mode emacs. On macOS the ~open~ command is particallarly good for this. ** 8. Splash screens are evil Delete any app that has a startup window before you actually are able to use the app.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="slides.css"> <style> img { height: 70vh; } </style> </head> <body> <section class="inverted"> <code> # Lekce 8 - Úvod do JavaScriptu </code> </section> <section class="inverted"> <code> # Hello World day - 21.11.2018! </code> </section> <section class=""> <code> # Co je JavaScript? * Programovací jazyk (na rozdíl od HTML, CSS, stejně jako PHP) * Rozumí mu prohlížeče (stejně jako HTML, CSS, na rozdíl od PHP) * Je nejsilnějším a nejsložitějším nástrojem webu </code> </section> <section class=""> <code> # V prohlížeči slouží k * reakci na události * změně obsahu webu bez přecházení na další HTML stránky * komunikaci se serverem (odesílání a načítání dat) * zpracování dat, validace dat, efekty </code> </section> <section class=""> <code> # Kde jinde jej lze ještě použít? * Všude * Software jí svět * JavaScript jí software </code> </section> <section class=""> <code> # Kde jinde jej lze ještě použít? * Příkazová řádka (node.js) * Mobilní aplikace (PWA, React Native, ...) * Desktop aplikace (Elektron) * Hry * Mikroprocesory (Espruino) * Vizualizace dat (d3.js) * ... </code> </section> <section class=""> <code> # Výhody JS * Šíře využití (nejširší na světě) * Popularita = komunita - nejpopulárnější jazyk světa a roste * Snadný začátek * Výkon * Je good-enough - ne nejlepší, ale stačí </code> </section> <section class=""> <code> # Nevýhody JS * Špatná práce s kódem u velkých projektů * Zpětná kompatibilita a špatné nápady kdysi dávno ## Řešení * jsou, ale nad rámec dneška </code> </section> <section class="inverted"> <code> # Pojmy - nudná/nutná teorie * Hodnota * Proměnná * Výraz * Funkce * Větvení * Opakování * Událost </code> </section> <section class=""> <code> # Hodnota - typy * Číslo - number * Text - řetězec - string * Ano/ne - bool * Více hodnot - pole - array * Jmenný seznam hodnot - objekt - object * Nic - undefined * Série příkazů - funkce (viz dále) </code> </section> <section class=""> <code> # Proměnná * Pojmenovaný zástupce za hodnotu * Může držet jakýkoli typ </code> </section> <section class=""> <code> # Výraz * Vytváří hodnotu nebo provádí akci * tj. volání funkce * speciální funkce (+, - , &&, || ...) </code> </section> <section class=""> <code> # Funkce * Deklarace * Volání </code> </section> <section class=""> <code> # Větvení * Podmínka * Chci něco udělat jen někdy </code> </section> <section class=""> <code> # Opakování * Cyklus * Chci něco udělat vícekrát </code> </section> <section class=""> <code> # Událost * Něco se stalo * Klik myší * Stisk tlačítka * Posun myši * Zápis do formuláře * Změna velikosti viewportu * Spustí se funkce, pokud je zaregistrovaná </code> </section> <section class=""> <code> # To stačí * Složité je, jak to aplikovat na reálný problém </code> </section> <section class=""> <code> # Prohlížeč * Umí provést kód * Nabízí API - funkce jak s ním komunikovat * jQuery - knihovna, která nám zjednoduší API prohlížeče </code> </section> <section class="inverted"> <code> # Prakticky * Vložíme JavaScript do HTML * `<script></script>` * na konec stránky, před `/body` * Provedeme kód ve stránce * `alert('Hello World')` * Provedeme kód v konzoli </code> </section> <section class=""> <code> # Jak se to píše * Vyvoříme hodnotu * číslo - `1` * string - `'text'` * bool - `true` * pole - `['moje pole']` * objekt - `{jmeno: 'Aleš'}` * nic - `undefined` </code> </section> <section class=""> <code> # Uděláme proměnnou * `var mojeJmeno = 'Aleš'` </code> </section> <section class=""> <code> # Výraz - složitější příklad ``` var mujVek = Number(prompt('Kolik ti je let?')) var letOdPlnoletosti = mujVek - 18 alert('Jsi plnoletý již ' + letOdPlnoletosti + ' let') ``` </code> </section> <section class=""> <code> # Funkce - Deklarace (lze bez jména) ``` function mojeFunkce(mujParameter) { mujPrikaz() return 'hodnota kterou vracim' } ``` </code> </section> <section class=""> <code> # Funkce - Deklarace prakticky ``` function secti(a, b) { return a + b } ``` </code> </section> <section class=""> <code> # Funkce - Volání ``` var soucet = secti(1, 2) alert(soucet) ``` </code> </section> <section class=""> <code> # Větvení, opakování Chytře se mu zkusíme vyhnout </code> </section> <section class=""> <code> # Pracujeme s DOM - Document Object Model pomocí [jQuery](https://jquery.com/) * Vložíme jQuery na stránku před náš JavaScript * `<script src="https://code.jquery.com/jquery-3.3.1.js"></script>` </code> </section> <section class=""> <code> # Najdeme si elementy, se kterými chceme pracovat ``` $('css selektor') var nadpis = $('h1') ``` </code> </section> <section class=""> <code> # Měníme obsah elementu ``` var nadpis = $('h1') nadpis.text('Změněný text') nadpis.html('Změněný <strong>text</strong>') ``` </code> </section> <section class=""> <code> # Reagujeme na události ``` var nadpis = $('h1') nadpis.on('click', function() { nadpis.text('Změněný text') }) ``` </code> </section> <section class=""> <code> # Měníme vzhled elementu ``` nadpis.addClass('moje-trida') nadpis.removeClass('moje-trida') nadpis.toggleClass('moje-trida') nadpis.css('display', 'none') nadpis.css({display: 'bool', color: 'red'}) ``` </code> </section> <section class=""> <code> # Děláme skrývací menu </code> </section> <script src="marked.min.js"></script> <script src="slides.js"></script> </body> </html>
library(tidyverse) library(stringi) library(stringr) library(data.table) library(foreign) library(broom) library(sf) full<-data.frame() cty.names<-c("ALA","BAY", "BRA", "BRE", "CAL","CHA","CIT","CLA","CLL", "IND", "CLM","DAD","DES","DIX","DUV","ESC","FLA","FRA","GAD", "GLA","GUL", "HAM","HEN","HER","HIG","HIL","HOL","JAC","JEF","LAF","LAK","LEE", "LEO","LEV","LIB","MAD","MAN","MRN","MRT","NAS","OKA","OKE","ORA", "OSC","PAL","PAS","PIN","POL","SAN","SAR","STJ","STL","SUM", "SUW","TAY","VOL","WAK","WAL","PUT","HAR","BAK","SEM","BRO","GIL") for(cty in cty.names){ file <- paste("C:/Users/prlic/Downloads/precinctlevelelectionresults2018gen/", cty,"_PctResults20181106.txt",sep = "") cty<-read.csv2(file,sep = "\t",header = F, na.strings = " ", colClasses = c("V13"="character", "V16"="character")) cty <- cty %>% # Rename the base variables rename(county.code = V1, name = V2, el.number = V3, el.date = V4, el.name = V5, prec.id = V6, prec.loc = V7, tot.reg = V8, tot.reg.rep = V9, tot.reg.dem = V10, tot.reg.oth = V11, contest = V12, district = V13, contest.code = V14, candidate= V15, cand.pty.code = V16, cand.vtr.id = V17, doe.num = V18, total.votes = V19)%>% # Create a precinct ID based on county and precinct name. mutate(prec.id2 = paste(county.code,prec.id,sep=""), contest = tolower(contest), prec.id2 = case_when( str_length(prec.id) == 1 ~ paste(county.code,"000",prec.id,sep = ""), str_length(prec.id) == 2 ~ paste(county.code,"00",prec.id,sep = ""), str_length(prec.id) == 3 ~ paste(county.code,"0",prec.id,sep = ""), str_length(prec.id) >= 4 ~ paste(county.code, prec.id,sep = "") )) %>% # Remove statewide offices and blank precincts filter(!(candidate == "OverVotes" | candidate == "UnderVotes" | candidate == "WriteinVotes"), !(prec.id==0), !(contest == "united states senator" | contest == "governor"| contest == "attorney general" | contest == "chief financial officer" | contest == "commissioner of agriculture" | grepl("amend",contest))) full <- rbind(full,cty) } #UNI uni<-read.csv2("C:/Users/prlic/Downloads/precinctlevelelectionresults2018gen/UNI_PctResults20181106.txt",sep = "\t",header = F, na.strings = " ", colClasses = c("V13"="character", "V16"="character")) uni1<- uni %>% rename(county.code = V1, name = V2, el.number = V3, el.date = V4, el.name = V5, prec.id = V6, prec.loc = V7, tot.reg = V8, tot.reg.rep = V9, tot.reg.dem = V10, tot.reg.oth = V11, contest = V12, district = V13, contest.code = V14, candidate= V15, cand.pty.code = V16, cand.vtr.id = V17, doe.num = V18, total.votes = V19) %>% mutate(prec.id = ifelse(grepl("&",prec.id, fixed = T),substr(prec.id,1,2),as.character(prec.id))) cty <- uni1 cty <- cty %>% mutate(prec.id2 = paste(county.code,prec.id,sep=""), contest = tolower(contest), prec.id2 = case_when( str_length(prec.id) == 1 ~ paste(county.code,"000",prec.id,sep = ""), str_length(prec.id) == 2 ~ paste(county.code,"00",prec.id,sep = ""), str_length(prec.id) == 3 ~ paste(county.code,"0",prec.id,sep = ""), str_length(prec.id) >= 4 ~ paste(county.code, prec.id,sep = "") )) %>% filter(!(candidate == "OverVotes" | candidate == "UnderVotes" | candidate == "WriteinVotes"), !(prec.id==0), !(contest == "united states senator" | contest == "governor"| contest == "attorney general" | contest == "chief financial officer" | contest == "commissioner of agriculture" | grepl("amend",contest))) full <- rbind(full,cty) #For Monroe and Washington, the counties sent a different precinct ID for the dbf than they sent #to the state. I had to manually adjust these.I chose to change state data rather than dbf. #Monroe mon<-read.csv2("C:/Users/prlic/Downloads/precinctlevelelectionresults2018gen/MON_PctResults20181106.txt",sep = "\t",header = F, na.strings = " ", colClasses = c("V13"="character", "V16"="character")) mon1a<-mon mon2<-data.frame() i<-0 mon.prec.state<-c(1,2,3,4,5,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,28,29,30,31,32,35,36,37,38,41) mon.prec.dbf <-c(1,2,3,4,5,6,7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33) #Manual adjust function for(y in mon.prec.state){ i <- i+1 mon1<-mon1a %>% mutate(V6 = ifelse(V6 == y,mon.prec.dbf[i],V6))%>% filter(V6 == mon.prec.dbf[i]) mon1a<-mon1a %>% filter(!(V6==y)) mon2<-rbind(mon2,mon1) } cty <- mon2 cty <- cty %>% rename(county.code = V1, name = V2, el.number = V3, el.date = V4, el.name = V5, prec.id = V6, prec.loc = V7, tot.reg = V8, tot.reg.rep = V9, tot.reg.dem = V10, tot.reg.oth = V11, contest = V12, district = V13, contest.code = V14, candidate= V15, cand.pty.code = V16, cand.vtr.id = V17, doe.num = V18, total.votes = V19)%>% mutate(prec.id2 = paste(county.code,prec.id,sep=""), contest = tolower(contest), prec.id2 = case_when( str_length(prec.id) == 1 ~ paste(county.code,"000",prec.id,sep = ""), str_length(prec.id) == 2 ~ paste(county.code,"00",prec.id,sep = ""), str_length(prec.id) == 3 ~ paste(county.code,"0",prec.id,sep = ""), str_length(prec.id) >= 4 ~ paste(county.code, prec.id,sep = "") )) %>% filter(!(candidate == "OverVotes" | candidate == "UnderVotes" | candidate == "WriteinVotes"), !(prec.id==0), !(contest == "united states senator" | contest == "governor"| contest == "attorney general" | contest == "chief financial officer" | contest == "commissioner of agriculture" | grepl("amend",contest))) full <- rbind(full,cty) #Washington County was<-read.csv2("C:/Users/prlic/Downloads/precinctlevelelectionresults2018gen/WAS_PctResults20181106.txt",sep = "\t",header = F, na.strings = " ", colClasses = c("V13"="character", "V16"="character")) was2<-was %>% mutate(V6 = case_when( V6 == 12 ~ 15, V6 == 11 ~ 12, V6 == 10 ~ 11, T ~ as.double(V6) )) cty <- was2 cty <- cty %>% rename(county.code = V1, name = V2, el.number = V3, el.date = V4, el.name = V5, prec.id = V6, prec.loc = V7, tot.reg = V8, tot.reg.rep = V9, tot.reg.dem = V10, tot.reg.oth = V11, contest = V12, district = V13, contest.code = V14, candidate= V15, cand.pty.code = V16, cand.vtr.id = V17, doe.num = V18, total.votes = V19)%>% mutate(prec.id2 = paste(county.code,prec.id,sep=""), contest = tolower(contest), prec.id2 = case_when( str_length(prec.id) == 1 ~ paste(county.code,"000",prec.id,sep = ""), str_length(prec.id) == 2 ~ paste(county.code,"00",prec.id,sep = ""), str_length(prec.id) == 3 ~ paste(county.code,"0",prec.id,sep = ""), str_length(prec.id) >= 4 ~ paste(county.code, prec.id,sep = "") )) %>% filter(!(candidate == "OverVotes" | candidate == "UnderVotes" | candidate == "WriteinVotes"), !(prec.id==0), !(contest == "united states senator" | contest == "governor"| contest == "attorney general" | contest == "chief financial officer" | contest == "commissioner of agriculture" | grepl("amend",contest))) full <- rbind(full,cty) full <- full %>% mutate(prec.id2 = ifelse(prec.id2 == "CAL201/201C","CAL0201",paste(prec.id2))) ### Lower State House #Read in shapefile that dealt with split precincts. FL.2018.lh <- st_read("H:/Research/2019 Research/TampaBayTimes/2018_Precincts/2018LowerHousePrecinctGeneral/2018LowerHousePrecinctGeneral.shp") full.lower.state<- full %>% #Dealing with state data filter(grepl("state rep",contest)) %>% group_by(prec.id2, contest, district, cand.pty.code,candidate,tot.reg) %>% summarise(total.votes = sum(total.votes)) %>% #renaming contest to be able to make a merge variable #A bit superfluous but it works. mutate(contest1 = ifelse((contest == "state representative"),paste("state house",district,sep = ""),paste(contest)), contest1 = ifelse((contest == "state senator"),paste("state senate",district,sep = ""),paste(contest1)), contest1 = ifelse((contest == 'representative in congress'),paste("congressional",district,sep = ""),paste(contest1))) %>% ungroup() %>% #Converting to wide from long dcast(prec.id2 + contest1 +tot.reg~ cand.pty.code, value.var = "total.votes", fun.aggregate=sum ) %>% #Creation of merge variable mutate(prec.id3 = paste(prec.id2,str_to_lower(contest1),sep=""), prec.id3 = stri_replace_all_fixed(prec.id3," ","")) FL.2018.lh <- FL.2018.lh %>% #Creation of merge variable in shapefile mutate(prec.id3 = paste(Pct_std, str_to_lower(NAMELSAD),sep = ""), prec.id3 = str_replace_all(prec.id3, fixed(" "),"")) #Merge FL2018LowerHouse <- sp::merge(x= FL.2018.lh, y =full.lower.state, by = "prec.id3", all.x = T, all.y = T) #Dealing FL2018LowerHouse <- FL2018LowerHouse %>% replace(., is.na(.),-9)%>% mutate(district = str_sub(GEOID,3,6)) %>% select(-c(STATEFP, INTPTLAT, INTPTLON, SLDLST, NAMELSAD, LSY, MTFCC, FUNCSTAT, ALAND, AWATER, Pct_std, prec.id3,prec.id2,contest1, GEOID)) %>% rename(G18SLHREP = REP, G18SLHDEM = DEM, G18SLHGRE = GRE, G18SLHLPF = LPF, G18SLHNPA = NPA) #SLH = State Lower House st_write(FL2018LowerHouse, "H:/Research/2019 Research/TampaBayTimes/2018_Precincts/2018LowerHousePrecinctGeneral/FL2018GenLowerHouse.shp" ) ### State Senate FL.2018.uh <- st_read("H:/Research/2019 Research/TampaBayTimes/2018_Precincts/2018UpperHousePrecinctGeneral/2018UpperHousePrecinctMergeGeneral.shp") full.upper.state<- full %>% filter(grepl("state sen",contest)) %>% group_by(prec.id2, contest, district, cand.pty.code,candidate,tot.reg) %>% summarise(total.votes = sum(total.votes)) %>% mutate(contest1 = ifelse((contest == "state representative"),paste("state house",district,sep = ""),paste(contest)), contest1 = ifelse((contest == "state senator"),paste("state senate",district,sep = ""),paste(contest1)), contest1 = ifelse((contest == 'representative in congress'),paste("congressional",district,sep = ""),paste(contest1))) %>% ungroup() %>% dcast(prec.id2 + contest1 +tot.reg~ cand.pty.code, value.var = "total.votes", fun.aggregate=sum ) %>% mutate(prec.id3 = paste(prec.id2,str_to_lower(contest1),sep=""), prec.id3 = stri_replace_all_fixed(prec.id3," ","")) FL.2018.uh <- FL.2018.uh %>% mutate(prec.id3 = paste(Pct_std, str_to_lower(NAMELSAD_2),sep = ""), prec.id3 = str_replace_all(prec.id3, fixed(" "),"")) FL2018UpperHouse <- sp::merge(x= FL.2018.uh, y =full.upper.state, by = "prec.id3", all.x = T) FL2018UpperHouse <- FL2018UpperHouse %>% replace(., is.na(.),-9)%>% select(c( County, Precinct, District = SLDUST, tot.reg, G18SUHDEM = DEM, G18SUHREP = REP, G18SUHNPA = NPA, G18SUHLPF = LPF, geometry )) #SUH = State Upper House st_write(FL2018UpperHouse, "H:/Research/2019 Research/TampaBayTimes/2018_Precincts/2018UpperHousePrecinctGeneral/FL2018GenUpperHouse.shp" ) ### Federal House FL.2018.fh <- st_read("H:/Research/2019 Research/TampaBayTimes/2018_Precincts/2018FederalHousePrecinctGeneral/2018FederalHousePrecinctGeneral.shp") full.lower.federal<- full %>% filter(grepl("congress",contest)) %>% group_by(prec.id2, contest, district, cand.pty.code,candidate,tot.reg) %>% summarise(total.votes = sum(total.votes)) %>% mutate(contest1 = ifelse((contest == "state representative"),paste("state house",district,sep = ""),paste(contest)), contest1 = ifelse((contest == "state senator"),paste("state senate",district,sep = ""),paste(contest1)), contest1 = ifelse((contest == 'representative in congress'),paste("congressional",district,sep = ""),paste(contest1))) %>% ungroup() %>% dcast(prec.id2 + contest1 +tot.reg~ cand.pty.code, value.var = "total.votes", fun.aggregate=sum ) %>% mutate(prec.id3 = paste(prec.id2,str_to_lower(contest1),sep=""), prec.id3 = stri_replace_all_fixed(prec.id3," ","")) FL.2018.fh <- FL.2018.fh %>% mutate(prec.id3 = paste(Pct_std, "congressionaldistrict", str_to_lower(as.character(DISTRICT)),sep = ""), prec.id3 = str_replace_all(prec.id3, fixed(" "),"")) FL2018FederalHouse <- sp::merge(x= FL.2018.fh, y =full.lower.federal, by = "prec.id3", all.x = T) FL2018FederalHouse <- FL2018FederalHouse %>% select(c(County, Precinct, District = DISTRICT, tot.reg, G18USHDEM = DEM, G18USHREP = REP, G18USHNPA = NPA, geometry)) %>% replace(., is.na(.), -9) #USH = US House st_write(FL2018FederalHouse, "H:/Research/2019 Research/TampaBayTimes/2018_Precincts/2018FederalHousePrecinctGeneral/FL2018GenFederalHouse.shp")
//Import Statements const { SlashCommandBuilder } = require("@discordjs/builders"); var mongoUtil = require("../../mongoUtil"); const config = require("../../config.json"); const func = require("../../functions"); const Discord = require("discord.js"); const shop = require("./shop.json"); module.exports = { data: new SlashCommandBuilder() .setName("take") .setDescription("Take an item from a user") .addStringOption((option) => option .setName("take") .setDescription("Take an item from someone, use spaces between words") .setRequired(true) ) .addMentionableOption((option) => option .setName("mention") .setDescription("Mention someone") .setRequired(true) ), async execute(client, interaction) { if (interaction.user.id != config.ownerID) { return func.embedInteraction( interaction, `You don't have permissions to run this command!` ); } //Options Storage const member = interaction.options.getMentionable("mention") || interaction.user; const colorChoice = interaction.options .getString("take") .toLowerCase() .trim() .split(/\s+/) .join("-"); //Get Database var db = mongoUtil.getDb(); const economyCollection = db .db(config.database) .collection(config.collection.economy); //Find a document within the collection that matched the member id var dat = await economyCollection.findOne({ userID: member.id }); //Check if there is a document for that user if (typeof shop[colorChoice] === "undefined") { return func.embedInteraction( interaction, `**${colorChoice}** is not a valid color` ); //Check if user data exists } else if (dat === null) { await economyCollection.insertOne({ userID: member.id, tokens: 0, colors: [], equippedColor: "nothing", }); return func.embedInteraction( interaction, `${member.user.username} has nothing to take!` ); } else { //Check whether they own the color for (let i = 0; i < dat.colors.length; i++) { if (dat.colors[i] == colorChoice) { //If they have the color equipped, remove it if (dat.equippedColor == colorChoice) { await interaction.member.roles.remove( shop[dat.equippedColor].roleId ); await economyCollection.updateOne( { userID: member.id }, { $set: { equippedColor: "nothing" } } ); } //Remove the item await economyCollection.updateOne( { userID: member.id }, { $pull: { colors: colorChoice } } ); return func.embedInteraction( interaction, `Took **${shop[colorChoice].name}** from ${member.user.username}` ); } } return func.embedInteraction( interaction, `${member.user.username} does not own **${shop[colorChoice].name}**. There is nothing to take.` ); } }, category: "economy", };
<template> <v-dialog @click:outside="$emit('done')" width="500px" v-model="dialog"> <v-card class="px-2 py-2"> <v-card-title class="d-flex justify-center"> New Team </v-card-title> <v-divider class="mb-3" /> <v-form class="px-8" @submit.prevent="submit" @keyup.esc.native="$emit('done')" @keyup.enter.native="submit" ref="form" > <v-text-field label="Team Name" :rules="required" outlined v-model="team_name" > </v-text-field> </v-form> <v-card-actions> <v-spacer /> <v-btn text color="primary" v-on:click="submit"> Submit </v-btn> <v-btn text v-on:click="$emit('done')"> Cancel </v-btn> </v-card-actions> </v-card> </v-dialog> </template> <script> export default { name: "NewTeam", data() { return { dialog: true, team_name: "", required: [(v) => !!v || "This field is required"], }; }, props: { course_id: String, }, methods: { async submit() { if (!this.$refs.form.validate()) { return; } const team_name = this.team_name; const course_id = this.course_id; await this.$axios .post("/faculty/team/new", { team_name, course_id, }) .then(() => { this.$snack.success("Team added!"); this.$emit("done"); }) .catch((err) => { if (err.response.status) { this.$snack.error("Team already exists"); } else { this.$snack.error("An error occurred"); } }); }, }, }; </script>
package com.tokopedia.product.info.data.query import com.tokopedia.gql_query_annotation.GqlQueryInterface /** * Created by yovi.putra on 16/09/22" * Project name: android-tokopedia-core **/ object GetProductDetailBottomSheetQuery : GqlQueryInterface { private const val OPERATION_NAME = "PdpGetDetailBottomSheet" private const val SHOP_ID_PARAM = "shopId" private const val PRODUCT_ID_PARAM = "productId" private const val GIFTABLE_PARAM = "isGiftable" private const val PARENT_ID_PARAM = "parentId" private const val BOTTOM_SHEET_PARAM = "bottomsheetParam" private const val CATALOG_ID_PARAM = "catalogId" fun createParams( productId: String, shopId: String, parentId: String, isGiftable: Boolean, catalogId: String, bottomSheetParam: String ): HashMap<String, Any> = hashMapOf( PRODUCT_ID_PARAM to productId, SHOP_ID_PARAM to shopId, PARENT_ID_PARAM to parentId, GIFTABLE_PARAM to isGiftable, CATALOG_ID_PARAM to catalogId, BOTTOM_SHEET_PARAM to bottomSheetParam ) override fun getOperationNameList() = listOf(OPERATION_NAME) override fun getQuery() = """ query $OPERATION_NAME(${'$'}$PRODUCT_ID_PARAM:String,${'$'}$SHOP_ID_PARAM:String,${'$'}$CATALOG_ID_PARAM:String, ${'$'}$GIFTABLE_PARAM:Boolean, ${'$'}$PARENT_ID_PARAM:String, ${'$'}$BOTTOM_SHEET_PARAM:String){ pdpGetDetailBottomSheet(productID:${'$'}$PRODUCT_ID_PARAM, shopID:${'$'}$SHOP_ID_PARAM, catalogID:${'$'}$CATALOG_ID_PARAM, isGiftable:${'$'}$GIFTABLE_PARAM, parentID:${'$'}$PARENT_ID_PARAM, bottomsheetParam:${'$'}$BOTTOM_SHEET_PARAM){ bottomsheetData{ title componentName isApplink isShowable value applink icon row { key value } } dataShopNotes{ shopNotesData{ shopNotesID title content isTerms position url updateTime updateTimeUTC } error } discussion{ title buttonType buttonCopy } error{ Code Message DevMessage } } } """.trimIndent() override fun getTopOperationName() = OPERATION_NAME }
import numpy as np import torch from src.trainer.base_trainer import BaseKDTrainer from src.trainer.utils import L2Loss class ReferenceTrainer(BaseKDTrainer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.feature_criterion = L2Loss(reduce=None, square=False) def teacher_model(self, teacher_source): return self._teachers[teacher_source] def reference_loss( self, images, labels, ratio_ref=1, label_smoothing=0.0, teacher_source="pretrained", **_, ): ref_images, _ = self.get_ref_data(self.ref_loader) base_loss, loss_dict = self.base_loss( images, labels, label_smoothing=label_smoothing ) with torch.no_grad(): (teacher_ref_image_embedding, _, _,) = self.teacher_model( teacher_source )(ref_images, get_features=True) student_ref_image_embedding = self.unwrapped_model(self.train_model).encode( images=ref_images ) kd_loss = self._get_kd_loss( student_ref_image_embedding, teacher_ref_image_embedding, feature_criterion=self.feature_criterion, ) return ( base_loss + ratio_ref * kd_loss, { **loss_dict, "kd_loss": kd_loss.item(), }, ) class ZSCLTrainer(BaseKDTrainer): @property def l2_model(self): return self._teachers["l2"] @property def ref_sentences(self): return self.dataloaders["ref_sentences"] def l2_loss(self, model, model_ref): loss = 0.0 for param_q, param_k in zip(model.parameters(), model_ref.parameters()): loss += torch.nn.functional.mse_loss( param_q, param_k.detach(), reduction="sum" ) return loss def zscl_loss(self, images, labels, label_smoothing=0.2, l2_ratio=1, **_): ref_images, _ = self.get_ref_data(self.ref_loader) base_loss, loss_dict = self.base_loss( images, labels, label_smoothing=label_smoothing ) with torch.no_grad(): ( teacher_ref_image_embedding, teacher_ref_text_embedding, logit_scale, ) = self.pretrained_teacher_model( ref_images, self.ref_sentences, get_features=True ) student_ref_image_embedding = self.unwrapped_model(self.train_model).encode( images=ref_images ) student_logits = ( logit_scale * student_ref_image_embedding @ teacher_ref_text_embedding.t() ) teacher_logits = ( logit_scale * teacher_ref_image_embedding @ teacher_ref_text_embedding.t() ) zscl_image_loss = self._get_kd_loss(student_logits, teacher_logits) student_text_logits = student_logits.t() teacher_text_logits = teacher_logits.t() zscl_text_loss = self._get_kd_loss(student_text_logits, teacher_text_logits) loss = base_loss + zscl_image_loss + zscl_text_loss loss_dict.update( { "zscl_image_loss": zscl_image_loss.item(), "zscl_text_loss": zscl_text_loss.item(), } ) if l2_ratio > 0: l2_loss = self.l2_loss(self.train_model, self.l2_model) loss += l2_ratio * l2_loss loss_dict.update({"l2_loss": l2_loss.item()}) return loss, loss_dict def train(self, *args, **kwargs): self.dataloaders["ref_sentences"] = self.unwrapped_model( self.train_model ).tokenize(self.dataloaders["ref_sentences"]) super().train(*args, **kwargs) class PreviousAwareZSCLTrainer(ZSCLTrainer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.prev_teacher_model.eval() @property def prev_teacher_model(self): return self._teachers["prev"] @property def previous_loader(self): return self.dataloaders["prev"] def previous_aware_zscl_loss( self, images, labels, ratio_ref, ratio_prev, has_noise=False, label_smoothing=0.2, **_, ): zscl_loss, loss_dict = self.zscl_loss( images, labels, ratio_ref, feature_criterion=self.feature_criterion, label_smoothing=label_smoothing, ) previous_images, _ = self.get_ref_data( self.previous_loader, has_noise=has_noise ) previous_loss = self.get_kd_loss( previous_images, teacher_model=self.prev_teacher_model, feature_criterion=self.feature_criterion, ) loss_dict.update({"previous_loss": previous_loss.item()}) return zscl_loss + ratio_prev * previous_loss, loss_dict def train(self, *args, **kwargs): self.dataloaders["prev"].init() super().train(*args, **kwargs)
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Threading.Tasks; using Indo.Companies; using Indo.Currencies; using Indo.Customers; using Indo.Employees; using Indo.SalesOrders; using Indo.SalesQuotationDetails; using Microsoft.AspNetCore.Authorization; using Volo.Abp.Application.Dtos; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Repositories; namespace Indo.SalesQuotations { public class SalesQuotationAppService : IndoAppService, ISalesQuotationAppService { private readonly ICustomerRepository _customerRepository; private readonly IEmployeeRepository _employeeRepository; private readonly IEmployeeAppService _employeeAppService; private readonly ISalesQuotationRepository _salesQuotationRepository; private readonly SalesQuotationManager _salesQuotationManager; private readonly ISalesQuotationDetailRepository _salesQuotationDetailRepository; private readonly ICompanyAppService _companyAppService; public SalesQuotationAppService( ISalesQuotationRepository salesQuotationRepository, SalesQuotationManager salesQuotationManager, ICustomerRepository customerRepository, IEmployeeRepository employeeRepository, IEmployeeAppService employeeAppService, ISalesQuotationDetailRepository salesQuotationDetailRepository, ICompanyAppService companyAppService) { _salesQuotationRepository = salesQuotationRepository; _salesQuotationManager = salesQuotationManager; _customerRepository = customerRepository; _employeeRepository = employeeRepository; _employeeAppService = employeeAppService; _salesQuotationDetailRepository = salesQuotationDetailRepository; _companyAppService = companyAppService; } public async Task<QuotationCountDto> GetCountQuotationAsync() { await Task.Yield(); var result = new QuotationCountDto(); result.CountDraft = _salesQuotationRepository.Where(x => x.Status == SalesQuotationStatus.Draft).Count(); result.CountConfirm = _salesQuotationRepository.Where(x => x.Status == SalesQuotationStatus.Confirm).Count(); result.CountCancelled = _salesQuotationRepository.Where(x => x.Status == SalesQuotationStatus.Cancelled).Count(); return result; } public async Task<float> GetSummarySubTotalAsync(Guid id) { await Task.Yield(); var result = 0f; result = _salesQuotationDetailRepository .Where(x => x.SalesQuotationId.Equals(id)) .Sum(x => x.SubTotal); return result; } public async Task<string> GetSummarySubTotalInStringAsync(Guid id) { var result = await GetSummarySubTotalAsync(id); return result.ToString("##,##.00"); } public async Task<float> GetSummaryDiscAmtAsync(Guid id) { await Task.Yield(); var result = 0f; result = _salesQuotationDetailRepository .Where(x => x.SalesQuotationId.Equals(id)) .Sum(x => x.DiscAmt); return result; } public async Task<string> GetSummaryDiscAmtInStringAsync(Guid id) { var result = await GetSummaryDiscAmtAsync(id); return result.ToString("##,##.00"); } public async Task<float> GetSummaryBeforeTaxAsync(Guid id) { await Task.Yield(); var result = 0f; result = _salesQuotationDetailRepository .Where(x => x.SalesQuotationId.Equals(id)) .Sum(x => x.BeforeTax); return result; } public async Task<string> GetSummaryBeforeTaxInStringAsync(Guid id) { var result = await GetSummaryBeforeTaxAsync(id); return result.ToString("##,##.00"); } public async Task<float> GetSummaryTaxAmountAsync(Guid id) { await Task.Yield(); var result = 0f; result = _salesQuotationDetailRepository .Where(x => x.SalesQuotationId.Equals(id)) .Sum(x => x.TaxAmount); return result; } public async Task<string> GetSummaryTaxAmountInStringAsync(Guid id) { var result = await GetSummaryTaxAmountAsync(id); return result.ToString("##,##.00"); } public async Task<float> GetSummaryTotalAsync(Guid id) { await Task.Yield(); var result = 0f; result = _salesQuotationDetailRepository .Where(x => x.SalesQuotationId.Equals(id)) .Sum(x => x.Total); return result; } public async Task<string> GetSummaryTotalInStringAsync(Guid id) { var result = await GetSummaryTotalAsync(id); return result.ToString("##,##.00"); } public async Task<SalesQuotationReadDto> GetAsync(Guid id) { var queryable = await _salesQuotationRepository.GetQueryableAsync(); var query = from salesQuotation in queryable join customer in _customerRepository on salesQuotation.CustomerId equals customer.Id join employee in _employeeRepository on salesQuotation.SalesExecutiveId equals employee.Id where salesQuotation.Id == id select new { salesQuotation, customer, employee }; var queryResult = await AsyncExecuter.FirstOrDefaultAsync(query); if (queryResult == null) { throw new EntityNotFoundException(typeof(SalesQuotation), id); } var dto = ObjectMapper.Map<SalesQuotation, SalesQuotationReadDto>(queryResult.salesQuotation); dto.CustomerName = queryResult.customer.Name; dto.SalesExecutiveName = queryResult.employee.Name; dto.StatusString = L[$"Enum:SalesQuotationStatus:{(int)queryResult.salesQuotation.Status}"]; dto.PipelineString = L[$"Enum:SalesQuotationPipeline:{(int)queryResult.salesQuotation.Pipeline}"]; var defaultCompany = await _companyAppService.GetDefaultCompanyAsync(); dto.CurrencyName = defaultCompany.CurrencyName; return dto; } public async Task<List<SalesQuotationReadDto>> GetListAsync() { var queryable = await _salesQuotationRepository.GetQueryableAsync(); var query = from salesQuotation in queryable join customer in _customerRepository on salesQuotation.CustomerId equals customer.Id join employee in _employeeRepository on salesQuotation.SalesExecutiveId equals employee.Id select new { salesQuotation, customer, employee }; var queryResult = await AsyncExecuter.ToListAsync(query); var dtos = queryResult.Select(x => { var dto = ObjectMapper.Map<SalesQuotation, SalesQuotationReadDto>(x.salesQuotation); dto.CustomerName = x.customer.Name; dto.SalesExecutiveName = x.employee.Name; dto.StatusString = L[$"Enum:SalesQuotationStatus:{(int)x.salesQuotation.Status}"]; dto.PipelineString = L[$"Enum:SalesQuotationPipeline:{(int)x.salesQuotation.Pipeline}"]; return dto; }) .OrderByDescending(x => x.QuotationDate) .ToList(); return dtos; } public async Task<List<SalesQuotationReadDto>> GetListWithTotalAsync() { var company = await _companyAppService.GetDefaultCompanyAsync(); var queryable = await _salesQuotationRepository.GetQueryableAsync(); var query = from salesQuotation in queryable join customer in _customerRepository on salesQuotation.CustomerId equals customer.Id join employee in _employeeRepository on salesQuotation.SalesExecutiveId equals employee.Id select new { salesQuotation, customer, employee }; var queryResult = await AsyncExecuter.ToListAsync(query); var dtos = queryResult.Select(x => { var dto = ObjectMapper.Map<SalesQuotation, SalesQuotationReadDto>(x.salesQuotation); dto.CustomerName = x.customer.Name; dto.SalesExecutiveName = x.employee.Name; dto.StatusString = L[$"Enum:SalesQuotationStatus:{(int)x.salesQuotation.Status}"]; dto.PipelineString = L[$"Enum:SalesQuotationPipeline:{(int)x.salesQuotation.Pipeline}"]; dto.Total = _salesQuotationDetailRepository.Where(y => y.SalesQuotationId.Equals(x.salesQuotation.Id)).Sum(z => z.Total); dto.CurrencyName = company.CurrencyName; return dto; }) .OrderByDescending(x => x.QuotationDate) .ToList(); return dtos; } public async Task<List<SalesQuotationReadDto>> GetListWithTotalByCustomerAsync(Guid customerId) { var company = await _companyAppService.GetDefaultCompanyAsync(); var queryable = await _salesQuotationRepository.GetQueryableAsync(); var query = from salesQuotation in queryable join customer in _customerRepository on salesQuotation.CustomerId equals customer.Id join employee in _employeeRepository on salesQuotation.SalesExecutiveId equals employee.Id where salesQuotation.CustomerId == customerId select new { salesQuotation, customer, employee }; var queryResult = await AsyncExecuter.ToListAsync(query); var dtos = queryResult.Select(x => { var dto = ObjectMapper.Map<SalesQuotation, SalesQuotationReadDto>(x.salesQuotation); dto.CustomerName = x.customer.Name; dto.SalesExecutiveName = x.employee.Name; dto.StatusString = L[$"Enum:SalesQuotationStatus:{(int)x.salesQuotation.Status}"]; dto.PipelineString = L[$"Enum:SalesQuotationPipeline:{(int)x.salesQuotation.Pipeline}"]; dto.Total = _salesQuotationDetailRepository.Where(y => y.SalesQuotationId.Equals(x.salesQuotation.Id)).Sum(z => z.Total); dto.CurrencyName = company.CurrencyName; return dto; }) .OrderByDescending(x => x.QuotationDate) .ToList(); return dtos; } public async Task<ListResultDto<CustomerLookupDto>> GetCustomerLookupAsync() { var list = await _customerRepository.GetListAsync(); return new ListResultDto<CustomerLookupDto>( ObjectMapper.Map<List<Customer>, List<CustomerLookupDto>>(list) ); } public async Task<ListResultDto<SalesExecutiveLookupDto>> GetSalesExecutiveLookupAsync() { var list = await _employeeAppService.GetSalesListAsync(); return new ListResultDto<SalesExecutiveLookupDto>( ObjectMapper.Map<List<EmployeeReadDto>, List<SalesExecutiveLookupDto>>(list) ); } public async Task<SalesOrderReadDto> ConvertToOrderAsync(Guid salesQuotationId) { var obj = await _salesQuotationManager.ConvertToOrder(salesQuotationId); return ObjectMapper.Map<SalesOrder, SalesOrderReadDto>(obj); } public async Task<SalesQuotationReadDto> CreateAsync(SalesQuotationCreateDto input) { var obj = await _salesQuotationManager.CreateAsync( input.Number, input.CustomerId, input.SalesExecutiveId, input.QuotationDate, input.QuotationValidUntilDate ); obj.Description = input.Description; await _salesQuotationRepository.InsertAsync(obj); return ObjectMapper.Map<SalesQuotation, SalesQuotationReadDto>(obj); } public async Task UpdateAsync(Guid id, SalesQuotationUpdateDto input) { var obj = await _salesQuotationRepository.GetAsync(id); if (obj.Number != input.Number) { await _salesQuotationManager.ChangeNameAsync(obj, input.Number); } obj.CustomerId = input.CustomerId; obj.SalesExecutiveId = input.SalesExecutiveId; obj.Description = input.Description; obj.QuotationDate = input.QuotationDate; obj.QuotationValidUntilDate = input.QuotationValidUntilDate; obj.Pipeline = input.Pipeline; await _salesQuotationRepository.UpdateAsync(obj); } public async Task DeleteAsync(Guid id) { await _salesQuotationRepository.DeleteAsync(id); } public async Task<SalesQuotationReadDto> ConfirmAsync(Guid salesQuotationId) { var obj = await _salesQuotationManager.ConfirmAsync(salesQuotationId); return ObjectMapper.Map<SalesQuotation, SalesQuotationReadDto>(obj); } public async Task<SalesQuotationReadDto> CancelAsync(Guid salesQuotationId) { var obj = await _salesQuotationManager.CancelAsync(salesQuotationId); return ObjectMapper.Map<SalesQuotation, SalesQuotationReadDto>(obj); } } }
package cloud.lintcode.dp; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //给你一个由 无重复 正整数组成的集合 nums ,请你找出并返回其中最大的整除子集 answer ,子集中每一元素对 (answer[i], answer[ //j]) 都应当满足: // // answer[i] % answer[j] == 0 ,或 // answer[j] % answer[i] == 0 // // // 如果存在多个有效解子集,返回其中任何一个均可。 // // // // 示例 1: // // //输入:nums = [1,2,3] //输出:[1,2] //解释:[1,3] 也会被视为正确答案。 // // // 示例 2: // // //输入:nums = [1,2,4,8] //输出:[1,2,4,8] // // // // // 提示: // // // 1 <= nums.length <= 1000 // 1 <= nums[i] <= 2 * 10⁹ // nums 中的所有整数 互不相同 // // Related Topics 数组 数学 动态规划 排序 👍 450 👎 0 public class num368LargestDivisibleSubset { public static void main(String[] args) { Solution solution = new num368LargestDivisibleSubset().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { Arrays.sort(nums); int[] dp = new int[nums.length]; int[] prev = new int[nums.length]; for (int i = 0; i < nums.length; i++) { dp[i] = 1; prev[i] = -1; } for (int i = 1; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[i] % nums[j] == 0 && dp[j] + 1 >= dp[i]) { dp[i] = dp[j] + 1; prev[i] = j; } } } int pos = 0; int maxNumber = 1; for (int i = 0; i < nums.length; i++) { if (dp[i] > maxNumber) { maxNumber = dp[i]; pos = i; } } List<Integer> res = new ArrayList<>(); while (pos != -1) { res.add(nums[pos]); pos = prev[pos]; } return res; } } //leetcode submit region end(Prohibit modification and deletion) }
import { AiFillCode, AiOutlineFundProjectionScreen } from "react-icons/ai"; import { SITE_NAME, routePathRecord } from "@/configs"; import { HiMenuAlt1 } from "react-icons/hi"; import LabelList from "@/components/LabelList"; import Link from "next/link"; import clsx from "clsx"; import { labelsAtom } from "@/store"; import { motion } from "framer-motion"; import { useAtom } from "jotai"; import { useRouter } from "next/router"; import { useState } from "react"; function Menu() { const route = useRouter(); const [labelStore, setLabelStore] = useAtom(labelsAtom); return ( <div className="bg-white sticky top-0" style={{ zIndex: labelStore.isShow ? 10 : 999 }} > <motion.header className="relative sticky top-0 max-w-[1200px] mx-auto py-8 px-4 " initial={{ left: 30 }} animate={{ left: 0 }} transition={{ type: "spring", stiffness: 260, damping: 20, }} > <div className="flex items-center gap-2"> <div className="flex items-center justify-center sm:justify-start w-full gap-2 sm:mr-auto"> <AiFillCode className="w-6 h-6 dark:text-purple-600" /> <div className="flex items-center gap-1 w-40"> <Link href={"/"} className="h-4"> <a className="text-purple-600 dark:text-white text-2xl"> {SITE_NAME} </a> </Link> <motion.span className="w-1 h-6 bg-purple-600 dark:bg-white" initial={{ opacity: 1 }} animate={{ opacity: 0 }} transition={{ repeat: Infinity, type: "keyframes", duration: 1, }} ></motion.span> </div> </div> {/* 标签 */} <div className="flex fixed items-center bottom-0 bg-[#a865bb] p-4 sm:p-0 sm:bg-white left-0 right-0 justify-between flex-row-reverse sm:flex-row sm:relative"> <div className="text-white sm:text-purple-900 flex items-center gap-2 sm:mr-6 cursor-pointer w-16" onClick={() => setLabelStore((prev) => ({ ...prev, isShow: !prev.isShow })) } > <HiMenuAlt1 /> <span>分类</span> </div> {/* nav list */} <ul className="flex gap-8 overflow-hidden"> {Object.keys(routePathRecord) .filter((i) => i !== "index") .map((key) => { // @ts-ignore const { path, text, icon } = routePathRecord[key]; return ( <li key={path} className={clsx( "transform-all", route.pathname === path ? "sm:text-purple-500 text-white" : "sm:text-purple-900 sm:opacity-80 text-white", "sm:hover:text-purple-500 sm:hover:opacity-100" )} > <Link href={path}> <a className="flex items-center gap-2"> {icon} <span className="flex-grow overflow-ellipsis whitespace-nowrap overflow-hidden"> {text} </span> </a> </Link> </li> ); })} </ul> </div> </div> </motion.header> </div> ); } export default Menu;
# Import the 'inverse' function from the 'Cryptodome.Util.number' module from Cryptodome.Util.number import inverse # Define the plaintext message 'm' to be encrypted m = 12 # Define the prime numbers 'p' and 'q' for RSA encryption p = 3 q = 17 # Calculate the modulus 'n' by multiplying 'p' and 'q' n = (p * q) # Calculate Euler's totient function 'phi' for 'n' phi = (p - 1) * (q - 1) # Choose the public exponent 'e' (usually a small prime number, commonly 3 or 65537). e = 5 # Calculate the private exponent 'd' using the modular multiplicative inverse of 'e' modulo 'phi' d = inverse(e, phi) # Encrypt the plaintext 'm' using the public key (n, e) and the 'pow' function c = pow(m, e, n) # Print the encrypted message. print(f"The encrypted message is- {c}") # Decrypt the ciphertext 'c' using the private key (n, d) and the 'pow' function m = pow(c, d, n) # Print the decrypted message print(f"The decrypted message is- {m}")
/* eslint-disable react-hooks/exhaustive-deps */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import * as React from 'react' import { observer } from 'mobx-react-lite' import { useParams } from 'react-router-dom' import BigNumber from 'bignumber.js' import { useManageTokenStore } from '../../state/ManageTokenStore' import { isAddressValid } from '../../../../constants' const Details: React.FC = () => { const { tokenRoot } = useParams<{ tokenRoot: string }>() const managingToken = useManageTokenStore(tokenRoot!) const currentTargetAddressBalance = React.useMemo( () => new BigNumber(managingToken.targetWalletBalance) .decimalPlaces(+managingToken.token!.decimals, BigNumber.ROUND_DOWN) .toFixed() , [managingToken.targetWalletBalance], ) const afterTargetAddressBalance = React.useMemo( () => new BigNumber(managingToken.targetWalletBalance) .plus(managingToken.amountToMint) .decimalPlaces(+managingToken.token!.decimals, BigNumber.ROUND_DOWN) .toFixed() , [managingToken.targetWalletBalance, managingToken.amountToMint], ) const currentSupply = React.useMemo( () => new BigNumber(managingToken.token?.totalSupply ?? 0) .shiftedBy(-(managingToken.token?.decimals || 0)) .decimalPlaces(+managingToken.token!.decimals, BigNumber.ROUND_DOWN) .toFixed() , [managingToken.token!.totalSupply], ) const afterSupply = React.useMemo( () => new BigNumber(managingToken.token?.totalSupply ?? 0) .shiftedBy(-(managingToken.token?.decimals || 0)) .plus(managingToken.amountToMint ?? 0) .decimalPlaces(+managingToken.token!.decimals, BigNumber.ROUND_DOWN) .toFixed() , [managingToken.token!.totalSupply, managingToken.amountToMint], ) const getBalanceMessage = (): string => { if (!isAddressValid(managingToken.targetAddress)) { return "Enter valid target address" } if (!managingToken.amountToMint) { return "Enter amount to mint" } return "Enter target address" } return ( <div className="border border-[#DFE8F9] p-4 rounded-lg mt-3 overflow-hidden bg-[#F4F5FA] dark:bg-purple-darkest"> <h3 className="font-bold"> Target address balance </h3> <div> {managingToken.targetWalletBalance && managingToken.amountToMint ? ( <> <div className="flex items-center justify-between gap-4 text-xs"> <div> Current </div> <div className=''> {currentTargetAddressBalance} </div> </div> <div className="flex items-center justify-between gap-4 text-xs"> <div> After minting </div> <div> {afterTargetAddressBalance} </div> </div> </> ) : ( <div className="flex items-center justify-between gap-4 text-xs"> <div>{getBalanceMessage()}</div> </div> )} </div> <h3 className="font-bold mt-4"> Circulating Supply </h3> <div> {managingToken.amountToMint ? ( <> <div className="flex items-center justify-between gap-4 text-xs"> <div> Current </div> <div> {currentSupply} </div> </div> <div className="flex items-center justify-between gap-4 text-xs"> <div> After minting </div> <div> {afterSupply} </div> </div> </> ) : ( <div className="flex items-center justify-between gap-4 text-xs"> <div> Enter amount to mint </div> </div> )} </div> </div> ) } export const MintDetails = observer(Details)
Solve Commands ``mmSolver`` Command ++++++++++++++++++++ The command named ``mmSolver`` is the primary command used to perform a solve. Flags ----- The command can be run in both MEL and Python. Here is a table of command flags, as currently specified in the command. Flag Type Description Default Value -camera (-c) string, string Camera transform and shape nodes None -marker (-m) string, string, string Marker, Camera, Bundle None -attr (-a) string, string, string, string, string Node attribute, min value, max value, offset and scale None -frame (-f) long int Frame number to solve with 1 -attrStiffness (-asf) string, string, string, string Node attribute, weight plug name, variance plug name, value plug name. None -attrSmoothness (-asm) string, string, string, string Node attribute, weight plug name, variance plug name, value plug name. None -solverType (-st) unsigned int Type of solver to use. <auto detected> -sceneGraphMode (-sgm) unsigned int The Scene Graph used; 0=Maya DAG, 1=MM Scene Graph 0 (Maya DAG) -timeEvalMode (-tem) unsigned int How to evalulate values at different times, 0=DG Context 1=Set TIme 0 (DG Context) -iterations (-it) unsigned int Maximum number of iterations 20 -tauFactor (-t) double Initial Damping Factor 1E-03 -epsilon1 (-e1) double Acceptable gradient change 1E-06 -epsilon2 (-e2) double Acceptable parameter change 1E-06 -epsilon3 (-e3) double Acceptable error 1E-06 -delta (-dt) double Change to the guessed parameters each iteration 1E-04 -autoDiffType (-adt) unsigned int Auto-differencing type 0=forward 1=central 0 (forward) -verbose (-v) bool Prints more information False Return ------ The ``mmSolver`` command will return a list of strings. The list of strings has a specific structure and stores all the data from the core solver engines, so the user can do whatever they wish to. Example ------- Python Example: .. code:: python maya.cmds.mmSolver( camera=('camera1', 'cameraShape1'), marker=( ('marker1', 'camera1', 'bundle1'), ('marker2', 'camera1', 'bundle2'), ), attr=( ('node.attr', 'None', 'None', 'None', 'None'), ('bundle1.tx', 'None', 'None', 'None', 'None'), ('bundle1.ty', 'None', 'None', 'None', 'None'), ('camera1.rx', '-10.0', '25.0', '360.0', '1.0'), ), frame=(1, 12, 24,), iterations=10, ) MEL Example: .. code:: text mmSolver -camera "camera1" "cameraShape1" -marker "marker1" "camera1" "bundle1" -marker "marker2" "camera1" "bundle2" -attr "node.attr" "None" "None" "None" "None" -attr "bundle1.tx" "None" "None" "None" "None" -attr "bundle1.ty" "None" "None" "None" "None" -attr "camera1.rx" "-10.0" "25.0" "360.0" "1.0" -frame 1 -frame 12 -frame 24 -iterations 10; ``mmSolverType`` Command ++++++++++++++++++++++++ `mmSolverType` is used to query the current plug-in's available solvers. This tool is commonly used to dynamically query for the different types of solvers. See the :ref:`solver-faq-how-to-get-supported-solver-types` for more detail on this. Python Example: .. code:: python solvers = maya.cmds.mmSolverType(query=True, list=True) default_solver = maya.cmds.mmSolverType(query=True, default=True) ``mmSolverAffects`` Command +++++++++++++++++++++++++++ *To be written.* ``mmSolverSceneGraph`` Command ++++++++++++++++++++++++++++++ *To be written.* ``mmCameraRelativePose`` Command ++++++++++++++++++++++++++++++++ *To be written.* ``mmCameraPoseFromPoints`` Command ++++++++++++++++++++++++++++++++++ *To be written.*
type Query { person(name: String): [Person] } type Mutation { createPerson(person: PersonInput): Person deletePerson(id: ID!): ID } type Person { id: ID, name: String, birthYear: String, films: String, vehicles: String, } type Film { episodeId: ID title: String, opening_crawl: String, director: String, producer: String, release_date: String, } type Vehicle { id: ID, name: String, cargo_capacity: String, consumables: String, cost_in_credits: String, crew: String, length: String, manufacturer: String, max_atmosphering_speed: String, model: String, passengers: String, vehicle_class: String } input PersonInput{ id: ID, name: String, birthYear: String, films: String, filmss: [FilmInput], vehicles: String, } input FilmInput { episodeId: ID title: String, opening_crawl: String, director: String, producer: String, release_date: String, }
package backtracking; public class RatInMaze { public static void ratInMaze(int[][] maze) { int n = maze.length; int path[][] = new int[n][n]; printAllPaths(maze, 0, 0, path); } //recursion process for finding possible all path public static void printAllPaths(int maze[][], int i, int j, int path[][]){ int n = maze.length; // Check if i,j cell is valid or not if(i < 0 || i >= n || j < 0 || j >= n || maze[i][j] == 0 || path[i][j] == 1){ return; } // Include the cell in current path path[i][j] = 1; // Destination cell if(i == n - 1 && j == n - 1){ for(int r = 0; r < n; r++) { for(int c = 0; c < n; c++) { System.out.print(path[r][c] + " "); //printing the possible one path } System.out.println(); } System.out.println(); path[i][j] = 0; return; } // Explore further in all directions // top printAllPaths(maze, i - 1, j, path); // right printAllPaths(maze, i, j + 1, path); // Down printAllPaths(maze, i + 1 , j, path); // Left printAllPaths(maze, i, j - 1, path); path[i][j] = 0; } //recursion process for finding possible one path // public static boolean solveMaze(int maze[][], int i, int j, int path[][]){ // int n = maze.length; // // Check if i,j cell is valid or not // if(i < 0 || i >= n || j < 0 || j >= n || maze[i][j] == 0 // || path[i][j] == 1){ // return false; // } // // Include the cell in current path // path[i][j] = 1; // // Destination cell // if(i == n - 1 && j == n - 1){ // for(int r = 0; r < n; r++) { // for(int c = 0; c < n; c++) { // System.out.print(path[r][c] + " "); //printing the possible one path // } // System.out.println(); // } // return true; // } // // // Explore further in all directions // boolean pathPossible = false; // // top // if(solveMaze(maze, i - 1, j, path)){ // pathPossible = true; // } // // right // else if(solveMaze(maze, i, j + 1, path)){ // pathPossible = true; // } // // Down // else if(solveMaze(maze, i + 1 , j, path)){ // pathPossible = true; // } // // Left // else if(solveMaze(maze, i, j - 1, path)){ // pathPossible = true; // } // return pathPossible; // } public static void main(String[] args) { int maze[][] = {{1, 1, 0}, {1, 1, 0}, {1, 1, 1}}; ratInMaze(maze); // boolean pathpossible = ratInMaze(maze); // System.out.println(pathpossible); } }
<?php /** * Candidate parameters data fetch * * Gets data to populate the front-end form fields * * PHP Version 5 * * @category Loris * @package Media * @author Stella L. <slee.mcin@gmail.com> * @license Loris license * @link https://github.com/aces/Loris-Trunk */ use \LORIS\StudyEntities\Candidate\CandID; $user = \NDB_Factory::singleton()->user(); $candID = new CandID($_GET['candID']); $candidate = \Candidate::singleton($candID); if (!$user->hasPermission('access_all_profiles') && !($user->hasAnyPermission( [ 'candidate_parameter_edit', 'candidate_parameter_view' ] ) && $user->hasCenter($candidate->getCenterID())) ) { header("HTTP/1.1 403 Forbidden"); exit; } $data = $_GET['data'] ?? ''; if ($data == '') { header("HTTP/1.1 400 Bad Request"); exit; } switch ($data) { case 'candidateInfo': echo json_encode(getCandInfoFields()); exit; case 'probandInfo': echo json_encode(getProbandInfoFields()); exit; case 'familyInfo': echo json_encode(getFamilyInfoFields()); exit; case 'participantStatus': echo json_encode(getParticipantStatusFields()); exit; case 'consentStatus': echo json_encode(getConsentStatusFields()); exit; case 'candidateDOB': echo json_encode(getDOBFields()); exit; case 'candidateDOD': echo json_encode(getDODFields()); exit; case 'diagnosisEvolution': echo json_encode(getDiagnosisEvolutionFields()); exit; default: header("HTTP/1.1 404 Not Found"); exit; } /** * Handles the fetching of Candidate Info fields * * @throws DatabaseException * * @return array */ function getCandInfoFields() { $candID = new CandID($_GET['candID']); $db = \NDB_Factory::singleton()->database(); // get caveat options $caveat_options = []; $options = $db->pselect( "SELECT ID, Description FROM caveat_options", [] ); foreach ($options as $row) { $caveat_options[$row['ID']] = $row['Description']; } // get pscid $pscid = $db->pselectOne( 'SELECT PSCID FROM candidate WHERE CandID = :candid', ['candid' => $candID] ); $flag = $db->pselectOne( 'SELECT flagged_caveatemptor FROM candidate WHERE CandID = :candid', ['candid' => $candID] ); $reason = $db->pselectOne( 'SELECT flagged_reason FROM candidate WHERE CandID = :candid', ['candid' => $candID] ); $other = $db->pselectOne( 'SELECT flagged_other FROM candidate WHERE CandID = :candid', ['candid' => $candID] ); $extra_parameters = $db->pselect( "SELECT CONCAT('PTID', pt.ParameterTypeID) AS ParameterTypeID, pt.Name, pt.Type, pt.Description FROM parameter_type pt JOIN parameter_type_category_rel ptcr USING (ParameterTypeID) JOIN parameter_type_category ptc USING (ParameterTypeCategoryID) WHERE ptc.Name='Candidate Parameters' ORDER BY pt.ParameterTypeID, pt.name ASC", [] ); $fields = $db->pselect( "SELECT CONCAT('PTID', ParameterTypeID) AS ParameterTypeID, Value FROM parameter_candidate WHERE CandID=:cid", ['cid' => $candID] ); $parameter_values = []; foreach ($fields as $row) { $parameter_values[$row['ParameterTypeID']] = $row['Value']; } $result = [ 'pscid' => $pscid, 'candID' => $candID->__toString(), 'caveatReasonOptions' => $caveat_options, 'flagged_caveatemptor' => $flag, 'flagged_reason' => $reason, 'flagged_other' => $other, 'extra_parameters' => $extra_parameters, 'parameter_values' => $parameter_values, ]; return $result; } /** * Handles the fetching of Proband Info fields * * @throws DatabaseException * * @return array */ function getProbandInfoFields() { $candID = new CandID($_GET['candID']); $db = \NDB_Factory::singleton()->database(); // get pscid $pscid = $db->pselectOne( 'SELECT PSCID FROM candidate where CandID = :candid', ['candid' => $candID] ); $sex = $db->pselectOne( 'SELECT ProbandSex FROM candidate where CandID = :candid', ['candid' => $candID] ); $dob = $db->pselectOne( 'SELECT ProbandDoB FROM candidate where CandID = :candid', ['candid' => $candID] ); $extra_parameters = $db->pselect( "SELECT CONCAT('PTID', pt.ParameterTypeID) AS ParameterTypeID, pt.Name, pt.Type, pt.Description FROM parameter_type pt JOIN parameter_type_category_rel ptcr USING (ParameterTypeID) JOIN parameter_type_category ptc USING (ParameterTypeCategoryID) WHERE ptc.Name='Candidate Parameters Proband' ORDER BY pt.ParameterTypeID, pt.name ASC", [] ); $fields = $db->pselect( "SELECT CONCAT('PTID', ParameterTypeID) AS ParameterTypeID, Value FROM parameter_candidate WHERE CandID=:cid", ['cid' => $candID] ); $parameter_values = []; foreach ($fields as $row) { $parameter_values[$row['ParameterTypeID']] = $row['Value']; } // Calculate age difference $ageDifference = "Could not calculate age"; $candidateDOB = $db->pselectOne( "SELECT DoB FROM candidate WHERE CandID=:CandidateID", ['CandidateID' => $candID] ); if (!empty($candidateDOB) && !empty($dob)) { $age = \Utility::calculateAge($dob, $candidateDOB); if ($age !== null) { $ageDifference = $age['year'] * 12 + $age['mon'] + round($age['day'] / 30, 2); } } $result = [ 'pscid' => $pscid, 'candID' => $candID->__toString(), 'ProbandSex' => $sex, 'ProbandDoB' => $dob, 'ageDifference' => $ageDifference, 'extra_parameters' => $extra_parameters, 'parameter_values' => $parameter_values, 'sexOptions' => \Utility::getSexList(), ]; return $result; } /** * Handles the fetching of Family Info fields * * @throws DatabaseException * * @return array */ function getFamilyInfoFields() { $candID = new CandID($_GET['candID']); $db = \NDB_Factory::singleton()->database(); // get pscid $pscid = $db->pselectOne( 'SELECT PSCID FROM candidate where CandID = :candid', ['candid' => $candID] ); $candidatesList = $db->pselect( "SELECT CandID FROM candidate ORDER BY CandID", [] ); $siblingsList = $db->pselect( "SELECT f1.CandID FROM family f1 JOIN family f2 ON f1.FamilyID=f2.FamilyID WHERE f2.CandId=:candid GROUP BY f1.CandID", ['candid' => $candID] ); $siblings = []; foreach (array_values($siblingsList) as $siblingArray) { foreach ($siblingArray as $ID) { array_push($siblings, $ID); } } $candidates = []; // Remove own ID and sibling IDs from list of possible family members foreach ($candidatesList as $key => $candidate) { foreach ($candidate as $ID) { if ($ID == $candID || in_array($ID, $siblings)) { unset($candidatesList[$key]); } else { $candidates[$ID] = $ID; } } } $familyMembers = $db->pselect( "SELECT f1.CandID as FamilyCandID, f1.Relationship_type FROM family f1 JOIN family f2 ON f1.FamilyID=f2.FamilyID WHERE f2.CandID = :candid AND f1.CandID <> :candid2 ORDER BY f1.CandID", [ 'candid' => $candID, 'candid2' => $candID, ] ); $result = [ 'pscid' => $pscid, 'candID' => $candID->__toString(), 'candidates' => $candidates, 'existingFamilyMembers' => $familyMembers, ]; return $result; } /** * Handles the fetching of Participant Status fields * * @throws DatabaseException * * @return array */ function getParticipantStatusFields() { global $loris; $loris->getModule('candidate_parameters')->registerAutoloader(); $candID = new CandID($_GET['candID']); $db = \NDB_Factory::singleton()->database(); // get pscid $pscid = $db->pselectOne( 'SELECT PSCID FROM candidate where CandID = :candid', ['candid' => $candID] ); $statusOptions = \Candidate::getParticipantStatusOptions(); $reasonOptions = []; $req = $db->pselect( 'SELECT ID from participant_status_options where Required=1', [] ); $required = []; foreach ($req as $k=>$row) { $required[$k] = $row['ID']; } $parentIDs = $db->pselect( 'SELECT distinct(parentID) from participant_status_options', [] ); $parentIDMap = []; foreach ($parentIDs as $ID) { $reasonOptions = []; foreach ($ID as $parentID) { if ($parentID != null) { $options = $db->pselect( "SELECT ID, Description FROM participant_status_options WHERE parentID=:pid", ['pid' => $parentID] ); foreach ($options as $option) { $reasonOptions[$option['ID']] = $option['Description']; } $parentIDMap[$parentID] = $reasonOptions; } } } $query = "SELECT participant_status, participant_suboptions, reason_specify FROM participant_status WHERE CandID=:candid"; $row = $db->pselectRow($query, ['candid' => $candID]); $status = !empty($row['participant_status']) ? $row['participant_status'] : null; $suboption = !empty($row['participant_suboptions']) ? $row['participant_suboptions'] : null; $reason = !empty($row['reason_specify']) ? $row['reason_specify'] : null; $history = getParticipantStatusHistory($candID); $result = [ 'pscid' => $pscid, 'candID' => $candID->__toString(), 'statusOptions' => $statusOptions, 'required' => $required, 'reasonOptions' => $reasonOptions, 'parentIDs' => $parentIDMap, 'participantStatus' => $status, 'participantSuboptions' => $suboption, 'reasonSpecify' => $reason, 'history' => $history, ]; return $result; } /** * Handles the fetching of Participant Status History * * @param CandID $candID current candidate's ID * * @throws DatabaseException * * @return array */ function getParticipantStatusHistory(CandID $candID) { $db = \NDB_Factory::singleton()->database(); $unformattedComments = $db->pselect( "SELECT entry_staff, data_entry_date, (SELECT Description FROM participant_status_options pso WHERE ID=psh.participant_status) AS status, (SELECT Description from participant_status_options pso WHERE ID=psh.participant_subOptions) AS suboption, reason_specify FROM participant_status_history psh WHERE CandID=:cid", ['cid' => $candID] ); return $unformattedComments; } /** * Handles the fetching of Consent Status fields * * @throws DatabaseException * * @return array */ function getConsentStatusFields() { $candID = new CandID($_GET['candID']); $candidate = \Candidate::singleton($candID); // get pscid $pscid = $candidate->getPSCID(); $consentList = []; $status = []; $date = []; $withdrawalDate = []; // Get consent groups $consentGroups = \Utility::getConsentGroups(); // Get list of all consent types $consentDetails = \Utility::getConsentList(); // Get list of consents for candidate $candidateConsent = $candidate->getConsents(); foreach ($consentDetails as $consentID=>$consent) { $consentName = $consent['Name']; $consentList[$consentName] = $consent['Label']; $groupID = $consent['ConsentGroupID']; // Append consent as a child to its group $consentGroups[$groupID]['Children'][] = $consentName; if (isset($candidateConsent[$consentID])) { $candidateConsentID = $candidateConsent[$consentID]; $status[$consentName] = $candidateConsentID['Status']; $date[$consentName] = $candidateConsentID['DateGiven']; $withdrawalDate[$consentName] = $candidateConsentID['DateWithdrawn']; } else { $status[$consentName] = null; $date[$consentName] = null; $withdrawalDate[$consentName] = null; } } $history = getConsentStatusHistory($pscid); $result = [ 'pscid' => $pscid, 'candID' => $candID->__toString(), 'consentStatuses' => $status, 'consentDates' => $date, 'withdrawals' => $withdrawalDate, 'consents' => $consentList, 'history' => $history, 'consentGroups' => $consentGroups, ]; return $result; } /** * Handles the fetching of Consent Status history * * @param string $pscid current candidate's PSCID * * @throws DatabaseException * * @return array */ function getConsentStatusHistory($pscid) { $db = (\NDB_Factory::singleton())->database(); $historyData = $db->pselect( "SELECT EntryDate, DateGiven, DateWithdrawn, PSCID, ConsentName, ConsentLabel, Status, EntryStaff FROM candidate_consent_history WHERE PSCID=:pscid ORDER BY EntryDate ASC", ['pscid' => $pscid] ); $formattedHistory = []; foreach ($historyData as $entry) { $formattedHistory[] = [ 'data_entry_date' => $entry['EntryDate'], 'entry_staff' => $entry['EntryStaff'], 'consentStatus' => $entry['Status'], 'date' => $entry['DateGiven'], 'withdrawal' => $entry['DateWithdrawn'], 'label' => $entry['ConsentLabel'], 'consentType' => $entry['ConsentName'], ]; } return $formattedHistory; } /** * Handles the fetching of candidate's date of birth. * * @return array */ function getDOBFields(): array { $candID = new CandID($_GET['candID']); $db = \NDB_Factory::singleton()->database(); // Get PSCID $candidateData = $db->pselectRow( 'SELECT PSCID,DoB FROM candidate where CandID =:candid', ['candid' => $candID->__toString()] ); $pscid = $candidateData['PSCID'] ?? null; $dob = $candidateData['DoB'] ?? null; // Get DoB format $factory = \NDB_Factory::singleton(); $config = $factory->config(); $dobFormat = $config->getSetting('dobFormat'); $dobProcessedFormat = implode("-", str_split($dobFormat, 1)); $dobDate = DateTime::createFromFormat('Y-m-d', $dob); $formattedDate = $dobDate ? $dobDate->format($dobProcessedFormat) : null; $result = [ 'pscid' => $pscid, 'candID' => $candID->__toString(), 'dob' => $formattedDate, 'dobFormat' => $dobFormat, ]; return $result; } /** * Handles the fetching of candidate's date of death. * * @return array */ function getDODFields(): array { $candID = new CandID($_GET['candID']); $db = \NDB_Factory::singleton()->database(); $candidateData = $db->pselectRow( 'SELECT PSCID,DoD, DoB FROM candidate where CandID =:candid', ['candid' => $candID] ); if ($candidateData === null) { throw new \LorisException("Invalid candidate"); } $factory = \NDB_Factory::singleton(); $config = $factory->config(); // Get formatted dod $dodFormat = $config->getSetting('dodFormat'); $dodProcessedFormat = implode("-", str_split($dodFormat, 1)); $dodDate = DateTime::createFromFormat('Y-m-d', $candidateData['DoD']); $dod = $dodDate ? $dodDate->format($dodProcessedFormat) : null; // Get formatted dob $dobFormat = $config->getSetting('dobFormat'); $dobProcessedFormat = implode("-", str_split($dobFormat, 1)); $dobDate = DateTime::createFromFormat('Y-m-d', $candidateData['DoB']); $dob = $dobDate ? $dobDate->format($dobProcessedFormat) : null; $result = [ 'pscid' => $candidateData['PSCID'], 'candID' => $candID->__toString(), 'dod' => $dod, 'dob' => $dob, 'dodFormat' => $config->getSetting('dodFormat'), ]; return $result; } /** * Handles the fetching of candidate's diagnosis evolution. * * @return array */ function getDiagnosisEvolutionFields(): array { $candID = new CandID($_GET['candID']); $db = \NDB_Factory::singleton()->database(); $pscid = $db->pselectOne( "SELECT PSCID FROM candidate WHERE CandID=:candID", ['candID' => $candID] ); $candidateDiagnosisEvolution = $db->pselect( "SELECT de.Name AS TrajectoryName, p.Name AS Project, visitLabel, instrumentName, sourceField, Diagnosis, Confirmed, LastUpdate, OrderNumber FROM candidate_diagnosis_evolution_rel JOIN diagnosis_evolution de USING (DxEvolutionID) JOIN Project p USING (ProjectID) WHERE CandID=:candID", ['candID' => $candID] ); $projectList = \Utility::getProjectList(); // Get all candidate's project affiliations $candProjIDs = $db->pselectCol( "SELECT DISTINCT ProjectID FROM session WHERE CandID=:candID", ['candID' => $candID] ); $candProjects = []; $candidate = \Candidate::singleton($candID); $latestDiagnosis = []; $latestConfirmedDiagnosis = []; foreach ($candProjIDs as $projectID) { $candProjects[$projectID] = $projectList[$projectID]; $latestDiagnosis[] = $candidate->getLatestDiagnosis( new \ProjectID($projectID), false ); $latestConfirmedDiagnosis[] = $candidate->getLatestDiagnosis( new \ProjectID($projectID), true ); } // remove null results and re-index $latestDiagnosis = array_values(array_filter($latestDiagnosis)); $latestConfirmedDiagnosis = array_values( array_filter($latestConfirmedDiagnosis) ); $result = [ 'pscid' => $pscid, 'candID' => $candID, 'diagnosisEvolution' => $candidateDiagnosisEvolution, 'latestProjectDiagnosis' => $latestDiagnosis, 'latestConfirmedProjectDiagnosis' => $latestConfirmedDiagnosis, 'projects' => $candProjects ]; return $result; }
<script> import axios from 'axios'; let isVisible = true; import { user } from '../../stores/store.js'; import { page } from '$app/stores'; import iconLogo from '../../assets/elogo.png'; let showHiddenMenu = false; const handleLogout = async () => { try { //deleting the localStorage key const res = await axios.post( 'http://localhost:8000/api/userlogout', {}, { withCredentials: true } ); console.log(res.data); if (res.data) { localStorage.removeItem('isLoggedIn'); window.location.href = '/'; } } catch (err) { console.log(err); } }; </script> {#if isVisible} <nav class="bg-white py-4 px-16 w-full sticky top-0 shadow-shadow2 h-20 hidden lg:flex items-center justify-between z-20" > <div> <a href="/" class="text-2xl font-extrabold flex items-center" ><img src={iconLogo} alt="logo" class="h-7 w-7" /> <span class="text-orange-600">asycruise</span></a > </div> <div class="relative flex items-center justify-between"> <a class="py-2 px-6 text-lg mx-2 rounded-md font-medium {$page.url.pathname == '/' ? 'bg-blue-50 text-blue-600 ' : 'bg-white'}" href="/">Flights</a > <a class="py-2 px-6 text-lg mx-2 rounded-md font-medium {$page.url.pathname == '/about' ? 'bg-blue-50 text-blue-600 ' : 'bg-white'}" href="/about">About</a > <a class="py-2 px-6 text-lg mx-2 rounded-md font-medium {$page.url.pathname == '/contact' ? 'bg-blue-50 text-blue-600 ' : 'bg-white'}" href="/contact">Contact us</a > {#if $user} <button class="h-12 w-12 mx-4 rounded-full bg-orange1 text-white font-bold text-lg" type="button" on:click={() => (showHiddenMenu = !showHiddenMenu)}>{$user.data.username[0]}</button > {:else} <a class="mx-4 text-white font-medium bg-blue-700 hover:bg-blue-800 py-2.5 px-8 rounded-md" href="/signin">Login / Signup</a > {/if} {#if showHiddenMenu} <div class="absolute shadow-shadow2 rounded-md px-4 pt-4 pb-6 h-72 w-64 bg-white right-2 top-16 flex flex-col justify-between" > <a href="/profile" class="hover:bg-gray-100 bg-gray-50 rounded-md w-full px-4 py-3" >Profile</a > <button class=" text-white text-lg font-bold bg-blue-700 hover:bg-blue-800 py-3 rounded-md w-full" type="button" on:click={handleLogout}>Logout</button > </div> {/if} </div> </nav> {/if}
import { Button, Grid, Typography } from "@mui/material"; import Image from "next/image"; import React, { useEffect } from "react"; import styles from "@/styles/sass/Dashboard/Forms/main.module.scss"; import { toast } from "sonner"; import Aos from "aos"; import "aos/dist/aos.css"; import ActionsButtons from "./ActionsButtons"; import { useTranslation } from "react-i18next"; import VerificationCodeInput from "../shared/VerficationInput/page"; import InputForShapeTest from "../shared/VerficationInput/VerficationForShapeTest"; const ShapeTest = ({ handleNext, steps, formData, setSteps, currentIndex, handleBack, setFormData, }: any) => { const [showNext, setShowNext] = React.useState(false); const { t, i18n } = useTranslation(); const lang = i18n.resolvedLanguage; useEffect(() => { Aos.init(); }, []); const handleSubmit = () => { if (showNext) { steps[currentIndex].isCompleted = true; handleNext(); } else { toast.warning(t("Please fill all fields")); } }; return ( <div style={{ display: "flex", flexDirection: "column", gap: "20px", alignItems: "center", justifyContent: "center", width: "100%", }} data-aos="fade-right" > <Typography color={"primary"} style={{ fontFamily: "Tajawal", fontSize: "20px", }} > رتب أرقام المربعات من المفضل للأقل تفضيلاً </Typography> <Image src={"/images/Dashboard/shape_test.jpg"} width={400} height={600} alt="Shape-Test" /> <InputForShapeTest setShowNext={setShowNext} code={formData?.shapeTest} formData={formData} setCode={setFormData} /> <Grid container flexDirection={lang == "en" ? "row" : "row-reverse"} sx={{ mt: 4 }} > <Grid sx={{ display: "flex", justifyContent: lang == "en" ? "flex-end" : "flex-start", padding: "5px", }} item xs={6} md={6} > <Button color="error" disabled={currentIndex === 0} onClick={handleBack} sx={{ mr: 1 }} className={styles.backBtn} variant="outlined" > {t("Back")} </Button> </Grid> <Grid sx={{ display: "flex", justifyContent: lang == "en" ? "flex-start" : "flex-end", padding: "5px", }} item xs={6} md={6} > <Button disabled={showNext ? false : true} onClick={handleSubmit} className={styles.nextBtn} > {currentIndex === steps.length - 1 ? t("Finish") : t("Next")} </Button> </Grid> </Grid> </div> ); }; export default ShapeTest;
/* eslint-disable */ import * as React from "react"; import { ethers } from "ethers"; import './App.css'; import abi from "./utils/WavePortal.json"; import TextField from '@material-ui/core/TextField'; export default function App() { // Store the user's account as a state variable const [currAccount, setCurrentAccount] = React.useState(""); const [currWaveCount, setCurrentWaveCount] = React.useState(0); const [allWaves, setAllWaves] = React.useState([]); const [message, setMessage] = React.useState(""); const contractAddress = "0x4407D2c2AB2290b866c76669c29b29C881940355"; const contractABI = abi.abi; const checkIfWalletIsConnected = () => { // First make sure we have access to window.ethereum const { ethereum } = window; if(!ethereum) { console.log("Make sure you have Metamask!"); return } else { console.log("We have the ethereum object!", ethereum) } // ** Try to get access to the user's wallet ethereum.request({ method: 'eth_accounts' }) .then((accounts) => { // ** There could be multiple accounts if(accounts.length !== 0) { // ** Get the first account const account = accounts[0]; console.log("Using the first authorized account:", account); // ** Store the account setCurrentAccount(account); // ** Get all the waves getAllWaves(); // ** Get the wave count getWaveCount(); } else { console.log("No authorized account found!"); } }) } const connectWallet = () => { const { ethereum } = window; if(!ethereum) { alert("Get Metamask!"); } ethereum.request({ method: 'eth_requestAccounts' }) .then((accounts) => { console.log("Connected:", accounts[0]); setCurrentAccount(accounts[0]); }) .catch((e) => console.log(e)) } const wave = async () => { const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); const waveportalContract = new ethers.Contract(contractAddress, contractABI, signer); let count = await waveportalContract.getTotalWaves(); setCurrentWaveCount(count.toNumber()); console.log("Retrieved total wave count...", count.toNumber()); const waveTxn = await waveportalContract.wave(message, { gasLimit: 300000 }); console.log("Mining...", waveTxn.hash); try { await waveTxn.wait(); console.log("Mined --", waveTxn.hash); } catch (e) { console.error(e); alert("Your transaction failed!!"); } count = await waveportalContract.getTotalWaves(); setCurrentWaveCount(count.toNumber()); console.log("Retrieved total wave count...", count.toNumber()); } const getWaveCount = async () => { const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); const waveportalContract = new ethers.Contract(contractAddress, contractABI, signer); let count = await waveportalContract.getTotalWaves(); setCurrentWaveCount(count.toNumber()); } const getAllWaves = async () => { const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); const waveportalContract = new ethers.Contract(contractAddress, contractABI, signer); let waves = await waveportalContract.getAllWaves(); let wavesCleaned = []; waves.forEach((wave) => { wavesCleaned.push({ address: wave.waver, timestamp: new Date(wave.timestamp * 1000), message: wave.message }) }) setAllWaves(wavesCleaned); waveportalContract.on("NewWave", (from, timestamp, message) => { console.log("NewWave", from, timestamp, message) setAllWaves(oldArray => [...oldArray, { address: from, timestamp: new Date(timestamp * 1000), message: message }]) }) } React.useEffect(() => { checkIfWalletIsConnected(); // eslint-disable-next-line }, []) return ( <div className="mainContainer"> <div className="dataContainer"> <div className="header"> <span role="img" aria-label="wave">👋</span> Hey there! </div> <div className="bio"> I am Eka and I'm a Junior Blockchain Developer! Connect your Ethereum wallet and wave at me! </div> <div className="bio2"> Current Waves: {currWaveCount} </div> <TextField id="filled-full-width" label="Message" style={{ margin: 8 }} placeholder="Enter your message here..." fullWidth margin="normal" InputLabelProps={{ shrink: true, }} variant="filled" onBlur={(e) => setMessage(e.target.value)} /> <button className="waveButton" onClick={wave}> Wave at Me </button> {currAccount ? null : ( <button className="waveButton" onClick={connectWallet}> Connect Wallet </button> )} {allWaves.map((wave, index) => { return ( <div key={Object.entries(wave).toString() + index.toString()} style={{backgroundColor: "OldLace", marginTop: "16px", padding: "8px"}}> <div>Address: {wave.address}</div> <div>Time: {wave.timestamp.toString()}</div> <div>Message: {wave.message}</div> </div> ) })} </div> </div> ); } // import React, { useEffect, useState } from "react"; // import { ethers } from "ethers"; // import './App.css'; // import abi from "./utils/WavePortal.json"; // import TextField from '@material-ui/core/TextField'; // export default function App () { // const [currentAccount, setCurrentAccount] = useState(""); // const [allWaves, setAllWaves] = useState([]); // const [message, setAllMessages] = useState("") // const contractAddress = "0x4407D2c2AB2290b866c76669c29b29C881940355"; // const contractABI = abi.abi; // const getAllWaves = async () => { // try { // if (window.ethereum) { // const provider = new ethers.providers.Web3Provider // const signer = provider.getSigner(); // const wavePortalContract = new ethers.Contract(contractAddress, wavePortal.abi, signer); // const waves = await wavePortalContract.getAllWaves(); // let wavesCleaned = []; // waves.forEach(wave => { // wavesCleaned.push({ // address: wave.waver, // timestamp: new Date(wave.timestamp * 1000), // message: wave.message // }); // }); // setAllWaves(wavesCleaned); // wavePortalContract.on("NewWave", (from, timestamp, message) => { // console.log("NewWave", from, timestamp, message); // setAllWaves(prevState => [...prevState, { // address: from, // timestamp: new Date(timestamp * 1000), // message: message // }]); // }); // } else { // console.log("Ethereum object doesn't exist!") // } // } catch (error) { // console.log(error); // } // } // const checkIfWalletIsConnected = async () => { // try { // const { ethereum } = window; // if (!ethereum) { // console.log("Make sure you have metamask!"); // return; // } else { // console.log("We have the ethereum object", ethereum); // } // const accounts = await ethereum.request({ method: 'eth_accounts' }); // if (accounts.length !== 0) { // const account = accounts[0]; // console.log("Found an authorized account:", account); // } else { // console.log("No authorized account found") // } // } catch (error) { // console.log(error); // } // } // const connectWallet = async () => { // try { // const { ethereum } = window; // if (!ethereum) { // alert("Get MetaMask!"); // return; // } // const accounts = await ethereum.request({ method: "eth_requestAccounts" }); // console.log("Connected", accounts[0]); // setCurrentAccount(accounts[0]); // } catch (error) { // console.log(error) // } // } // const wave = async () => { // try { // const { ethereum } = window; // if (ethereum) { // const provider = new ethers.providers.Web3Provider(ethereum); // const signer = provider.getSigner(); // const wavePortalContract = new ethers.Contract(contractAddress, wavePortal.abi, signer); // let count = await waveportalContract.getTotalWaves(); // console.log("Retrieved total wave count...", count.toNumber()); // const waveTxn = await wavePortalContract.wave(message, { gasLimit: 300000 }) // console.log("Mining...", waveTxn.hash); // await waveTxn.wait(); // console.log("Mined -- ", waveTxn.hash); // count = await wavePortalContract.getTotalWaves(); // console.log("Retrieved total wave count...", count.toNumber()); // } else { // console.log("Ethereum object doesn't exist!"); // } // } catch (error) { // console.log(error) // } // } // useEffect(() => { // checkIfWalletIsConnected(); // }, []) // return ( // <div className="mainContainer"> // <div className="dataContainer"> // <div className="header"> // <span role="img" aria-label="wave">👋</span> Hey there! // </div> // <div className="bio"> // I am Andreas and I'm an undergraduate at USC majoring in computer science! Connect your Ethereum wallet and wave at me! // </div> // <div className="bio"> // Current Waves: {currWaveCount} // </div> // <TextField // id="filled-full-width" // label="Message" // style={{ margin: 8 }} // placeholder="Enter your message here..." // fullWidth // margin="normal" // InputLabelProps={{ // shrink: true, // }} // variant="filled" // onBlur={(e) => setMessage(e.target.value)} // /> // <button className="waveButton" onClick={wave}> // Wave at Me // </button> // {currAccount ? null : ( // <button className="waveButton" onClick={connectWallet}> // Connect Wallet // </button> // )} // {allWaves.map((wave, index) => { // return ( // <div key={Object.entries(wave).toString() + index.toString()} style={{backgroundColor: "OldLace", marginTop: "16px", padding: "8px"}}> // <div>Address: {wave.address}</div> // <div>Time: {wave.timestamp.toString()}</div> // <div>Message: {wave.message}</div> // </div> // ) // })} // </div> // </div> // ); // }
"use client"; import { motion } from "framer-motion"; function AboutPage() { const words = [ "About", <span key="keystone" className="text-green-500"> Keystone </span>, "and", <span key="me" className="text-yellow-400"> Me </span>, ]; const delayPerWord = 0.5; // Delay in seconds per word const totalDelay = words.length * delayPerWord; // Total delay for the title const variants = { hidden: { opacity: 0 }, visible: (i: number) => ({ opacity: 1, transition: { delay: i * delayPerWord, }, }), visibleAfterTitle: { opacity: 1, transition: { delay: totalDelay, }, }, }; return ( <main className="container flex justify-center mt-6"> <section className="flex flex-col gap-4 justify-items-start w-3/4"> <h1> {words.map((word, i) => ( <motion.span key={i} variants={variants} initial="hidden" animate="visible" custom={i} className="inline-block mx-1 text-5xl font-semibold tracking-tight transition-colors" > {word}{" "} </motion.span> ))} </h1> <div className="flex flex-col gap-2"> <motion.div className="mx-1" variants={variants} initial="hidden" animate="visibleAfterTitle" > <h2 className="scroll-m-20 border-b pb-2 text-2xl font-semibold tracking-tight transition-colors mb-2 w-1/4"> What is Keystone? </h2> <p className="leading-7 [&:not(:first-child)]:mt-3"> <span className="text-green-500">Keystone</span> is a open source free to use service that allows you to search world of warcraft characters and save your own characters to your own profile. This is purely a side project and practice for me to learn new technologies. </p> <div className="flex flex-col mt-2 gap-1"> <h3> <span className="text-green-500">Keystone</span> is built with: </h3> <ul className="flex flex-col my-3 ml-6 list-disc [&>li]:mt-1"> <li> <span className="text-blue-500">Frontend & Backend:</span>{" "} Next.js with typecript and the new app directory </li> <li> <span className="text-yellow-500">ORM:</span> Prisma </li> <li> <span className="text-red-500">Database & DB provider:</span>{" "} MySQL & Planetscale </li> <li> <span className="text-purple-500">Authentication:</span> Clerk Authentication </li> <li> <span className="text-lime-500">Styling & UI:</span> Tailwind & shadcn/UI </li> </ul> <div className="flex flex-col mt-6"> <h3 className="text-yellow-400 scroll-m-20 text-3xl font-semibold tracking-tight"> The developer: </h3> <p className="mx-1 leading-7 [&:not(:first-child)]:mt-3"> I have been a developer for about 1 year now. This is currently a hobby for me and i work full time as a security system installer. I am starting my bachelors degree in computer science this fall so i look forward to get into web development full time in the coming years! </p> </div> </div> </motion.div> </div> </section> </main> ); } export default AboutPage;
<template> <b-modal :active.sync="isModalActive" has-modal-card full-screen :can-cancel="false" > <div class="modal-card" style="width: auto"> <header class="modal-card-head"> <p class="modal-card-title"><i class="fas fa-user-secret"></i> Impostor</p> </header> <section class="modal-card-body is-relative"> <article class="message is-info"> <div class="message-body"> {{ trans.get('utils.impostor_select') }} </div> </article> <div class="buttons mb-1"> <button class="button is-primary" @click="generate"> {{ trans.get('utils.impostor_generate') }} </button> <button class="button is-info" v-if="impostor" @click="apply"> {{ trans.get('utils.impostor_apply') }} </button> <button class="button is-danger" v-if="impostor" @click="clear"> {{ trans.get('utils.impostor_delete') }} </button> </div> <div v-if="showImpostor" class="hiddenName is-size-1 p-3"> <div class="hideObj"></div> <h2 class="p-3" v-if="impostor">{{ impostor.name }}</h2> </div> </section> <footer class="modal-card-foot columns is-multiline" style="overflow-x: auto" > <div class="column is-narrow"> <button class="button" type="button" @click="$parent.isImpostorActive = false" > {{ trans.get("general.close") }} </button> </div> </footer> </div> </b-modal> </template> <script> // import Utils from "../../utils.js"; export default { props: ["code", "students", "current"], mounted() { if(this.current != -1) { this.showImpostor = true; setTimeout(() => { this.impostor = this.current; }, 100); } }, data: function () { return { isModalActive: true, impostor: null, studentsArray: [], showImpostor: false, }; }, methods: { clear() { this.showImpostor = false; this.impostor = null; axios.delete('/classroom/' + this.code + '/utils/impostor/clear'); }, apply() { axios .post("/classroom/" + this.code + "/utils/impostor", { id: this.impostor.id, }) .then((response) => { this.$toast(this.trans.get("success_error.update_success"), { type: "success", }); this.$parent.isImpostorActive = false; axios .post("/classroom/" + this.code + "/push", { message: "🤫 " + this.trans.get('utils.impostor'), id: this.impostor.id, }) axios .post("/classroom/" + this.code + "/push/all", { message: this.trans.get('utils.impostor_active'), }) }); }, generate() { this.studentsArray = _.shuffle(this.students); this.showImpostor = true; setTimeout(() => { this.impostor = this.studentsArray[0]; }, 100); }, }, }; </script>
#include "libs/defs.h" #include "kern/driver/stdio.h" #include "kern/sync/wait.h" #include "kern/sync/sync.h" #include "kern/process/proc.h" #include "kern/schedule/sched.h" #include "kern/fs/devs/dev.h" #include "kern/fs/vfs/vfs.h" #include "kern/fs/iobuf.h" #include "kern/fs/vfs/inode.h" #include "libs/unistd.h" #include "libs/error.h" #include "kern/debug/assert.h" #define STDIN_BUFSIZE 4096 static char stdin_buffer[STDIN_BUFSIZE]; static off_t p_rpos, p_wpos; static wait_queue_t __wait_queue, *wait_queue = &__wait_queue; void dev_stdin_write(char c) { bool intr_flag; if (c != '\0') { local_intr_save(intr_flag); { stdin_buffer[p_wpos % STDIN_BUFSIZE] = c; if (p_wpos - p_rpos < STDIN_BUFSIZE) { p_wpos++; } if (!wait_queue_empty(wait_queue)) { wakeup_queue(wait_queue, WT_KBD, 1); } } local_intr_restore(intr_flag); } } static int dev_stdin_read(char *buf, size_t len) { int ret = 0; bool intr_flag; local_intr_save(intr_flag); { for (; ret < len; ret++, p_rpos++) { try_again: if (p_rpos < p_wpos) { *buf++ = stdin_buffer[p_rpos % STDIN_BUFSIZE]; } else { wait_t __wait, *wait = &__wait; wait_current_set(wait_queue, wait, WT_KBD); local_intr_restore(intr_flag); schedule(); local_intr_save(intr_flag); wait_current_del(wait_queue, wait); if (wait->wakeup_flags == WT_KBD) { goto try_again; } break; } } } local_intr_restore(intr_flag); return ret; } static int stdin_open(struct device *dev, uint32_t open_flags) { if (open_flags != O_RDONLY) { return -E_INVAL; } return 0; } static int stdin_close(struct device *dev) { return 0; } static int stdin_io(struct device *dev, struct iobuf *iob, bool write) { if (!write) { int ret; if ((ret = dev_stdin_read(iob->io_base, iob->io_resid)) > 0) { iob->io_resid -= ret; } return ret; } return -E_INVAL; } static int stdin_ioctl(struct device *dev, int op, void *data) { return -E_INVAL; } static void stdin_device_init(struct device *dev) { dev->d_blocks = 0; dev->d_blocksize = 1; dev->d_open = stdin_open; dev->d_close = stdin_close; dev->d_io = stdin_io; dev->d_ioctl = stdin_ioctl; p_rpos = p_wpos = 0; wait_queue_init(wait_queue); } void dev_init_stdin(void) { struct inode *node; if ((node = dev_create_inode()) == NULL) { panic("stdin: dev_create_node.\n"); } stdin_device_init(vop_info(node, device)); int ret; if ((ret = vfs_add_dev("stdin", node, 0)) != 0) { panic("stdin: vfs_add_dev: %e.\n", ret); } }
// // ApiModelCreator.swift // CryptoCoins // // Created by Александр Рахимов on 27.04.2023. // import Foundation protocol ApiModelCreatorServiceProtocol { func createCryptoListApi(from data: Data) -> CryptoListAPI? func createCriptoPricesApi(from data: Data) -> CryptoPricesAPI? } class ApiModelCreatorService: ApiModelCreatorServiceProtocol { let decoder = JSONDecoder() func createCryptoListApi(from data: Data) -> CryptoListAPI? { do { let cryptoListApi = try decoder.decode(CryptoListAPI.self, from: data) return cryptoListApi } catch { print(Errors.errorCreateCryptoListAPI) } return nil } func createCriptoPricesApi(from data: Data) -> CryptoPricesAPI? { do { let cryptoPricesApi = try decoder.decode(CryptoPricesAPI.self, from: data) return cryptoPricesApi } catch { print(Errors.errorCreateCryptoPricesArray) } return nil } }
import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfTransformer, ENGLISH_STOP_WORDS, TfidfVectorizer # the function takes 3 parameters # first parameter is category. "business", "politics" etc. # second parameter is pres_or_abs. you should decide why to use presence or absence. # third parameter is withStopWord. you should decide use StopWord or not. def analyzeWithStopWords(category, pres_or_abs, withStopWord): print("\n" + category, pres_or_abs, withStopWord, "\n") # read the file with pandas library df = pd.read_csv('English Dataset.csv') # make dataframe to numpy array df = df.to_numpy() # we initialize a list which have all category and count categoryList = list(df[:, 2]) # we initialize a list for each category # make for loop which indexes assigned to which category businessList, politicsList, techList, entList, sportList = [], [], [], [], [], for i in categoryList: if i == "business": businessList.append(True) politicsList.append(False) techList.append(False) entList.append(False) sportList.append(False) elif i == "politics": businessList.append(False) politicsList.append(True) techList.append(False) entList.append(False) sportList.append(False) elif i == "tech": businessList.append(False) politicsList.append(False) techList.append(True) entList.append(False) sportList.append(False) elif i == "entertainment": businessList.append(False) politicsList.append(False) techList.append(False) entList.append(True) sportList.append(False) elif i == "sport": businessList.append(False) politicsList.append(False) techList.append(False) entList.append(False) sportList.append(True) # make our lists to numpy array to be faster businessList = np.array(businessList) politicsList = np.array(politicsList) techList = np.array(techList) entList = np.array(entList) sportList = np.array(sportList) if category == "business": categoryList = businessList elif category == "politics": categoryList = politicsList elif category == "tech": categoryList = techList elif category == "entertainment": categoryList = entList elif category == "sport": categoryList = sportList ngram = (0, 0) if pres_or_abs == "presence": ngram = (1, 1) elif pres_or_abs == "absence": ngram = (2, 2) data = df[categoryList] # Now we are going to compute the IDF values by calling tfidf_transformer = TfidfTransformer(smooth_idf=True, use_idf=True) # With Tfidfvectorizer you compute the word counts, idf and tf-idf values all at once vectorizer = TfidfVectorizer(use_idf=True) # then we decide use stop word or not if withStopWord == "withStopWord": vectorizer = TfidfVectorizer(use_idf=True, smooth_idf=True, ngram_range=ngram) elif withStopWord == "withoutStopWord": vectorizer = TfidfVectorizer(use_idf=True, stop_words=ENGLISH_STOP_WORDS, smooth_idf=True, ngram_range=ngram) # this steps generates word counts for the words word_count_vector = vectorizer.fit_transform(data[:, 1]) # get the all vector out tf_idf_vector = np.sum(word_count_vector, axis=0) # place tf-idf values in a pandas data frame df = pd.DataFrame(tf_idf_vector.A1, index=vectorizer.get_feature_names_out(), columns=["tfidf"]) # list the scores for just first 10 words as you mention in pdf. df_category = df.sort_values(by=["tfidf"], ascending=False) return df_category.head(10) print(analyzeWithStopWords("business", "presence", "withStopWord")) print(analyzeWithStopWords("business", "presence", "withoutStopWord")) print(analyzeWithStopWords("business", "absence", "withoutStopWord")) print(analyzeWithStopWords("business", "absence", "withStopWord")) print(analyzeWithStopWords("politics", "presence", "withStopWord")) print(analyzeWithStopWords("politics", "presence", "withoutStopWord")) print(analyzeWithStopWords("politics", "absence", "withoutStopWord")) print(analyzeWithStopWords("politics", "absence", "withStopWord")) print(analyzeWithStopWords("tech", "presence", "withStopWord")) print(analyzeWithStopWords("tech", "presence", "withoutStopWord")) print(analyzeWithStopWords("tech", "absence", "withoutStopWord")) print(analyzeWithStopWords("tech", "absence", "withStopWord")) print(analyzeWithStopWords("entertainment", "presence", "withStopWord")) print(analyzeWithStopWords("entertainment", "presence", "withoutStopWord")) print(analyzeWithStopWords("entertainment", "absence", "withoutStopWord")) print(analyzeWithStopWords("entertainment", "absence", "withStopWord")) print(analyzeWithStopWords("sport", "presence", "withStopWord")) print(analyzeWithStopWords("sport", "presence", "withoutStopWord")) print(analyzeWithStopWords("sport", "absence", "withoutStopWord")) print(analyzeWithStopWords("sport", "absence", "withStopWord"))
import 'package:beasy/utilities/widgets/custom_app_bar.dart'; import 'package:beasy/utilities/widgets/custom_title_textfiled.dart'; import 'package:beasy/utilities/widgets/rounded_button.dart'; import 'package:flutter/material.dart'; import '../../utilities/constants/asstes.dart'; import '../../utilities/constants/constants.dart'; import '../../utilities/constants/strings.dart'; import '../../utilities/widgets/image_collection_widget.dart'; class DetailServiceScreen extends StatefulWidget { const DetailServiceScreen({ super.key, this.isEditable = false, }); final bool isEditable; @override State<DetailServiceScreen> createState() => _DetailServiceScreenState(); } class _DetailServiceScreenState extends State<DetailServiceScreen> { late bool _isEdiatble; @override void initState() { super.initState(); _isEdiatble = widget.isEditable; } @override Widget build(BuildContext context) { return Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(40), child: CustomAppBar( title: _isEdiatble ? "Edit" : "Detail", ), ), body: SafeArea( child: Padding( padding: const EdgeInsets.only(left: 30, right: 30, top: 30), child: CustomScrollView( physics: const ScrollPhysics(), slivers: <Widget>[ SliverFillRemaining( hasScrollBody: false, child: Column( children: [ SizedBox( width: screenWidth, height: screenHeight * 0.45, child: ImageCollectionWidget( title: _isEdiatble ? AppStrings.addImages : "Service Images", height: screenHeight * 0.35, images: const [ Assets.demoCar, Assets.demoCar, Assets.demoCar, ], isShowUploadButton: _isEdiatble, onClickUploadCard: (index) { debugPrint("Upload Card Pressed $index"); }, onClickDeleteButton: _isEdiatble ? (index) { debugPrint("Delete Item at $index"); } : null, onClickCard: (index) { debugPrint("Pressed Image at $index"); }, ), ), gapH10, CustomTitleTextField( fieldText: AppStrings.carName, hintText: AppStrings.carName, isShowEdiatbleButton: _isEdiatble, isReadyOnly: true, ), gapH24, CustomTitleTextField( fieldText: AppStrings.carDescription, hintText: AppStrings.enterHere, maxLines: 4, isShowEdiatbleButton: _isEdiatble, isReadyOnly: true, ), gapH24, CustomTitleTextField( fieldText: AppStrings.addModel, hintText: AppStrings.enterModel, isShowEdiatbleButton: _isEdiatble, isReadyOnly: true, ), gapH24, CustomTitleTextField( fieldText: AppStrings.year, hintText: AppStrings.enterYear, keyboardType: TextInputType.number, isShowEdiatbleButton: _isEdiatble, isReadyOnly: true, ), gapH24, CustomTitleTextField( fieldText: "Price", hintText: AppStrings.enterPriceHour, keyboardType: const TextInputType.numberWithOptions(decimal: true), isShowEdiatbleButton: _isEdiatble, isReadyOnly: true, ), const Spacer(), gapH50, RoundedButton( title: _isEdiatble ? "Save" : "Edit", onPressed: () { if (!widget.isEditable) { setState( () { _isEdiatble = true; }, ); } }, ) ], ), ), ], ), ), ), ); } }
#include "shell.h" #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <string.h> int main((int argc, char *argv[]) __attribute__(unused), char **env); int _execute(char *arguments, struct stat *statbuf, char **envp); bool check_file_status(char *pathname, struct stat *statbuf); void handle_error(pid_t pid); char **split_string(const char *str, const char *delimiter, int *count); void free_substrings(char **substrings, int count); /** * main - Shell program to run commands * @argc: Argument count * @argv: Argument vector * @env: Parameter * Return: 0 on success */ int main((int argc, char *argv[]) __attribute__(unused), char **env) { char *buff = NULL, *prompt = "$"; size_t buff_size = 0; ssize_t bytes; pid_t wpid; int wstatus; bool from_pipe = false; struct stat statbuf; while (1 && !from_pipe) { if (isatty(STDIN_FILENO) == 0) from_pipe = true; write(STDOUT_FILENO, prompt, 1); bytes = getline(&buff, &buff_size, stdin); if (bytes == -1) { perror("Error (getline)"); free(buff); exit(EXIT_FAILURE); } if (buff[bytes - 1] == '\n') buff[bytes - 1] = '\0'; wpid = fork(); if (wpid == -1) { perror("Error (fork)"); exit(EXIT_FAILURE); } if (wpid == 0) _execute(buff, &statbuf, env); if (waitpid(wpid, &wstatus, 0) == -1) { perror("ERROR (wait)"); exit(EXIT_FAILURE); } } free(buff); return (0); } /** * _execute - Execute * @envp: Environment variable * @arguments: Command arguments * @statbuf: Buffer for file status * Return: on success */ int _execute(char *arguments, struct stat *statbuf, char **envp) { int argc; char **argv; char *exe__attribute__(unused); argv = split_string(arguments, " ", &argc); if (!check_file_status(argv[0], statbuf)) { perror("Error"); exit(EXIT_FAILURE); } execve(argv[0], argv, envp); perror("Error (execute)"); exit(EXIT_FAILURE); } /** * check_file_status - Check status * @pathname: Name of path * @statbuf: Buffer * Return: True if file exists, false otherwise */ bool check_file_status(char *pathname, struct stat *statbuf) { int stat_return; stat_return = stat(pathname, statbuf); if (stat_return == 0) return (true); return (false); } /** * handle_error - Will handle the error * @pid: Parent process id * Return: void */ void handle_error(pid_t pid) { if (pid == -1) { printf("Error"); exit(EXIT_FAILURE); } } /** * split_string - Will split string * @str: String input * substrings: strings * @count: Pointer of substrings count * @delimiter: character * Return: Array of substrings */ char **split_string(const char *str, const char *delimiter, int *count) { char **substrings = NULL; int substrings_count = 0; char *str_copy = strdup(str); char *token = strtok(str_copy, delimiter); while (token != NULL) { substrings = realloc(substrings, sizeof(char *) * (substrings_count + 1)); substrings[substrings_count] = strdup(token); substrings_count++; token = strtok(NULL, delimiter); } free(str_copy); *count = substrings_count; return (substrings); } /** * free_substrings - Will free memory allocated for substrings array. * @substrings: Strings array * @count: Number of substrings * this function frees memory allocated for each substrings * and then frees the memory for allocated array. */ void free_substrings(char **substrings, int count) { for (int i = 0; i < count; i++) { free(substrings[i]); } free(substrings[i]); }